From a2b0cb484531d74fec7b4492f2be02a874ede6b3 Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Thu, 14 Mar 2024 15:36:41 +0300 Subject: [PATCH 1/6] Fix code formatting --- .clang-format | 237 +++++ src/Account.cpp | 359 ++++---- src/Account.h | 60 +- src/AccountListItem.cpp | 91 +- src/AccountListItem.h | 15 +- src/AccountSettingsWindow.cpp | 192 ++-- src/AccountSettingsWindow.h | 19 +- src/App.cpp | 206 +++-- src/App.h | 5 +- src/AutoTextControl.cpp | 177 ++-- src/AutoTextControl.h | 107 +-- src/Budget.cpp | 103 +-- src/Budget.h | 27 +- src/BudgetReport.cpp | 577 ++++++------ src/BudgetWindow.cpp | 905 ++++++++++--------- src/BudgetWindow.h | 68 +- src/BuildOptions.h | 8 +- src/CBLocale.h | 81 +- src/CashFlowReport.cpp | 355 ++++---- src/Category.cpp | 199 ++--- src/Category.h | 44 +- src/CategoryBox.cpp | 91 +- src/CategoryBox.h | 26 +- src/CategoryWindow.cpp | 842 +++++++++--------- src/CategoryWindow.h | 5 +- src/CheckNumBox.cpp | 150 ++-- src/CheckNumBox.h | 27 +- src/CheckView.cpp | 504 +++++------ src/CheckView.h | 53 +- src/CppSQLite3.cpp | 1322 +++++++++++----------------- src/CppSQLite3.h | 341 ++++---- src/CurrencyBox.cpp | 75 +- src/CurrencyBox.h | 21 +- src/DAlert.cpp | 412 ++++----- src/DAlert.h | 173 ++-- src/DStringList.cpp | 132 ++- src/DStringList.h | 85 +- src/Database.cpp | 1547 ++++++++++++++++----------------- src/Database.h | 111 +-- src/DateBox.cpp | 145 ++- src/DateBox.h | 27 +- src/EscapeCancelFilter.h | 27 +- src/Fixed.cpp | 226 +++-- src/Fixed.h | 18 +- src/HelpButton.cpp | 80 +- src/HelpButton.h | 8 +- src/Import.cpp | 693 +++++++-------- src/Import.h | 6 +- src/Language.cpp | 170 ++-- src/Language.h | 37 +- src/LanguageRoster.cpp | 93 +- src/LanguageRoster.h | 14 +- src/Locale.cpp | 1279 +++++++++++++-------------- src/MainWindow.cpp | 1147 ++++++++++++------------ src/MainWindow.h | 46 +- src/MsgDefs.h | 6 +- src/NavTextBox.cpp | 38 +- src/NavTextBox.h | 26 +- src/NetWorthReport.cpp | 164 ++-- src/Notifier.cpp | 38 +- src/Notifier.h | 110 +-- src/NumBox.cpp | 65 +- src/NumBox.h | 26 +- src/ObjectList.h | 471 +++++----- src/PayeeBox.cpp | 95 +- src/PayeeBox.h | 28 +- src/PrefWindow.cpp | 396 ++++----- src/PrefWindow.h | 74 +- src/Preferences.cpp | 156 ++-- src/Preferences.h | 25 +- src/QuickTrackerItem.cpp | 271 +++--- src/QuickTrackerItem.h | 36 +- src/ReconcileItem.cpp | 94 +- src/ReconcileItem.h | 13 +- src/ReconcileWindow.cpp | 1067 +++++++++++------------ src/ReconcileWindow.h | 38 +- src/RegisterView.cpp | 213 ++--- src/RegisterView.h | 20 +- src/ReportGrid.cpp | 182 ++-- src/ReportGrid.h | 59 +- src/ReportWindow.cpp | 689 +++++++-------- src/ReportWindow.h | 75 +- src/ScheduleAddWindow.cpp | 333 ++++--- src/ScheduleAddWindow.h | 18 +- src/ScheduleListWindow.cpp | 349 ++++---- src/ScheduleListWindow.h | 5 +- src/ScheduledExecutor.cpp | 69 +- src/ScheduledExecutor.h | 3 +- src/ScheduledTransData.cpp | 126 ++- src/ScheduledTransData.h | 38 +- src/ScheduledTransItem.cpp | 171 ++-- src/ScheduledTransItem.h | 23 +- src/SplitItem.cpp | 48 +- src/SplitItem.h | 19 +- src/SplitView.cpp | 1088 +++++++++++------------ src/SplitView.h | 57 +- src/SplitViewFilter.cpp | 307 +++---- src/SplitViewFilter.h | 9 +- src/StickyDrawButton.cpp | 107 +-- src/StickyDrawButton.h | 57 +- src/TextFile.cpp | 69 +- src/TextFile.h | 31 +- src/TimeSupport.cpp | 232 +++-- src/TimeSupport.h | 87 +- src/Transaction.cpp | 40 +- src/Transaction.h | 47 +- src/TransactionData.cpp | 205 ++--- src/TransactionData.h | 90 +- src/TransactionEditWindow.cpp | 71 +- src/TransactionEditWindow.h | 11 +- src/TransactionItem.cpp | 176 ++-- src/TransactionItem.h | 19 +- src/TransactionLayout.cpp | 47 +- src/TransactionLayout.h | 18 +- src/TransactionReport.cpp | 306 ++++--- src/TransactionView.cpp | 436 ++++------ src/TransactionView.h | 38 +- src/TransferWindow.cpp | 381 ++++---- src/TransferWindow.h | 35 +- 119 files changed, 10932 insertions(+), 12477 deletions(-) create mode 100755 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100755 index 0000000..3ef6673 --- /dev/null +++ b/.clang-format @@ -0,0 +1,237 @@ +--- +Language: Cpp + # BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: TopLevel +AlwaysBreakAfterReturnType: TopLevel +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAfterAttributes: Always +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 100 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Always +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseTab: Always +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + + diff --git a/src/Account.cpp b/src/Account.cpp index f3fd6bd..4dc9edf 100644 --- a/src/Account.cpp +++ b/src/Account.cpp @@ -4,33 +4,23 @@ #include Account::Account(const char *name, const bool &isclosed) - : fName(name), - fID(0), - fClosed(isclosed), - fCurrentTransaction(0), - fLastCheckNumber(0), - fUseDefaultLocale(true) -{ -} + : fName(name), fID(0), fClosed(isclosed), fCurrentTransaction(0), fLastCheckNumber(0), + fUseDefaultLocale(true) {} -Account::~Account(void) -{ -} +Account::~Account(void) {} -void Account::SetName(const char *name) -{ +void +Account::SetName(const char *name) { fName = name; } -bool Account::SetCurrentTransaction(const uint32 &id) -{ - if(gDatabase.HasTransaction(id)) - { - if(id != fCurrentTransaction) - { +bool +Account::SetCurrentTransaction(const uint32 &id) { + if (gDatabase.HasTransaction(id)) { + if (id != fCurrentTransaction) { BMessage msg; - msg.AddInt32("id",id); - Notify(WATCH_TRANSACTION | WATCH_SELECT,&msg); + msg.AddInt32("id", id); + Notify(WATCH_TRANSACTION | WATCH_SELECT, &msg); } fCurrentTransaction = id; return true; @@ -38,319 +28,292 @@ bool Account::SetCurrentTransaction(const uint32 &id) return false; } -uint16 Account::LookupLastCheckNumber(void) -{ +uint16 +Account::LookupLastCheckNumber(void) { BString command("select max(type) from account_"); command << fID << " where type between 0 and 65536;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"Account::LookupLastCheckNumber"); - if(query.eof()) + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::LookupLastCheckNumber"); + if (query.eof()) return 0; - + return query.getIntField(0); } -Fixed Account::Balance(void) -{ +Fixed +Account::Balance(void) { BString command("select sum(amount) from account_"); command << fID << ";"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(), - "Account::Balance"); - + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::Balance"); + int64 amount = 0; - if(query.eof()) + if (query.eof()) return Fixed(); - + amount = query.getInt64Field(0); - + Fixed f; f.SetPremultiplied(amount); return f; } -Fixed Account::BalanceAt(const time_t &date) -{ +Fixed +Account::BalanceAt(const time_t &date) { BString command("select sum(amount) from account_"); command << fID << " where date <= " << date << " order by payee;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"Account::BalanceAt"); - + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::BalanceAt"); + int64 amount = 0; - if(query.eof()) + if (query.eof()) return Fixed(); - + amount = query.getInt64Field(0); - + Fixed f; f.SetPremultiplied(amount); return f; } -Fixed Account::BalanceAtTransaction(const time_t &time, const char *payee) -{ - if(!payee) +Fixed +Account::BalanceAtTransaction(const time_t &time, const char *payee) { + if (!payee) return Fixed(); - + BString command("select date,payee,amount from account_"); command << fID << " where date <= " << time << " order by date,payee;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"Account::BalanceAt"); - + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::BalanceAt"); + int64 amount = 0; time_t date = 0; - - while(!query.eof()) - { + + while (!query.eof()) { date = query.getInt64Field(0); - if(date < time) - { + if (date < time) { amount += query.getInt64Field(2); - } - else - { + } else { BString temp(DeescapeIllegalCharacters(query.getStringField(1))); - if(strcmp(temp.String(),payee)<1) + if (strcmp(temp.String(), payee) < 1) amount += query.getInt64Field(2); } query.nextRow(); } - - + + Fixed f; f.SetPremultiplied(amount); return f; - } -BString Account::AutocompleteCategory(const char *input) -{ - if(!input) +BString +Account::AutocompleteCategory(const char *input) { + if (!input) return BString(); - + // TODO: Add language support here - if(toupper(input[0]) == (int)'S') - { + if (toupper(input[0]) == (int)'S') { int32 inputlength = strlen(input); - if(strncasecmp(input,"Split",inputlength)==0) + if (strncasecmp(input, "Split", inputlength) == 0) return "Split"; } - + BString command("select name from categorylist where name like '"); command << EscapeIllegalCharacters(input) << "%' ;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(), - "Account::AutocompleteCategory"); - - if(query.eof()) + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::AutocompleteCategory"); + + if (query.eof()) return NULL; - + return DeescapeIllegalCharacters(query.getStringField(0)); } -BString Account::AutocompletePayee(const char *input) -{ - if(!input) +BString +Account::AutocompletePayee(const char *input) { + if (!input) return BString(); - + BString command("select payee from account_"); - command << fID << " where payee like '" - << EscapeIllegalCharacters(input) << "%' ;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(), - "Account::AutocompletePayee"); - - if(query.eof()) + command << fID << " where payee like '" << EscapeIllegalCharacters(input) << "%' ;"; + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::AutocompletePayee"); + + if (query.eof()) return NULL; - + return DeescapeIllegalCharacters(query.getStringField(0)); } -BString Account::AutocompleteType(const char *input) -{ - if(!input) +BString +Account::AutocompleteType(const char *input) { + if (!input) return BString(); - - if(toupper(input[0]) == (int)'A') - { + + if (toupper(input[0]) == (int)'A') { int32 inputlength = strlen(input); - if(strncasecmp(input,"ATM",inputlength)==0) + if (strncasecmp(input, "ATM", inputlength) == 0) return BString("ATM"); - } - else - if(toupper(input[0]) == (int)'D') - { + } else if (toupper(input[0]) == (int)'D') { int32 inputlength = strlen(input); - if(strncasecmp(input,"DEP",inputlength)==0) + if (strncasecmp(input, "DEP", inputlength) == 0) return BString("DEP"); - } - else - { + } else { // Numeric autocompletion BString str; str << fLastCheckNumber; - if(input[0] == str.ByteAt(0)) + if (input[0] == str.ByteAt(0)) return str; } - + BString command("select type from account_"); - command << fID << " where type like '" - << EscapeIllegalCharacters(input) << "%' ;"; - - CppSQLite3Query query = gDatabase.DBQuery(command.String(), - "Account::AutocompleteType"); - - if(query.eof()) + command << fID << " where type like '" << EscapeIllegalCharacters(input) << "%' ;"; + + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::AutocompleteType"); + + if (query.eof()) return BString(); - + return DeescapeIllegalCharacters(query.getStringField(0)); } -Locale Account::GetLocale(void) const -{ +Locale +Account::GetLocale(void) const { return fUseDefaultLocale ? gDefaultLocale : fLocale; } -void Account::SetLocale(const Locale &locale) -{ - if(fUseDefaultLocale) - { +void +Account::SetLocale(const Locale &locale) { + if (fUseDefaultLocale) { ShowBug("Calling SetLocale on an account with default locale settings"); return; } - - if(locale != fLocale) - { + + if (locale != fLocale) { fLocale = locale; - gDatabase.SetAccountLocale(fID,fLocale); - + gDatabase.SetAccountLocale(fID, fLocale); + BMessage msg; - msg.AddPointer("item",this); - Notify(WATCH_ACCOUNT | WATCH_LOCALE | WATCH_CHANGE,&msg); + msg.AddPointer("item", this); + Notify(WATCH_ACCOUNT | WATCH_LOCALE | WATCH_CHANGE, &msg); } } -uint32 Account::CountTransactions(void) -{ +uint32 +Account::CountTransactions(void) { BString command("select * from account_"); command << GetID() << " order by transid"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(), - "Account::CountTransactions"); - - if(query.eof()) + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::CountTransactions"); + + if (query.eof()) return 0; - - uint32 currentid=0,newid=0,count=0; - currentid=query.getIntField(1); - newid=query.getIntField(1); - - while(!query.eof()) - { + + uint32 currentid = 0, newid = 0, count = 0; + currentid = query.getIntField(1); + newid = query.getIntField(1); + + while (!query.eof()) { count++; query.nextRow(); } return count; } -void Account::DoForEachTransaction(void (*func)(const TransactionData &,void*),void *ptr) -{ +void +Account::DoForEachTransaction(void (*func)(const TransactionData &, void *), void *ptr) { BString command("select * from account_"); command << GetID() << " order by date,transid"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"Account::DoForEachTransaction"); - - uint32 currentid=0,newid=0; - if(!query.eof()) - { + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::DoForEachTransaction"); + + uint32 currentid = 0, newid = 0; + if (!query.eof()) { TransactionData data; - - currentid=query.getIntField(1); - newid=query.getIntField(1); + + currentid = query.getIntField(1); + newid = query.getIntField(1); data.SetID(currentid); data.SetDate(atol(query.getStringField(2))); data.SetType(DeescapeIllegalCharacters(query.getStringField(3)).String()); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(4)).String()); data.SetAccount(this); - + Fixed f; f.SetPremultiplied(atol(query.getStringField(5))); - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(),f,true); - - if(!query.fieldIsNull(7)) - data.SetMemoAt(data.CountCategories()-1, - DeescapeIllegalCharacters(query.getStringField(7)).String()); - + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(), f, true); + + if (!query.fieldIsNull(7)) + data.SetMemoAt( + data.CountCategories() - 1, + DeescapeIllegalCharacters(query.getStringField(7)).String() + ); + BString status = query.getStringField(8); - if(status.ICompare("Reconciled")==0) + if (status.ICompare("Reconciled") == 0) data.SetStatus(TRANS_RECONCILED); - else - if(status.ICompare("Cleared")==0) + else if (status.ICompare("Cleared") == 0) data.SetStatus(TRANS_CLEARED); else data.SetStatus(TRANS_OPEN); query.nextRow(); - - while(!query.eof()) - { - newid=query.getIntField(1); - - if(currentid!=newid) - { - if(data.CountCategories() == 1) + + while (!query.eof()) { + newid = query.getIntField(1); + + if (currentid != newid) { + if (data.CountCategories() == 1) data.SetMemo(data.MemoAt(0)); - - func(data,ptr); + + func(data, ptr); data.MakeEmpty(); - - currentid=newid; - newid=query.getIntField(1); + + currentid = newid; + newid = query.getIntField(1); data.SetID(currentid); data.SetDate(atol(query.getStringField(2))); data.SetType(DeescapeIllegalCharacters(query.getStringField(3)).String()); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(4)).String()); data.SetAccount(this); } - + f.SetPremultiplied(atol(query.getStringField(5))); - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(),f,true); - - if(!query.fieldIsNull(7)) - data.SetMemoAt(data.CountCategories()-1, - DeescapeIllegalCharacters(query.getStringField(7)).String()); - + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(), f, true); + + if (!query.fieldIsNull(7)) + data.SetMemoAt( + data.CountCategories() - 1, + DeescapeIllegalCharacters(query.getStringField(7)).String() + ); + status = query.getStringField(8); - if(status.ICompare("Reconciled")==0) + if (status.ICompare("Reconciled") == 0) data.SetStatus(TRANS_RECONCILED); - else - if(status.ICompare("Cleared")==0) + else if (status.ICompare("Cleared") == 0) data.SetStatus(TRANS_CLEARED); else data.SetStatus(TRANS_OPEN); query.nextRow(); } - - func(data,ptr); + + func(data, ptr); } } -void Account::UseDefaultLocale(const bool &usedefault) -{ - if(usedefault == fUseDefaultLocale) +void +Account::UseDefaultLocale(const bool &usedefault) { + if (usedefault == fUseDefaultLocale) return; - + fUseDefaultLocale = usedefault; - + BString command; - if(fUseDefaultLocale) - { + if (fUseDefaultLocale) { command = "delete from accountlocale where accountid = "; command << fID << ";"; - } - else - { + } else { // update the local copy in case it changed since the program was opened fLocale = gDefaultLocale; - - gDatabase.SetAccountLocale(fID,fLocale); - } + gDatabase.SetAccountLocale(fID, fLocale); + } } diff --git a/src/Account.h b/src/Account.h index 1bea4af..0cbe5be 100644 --- a/src/Account.h +++ b/src/Account.h @@ -1,61 +1,64 @@ #ifndef ACCOUNT_H #define ACCOUNT_H -#include -#include "ObjectList.h" +#include "CBLocale.h" #include "Notifier.h" +#include "ObjectList.h" #include "Transaction.h" #include "TransactionData.h" -#include "CBLocale.h" +#include + +typedef enum { ACCOUNT_BANK = 0, ACCOUNT_CASH, ACCOUNT_CREDIT } AccountType; -typedef enum -{ - ACCOUNT_BANK=0, - ACCOUNT_CASH, - ACCOUNT_CREDIT -} AccountType; - -class Account : public Notifier -{ -public: - Account(const char *name = NULL, const bool &isclosed=false); +class Account : public Notifier { + public: + Account(const char *name = NULL, const bool &isclosed = false); ~Account(void); - + void SetName(const char *name); + const char *Name(void) const { return fName.String(); } - + void SetID(const time_t &id) { fID = id; } + uint32 GetID(void) const { return fID; } - + void SetClosed(const bool &value) { fClosed = value; } + bool IsClosed(void) const { return fClosed; } - + uint32 CurrentTransaction(void) const { return fCurrentTransaction; } + bool SetCurrentTransaction(const uint32 &id); uint16 LastCheckNumber(void) const { return fLastCheckNumber; } + uint16 LookupLastCheckNumber(void); - void SetLastCheckNumber(const uint16 &value) { fLastCheckNumber=value; } - + + void SetLastCheckNumber(const uint16 &value) { fLastCheckNumber = value; } + BString AutocompleteCategory(const char *input); BString AutocompletePayee(const char *input); BString AutocompleteType(const char *input); - + Fixed Balance(void); Fixed BalanceAt(const time_t &time); Fixed BalanceAtTransaction(const time_t &time, const char *payee); - + Locale GetLocale(void) const; void SetLocale(const Locale &locale); - + uint32 CountTransactions(void); - - void DoForEachTransaction(void (*TransactionIteratorFunc)(const TransactionData &,void*),void *ptr); - + + void DoForEachTransaction( + void (*TransactionIteratorFunc)(const TransactionData &, void *), void *ptr + ); + void UseDefaultLocale(const bool &usedefault); + bool IsUsingDefaultLocale(void) const { return fUseDefaultLocale; } - -private: + + private: BString fName; uint32 fID; bool fClosed; @@ -66,4 +69,3 @@ class Account : public Notifier }; #endif - diff --git a/src/AccountListItem.cpp b/src/AccountListItem.cpp index b847b16..445ae39 100644 --- a/src/AccountListItem.cpp +++ b/src/AccountListItem.cpp @@ -1,71 +1,57 @@ -#include +#include "AccountListItem.h" +#include "Account.h" +#include "CBLocale.h" +#include "Database.h" +#include "Preferences.h" +#include "TransactionLayout.h" +#include "Translate.h" #include #include #include #include -#include "CBLocale.h" -#include "TransactionLayout.h" -#include "Preferences.h" -#include "Database.h" -#include "Account.h" -#include "AccountListItem.h" -#include "Translate.h" +#include -AccountListItem::AccountListItem(Account *acc) : BListItem() -{ +AccountListItem::AccountListItem(Account *acc) : BListItem() { fAccount = acc; fEnabled = true; } -void AccountListItem::SetEnabled(bool enabled) -{ +void +AccountListItem::SetEnabled(bool enabled) { fEnabled = enabled; } -void AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) -{ - if(IsSelected()) - { - if(IsEnabled()) - { - if(fAccount->IsClosed()) - { +void +AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) { + if (IsSelected()) { + if (IsEnabled()) { + if (fAccount->IsClosed()) { owner->SetHighColor(GetColor(BC_SELECTION_NOFOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_NOFOCUS)); - } - else - { + } else { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); } - } - else - { + } else { owner->SetHighColor(230, 230, 230); owner->SetLowColor(230, 230, 230); } - } - else - { - if(fAccount->IsClosed()) - { - owner->SetHighColor(240, 240, 240,128); - owner->SetLowColor(240, 240, 240,128); - } - else - { - owner->SetHighColor(255, 255, 255,128); - owner->SetLowColor(255, 255, 255,128); + } else { + if (fAccount->IsClosed()) { + owner->SetHighColor(240, 240, 240, 128); + owner->SetLowColor(240, 240, 240, 128); + } else { + owner->SetHighColor(255, 255, 255, 128); + owner->SetLowColor(255, 255, 255, 128); } } owner->FillRect(frame); - - if(IsSelected()) - { + + if (IsSelected()) { owner->SetHighColor(100, 100, 100); owner->StrokeRect(frame); } - + if (IsEnabled()) owner->SetHighColor(0, 0, 0); else @@ -74,23 +60,22 @@ void AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) BFont font; owner->DrawString(fAccount->Name(), BPoint(frame.left + 5, frame.top + (font.Size()))); owner->SetFont(be_plain_font); - - if(fAccount->IsClosed()) - { - owner->DrawString(TRANSLATE("Closed"), BPoint(frame.left + 5, frame.top + (font.Size() * 2))); - } - else - { + + if (fAccount->IsClosed()) { + owner->DrawString( + TRANSLATE("Closed"), BPoint(frame.left + 5, frame.top + (font.Size() * 2)) + ); + } else { BString text; - fAccount->GetLocale().CurrencyToString(fAccount->Balance(),text); + fAccount->GetLocale().CurrencyToString(fAccount->Balance(), text); owner->DrawString(text.String(), BPoint(frame.left + 5, frame.top + (font.Size() * 2))); } } -void AccountListItem::Update(BView* owner, const BFont* finfo) -{ +void +AccountListItem::Update(BView *owner, const BFont *finfo) { BListItem::Update(owner, finfo); - + // We can afford to make this call because the row height is just a sane // value based on the height of be_plain_font, which we are also using here SetHeight(TRowHeight() * 2); diff --git a/src/AccountListItem.h b/src/AccountListItem.h index b78f8c8..605b864 100644 --- a/src/AccountListItem.h +++ b/src/AccountListItem.h @@ -5,18 +5,19 @@ class Account; -class AccountListItem : public BListItem -{ -public: +class AccountListItem : public BListItem { + public: AccountListItem(Account *acc); void SetEnabled(bool enabled); + bool IsEnabled(void) const { return fEnabled; } - + void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView* owner, const BFont* finfo); + void Update(BView *owner, const BFont *finfo); + Account *GetAccount(void) const { return fAccount; } - -private: + + private: Account *fAccount; bool fEnabled; }; diff --git a/src/AccountSettingsWindow.cpp b/src/AccountSettingsWindow.cpp index a5bf1ac..e983a4a 100644 --- a/src/AccountSettingsWindow.cpp +++ b/src/AccountSettingsWindow.cpp @@ -10,134 +10,124 @@ #include "PrefWindow.h" #include "Translate.h" -#define M_EDIT_ACCOUNT_SETTINGS 'east' +#define M_EDIT_ACCOUNT_SETTINGS 'east' #define M_NAME_CHANGED 'nmch' #define M_TOGGLE_USE_DEFAULT 'tgud' AccountSettingsWindow::AccountSettingsWindow(Account *account) - : BWindow(BRect(0, 0, 1, 1),TRANSLATE("Account Settings"),B_FLOATING_WINDOW_LOOK, - B_MODAL_APP_WINDOW_FEEL,B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | - B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fAccount(account) -{ + : BWindow( + BRect(0, 0, 1, 1), TRANSLATE("Account Settings"), B_FLOATING_WINDOW_LOOK, + B_MODAL_APP_WINDOW_FEEL, + B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS + ), + fAccount(account) { AddCommonFilter(new EscapeCancelFilter); - + BString temp; - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut('Q',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + BView *back = new BView("back", B_WILL_DRAW); - back->SetViewColor(240,240,240); + back->SetViewColor(240, 240, 240); - temp = TRANSLATE("Account Name"); temp += ":"; - fAccountName = new AutoTextControl("accname",temp.String(), - (fAccount ? fAccount->Name() : NULL ), - new BMessage(M_NAME_CHANGED)); + temp = TRANSLATE("Account Name"); + temp += ":"; + fAccountName = new AutoTextControl( + "accname", temp.String(), (fAccount ? fAccount->Name() : NULL), new BMessage(M_NAME_CHANGED) + ); fAccountName->SetCharacterLimit(32); - + fAccountName->MakeFocus(true); - fAccountName->SetDivider(fAccountName->StringWidth(temp.String())+3); - - fUseDefault = new BCheckBox("usedefault","Use Default Currency Settings", - new BMessage(M_TOGGLE_USE_DEFAULT)); - if(!fAccount || fAccount->IsUsingDefaultLocale()) + fAccountName->SetDivider(fAccountName->StringWidth(temp.String()) + 3); + + fUseDefault = new BCheckBox( + "usedefault", "Use Default Currency Settings", new BMessage(M_TOGGLE_USE_DEFAULT) + ); + if (!fAccount || fAccount->IsUsingDefaultLocale()) fUseDefault->SetValue(B_CONTROL_ON); - + Locale templocale; - if(fAccount) + if (fAccount) templocale = fAccount->GetLocale(); - fPrefView = new CurrencyPrefView("prefview",&templocale); - - fOK = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_EDIT_ACCOUNT_SETTINGS)); + fPrefView = new CurrencyPrefView("prefview", &templocale); + + fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_ACCOUNT_SETTINGS)); fOK->SetLabel(TRANSLATE("OK")); - - if(strlen(fAccountName->Text())<1) + + if (strlen(fAccountName->Text()) < 1) fOK->SetEnabled(false); - - fCancel = new BButton("cancelbutton",TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); - + + fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + SetDefaultButton(fOK); - if(!fAccount || fAccount->IsUsingDefaultLocale()) - { - fPrefView->Hide(); + if (!fAccount || fAccount->IsUsingDefaultLocale()) { + fPrefView->Hide(); } BLayoutBuilder::Group<>(back, B_VERTICAL, 0.0f) .SetInsets(10) .AddGroup(B_VERTICAL, 0.0f) - .Add(fAccountName) - .Add(fUseDefault) - .Add(fPrefView) + .Add(fAccountName) + .Add(fUseDefault) + .Add(fPrefView) .End() .AddGrid(0.0f, 0.0f) - .AddGlue(0, 0) - .Add(fCancel, 1, 0) - .Add(fOK, 2, 0) + .AddGlue(0, 0) + .Add(fCancel, 1, 0) + .Add(fOK, 2, 0) .End() - .End(); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f) - .SetInsets(0) - .Add(back) - .End(); + .End(); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f).SetInsets(0).Add(back).End(); } -void AccountSettingsWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_EDIT_ACCOUNT_SETTINGS: - { - Locale temp; - - if(!fAccount) - { - temp = gDefaultLocale; - fPrefView->GetSettings(temp); - gDatabase.AddAccount(fAccountName->Text(),ACCOUNT_BANK,"Open",&temp); - } - else - { - if(strcmp(fAccountName->Text(),fAccount->Name())!=0) - gDatabase.RenameAccount(fAccount,fAccountName->Text()); - - temp = fAccount->GetLocale(); - fPrefView->GetSettings(temp); - if(temp!=fAccount->GetLocale()) - fAccount->SetLocale(temp); - } - - PostMessage(B_QUIT_REQUESTED); - break; - } - case M_TOGGLE_USE_DEFAULT: - { - bool useDefault = fUseDefault->Value() == B_CONTROL_ON; - - if (useDefault) - fPrefView->Hide(); - else - fPrefView->Show(); - - if (fAccount != NULL) - fAccount->UseDefaultLocale(useDefault); - - break; - } - case M_NAME_CHANGED: - { - if(strlen(fAccountName->Text())<1) - fOK->SetEnabled(false); - else - fOK->SetEnabled(true); - - break; - } - default: - { - BWindow::MessageReceived(msg); - break; +void +AccountSettingsWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_EDIT_ACCOUNT_SETTINGS: { + Locale temp; + + if (!fAccount) { + temp = gDefaultLocale; + fPrefView->GetSettings(temp); + gDatabase.AddAccount(fAccountName->Text(), ACCOUNT_BANK, "Open", &temp); + } else { + if (strcmp(fAccountName->Text(), fAccount->Name()) != 0) + gDatabase.RenameAccount(fAccount, fAccountName->Text()); + + temp = fAccount->GetLocale(); + fPrefView->GetSettings(temp); + if (temp != fAccount->GetLocale()) + fAccount->SetLocale(temp); } + + PostMessage(B_QUIT_REQUESTED); + break; + } + case M_TOGGLE_USE_DEFAULT: { + bool useDefault = fUseDefault->Value() == B_CONTROL_ON; + + if (useDefault) + fPrefView->Hide(); + else + fPrefView->Show(); + + if (fAccount != NULL) + fAccount->UseDefaultLocale(useDefault); + + break; + } + case M_NAME_CHANGED: { + if (strlen(fAccountName->Text()) < 1) + fOK->SetEnabled(false); + else + fOK->SetEnabled(true); + + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } diff --git a/src/AccountSettingsWindow.h b/src/AccountSettingsWindow.h index c029620..ec51fc7 100644 --- a/src/AccountSettingsWindow.h +++ b/src/AccountSettingsWindow.h @@ -1,30 +1,29 @@ #ifndef NEW_ACCOUNT_WINDOW_H #define NEW_ACCOUNT_WINDOW_H -#include -#include +#include "Fixed.h" #include #include -#include "Fixed.h" +#include +#include class AutoTextControl; class CurrencyPrefView; class Account; -class AccountSettingsWindow : public BWindow -{ -public: +class AccountSettingsWindow : public BWindow { + public: AccountSettingsWindow(Account *name); void MessageReceived(BMessage *msg); - -private: + + private: friend class NewAccountFilter; - + AutoTextControl *fAccountName; BButton *fCancel, *fOK; CurrencyPrefView *fPrefView; Account *fAccount; - BCheckBox *fUseDefault; + BCheckBox *fUseDefault; }; #endif diff --git a/src/App.cpp b/src/App.cpp index 12db3c6..10a6695 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -1,111 +1,109 @@ -#include #include "Database.h" +#include -//#define DEBUG_DATABASE +// #define DEBUG_DATABASE #ifndef DEBUG_DATABASE -#include #include "App.h" -#include "MainWindow.h" -#include "CBLocale.h" #include "BuildOptions.h" +#include "CBLocale.h" +#include "LanguageRoster.h" +#include "MainWindow.h" #include "Preferences.h" #include "TimeSupport.h" -#include "LanguageRoster.h" +#include #include "ReportWindow.h" -bool gRestartApp=false; +bool gRestartApp = false; + +App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { +#ifdef BETA_MODE -App::App(void) - : BApplication("application/x-vnd.wgp-CapitalBe") -{ - #ifdef BETA_MODE - // To create the UNIX number, run the Terminal command // date --date="25 Dec 2006" +%s // and change the date accordingly - if(GetCurrentDate() > 1167022800) - { - ShowAlert("This beta version has expired.", + if (GetCurrentDate() > 1167022800) { + ShowAlert( + "This beta version has expired.", "This is only a test version of Capital Be and is intended to work only " "for a short period of time to allow the community to help find bugs and " "make Capital Be the best financial manager possible.\n\nYou can download " - "a new copy of Capital Be from http://www.capitalbe.com/"); + "a new copy of Capital Be from http://www.capitalbe.com/" + ); be_app->PostMessage(B_QUIT_REQUESTED); return; } - - #endif - + +#endif + // Load preferences and then initialize the translation system LoadPreferences(PREFERENCES_PATH "/CapitalBeSettings"); - + BString languagepath = gAppPath.String(); languagepath += "R5LanguageFiles"; language_roster = new LanguageRoster(languagepath.String()); - - + + // We can skip locking because nothing else is open at this point :) BRect winframe; - if(gPreferences.FindRect("mainframe",&winframe)==B_OK) + if (gPreferences.FindRect("mainframe", &winframe) == B_OK) ConstrainWindowFrameToScreen(&winframe); else - winframe.Set(100,100,620,360); - + winframe.Set(100, 100, 620, 360); + MainWindow *win = new MainWindow(winframe); win->Show(); - - #ifdef PREVIEW_MODE - - ShowAlert("Welcome to Capital Be's Technology Preview!", + +#ifdef PREVIEW_MODE + + ShowAlert( + "Welcome to Capital Be's Technology Preview!", "Welcome and thank you for trying Capital Be, what will be the foremost " "personal finance manager for BeOS, Zeta, and Haiku.\n\n" "This preview version may contain bugs and is not feature complete, but " "will give you an idea of what the full version will be like when released.\n\n" "Please feel free to experiment and send any feedback to capitalbe@earthlink.net", - B_IDEA_ALERT); - - #endif + B_IDEA_ALERT + ); + +#endif } -App::~App(void) -{ +App::~App(void) { delete language_roster; language_roster = NULL; - } -void App::MessageReceived(BMessage *msg) -{ - if(msg->what==M_QUIT_NOW) +void +App::MessageReceived(BMessage *msg) { + if (msg->what == M_QUIT_NOW) Quit(); else BApplication::MessageReceived(msg); } -int main(void) -{ +int +main(void) { // Attempt to load the default data file - + BEntry entry("/boot/home/config/settings/CapitalBe"); BFile file; - - if(!entry.Exists()) - create_directory(PREFERENCES_PATH,0777); + + if (!entry.Exists()) + create_directory(PREFERENCES_PATH, 0777); entry.SetTo(PREFERENCES_PATH "/CapitalBeSettings"); - if(!entry.Exists()) - { - file.SetTo(PREFERENCES_PATH "/CapitalBeSettings",B_READ_WRITE|B_CREATE_FILE); + if (!entry.Exists()) { + file.SetTo(PREFERENCES_PATH "/CapitalBeSettings", B_READ_WRITE | B_CREATE_FILE); file.Unset(); } - + App *app = new App; app->Run(); delete app; - + return 0; } @@ -113,71 +111,71 @@ int main(void) // Test code -#include -#include "Fixed.h" -#include "Transaction.h" #include "CBLocale.h" +#include "Fixed.h" #include "Import.h" +#include "Transaction.h" +#include -void StartFile(void) -{ +void +StartFile(void) { BEntry entry("/boot/develop/projects/Capital Be/cbsql/testdb"); - if(entry.Exists()) + if (entry.Exists()) entry.Remove(); gDatabase.CreateFile("/boot/develop/projects/Capital Be/cbsql/testdb"); -/* gDatabase.AddAccount("Test Account 1",ACCOUNT_BANK); - gDatabase.AddAccount("Test Account 2",ACCOUNT_BANK); - - Locale ld; - ld.SetCurrencySymbol("£"); - ld.SetCurrencySymbolPrefix(false); - gDatabase.SetAccountLocale(1,ld); - - gDatabase.AddBudgetEntry("Misc",Fixed(0L)); - gDatabase.AddBudgetEntry("Auto_Fuel",Fixed(75)); - gDatabase.AddBudgetEntry("Misc",Fixed(150)); - gDatabase.AddBudgetEntry("RemoveMe",Fixed(15.50)); - gDatabase.RemoveBudgetEntry("RemoveMe"); - - gDatabase.RemoveAccount(1); - gDatabase.AddAccount("Test Account 2",ACCOUNT_BANK); - - uint32 id = gDatabase.NextTransactionID(); - gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("DEP"),"Paychecks", - Fixed(1000),"Salary",NULL); - - id = gDatabase.NextTransactionID(); - Fixed f; - f.SetPremultiplied(5097); - gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", - f,"Misc",NULL); - f.SetPremultiplied(1234); - gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", - f,"Clothing",NULL); - f.SetPremultiplied(4321); - gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", - f,"Computer",NULL); - - id = gDatabase.NextTransactionID(); - f.SetPremultiplied(1934); - gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Gas", - f,"Auto_Fuel",NULL); - gDatabase.RemoveTransaction(1); - - - entry.SetTo("/darkstar/Quicken Data/QIF/import.qif"); - entry_ref ref; - entry.GetRef(&ref); - ImportQIF(ref); -*/ + /* gDatabase.AddAccount("Test Account 1",ACCOUNT_BANK); + gDatabase.AddAccount("Test Account 2",ACCOUNT_BANK); + + Locale ld; + ld.SetCurrencySymbol("£"); + ld.SetCurrencySymbolPrefix(false); + gDatabase.SetAccountLocale(1,ld); + + gDatabase.AddBudgetEntry("Misc",Fixed(0L)); + gDatabase.AddBudgetEntry("Auto_Fuel",Fixed(75)); + gDatabase.AddBudgetEntry("Misc",Fixed(150)); + gDatabase.AddBudgetEntry("RemoveMe",Fixed(15.50)); + gDatabase.RemoveBudgetEntry("RemoveMe"); + + gDatabase.RemoveAccount(1); + gDatabase.AddAccount("Test Account 2",ACCOUNT_BANK); + + uint32 id = gDatabase.NextTransactionID(); + gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("DEP"),"Paychecks", + Fixed(1000),"Salary",NULL); + + id = gDatabase.NextTransactionID(); + Fixed f; + f.SetPremultiplied(5097); + gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", + f,"Misc",NULL); + f.SetPremultiplied(1234); + gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", + f,"Clothing",NULL); + f.SetPremultiplied(4321); + gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Stuff-Mart", + f,"Computer",NULL); + + id = gDatabase.NextTransactionID(); + f.SetPremultiplied(1934); + gDatabase.AddTransaction(0,id,real_time_clock(),TransactionType("ATM"),"Gas", + f,"Auto_Fuel",NULL); + gDatabase.RemoveTransaction(1); + + + entry.SetTo("/darkstar/Quicken Data/QIF/import.qif"); + entry_ref ref; + entry.GetRef(&ref); + ImportQIF(ref); + */ } -int main(void) -{ -// gDatabase.OpenFile("/boot/develop/projects/Capital Be/cbsql/testdb"); - +int +main(void) { + // gDatabase.OpenFile("/boot/develop/projects/Capital Be/cbsql/testdb"); + StartFile(); } #endif // end disabled test code diff --git a/src/App.h b/src/App.h index 0ff0c3c..84e77ff 100644 --- a/src/App.h +++ b/src/App.h @@ -6,9 +6,8 @@ #define M_QUIT_NOW 'qnow' -class App : public BApplication -{ -public: +class App : public BApplication { + public: App(void); ~App(void); void MessageReceived(BMessage *msg); diff --git a/src/AutoTextControl.cpp b/src/AutoTextControl.cpp index 0fa0f7f..2524033 100644 --- a/src/AutoTextControl.cpp +++ b/src/AutoTextControl.cpp @@ -4,219 +4,180 @@ Released under the MIT license. */ #include "AutoTextControl.h" -#include +#include #include -#include +#include #include -#include +#include static property_info sProperties[] = { - { "CharacterLimit", { B_GET_PROPERTY, 0 }, { B_DIRECT_SPECIFIER, 0 }, - "Returns the maximum number of characters that the AutoTextControl will allow.", - 0, { B_INT32_TYPE } - }, - - { "CharacterLimit", { B_SET_PROPERTY, 0 }, { B_DIRECT_SPECIFIER, 0}, - "Sets the maximum number of characters that the AutoTextControl will allow.", - 0, { B_INT32_TYPE } - }, + {"CharacterLimit", + {B_GET_PROPERTY, 0}, + {B_DIRECT_SPECIFIER, 0}, + "Returns the maximum number of characters that the AutoTextControl will allow.", + 0, + {B_INT32_TYPE}}, + + {"CharacterLimit", + {B_SET_PROPERTY, 0}, + {B_DIRECT_SPECIFIER, 0}, + "Sets the maximum number of characters that the AutoTextControl will allow.", + 0, + {B_INT32_TYPE}}, }; -AutoTextControl::AutoTextControl(const char *name, const char *label, const char *text, - BMessage *msg, uint32 flags) - : BTextControl(name,label,text,msg,flags), - fFilter(NULL), - fCharLimit(0) -{ +AutoTextControl::AutoTextControl( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : BTextControl(name, label, text, msg, flags), fFilter(NULL), fCharLimit(0) { SetFilter(new AutoTextControlFilter(this)); } -AutoTextControl::~AutoTextControl(void) -{ +AutoTextControl::~AutoTextControl(void) { if (Window()) Window()->RemoveCommonFilter(fFilter); delete fFilter; } - -AutoTextControl::AutoTextControl(BMessage *data) - : BTextControl(data) -{ - if (data->FindInt32("_charlimit",(int32*)&fCharLimit) != B_OK) +AutoTextControl::AutoTextControl(BMessage *data) : BTextControl(data) { + if (data->FindInt32("_charlimit", (int32 *)&fCharLimit) != B_OK) fCharLimit = 0; } - BArchivable * -AutoTextControl::Instantiate(BMessage *data) -{ +AutoTextControl::Instantiate(BMessage *data) { if (validate_instantiation(data, "AutoTextControl")) return new AutoTextControl(data); return NULL; } - status_t -AutoTextControl::Archive(BMessage *data, bool deep) const -{ - status_t status = BTextControl::Archive(data,deep); - +AutoTextControl::Archive(BMessage *data, bool deep) const { + status_t status = BTextControl::Archive(data, deep); + if (status == B_OK) - status = data->AddInt32("_charlimit",fCharLimit); - + status = data->AddInt32("_charlimit", fCharLimit); + if (status == B_OK) - status = data->AddString("class","AutoTextControl"); - + status = data->AddString("class", "AutoTextControl"); + return status; } - status_t -AutoTextControl::GetSupportedSuites(BMessage *msg) -{ - msg->AddString("suites","suite/vnd.DW-autotextcontrol"); - +AutoTextControl::GetSupportedSuites(BMessage *msg) { + msg->AddString("suites", "suite/vnd.DW-autotextcontrol"); + BPropertyInfo prop_info(sProperties); - msg->AddFlat("messages",&prop_info); + msg->AddFlat("messages", &prop_info); return BTextControl::GetSupportedSuites(msg); } - BHandler * -AutoTextControl::ResolveSpecifier(BMessage *msg, int32 index, BMessage *specifier, - int32 form, const char *property) -{ +AutoTextControl::ResolveSpecifier( + BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property +) { return BControl::ResolveSpecifier(msg, index, specifier, form, property); } - void -AutoTextControl::AttachedToWindow(void) -{ +AutoTextControl::AttachedToWindow(void) { BTextControl::AttachedToWindow(); - if (fFilter) - { + if (fFilter) { Window()->AddCommonFilter(fFilter); - fFilter->SetMessenger(new BMessenger(NULL,Window())); + fFilter->SetMessenger(new BMessenger(NULL, Window())); } } - void -AutoTextControl::DetachedFromWindow(void) -{ - if (fFilter) - { +AutoTextControl::DetachedFromWindow(void) { + if (fFilter) { fFilter->SetMessenger(NULL); Window()->RemoveCommonFilter(fFilter); } BTextControl::DetachedFromWindow(); } - void -AutoTextControl::SetCharacterLimit(const uint32 &limit) -{ +AutoTextControl::SetCharacterLimit(const uint32 &limit) { fCharLimit = limit; } - uint32 -AutoTextControl::GetCharacterLimit(const uint32 &limit) -{ +AutoTextControl::GetCharacterLimit(const uint32 &limit) { return fCharLimit; } - void -AutoTextControl::SetFilter(AutoTextControlFilter *filter) -{ +AutoTextControl::SetFilter(AutoTextControlFilter *filter) { if (fFilter) { if (Window()) Window()->RemoveCommonFilter(fFilter); delete fFilter; } - + fFilter = filter; if (Window()) Window()->AddCommonFilter(fFilter); } AutoTextControlFilter::AutoTextControlFilter(AutoTextControl *box) - : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE,B_KEY_DOWN), - fBox(box), - fCurrentMessage(NULL), - fMessenger(NULL) -{ -} - - -AutoTextControlFilter::~AutoTextControlFilter(void) -{ -} + : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fBox(box), + fCurrentMessage(NULL), fMessenger(NULL) {} +AutoTextControlFilter::~AutoTextControlFilter(void) {} filter_result -AutoTextControlFilter::Filter(BMessage *msg, BHandler **target) -{ - int32 rawchar,mod; - msg->FindInt32("raw_char",&rawchar); - msg->FindInt32("modifiers",&mod); - - BView *view = dynamic_cast(*target); - if (!view || strcmp("_input_",view->Name()) != 0) +AutoTextControlFilter::Filter(BMessage *msg, BHandler **target) { + int32 rawchar, mod; + msg->FindInt32("raw_char", &rawchar); + msg->FindInt32("modifiers", &mod); + + BView *view = dynamic_cast(*target); + if (!view || strcmp("_input_", view->Name()) != 0) return B_DISPATCH_MESSAGE; - - AutoTextControl *text = dynamic_cast(view->Parent()); + + AutoTextControl *text = dynamic_cast(view->Parent()); if (!text || text != fBox) return B_DISPATCH_MESSAGE; - + fCurrentMessage = msg; - filter_result result = KeyFilter(rawchar,mod); + filter_result result = KeyFilter(rawchar, mod); fCurrentMessage = NULL; - + if (fBox->fCharLimit && result == B_DISPATCH_MESSAGE) { // See to it that we still allow shortcut keys if (mod & B_COMMAND_KEY) return B_DISPATCH_MESSAGE; - + // We don't use strlen() because it is not UTF-8 aware, which can affect // how many characters can be typed. - if (isprint(rawchar) && - (uint32)BString(text->Text()).CountChars() == text->fCharLimit) + if (isprint(rawchar) && (uint32)BString(text->Text()).CountChars() == text->fCharLimit) return B_SKIP_MESSAGE; } - + return result; } - filter_result -AutoTextControlFilter::KeyFilter(const int32 &rawchar, const int32 &mod) -{ +AutoTextControlFilter::KeyFilter(const int32 &rawchar, const int32 &mod) { if (fBox) fBox->Invoke(); - + return B_DISPATCH_MESSAGE; } - void -AutoTextControlFilter::SendMessage(BMessage *msg) -{ +AutoTextControlFilter::SendMessage(BMessage *msg) { if (fMessenger && msg) fMessenger->SendMessage(msg); } - void -AutoTextControlFilter::SetMessenger(BMessenger *msgr) -{ +AutoTextControlFilter::SetMessenger(BMessenger *msgr) { if (fMessenger) delete fMessenger; fMessenger = msgr; } - - diff --git a/src/AutoTextControl.h b/src/AutoTextControl.h index 12e6eb0..3dd4d61 100644 --- a/src/AutoTextControl.h +++ b/src/AutoTextControl.h @@ -6,79 +6,82 @@ #ifndef AUTO_TEXT_CONTROL_H #define AUTO_TEXT_CONTROL_H -#include #include +#include class AutoTextControlFilter; /* The AutoTextControl provides realtime updates to any changes made to it. - It also provides the ability to limit the text to a certain number of + It also provides the ability to limit the text to a certain number of characters. - + If, for some reason, you want to disable the updates-per-keypress, pass a regular BMessageFilter to the SetFilter method. */ -class AutoTextControl : public BTextControl -{ -public: - AutoTextControl(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); - - AutoTextControl(BMessage *data); - static BArchivable * Instantiate(BMessage *data); - virtual status_t Archive(BMessage *data, bool deep = true) const; - - virtual status_t GetSupportedSuites(BMessage *msg); - virtual BHandler * ResolveSpecifier(BMessage *msg, int32 index, - BMessage *specifier, int32 form, - const char *property); - - virtual ~AutoTextControl(void); - - virtual void AttachedToWindow(void); - virtual void DetachedFromWindow(void); - - void SetFilter(AutoTextControlFilter *filter); - AutoTextControlFilter * GetFilter(void) { return fFilter; } - - void SetCharacterLimit(const uint32 &limit); - uint32 GetCharacterLimit(const uint32 &limit); - -private: +class AutoTextControl : public BTextControl { + public: + AutoTextControl( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); + + AutoTextControl(BMessage *data); + static BArchivable *Instantiate(BMessage *data); + virtual status_t Archive(BMessage *data, bool deep = true) const; + + virtual status_t GetSupportedSuites(BMessage *msg); + virtual BHandler *ResolveSpecifier( + BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property + ); + + virtual ~AutoTextControl(void); + + virtual void AttachedToWindow(void); + virtual void DetachedFromWindow(void); + + void SetFilter(AutoTextControlFilter *filter); + + AutoTextControlFilter *GetFilter(void) { return fFilter; } + + void SetCharacterLimit(const uint32 &limit); + uint32 GetCharacterLimit(const uint32 &limit); + + private: friend class AutoTextControlFilter; - - AutoTextControlFilter *fFilter; - uint32 fCharLimit; + + AutoTextControlFilter *fFilter; + uint32 fCharLimit; }; /* This class does all of the heavy lifting for AutoTextControl's realtime updates. - - You can further customize input and updates by subclassing the + + You can further customize input and updates by subclassing the KeyFilter hook function. When doing so, the current key message can be accessed by way of GetCurrentMessage(). However, it will return NULL when called from any other method. */ -class AutoTextControlFilter : public BMessageFilter -{ -public: - AutoTextControlFilter(AutoTextControl *checkview); - ~AutoTextControlFilter(void); - virtual filter_result Filter(BMessage *msg, BHandler **target); - virtual filter_result KeyFilter(const int32 &key, const int32 &mod); - - AutoTextControl * TextControl(void) const { return fBox; } - BMessage * GetCurrentMessage(void) { return fCurrentMessage; } - void SendMessage(BMessage *msg); - void SetMessenger(BMessenger *msgr); -private: - AutoTextControl *fBox; - BMessage *fCurrentMessage; - BMessenger *fMessenger; +class AutoTextControlFilter : public BMessageFilter { + public: + AutoTextControlFilter(AutoTextControl *checkview); + ~AutoTextControlFilter(void); + virtual filter_result Filter(BMessage *msg, BHandler **target); + virtual filter_result KeyFilter(const int32 &key, const int32 &mod); + + AutoTextControl *TextControl(void) const { return fBox; } + + BMessage *GetCurrentMessage(void) { return fCurrentMessage; } + + void SendMessage(BMessage *msg); + void SetMessenger(BMessenger *msgr); + + private: + AutoTextControl *fBox; + BMessage *fCurrentMessage; + BMessenger *fMessenger; }; #endif diff --git a/src/Budget.cpp b/src/Budget.cpp index f6806d0..3d73598 100644 --- a/src/Budget.cpp +++ b/src/Budget.cpp @@ -1,89 +1,74 @@ #include "Budget.h" #include "Translate.h" -BudgetEntry::BudgetEntry(void) -{ - Set("",0,BUDGET_MONTHLY,true); -} +BudgetEntry::BudgetEntry(void) { Set("", 0, BUDGET_MONTHLY, true); } -BudgetEntry::BudgetEntry(const char *nm, const Fixed &amt, const BudgetPeriod &per, - const bool &isexp) -{ - Set(nm,amt,per,isexp); +BudgetEntry::BudgetEntry( + const char *nm, const Fixed &amt, const BudgetPeriod &per, const bool &isexp +) { + Set(nm, amt, per, isexp); } -BudgetEntry::BudgetEntry(const BudgetEntry &from) -{ - Set(from.name.String(),from.amount,from.period,from.isexpense); +BudgetEntry::BudgetEntry(const BudgetEntry &from) { + Set(from.name.String(), from.amount, from.period, from.isexpense); } -BudgetEntry &BudgetEntry::operator=(const BudgetEntry &from) -{ - Set(from.name.String(),from.amount,from.period,from.isexpense); +BudgetEntry & +BudgetEntry::operator=(const BudgetEntry &from) { + Set(from.name.String(), from.amount, from.period, from.isexpense); return *this; } -void BudgetEntry::Set(const char *nm, const Fixed &amt, const BudgetPeriod &per, - const bool &isexp) -{ +void +BudgetEntry::Set(const char *nm, const Fixed &amt, const BudgetPeriod &per, const bool &isexp) { name = nm; amount = amt; period = per; isexpense = isexp; } -BString BudgetPeriodToString(const BudgetPeriod &period) -{ - switch(period) - { - case BUDGET_MONTHLY: - { - return BString(TRANSLATE("Monthly")); - break; - } - case BUDGET_WEEKLY: - { - return BString(TRANSLATE("Weekly")); - break; - } - case BUDGET_QUARTERLY: - { - return BString(TRANSLATE("Quarterly")); - break; - } - case BUDGET_ANNUALLY: - { - return BString(TRANSLATE("Annually")); - break; - } - default: - { - return BString(TRANSLATE("Unknown")); - break; - } +BString +BudgetPeriodToString(const BudgetPeriod &period) { + switch (period) { + case BUDGET_MONTHLY: { + return BString(TRANSLATE("Monthly")); + break; + } + case BUDGET_WEEKLY: { + return BString(TRANSLATE("Weekly")); + break; + } + case BUDGET_QUARTERLY: { + return BString(TRANSLATE("Quarterly")); + break; + } + case BUDGET_ANNUALLY: { + return BString(TRANSLATE("Annually")); + break; + } + default: { + return BString(TRANSLATE("Unknown")); + break; + } } } -BudgetPeriod StringToBudgetPeriod(const char *string) -{ +BudgetPeriod +StringToBudgetPeriod(const char *string) { // TODO: Does this need translated? BString str(string); - if(str.CountChars()<1) + if (str.CountChars() < 1) return BUDGET_UNKNOWN; - - if(str.ICompare("monthly")==0) + + if (str.ICompare("monthly") == 0) return BUDGET_MONTHLY; - else - if(str.ICompare("weekly")==0) + else if (str.ICompare("weekly") == 0) return BUDGET_WEEKLY; - else - if(str.ICompare("quarterly")==0) + else if (str.ICompare("quarterly") == 0) return BUDGET_QUARTERLY; - else - if(str.ICompare("annually")==0) + else if (str.ICompare("annually") == 0) return BUDGET_ANNUALLY; - else - if(str.ICompare("yearly")==0) + else if (str.ICompare("yearly") == 0) return BUDGET_ANNUALLY; return BUDGET_UNKNOWN; diff --git a/src/Budget.h b/src/Budget.h index 9648779..e76102b 100644 --- a/src/Budget.h +++ b/src/Budget.h @@ -5,27 +5,26 @@ #include // This is ordered from smallest interval to largest for a reason. :^) -// Note that if this is changed, you need to also change the SUBTOTAL_ enum in +// Note that if this is changed, you need to also change the SUBTOTAL_ enum in // ReportWindow.h. The BudgetReport code depends on them having the same values -typedef enum -{ - BUDGET_WEEKLY=0, +typedef enum { + BUDGET_WEEKLY = 0, BUDGET_MONTHLY, BUDGET_QUARTERLY, BUDGET_ANNUALLY, BUDGET_UNKNOWN } BudgetPeriod; -class BudgetEntry -{ -public: +class BudgetEntry { + public: BudgetEntry(void); - BudgetEntry(const char *name, const Fixed &amount, const BudgetPeriod &period, - const bool &isexpense); + BudgetEntry( + const char *name, const Fixed &amount, const BudgetPeriod &period, const bool &isexpense + ); BudgetEntry(const BudgetEntry &from); BudgetEntry &operator=(const BudgetEntry &from); - void Set(const char *name, const Fixed &amount, const BudgetPeriod &period, - const bool &isexpense); + void + Set(const char *name, const Fixed &amount, const BudgetPeriod &period, const bool &isexpense); BString name; Fixed amount; @@ -33,7 +32,9 @@ class BudgetEntry bool isexpense; }; -BString BudgetPeriodToString(const BudgetPeriod &period); -BudgetPeriod StringToBudgetPeriod(const char *string); +BString +BudgetPeriodToString(const BudgetPeriod &period); +BudgetPeriod +StringToBudgetPeriod(const char *string); #endif diff --git a/src/BudgetReport.cpp b/src/BudgetReport.cpp index f21e801..12db825 100644 --- a/src/BudgetReport.cpp +++ b/src/BudgetReport.cpp @@ -1,285 +1,265 @@ -#include "ReportWindow.h" #include "Account.h" +#include "Budget.h" #include "CBLocale.h" -#include "Database.h" -#include "ReportGrid.h" #include "ColumnListView.h" #include "ColumnTypes.h" +#include "Database.h" +#include "ReportGrid.h" +#include "ReportWindow.h" #include "TimeSupport.h" -#include "Budget.h" /* Status: Different tack on the same task - go one row at a time by querying once for all transactions in the category within the time range and iterating over the row. Right now, it only acts on the first category in the list (easy to mod to - work on all of 'em) and the logic doesn't work right. No subtotaling results + work on all of 'em) and the logic doesn't work right. No subtotaling results in proper display, but going to monthly displays absolutely nothing - + There also seems to be some bugs in the BudgetWindow editor code -- are the items in the budget defaulting to a Weekly period? */ -typedef enum -{ - MAP_UNCHANGED = 0, - MAP_CHANGED = 1, - MAP_BAD_VALUE = -1 -} map_status; +typedef enum { MAP_UNCHANGED = 0, MAP_CHANGED = 1, MAP_BAD_VALUE = -1 } map_status; + +map_status +MapBudgetToSubtotal( + Fixed &fixed, const int &budgetperiod, const int &subtotal, const time_t &start, + const time_t &end +); -map_status MapBudgetToSubtotal(Fixed &fixed, const int &budgetperiod, const int &subtotal, - const time_t &start, const time_t &end); +void +ReportWindow::ComputeBudget(void) { + BObjectList timelist(20, true); -void ReportWindow::ComputeBudget(void) -{ - BObjectList timelist(20,true); - // Calculate the number of columns and the starting date for each one - if(fSubtotalMode == SUBTOTAL_NONE) - { + if (fSubtotalMode == SUBTOTAL_NONE) { timelist.AddItem(new time_t(fStartDate)); timelist.AddItem(new time_t(fEndDate)); - } - else - { - for (time_t t = fStartDate; t < fEndDate; ) - { - time_t *item = new time_t(t); + } else { + for (time_t t = fStartDate; t < fEndDate;) { + time_t *item = new time_t(t); timelist.AddItem(item); - - switch (fSubtotalMode) - { - case SUBTOTAL_MONTH: - { - t = IncrementDateByMonth(t); - break; - } - case SUBTOTAL_QUARTER: - { - t = IncrementDateByQuarter(t); - break; - } - case SUBTOTAL_YEAR: - { - t = IncrementDateByYear(t); - break; - } - default: - { - t = fEndDate; - break; - } + + switch (fSubtotalMode) { + case SUBTOTAL_MONTH: { + t = IncrementDateByMonth(t); + break; + } + case SUBTOTAL_QUARTER: { + t = IncrementDateByQuarter(t); + break; + } + case SUBTOTAL_YEAR: { + t = IncrementDateByYear(t); + break; + } + default: { + t = fEndDate; + break; + } } } timelist.AddItem(new time_t(fEndDate)); } - + // Here's where all the *real* work begins. For each category in the selected // accounts, we need to get the budget amount, the actual amount, and the difference // for each time period. - - // The real kicker is that the subtotal period may not necessarily fit the + + // The real kicker is that the subtotal period may not necessarily fit the // budget period. A category budgeted in quarterly periods should not be arbitrarily // divided up by 3 for a monthly display -- it should be displayed only at the // beginning of each quarter. Yuck. int32 count = timelist.CountItems() - 1; - + // Just in case I missed it somewhere else. Otherwise, this will crash rather // spectacularly. // "Where's the kaboom? There's supposed to be an earth-shattering kaboom!" if (count < 1) return; - + // Add all the columns that we'll need for the report - + // The rest of the array will be initialized in the column-adding loop float maxwidths[count + 1]; maxwidths[0] = be_plain_font->StringWidth("Category") + 20; - fGridView->AddColumn(new BStringColumn("Category",maxwidths[0],10,300,B_TRUNCATE_END),0); - + fGridView->AddColumn(new BStringColumn("Category", maxwidths[0], 10, 300, B_TRUNCATE_END), 0); + int32 i; - for(i = 0; i < timelist.CountItems() - 1; i++) - { + for (i = 0; i < timelist.CountItems() - 1; i++) { char columntitle[128]; - struct tm *timestruct = localtime((time_t*)timelist.ItemAt(i)); - + struct tm *timestruct = localtime((time_t *)timelist.ItemAt(i)); + BString formatstring; - switch(fSubtotalMode) - { - case SUBTOTAL_MONTH: - { - strftime(columntitle,128,"%b %Y",timestruct); - break; - } - case SUBTOTAL_QUARTER: - { - char year[10]; - int quarternumber = ((timestruct->tm_mon + 2) / 3)+1; - strftime(year,10,"%Y",timestruct); - sprintf(columntitle, "Q%d %s", quarternumber, year); - break; - } - case SUBTOTAL_YEAR: - { - strftime(columntitle,128,"%Y",timestruct); - break; - } - default: - { - sprintf(columntitle,TRANSLATE("Amount")); - break; - } + switch (fSubtotalMode) { + case SUBTOTAL_MONTH: { + strftime(columntitle, 128, "%b %Y", timestruct); + break; + } + case SUBTOTAL_QUARTER: { + char year[10]; + int quarternumber = ((timestruct->tm_mon + 2) / 3) + 1; + strftime(year, 10, "%Y", timestruct); + sprintf(columntitle, "Q%d %s", quarternumber, year); + break; + } + case SUBTOTAL_YEAR: { + strftime(columntitle, 128, "%Y", timestruct); + break; + } + default: { + sprintf(columntitle, TRANSLATE("Amount")); + break; + } } maxwidths[i + 1] = be_plain_font->StringWidth(columntitle) + 20; - fGridView->AddColumn(new BStringColumn(columntitle,maxwidths[i + 1], - 10,300,B_TRUNCATE_END),i + 1); + fGridView->AddColumn( + new BStringColumn(columntitle, maxwidths[i + 1], 10, 300, B_TRUNCATE_END), i + 1 + ); } - + // Later this will iterate over all items in the category list - BStringItem *stringitem = (BStringItem*)fCategoryList->ItemAt(0); - if (!stringitem) - { + BStringItem *stringitem = (BStringItem *)fCategoryList->ItemAt(0); + if (!stringitem) { ShowBug("NULL category BStringItem in ReportWindow::ComputeBudget"); return; } - + BudgetEntry budgetentry; - + // Remove this line when moving to code which loops over all categories - gDatabase.GetBudgetEntry(stringitem->Text(),budgetentry); - + gDatabase.GetBudgetEntry(stringitem->Text(), budgetentry); + // TODO: Operate only on selected categories which are in the budget. For now, // only fight with the first entry -// if( !stringitem->IsSelected() || -// !gDatabase.GetBudgetEntry(stringitem->Text(),budgetentry) ) -// continue; - - + // if( !stringitem->IsSelected() || + // !gDatabase.GetBudgetEntry(stringitem->Text(),budgetentry) ) + // continue; + + // Spacer row under title headings fGridView->AddRow(new BRow()); - + // Construct and execute the query which finds all expense in the selected // category BString command; BString escaped = EscapeIllegalCharacters(stringitem->Text()); int32 accountcount = 0; - for(i = 0; i < fAccountList->CountItems(); i++) - { - AccountItem *item = (AccountItem*)fAccountList->ItemAt(i); - if(!item || !item->IsSelected()) + for (i = 0; i < fAccountList->CountItems(); i++) { + AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + if (!item || !item->IsSelected()) continue; - - if(accountcount > 0) + + if (accountcount > 0) command << " union all "; - + command << "select date,amount from account_"; command << item->account->GetID() << " where category = '" << escaped - << "' and date >= " << fStartDate - << " and date < " << fEndDate; - + << "' and date >= " << fStartDate << " and date < " << fEndDate; + accountcount++; } command << " order by date;"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"ComputeBudget::Get amounts"); -//printf("%s\n",command.String()); + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "ComputeBudget::Get amounts"); + // printf("%s\n",command.String()); if (query.eof()) return; - + BRow *budrow = new BRow(); fGridView->AddRow(budrow); - budrow->SetField(new BStringField(stringitem->Text()),0); - + budrow->SetField(new BStringField(stringitem->Text()), 0); + BRow *amtrow = new BRow(); fGridView->AddRow(amtrow); - amtrow->SetField(new BStringField(""),0); - + amtrow->SetField(new BStringField(""), 0); + BRow *diffrow = new BRow(); fGridView->AddRow(diffrow); - diffrow->SetField(new BStringField(""),0); - + diffrow->SetField(new BStringField(""), 0); + float stringwidth = be_plain_font->StringWidth(stringitem->Text()) + 20; if (maxwidths[0] < stringwidth) maxwidths[0] = stringwidth; - + // This flag is for getting the next value from the row only when we don't // already have a value bool have_row = false; time_t transdate = 0; Fixed transamount; Fixed transtotal; - + // This loop places values for a row into corresponding places in each grid - for(int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) - { - time_t subtotal_start = *((time_t*)timelist.ItemAt(subtotal_index)); - time_t subtotal_end = *((time_t*)timelist.ItemAt(subtotal_index+1)); - + for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { + time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + Fixed budamount = budgetentry.amount; - map_status mapstatus = MapBudgetToSubtotal(budamount, budgetentry.period, fSubtotalMode, - subtotal_start, subtotal_end); - + map_status mapstatus = MapBudgetToSubtotal( + budamount, budgetentry.period, fSubtotalMode, subtotal_start, subtotal_end + ); + if (mapstatus == MAP_UNCHANGED) continue; - else - if (mapstatus == MAP_BAD_VALUE) - { + else if (mapstatus == MAP_BAD_VALUE) { ShowBug("Passed bad value to ReportWindow::BudgetReport:MapBudgetToSubtotal"); return; } - - if (!have_row) - { + + if (!have_row) { transdate = query.getInt64Field(0); transamount.SetPremultiplied(query.getInt64Field(1)); have_row = true; } - + if (transdate < subtotal_start) continue; - - while (transdate < subtotal_end) - { + + while (transdate < subtotal_end) { transtotal += transamount; - + query.nextRow(); - + if (query.eof()) break; - + transdate = query.getInt64Field(0); transamount.SetPremultiplied(query.getInt64Field(1)); } - - printf("Actual vs Budget for %s: (%ld,%ld)\n",stringitem->Text(), - transtotal.AsLong(), - budamount.AsLong()); + + printf( + "Actual vs Budget for %s: (%ld,%ld)\n", stringitem->Text(), transtotal.AsLong(), + budamount.AsLong() + ); BString string; BStringField *field; - + string << budamount.AbsoluteValue().AsFloat(); field = new BStringField(string.String()); - budrow->SetField(field,i); - + budrow->SetField(field, i); + string = ""; string << transtotal.AbsoluteValue().AsFloat(); field = new BStringField(string.String()); - amtrow->SetField(field,i); - + amtrow->SetField(field, i); + transamount = budamount.AbsoluteValue() - transtotal.AbsoluteValue(); - + string = ""; string << transamount.AsFloat(); field = new BStringField(string.String()); - diffrow->SetField(field,i); - + diffrow->SetField(field, i); + } // end for-each-subtotal-period row loop query.finalize(); fGridView->AddRow(new BRow()); } -map_status MapBudgetToSubtotal(Fixed &fixed, const int &budgetperiod, const int &subtotal, - const time_t &start, const time_t &end) -{ +map_status +MapBudgetToSubtotal( + Fixed &fixed, const int &budgetperiod, const int &subtotal, const time_t &start, + const time_t &end +) { // Converts a Fixed value into the proper period. When the value is actually // converted (Subtotal-Monthly + Budget-Weekly, etc.), MAP_CHANGED is returned and // the actual value is found in the Fixed parameter originally passed to it. @@ -288,173 +268,144 @@ map_status MapBudgetToSubtotal(Fixed &fixed, const int &budgetperiod, const int // developer stupidity errors -- unsupported subtotal and budget periods. // This is currently unsupported - if(subtotal == SUBTOTAL_WEEK) - { + if (subtotal == SUBTOTAL_WEEK) { ShowBug("Weekly Subtotal period in MapBudgetToSubtotal"); return MAP_BAD_VALUE; } - + struct tm timestruct = *localtime(&start); - - switch(budgetperiod) - { - case BUDGET_WEEKLY: - { - switch(subtotal) - { - case SUBTOTAL_MONTH: - { - // Budget = $/Week, Report = Monthly - fixed *= 4; - break; - } - case SUBTOTAL_QUARTER: - { - // Budget = $/Week, Report = Quarterly - // We use the average # of weeks in a quarter for this: 13. - fixed *= 13; - break; - } - case SUBTOTAL_YEAR: - { - // Budget = $/Week, Report = Yearly - fixed *= 52; - break; - } - case SUBTOTAL_NONE: - { - // Budget = $/Week, Report = Whatever - time_t span = end - start; - span /= SECONDS_PER_WEEK; - fixed *= span; - return MAP_CHANGED; - } - default: - { - return MAP_BAD_VALUE; - } - } + + switch (budgetperiod) { + case BUDGET_WEEKLY: { + switch (subtotal) { + case SUBTOTAL_MONTH: { + // Budget = $/Week, Report = Monthly + fixed *= 4; break; } - case BUDGET_MONTHLY: - { - switch(subtotal) - { - case SUBTOTAL_MONTH: - { - // Budget = $/Month, Report = Monthly - // We do nothing because we want the monthly amount (which is - // what we were given) in the amount box. - break; - } - case SUBTOTAL_QUARTER: - { - // Budget = $/Month, Report = Quarterly - fixed *= 4; - break; - } - case SUBTOTAL_YEAR: - { - // Budget = $/Month, Report = Quarterly - fixed *= 12; - break; - } - case SUBTOTAL_NONE: - { - // Budget = $/Month, Report = Whatever - // basing calculations on a 30-day should work well enough - // for our purposes - time_t span = end - start; - span /= SECONDS_PER_DAY * 30; - fixed *= (span < 1) ? 1 : span; - break; - } - default: - { - return MAP_BAD_VALUE; - } - } + case SUBTOTAL_QUARTER: { + // Budget = $/Week, Report = Quarterly + // We use the average # of weeks in a quarter for this: 13. + fixed *= 13; break; } - case BUDGET_QUARTERLY: - { - switch(subtotal) - { - case SUBTOTAL_MONTH: - { - // Budget = $/Quarter, Report = Monthly - // If it's not the beginning of the quarter, return MAP_UNCHANGED - // so that the caller knows to skip this box in the grid - if (GetQuarterMonthForDate(start) != timestruct.tm_mon + 1) - return MAP_UNCHANGED; - - // Note that we don't do anything if it's the beginning of the - // quarter -- we *want* to return the budget amount in the box - // for the beginning of the quarter - break; - } - case SUBTOTAL_QUARTER: - { - // Budget = $/Quarter, Report = Quarterly - break; - } - case SUBTOTAL_YEAR: - { - // Budget = $/Quarter, Report = Yearly - fixed *= 4; - break; - } - case SUBTOTAL_NONE: - { - // Budget = $/Quarter, Report = Whatever - // Q1 is 90 days, Q2 is 91, Q3 is 92, Q4 is 91, so we will - // go with the average: 91 - time_t span = end - start; - span /= SECONDS_PER_DAY * 91; - fixed *= (span < 1) ? 1 : span; - break; - } - default: - { - return MAP_BAD_VALUE; - } - } + case SUBTOTAL_YEAR: { + // Budget = $/Week, Report = Yearly + fixed *= 52; break; } - case BUDGET_ANNUALLY: - { - switch(subtotal) - { - case SUBTOTAL_MONTH: - case SUBTOTAL_QUARTER: - { - // Budget = $/Year, Report = Monthly, Quarterly - // On yearly basis for a budget item, we only show the - // amount in January - if (timestruct.tm_mon != 0) - return MAP_UNCHANGED; - break; - } - case SUBTOTAL_YEAR: - { - break; - } - case SUBTOTAL_NONE: - { - time_t span = end - start; - span /= SECONDS_PER_YEAR; - fixed *= (span < 1) ? 1 : span; - break; - } - default: - { - return MAP_BAD_VALUE; - } - } + case SUBTOTAL_NONE: { + // Budget = $/Week, Report = Whatever + time_t span = end - start; + span /= SECONDS_PER_WEEK; + fixed *= span; + return MAP_CHANGED; + } + default: { + return MAP_BAD_VALUE; + } + } + break; + } + case BUDGET_MONTHLY: { + switch (subtotal) { + case SUBTOTAL_MONTH: { + // Budget = $/Month, Report = Monthly + // We do nothing because we want the monthly amount (which is + // what we were given) in the amount box. + break; + } + case SUBTOTAL_QUARTER: { + // Budget = $/Month, Report = Quarterly + fixed *= 4; + break; + } + case SUBTOTAL_YEAR: { + // Budget = $/Month, Report = Quarterly + fixed *= 12; break; } - default: + case SUBTOTAL_NONE: { + // Budget = $/Month, Report = Whatever + // basing calculations on a 30-day should work well enough + // for our purposes + time_t span = end - start; + span /= SECONDS_PER_DAY * 30; + fixed *= (span < 1) ? 1 : span; + break; + } + default: { + return MAP_BAD_VALUE; + } + } + break; + } + case BUDGET_QUARTERLY: { + switch (subtotal) { + case SUBTOTAL_MONTH: { + // Budget = $/Quarter, Report = Monthly + // If it's not the beginning of the quarter, return MAP_UNCHANGED + // so that the caller knows to skip this box in the grid + if (GetQuarterMonthForDate(start) != timestruct.tm_mon + 1) + return MAP_UNCHANGED; + + // Note that we don't do anything if it's the beginning of the + // quarter -- we *want* to return the budget amount in the box + // for the beginning of the quarter + break; + } + case SUBTOTAL_QUARTER: { + // Budget = $/Quarter, Report = Quarterly + break; + } + case SUBTOTAL_YEAR: { + // Budget = $/Quarter, Report = Yearly + fixed *= 4; + break; + } + case SUBTOTAL_NONE: { + // Budget = $/Quarter, Report = Whatever + // Q1 is 90 days, Q2 is 91, Q3 is 92, Q4 is 91, so we will + // go with the average: 91 + time_t span = end - start; + span /= SECONDS_PER_DAY * 91; + fixed *= (span < 1) ? 1 : span; + break; + } + default: { return MAP_BAD_VALUE; + } + } + break; + } + case BUDGET_ANNUALLY: { + switch (subtotal) { + case SUBTOTAL_MONTH: + case SUBTOTAL_QUARTER: { + // Budget = $/Year, Report = Monthly, Quarterly + // On yearly basis for a budget item, we only show the + // amount in January + if (timestruct.tm_mon != 0) + return MAP_UNCHANGED; + break; + } + case SUBTOTAL_YEAR: { + break; + } + case SUBTOTAL_NONE: { + time_t span = end - start; + span /= SECONDS_PER_YEAR; + fixed *= (span < 1) ? 1 : span; + break; + } + default: { + return MAP_BAD_VALUE; + } + } + break; + } + default: + return MAP_BAD_VALUE; } return MAP_CHANGED; } diff --git a/src/BudgetWindow.cpp b/src/BudgetWindow.cpp index 342f659..08b7cc7 100644 --- a/src/BudgetWindow.cpp +++ b/src/BudgetWindow.cpp @@ -1,15 +1,15 @@ #include "BudgetWindow.h" +#include "ColumnTypes.h" #include #include #include #include -#include "ColumnTypes.h" #include "Account.h" +#include "Budget.h" #include "CurrencyBox.h" #include "DStringList.h" -#include "Budget.h" #include "Database.h" #include "HelpButton.h" #include "MsgDefs.h" @@ -17,9 +17,8 @@ #include "TimeSupport.h" #include "Translate.h" -enum -{ - M_CATEGORIES_CHANGED='mccc', +enum { + M_CATEGORIES_CHANGED = 'mccc', M_BUDGET_CATEGORIES, M_BUDGET_RECALCULATE, @@ -34,23 +33,22 @@ enum M_SELECT_CATEGORY }; -extern int compare_stringitem(const void *item1, const void *item2); +extern int +compare_stringitem(const void *item1, const void *item2); BudgetWindow::BudgetWindow(const BRect &frame) - : BWindow(frame,TRANSLATE("Budget"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), - fIncomeGrid(13,0), - fSpendingGrid(13,0) -{ - fBackView = new BView("background",B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f) - .SetInsets(0) - .Add(fBackView) - .End(); - fBackView->SetViewColor(240,240,240); + : BWindow( + frame, TRANSLATE("Budget"), B_DOCUMENT_WINDOW, + B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ), + fIncomeGrid(13, 0), fSpendingGrid(13, 0) { + fBackView = new BView("background", B_WILL_DRAW); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f).SetInsets(0).Add(fBackView).End(); + fBackView->SetViewColor(240, 240, 240); fBar = new BMenuBar("menubar"); - fBar->AddItem(new BMenuItem(TRANSLATE("Recalculate All"),new BMessage(M_BUDGET_RECALCULATE))); - fBar->AddItem(new BMenuItem(TRANSLATE("Set All to Zero"),new BMessage(M_BUDGET_ZERO))); + fBar->AddItem(new BMenuItem(TRANSLATE("Recalculate All"), new BMessage(M_BUDGET_RECALCULATE))); + fBar->AddItem(new BMenuItem(TRANSLATE("Set All to Zero"), new BMessage(M_BUDGET_ZERO))); BuildBudgetSummary(); BuildStatsAndEditor(); @@ -62,224 +60,206 @@ BudgetWindow::BudgetWindow(const BRect &frame) .Add(fAmountLabel) .Add(fAmountBox) .AddGrid(B_USE_DEFAULT_SPACING, 1.0f) - .Add(fMonthly, 0, 0) - .Add(fWeekly, 1, 0) - .Add(fQuarterly, 0, 1) - .Add(fAnnually, 1, 1) - .End() - .End(); + .Add(fMonthly, 0, 0) + .Add(fWeekly, 1, 0) + .Add(fQuarterly, 0, 1) + .Add(fAnnually, 1, 1) + .End() + .End(); fAmountBox->SetText(""); fAmountBox->GetFilter()->SetMessenger(new BMessenger(this)); - if(gDatabase.CountBudgetEntries()==0) + if (gDatabase.CountBudgetEntries() == 0) GenerateBudget(false); RefreshBudgetGrid(); RefreshCategories(); RefreshBudgetSummary(); fCategoryList->MakeFocus(true); - + BLayoutBuilder::Group<>(fBackView, B_VERTICAL, 0.0f) .SetInsets(0) .Add(fBar) .AddGroup(B_VERTICAL) - .SetInsets(10, 10, 10, 10) - .AddGroup(B_HORIZONTAL) - .Add(fCategoryList) - .AddGroup(B_VERTICAL) - .Add(fCatBox) - .Add(fCatStat) - .End() - .End() - .Add(fBudgetSummary) + .SetInsets(10, 10, 10, 10) + .AddGroup(B_HORIZONTAL) + .Add(fCategoryList) + .AddGroup(B_VERTICAL) + .Add(fCatBox) + .Add(fCatStat) + .End() .End() - .End(); + .Add(fBudgetSummary) + .End() + .End(); } -BudgetWindow::~BudgetWindow(void) -{ -} +BudgetWindow::~BudgetWindow(void) {} -void BudgetWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_SELECT_CATEGORY: - { - HandleCategorySelection(); - fAmountBox->MakeFocus(true); - break; - } - case M_AMOUNT_CHANGED: - { - BString str(fAmountBox->Text()); - if(str.CountChars()<1) - str = "0"; - - Fixed f; - if(gDefaultLocale.StringToCurrency(str.String(),f)!=B_OK) - break; - f.Round(); - gDefaultLocale.CurrencyToString(f,str); - str.Truncate(str.FindFirst(gDefaultLocale.CurrencyDecimal())); - str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - - BRow *row = fCategoryList->CurrentSelection(); - if(!row) - break; - - row->SetField(new BStringField(str.String()),1); - fCategoryList->UpdateRow(row); - - BudgetEntry entry; - gDatabase.GetBudgetEntry( ((BStringField*)row->GetField(0))->String(),entry ); - entry.amount = f; - if(entry.isexpense) - entry.amount.Invert(); - gDatabase.AddBudgetEntry(entry); - - RefreshBudgetGrid(); - RefreshBudgetSummary(); - - fBudgetSummary->SetFocusRow( entry.isexpense ? 1 : 0); - fBudgetSummary->SetFocusRow(2); - break; - } - case M_BUDGET_RECALCULATE: - { - GenerateBudget(false); - RefreshBudgetGrid(); - RefreshBudgetSummary(); - RefreshCategories(); - break; - } - case M_BUDGET_ZERO: - { - GenerateBudget(true); - RefreshBudgetGrid(); - RefreshBudgetSummary(); - RefreshCategories(); - break; - } - case M_SET_PERIOD_MONTH: - { - SetPeriod(BUDGET_MONTHLY); - break; - } - case M_SET_PERIOD_WEEK: - { - SetPeriod(BUDGET_WEEKLY); - break; - } - case M_SET_PERIOD_QUARTER: - { - SetPeriod(BUDGET_QUARTERLY); - break; - } - case M_SET_PERIOD_YEAR: - { - SetPeriod(BUDGET_ANNUALLY); - break; - } - case M_NEXT_FIELD: - { - if(fAmountBox->ChildAt(0)->IsFocus()) - fMonthly->MakeFocus(true); +void +BudgetWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_SELECT_CATEGORY: { + HandleCategorySelection(); + fAmountBox->MakeFocus(true); + break; + } + case M_AMOUNT_CHANGED: { + BString str(fAmountBox->Text()); + if (str.CountChars() < 1) + str = "0"; + + Fixed f; + if (gDefaultLocale.StringToCurrency(str.String(), f) != B_OK) break; - } - case M_PREVIOUS_FIELD: - { - if(fAmountBox->ChildAt(0)->IsFocus()) - fCategoryList->MakeFocus(true); + f.Round(); + gDefaultLocale.CurrencyToString(f, str); + str.Truncate(str.FindFirst(gDefaultLocale.CurrencyDecimal())); + str.RemoveFirst(gDefaultLocale.CurrencySymbol()); + + BRow *row = fCategoryList->CurrentSelection(); + if (!row) break; - } - default: - BWindow::MessageReceived(msg); + + row->SetField(new BStringField(str.String()), 1); + fCategoryList->UpdateRow(row); + + BudgetEntry entry; + gDatabase.GetBudgetEntry(((BStringField *)row->GetField(0))->String(), entry); + entry.amount = f; + if (entry.isexpense) + entry.amount.Invert(); + gDatabase.AddBudgetEntry(entry); + + RefreshBudgetGrid(); + RefreshBudgetSummary(); + + fBudgetSummary->SetFocusRow(entry.isexpense ? 1 : 0); + fBudgetSummary->SetFocusRow(2); + break; + } + case M_BUDGET_RECALCULATE: { + GenerateBudget(false); + RefreshBudgetGrid(); + RefreshBudgetSummary(); + RefreshCategories(); + break; + } + case M_BUDGET_ZERO: { + GenerateBudget(true); + RefreshBudgetGrid(); + RefreshBudgetSummary(); + RefreshCategories(); + break; + } + case M_SET_PERIOD_MONTH: { + SetPeriod(BUDGET_MONTHLY); + break; + } + case M_SET_PERIOD_WEEK: { + SetPeriod(BUDGET_WEEKLY); + break; + } + case M_SET_PERIOD_QUARTER: { + SetPeriod(BUDGET_QUARTERLY); + break; + } + case M_SET_PERIOD_YEAR: { + SetPeriod(BUDGET_ANNUALLY); + break; + } + case M_NEXT_FIELD: { + if (fAmountBox->ChildAt(0)->IsFocus()) + fMonthly->MakeFocus(true); + break; + } + case M_PREVIOUS_FIELD: { + if (fAmountBox->ChildAt(0)->IsFocus()) + fCategoryList->MakeFocus(true); + break; + } + default: + BWindow::MessageReceived(msg); } } -void BudgetWindow::HandleCategorySelection(void) -{ +void +BudgetWindow::HandleCategorySelection(void) { BRow *row = fCategoryList->CurrentSelection(); - if(!row) - { + if (!row) { fAmountBox->SetText(""); fMonthly->SetValue(B_CONTROL_ON); - fStatAverageRow->SetField(new BStringField(""),1); - fStatHighestRow->SetField(new BStringField(""),1); - fStatLowestRow->SetField(new BStringField(""),1); + fStatAverageRow->SetField(new BStringField(""), 1); + fStatHighestRow->SetField(new BStringField(""), 1); + fStatLowestRow->SetField(new BStringField(""), 1); } BudgetEntry entry; - BStringField *strfield = (BStringField*)row->GetField(0); - if(!gDatabase.GetBudgetEntry(strfield->String(),entry)) + BStringField *strfield = (BStringField *)row->GetField(0); + if (!gDatabase.GetBudgetEntry(strfield->String(), entry)) return; - switch(entry.period) - { - case BUDGET_WEEKLY: - { - fWeekly->SetValue(B_CONTROL_ON); - break; - } - case BUDGET_QUARTERLY: - { - fQuarterly->SetValue(B_CONTROL_ON); - break; - } - case BUDGET_ANNUALLY: - { - fAnnually->SetValue(B_CONTROL_ON); - break; - } - default: - { - fMonthly->SetValue(B_CONTROL_ON); - break; - } + switch (entry.period) { + case BUDGET_WEEKLY: { + fWeekly->SetValue(B_CONTROL_ON); + break; + } + case BUDGET_QUARTERLY: { + fQuarterly->SetValue(B_CONTROL_ON); + break; + } + case BUDGET_ANNUALLY: { + fAnnually->SetValue(B_CONTROL_ON); + break; + } + default: { + fMonthly->SetValue(B_CONTROL_ON); + break; + } } BString str; - gDefaultLocale.CurrencyToString(entry.amount.AbsoluteValue(),str); + gDefaultLocale.CurrencyToString(entry.amount.AbsoluteValue(), str); str.Truncate(str.FindFirst(gDefaultLocale.CurrencyDecimal())); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); fAmountBox->SetText(str.String()); - Fixed high,low,avg; - CalcStats(entry.name.String(),high,low,avg); + Fixed high, low, avg; + CalcStats(entry.name.String(), high, low, avg); - gDefaultLocale.CurrencyToString(high.AbsoluteValue(),str); + gDefaultLocale.CurrencyToString(high.AbsoluteValue(), str); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fStatHighestRow->SetField(new BStringField(str.String()),1); + fStatHighestRow->SetField(new BStringField(str.String()), 1); - gDefaultLocale.CurrencyToString(low.AbsoluteValue(),str); + gDefaultLocale.CurrencyToString(low.AbsoluteValue(), str); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fStatLowestRow->SetField(new BStringField(str.String()),1); + fStatLowestRow->SetField(new BStringField(str.String()), 1); - gDefaultLocale.CurrencyToString(avg.AbsoluteValue(),str); + gDefaultLocale.CurrencyToString(avg.AbsoluteValue(), str); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fStatAverageRow->SetField(new BStringField(str.String()),1); + fStatAverageRow->SetField(new BStringField(str.String()), 1); fCatStat->Invalidate(); } -void BudgetWindow::RefreshCategories(void) -{ +void +BudgetWindow::RefreshCategories(void) { fCategoryList->Clear(); fIncomeRow = new BRow(); fCategoryList->AddRow(fIncomeRow); fSpendingRow = new BRow(); fCategoryList->AddRow(fSpendingRow); - fIncomeRow->SetField(new BStringField(TRANSLATE("Income")),0); - fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")),0); - - CppSQLite3Query query = gDatabase.DBQuery("select category,amount,period,isexpense from " - "budgetlist order by category", - "BudgetWindow::RefreshCategories"); - float maxwidth=fCategoryList->StringWidth("Category"); - while(!query.eof()) - { + fIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); + fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); + + CppSQLite3Query query = gDatabase.DBQuery( + "select category,amount,period,isexpense from " + "budgetlist order by category", + "BudgetWindow::RefreshCategories" + ); + float maxwidth = fCategoryList->StringWidth("Category"); + while (!query.eof()) { BString cat = DeescapeIllegalCharacters(query.getStringField(0)); Fixed amount; amount.SetPremultiplied(query.getInt64Field(1)); @@ -287,50 +267,47 @@ void BudgetWindow::RefreshCategories(void) BRow *row = new BRow(); - if(query.getIntField(3)==0) - fCategoryList->AddRow(row,fIncomeRow); + if (query.getIntField(3) == 0) + fCategoryList->AddRow(row, fIncomeRow); else - fCategoryList->AddRow(row,fSpendingRow); + fCategoryList->AddRow(row, fSpendingRow); - row->SetField(new BStringField(cat.String()),0); + row->SetField(new BStringField(cat.String()), 0); BString amountstr; - gDefaultLocale.CurrencyToString(amount.AbsoluteValue(),amountstr); + gDefaultLocale.CurrencyToString(amount.AbsoluteValue(), amountstr); amountstr.Truncate(amountstr.FindFirst(gDefaultLocale.CurrencyDecimal())); amountstr.RemoveFirst(gDefaultLocale.CurrencySymbol()); - row->SetField(new BStringField(amountstr.String()),1); + row->SetField(new BStringField(amountstr.String()), 1); float tempwidth = fCategoryList->StringWidth(cat.String()); - maxwidth = MAX(tempwidth,maxwidth); + maxwidth = MAX(tempwidth, maxwidth); - row->SetField(new BStringField(BudgetPeriodToString(period).String()),2); + row->SetField(new BStringField(BudgetPeriodToString(period).String()), 2); query.nextRow(); } - fCategoryList->ColumnAt(0)->SetWidth(maxwidth+30); - fCategoryList->ExpandOrCollapse(fIncomeRow,true); - fCategoryList->ExpandOrCollapse(fSpendingRow,true); + fCategoryList->ColumnAt(0)->SetWidth(maxwidth + 30); + fCategoryList->ExpandOrCollapse(fIncomeRow, true); + fCategoryList->ExpandOrCollapse(fSpendingRow, true); } -void BudgetWindow::RefreshBudgetSummary(void) -{ - Fixed itotal,stotal,mtotal,f; - Fixed irowtotal,srowtotal, ttotal; - for(int32 i=0; i<12; i++) - { +void +BudgetWindow::RefreshBudgetSummary(void) { + Fixed itotal, stotal, mtotal, f; + Fixed irowtotal, srowtotal, ttotal; + for (int32 i = 0; i < 12; i++) { itotal = stotal = mtotal = 0; - for(int32 j=0; jRowAt(1); BRow *mrow = fBudgetSummary->RowAt(2); - irow->SetField(new BStringField(itemp.String()),i+1); - srow->SetField(new BStringField(stemp.String()),i+1); - mrow->SetField(new BStringField(mtemp.String()),i+1); + irow->SetField(new BStringField(itemp.String()), i + 1); + srow->SetField(new BStringField(stemp.String()), i + 1); + mrow->SetField(new BStringField(mtemp.String()), i + 1); float colwidth = fBudgetSummary->StringWidth(itemp.String()) + 20; - if(fBudgetSummary->ColumnAt(i+1)->Width() < colwidth) - fBudgetSummary->ColumnAt(i+1)->SetWidth(colwidth); + if (fBudgetSummary->ColumnAt(i + 1)->Width() < colwidth) + fBudgetSummary->ColumnAt(i + 1)->SetWidth(colwidth); colwidth = fBudgetSummary->StringWidth(stemp.String()) + 20; - if(fBudgetSummary->ColumnAt(i+1)->Width() < colwidth) - fBudgetSummary->ColumnAt(i+1)->SetWidth(colwidth); + if (fBudgetSummary->ColumnAt(i + 1)->Width() < colwidth) + fBudgetSummary->ColumnAt(i + 1)->SetWidth(colwidth); colwidth = fBudgetSummary->StringWidth(mtemp.String()) + 20; - if(fBudgetSummary->ColumnAt(i+1)->Width() < colwidth) - fBudgetSummary->ColumnAt(i+1)->SetWidth(colwidth); + if (fBudgetSummary->ColumnAt(i + 1)->Width() < colwidth) + fBudgetSummary->ColumnAt(i + 1)->SetWidth(colwidth); } BString ttemp; - gDefaultLocale.CurrencyToString(irowtotal,ttemp); + gDefaultLocale.CurrencyToString(irowtotal, ttemp); ttemp.Truncate(ttemp.FindFirst(gDefaultLocale.CurrencyDecimal())); ttemp.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fBudgetSummary->RowAt(0)->SetField(new BStringField(ttemp.String()),13); + fBudgetSummary->RowAt(0)->SetField(new BStringField(ttemp.String()), 13); - gDefaultLocale.CurrencyToString(srowtotal,ttemp); + gDefaultLocale.CurrencyToString(srowtotal, ttemp); ttemp.Truncate(ttemp.FindFirst(gDefaultLocale.CurrencyDecimal())); ttemp.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fBudgetSummary->RowAt(1)->SetField(new BStringField(ttemp.String()),13); + fBudgetSummary->RowAt(1)->SetField(new BStringField(ttemp.String()), 13); - gDefaultLocale.CurrencyToString(ttotal,ttemp); + gDefaultLocale.CurrencyToString(ttotal, ttemp); ttemp.Truncate(ttemp.FindFirst(gDefaultLocale.CurrencyDecimal())); ttemp.RemoveFirst(gDefaultLocale.CurrencySymbol()); - fBudgetSummary->RowAt(2)->SetField(new BStringField(ttemp.String()),13); + fBudgetSummary->RowAt(2)->SetField(new BStringField(ttemp.String()), 13); fBudgetSummary->Invalidate(); } -void BudgetWindow::RefreshBudgetGrid(void) -{ +void +BudgetWindow::RefreshBudgetGrid(void) { fIncomeGrid.MakeEmpty(); fSpendingGrid.MakeEmpty(); - CppSQLite3Query query = gDatabase.DBQuery("select category,amount,period from " - "budgetlist order by category", - "BudgetWindow::RefreshCategories"); - while(!query.eof()) - { + CppSQLite3Query query = gDatabase.DBQuery( + "select category,amount,period from " + "budgetlist order by category", + "BudgetWindow::RefreshCategories" + ); + while (!query.eof()) { BString cat = DeescapeIllegalCharacters(query.getStringField(0)); Fixed amount; amount.SetPremultiplied(query.getInt64Field(1)); @@ -418,78 +396,69 @@ void BudgetWindow::RefreshBudgetGrid(void) grid->SetRowTitle(index, cat.String()); Fixed f(amount.AbsoluteValue()); - switch(period) - { - case BUDGET_QUARTERLY: - { - f /= 3; - Fixed qamt(amount); - qamt *= 4; - grid->SetValue(12,index,qamt); - break; - } - case BUDGET_ANNUALLY: - { - f /=12; - grid->SetValue(12,index,amount); - break; - } - default: - { - Fixed mamt(f); - mamt *= 12; - grid->SetValue(12,index,mamt); - break; - } + switch (period) { + case BUDGET_QUARTERLY: { + f /= 3; + Fixed qamt(amount); + qamt *= 4; + grid->SetValue(12, index, qamt); + break; + } + case BUDGET_ANNUALLY: { + f /= 12; + grid->SetValue(12, index, amount); + break; + } + default: { + Fixed mamt(f); + mamt *= 12; + grid->SetValue(12, index, mamt); + break; + } } - for(int32 i=0; i<12; i++) - grid->SetValue(i,index,f); + for (int32 i = 0; i < 12; i++) + grid->SetValue(i, index, f); query.nextRow(); } } -void BudgetWindow::GenerateBudget(const bool &zero) -{ +void +BudgetWindow::GenerateBudget(const bool &zero) { // Generate a budget based on the last year's transactions - ReportGrid income(1,0), spending(1,0); + ReportGrid income(1, 0), spending(1, 0); - gDatabase.DBCommand("delete from budgetlist", - "BudgetWindow::GenerateBudget:empty budget"); + gDatabase.DBCommand("delete from budgetlist", "BudgetWindow::GenerateBudget:empty budget"); CppSQLite3Query query; - query = gDatabase.DBQuery("select * from categorylist order by name", - "BudgetWindow::GenerateBudget:get categories"); + query = gDatabase.DBQuery( + "select * from categorylist order by name", "BudgetWindow::GenerateBudget:get categories" + ); - if(query.eof()) + if (query.eof()) return; - float maxwidth=fCategoryList->StringWidth(TRANSLATE("Category")); - while(!query.eof()) - { + float maxwidth = fCategoryList->StringWidth(TRANSLATE("Category")); + while (!query.eof()) { BString catname = DeescapeIllegalCharacters(query.getStringField(0)); - if(catname.ICompare(TRANSLATE("Transfer"))==0) - { + if (catname.ICompare(TRANSLATE("Transfer")) == 0) { query.nextRow(); continue; } bool isexpense = !query.getIntField(1); - if(isexpense) - { + if (isexpense) { spending.AddItem(); - spending.SetRowTitle(spending.CountItems()-1,catname.String()); - } - else - { + spending.SetRowTitle(spending.CountItems() - 1, catname.String()); + } else { income.AddItem(); - income.SetRowTitle(income.CountItems()-1,catname.String()); + income.SetRowTitle(income.CountItems() - 1, catname.String()); } float tempwidth = fCategoryList->StringWidth(catname.String()); - maxwidth = MAX(maxwidth,tempwidth); + maxwidth = MAX(maxwidth, tempwidth); query.nextRow(); } @@ -500,62 +469,57 @@ void BudgetWindow::GenerateBudget(const bool &zero) BString querystring; Fixed cattotal; - for(int32 i=0; iGetID() << " where category = '" - << EscapeIllegalCharacters(income.RowTitle(i)) - << "' and date > " << DecrementDateByYear(GetCurrentDate()) << ";"; - query = gDatabase.DBQuery(querystring.String(), - "BudgetWindow::GenerateBudget:get category"); + querystring = "select sum(amount) from account_"; + querystring << acc->GetID() << " where category = '" + << EscapeIllegalCharacters(income.RowTitle(i)) << "' and date > " + << DecrementDateByYear(GetCurrentDate()) << ";"; + query = gDatabase.DBQuery( + querystring.String(), "BudgetWindow::GenerateBudget:get category" + ); cattotal.AddPremultiplied(query.getInt64Field(0)); query.finalize(); } cattotal /= 12; cattotal.Round(); } - income.SetValue(0,i,cattotal); - gDatabase.AddBudgetEntry(BudgetEntry(income.RowTitle(i),cattotal,BUDGET_MONTHLY,false)); + income.SetValue(0, i, cattotal); + gDatabase.AddBudgetEntry(BudgetEntry(income.RowTitle(i), cattotal, BUDGET_MONTHLY, false)); } - for(int32 i=0; iGetID() << " where category = '" - << EscapeIllegalCharacters(spending.RowTitle(i)) - << "';"; - query = gDatabase.DBQuery(querystring.String(), - "BudgetWindow::GenerateBudget:get category"); + querystring = "select sum(amount) from account_"; + querystring << acc->GetID() << " where category = '" + << EscapeIllegalCharacters(spending.RowTitle(i)) << "';"; + query = gDatabase.DBQuery( + querystring.String(), "BudgetWindow::GenerateBudget:get category" + ); cattotal.AddPremultiplied(query.getInt64Field(0)); query.finalize(); } cattotal /= 12; cattotal.Round(); } - spending.SetValue(0,i,cattotal); - gDatabase.AddBudgetEntry(BudgetEntry(spending.RowTitle(i),cattotal,BUDGET_MONTHLY,true)); + spending.SetValue(0, i, cattotal); + gDatabase.AddBudgetEntry(BudgetEntry(spending.RowTitle(i), cattotal, BUDGET_MONTHLY, true)); } } -void BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) -{ - if(!cat) +void +BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { + if (!cat) return; BString querystring; @@ -563,15 +527,12 @@ void BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &av CppSQLite3Query query; // find the average amount - for(int32 j=0; jGetID() << " where category = '" - << EscapeIllegalCharacters(cat) + querystring = "select sum(amount) from account_"; + querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; - query = gDatabase.DBQuery(querystring.String(), - "BudgetWindow::CalcStats:get average"); + query = gDatabase.DBQuery(querystring.String(), "BudgetWindow::CalcStats:get average"); cattotal.AddPremultiplied(query.getInt64Field(0)); query.finalize(); } @@ -579,99 +540,83 @@ void BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &av avg /= 12; // find the highest amount - cattotal=0; - for(int32 j=0; jGetID() << " where category = '" - << EscapeIllegalCharacters(cat) + querystring = "select max(amount) from account_"; + querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; - query = gDatabase.DBQuery(querystring.String(), - "BudgetWindow::CalcStats:get highest"); + query = gDatabase.DBQuery(querystring.String(), "BudgetWindow::CalcStats:get highest"); Fixed value; value.SetPremultiplied(query.getInt64Field(0)); - cattotal = MAX(cattotal,value); + cattotal = MAX(cattotal, value); query.finalize(); } high = cattotal; // find the lowest amount - cattotal=0; - for(int32 j=0; jGetID() << " where category = '" - << EscapeIllegalCharacters(cat) + querystring = "select min(amount) from account_"; + querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; - query = gDatabase.DBQuery(querystring.String(), - "BudgetWindow::CalcStats:get highest"); + query = gDatabase.DBQuery(querystring.String(), "BudgetWindow::CalcStats:get highest"); Fixed value; value.SetPremultiplied(query.getInt64Field(0)); - cattotal = MIN(cattotal,value); + cattotal = MIN(cattotal, value); query.finalize(); } low = cattotal; } -void BudgetWindow::SetPeriod(const BudgetPeriod &period) -{ +void +BudgetWindow::SetPeriod(const BudgetPeriod &period) { BRow *row = fCategoryList->CurrentSelection(); - if(!row) + if (!row) return; BudgetEntry entry; - BStringField *strfield = (BStringField*)row->GetField(0); - if(!gDatabase.GetBudgetEntry(strfield->String(),entry)) + BStringField *strfield = (BStringField *)row->GetField(0); + if (!gDatabase.GetBudgetEntry(strfield->String(), entry)) return; // Convert the amount to reflect the change in period - switch(entry.period) - { - case BUDGET_WEEKLY: - { - entry.amount *= 52; - break; - } - case BUDGET_QUARTERLY: - { - entry.amount *= 4; - break; - } - case BUDGET_ANNUALLY: - { - break; - } - default: - { - entry.amount *= 12; - break; - } + switch (entry.period) { + case BUDGET_WEEKLY: { + entry.amount *= 52; + break; + } + case BUDGET_QUARTERLY: { + entry.amount *= 4; + break; + } + case BUDGET_ANNUALLY: { + break; + } + default: { + entry.amount *= 12; + break; + } } entry.period = period; - switch(entry.period) - { - case BUDGET_WEEKLY: - { - entry.amount /= 52; - break; - } - case BUDGET_QUARTERLY: - { - entry.amount /= 4; - break; - } - case BUDGET_ANNUALLY: - { - break; - } - default: - { - entry.amount /= 12; - break; - } + switch (entry.period) { + case BUDGET_WEEKLY: { + entry.amount /= 52; + break; + } + case BUDGET_QUARTERLY: { + entry.amount /= 4; + break; + } + case BUDGET_ANNUALLY: { + break; + } + default: { + entry.amount /= 12; + break; + } } // yeah, yeah, I know about rounding errors. It's not that big of a deal, // so deal with it. *famous last words* @@ -682,31 +627,32 @@ void BudgetWindow::SetPeriod(const BudgetPeriod &period) RefreshBudgetSummary(); BString str; - gDefaultLocale.CurrencyToString(entry.amount,str); + gDefaultLocale.CurrencyToString(entry.amount, str); str.Truncate(str.FindFirst(gDefaultLocale.CurrencyDecimal())); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - row->SetField(new BStringField(str.String()),1); + row->SetField(new BStringField(str.String()), 1); fAmountBox->SetText(str.String()); - row->SetField(new BStringField(BudgetPeriodToString(entry.period).String()),2); + row->SetField(new BStringField(BudgetPeriodToString(entry.period).String()), 2); fCategoryList->UpdateRow(row); } -void BudgetWindow::BuildStatsAndEditor(void) -{ +void +BudgetWindow::BuildStatsAndEditor(void) { // Add the category statistics BString temp; - rgb_color white = {255,255,255,255}; + rgb_color white = {255, 255, 255, 255}; float statwidth = fBackView->StringWidth(TRANSLATE("12 Month Statistics")) + 20; float amountwidth = fBackView->StringWidth("000,000.00") + 20; - fCatStat = new BColumnListView("categorystats", - B_WILL_DRAW | B_NAVIGABLE,B_FANCY_BORDER); - fCatStat->AddColumn(new BStringColumn(TRANSLATE("12 Month Statistics"),statwidth, - 10,300,B_TRUNCATE_END),0); - fCatStat->AddColumn(new BStringColumn(TRANSLATE("Amount"),amountwidth, - 10,300,B_TRUNCATE_END),1); + fCatStat = new BColumnListView("categorystats", B_WILL_DRAW | B_NAVIGABLE, B_FANCY_BORDER); + fCatStat->AddColumn( + new BStringColumn(TRANSLATE("12 Month Statistics"), statwidth, 10, 300, B_TRUNCATE_END), 0 + ); + fCatStat->AddColumn( + new BStringColumn(TRANSLATE("Amount"), amountwidth, 10, 300, B_TRUNCATE_END), 1 + ); fCatStat->SetSortingEnabled(false); fCatStat->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); fStatAverageRow = new BRow(); @@ -716,124 +662,151 @@ void BudgetWindow::BuildStatsAndEditor(void) fCatStat->AddRow(fStatHighestRow); fCatStat->AddRow(fStatLowestRow); - fStatAverageRow->SetField(new BStringField(TRANSLATE("Average")),0); - fStatHighestRow->SetField(new BStringField(TRANSLATE("Highest")),0); - fStatLowestRow->SetField(new BStringField(TRANSLATE("Lowest")),0); + fStatAverageRow->SetField(new BStringField(TRANSLATE("Average")), 0); + fStatHighestRow->SetField(new BStringField(TRANSLATE("Highest")), 0); + fStatLowestRow->SetField(new BStringField(TRANSLATE("Lowest")), 0); - fCatStat->SetColor(B_COLOR_BACKGROUND,white); - fCatStat->SetColor(B_COLOR_SELECTION,white); - fCatStat->SetColor(B_COLOR_NON_FOCUS_SELECTION,white); - fCatStat->SetColor(B_COLOR_SEPARATOR_BORDER,white); - fCatStat->SetColor(B_COLOR_SEPARATOR_LINE,white); - fCatStat->SetColor(B_COLOR_HEADER_BACKGROUND,GetColor(BC_GRID_HEADER)); + fCatStat->SetColor(B_COLOR_BACKGROUND, white); + fCatStat->SetColor(B_COLOR_SELECTION, white); + fCatStat->SetColor(B_COLOR_NON_FOCUS_SELECTION, white); + fCatStat->SetColor(B_COLOR_SEPARATOR_BORDER, white); + fCatStat->SetColor(B_COLOR_SEPARATOR_LINE, white); + fCatStat->SetColor(B_COLOR_HEADER_BACKGROUND, GetColor(BC_GRID_HEADER)); // Add the category editor fCatBox = new BBox("catbox"); fCatBox->SetLabel(TRANSLATE("Edit Category")); - fMonthly = new BRadioButton("monthoption",TRANSLATE("Monthly"),new BMessage(M_SET_PERIOD_MONTH)); - fWeekly = new BRadioButton("weekoption",TRANSLATE("Weekly"),new BMessage(M_SET_PERIOD_WEEK)); - fQuarterly = new BRadioButton("quarteroption",TRANSLATE("Quarterly"),new BMessage(M_SET_PERIOD_QUARTER)); - fAnnually = new BRadioButton("yearoption",TRANSLATE("Annually"),new BMessage(M_SET_PERIOD_YEAR)); + fMonthly = + new BRadioButton("monthoption", TRANSLATE("Monthly"), new BMessage(M_SET_PERIOD_MONTH)); + fWeekly = new BRadioButton("weekoption", TRANSLATE("Weekly"), new BMessage(M_SET_PERIOD_WEEK)); + fQuarterly = new BRadioButton( + "quarteroption", TRANSLATE("Quarterly"), new BMessage(M_SET_PERIOD_QUARTER) + ); + fAnnually = + new BRadioButton("yearoption", TRANSLATE("Annually"), new BMessage(M_SET_PERIOD_YEAR)); fMonthly->SetValue(B_CONTROL_ON); - temp = TRANSLATE("Amount"); temp += ":"; - fAmountLabel = new BStringView("amountlabel",temp.String()); + temp = TRANSLATE("Amount"); + temp += ":"; + fAmountLabel = new BStringView("amountlabel", temp.String()); - fAmountBox = new CurrencyBox("amountbox",NULL,"$00,000.00", - new BMessage(M_AMOUNT_CHANGED)); + fAmountBox = new CurrencyBox("amountbox", NULL, "$00,000.00", new BMessage(M_AMOUNT_CHANGED)); } -void BudgetWindow::BuildBudgetSummary(void) -{ - rgb_color white = {255,255,255,255}; +void +BudgetWindow::BuildBudgetSummary(void) { + rgb_color white = {255, 255, 255, 255}; fSummaryIncomeRow = new BRow(); fSummarySpendingRow = new BRow(); fSummaryTotalRow = new BRow(); - fBudgetSummary = new BColumnListView("budgetsummary", - B_WILL_DRAW | B_NAVIGABLE,B_FANCY_BORDER); + fBudgetSummary = + new BColumnListView("budgetsummary", B_WILL_DRAW | B_NAVIGABLE, B_FANCY_BORDER); fBudgetSummary->SetSortingEnabled(false); - fBudgetSummary->AddColumn(new BStringColumn(TRANSLATE("Summary"), - fBudgetSummary->StringWidth(TRANSLATE("Spending"))+20, - 10,300,B_TRUNCATE_END),0); + fBudgetSummary->AddColumn( + new BStringColumn( + TRANSLATE("Summary"), fBudgetSummary->StringWidth(TRANSLATE("Spending")) + 20, 10, 300, + B_TRUNCATE_END + ), + 0 + ); fBudgetSummary->AddRow(fSummaryIncomeRow); fBudgetSummary->AddRow(fSummarySpendingRow); fBudgetSummary->AddRow(fSummaryTotalRow); fBudgetSummary->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); - fSummaryIncomeRow->SetField(new BStringField(TRANSLATE("Income")),0); - fSummarySpendingRow->SetField(new BStringField(TRANSLATE("Spending")),0); - fSummaryTotalRow->SetField(new BStringField(TRANSLATE("Total")),0); + fSummaryIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); + fSummarySpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); + fSummaryTotalRow->SetField(new BStringField(TRANSLATE("Total")), 0); - fBudgetSummary->SetColor(B_COLOR_BACKGROUND,white); - fBudgetSummary->SetColor(B_COLOR_SELECTION,white); - fBudgetSummary->SetColor(B_COLOR_NON_FOCUS_SELECTION,white); - fBudgetSummary->SetColor(B_COLOR_SEPARATOR_BORDER,white); - fBudgetSummary->SetColor(B_COLOR_SEPARATOR_LINE,white); - fBudgetSummary->SetColor(B_COLOR_HEADER_BACKGROUND,GetColor(BC_GRID_HEADER)); + fBudgetSummary->SetColor(B_COLOR_BACKGROUND, white); + fBudgetSummary->SetColor(B_COLOR_SELECTION, white); + fBudgetSummary->SetColor(B_COLOR_NON_FOCUS_SELECTION, white); + fBudgetSummary->SetColor(B_COLOR_SEPARATOR_BORDER, white); + fBudgetSummary->SetColor(B_COLOR_SEPARATOR_LINE, white); + fBudgetSummary->SetColor(B_COLOR_HEADER_BACKGROUND, GetColor(BC_GRID_HEADER)); // Add all the calendar stuff time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); - for(int8 i=0; i<12; i++) - { + for (int8 i = 0; i < 12; i++) { char month[32]; timestruct.tm_mon = i; - strftime(month,32,"%b",×truct); - fBudgetSummary->AddColumn(new BStringColumn(month, - fBudgetSummary->StringWidth(month)+25, - 10,300,B_TRUNCATE_END,B_ALIGN_RIGHT),i+1); - fSummaryIncomeRow->SetField(new BStringField(""),i+1); - fSummarySpendingRow->SetField(new BStringField(""),i+1); - fSummaryTotalRow->SetField(new BStringField(""),i+1); - } - fBudgetSummary->AddColumn(new BStringColumn(TRANSLATE("Total"), - fBudgetSummary->StringWidth(TRANSLATE("Total"))+20, - 10,300,B_TRUNCATE_END,B_ALIGN_RIGHT),13); - fSummaryIncomeRow->SetField(new BStringField(""),13); - fSummarySpendingRow->SetField(new BStringField(""),13); - fSummaryTotalRow->SetField(new BStringField(""),13); + strftime(month, 32, "%b", ×truct); + fBudgetSummary->AddColumn( + new BStringColumn( + month, fBudgetSummary->StringWidth(month) + 25, 10, 300, B_TRUNCATE_END, + B_ALIGN_RIGHT + ), + i + 1 + ); + fSummaryIncomeRow->SetField(new BStringField(""), i + 1); + fSummarySpendingRow->SetField(new BStringField(""), i + 1); + fSummaryTotalRow->SetField(new BStringField(""), i + 1); + } + fBudgetSummary->AddColumn( + new BStringColumn( + TRANSLATE("Total"), fBudgetSummary->StringWidth(TRANSLATE("Total")) + 20, 10, 300, + B_TRUNCATE_END, B_ALIGN_RIGHT + ), + 13 + ); + fSummaryIncomeRow->SetField(new BStringField(""), 13); + fSummarySpendingRow->SetField(new BStringField(""), 13); + fSummaryTotalRow->SetField(new BStringField(""), 13); fBudgetSummary->UpdateRow(fSummaryIncomeRow); fBudgetSummary->UpdateRow(fSummarySpendingRow); fBudgetSummary->UpdateRow(fSummaryTotalRow); } -void BudgetWindow::BuildCategoryList(void) -{ - rgb_color white = {255,255,255,255}; +void +BudgetWindow::BuildCategoryList(void) { + rgb_color white = {255, 255, 255, 255}; - fCategoryList = new BColumnListView("categorylist", - B_WILL_DRAW | B_NAVIGABLE,B_FANCY_BORDER, true); + fCategoryList = + new BColumnListView("categorylist", B_WILL_DRAW | B_NAVIGABLE, B_FANCY_BORDER, true); fCategoryList->SetSortingEnabled(false); fCategoryList->SetSelectionMessage(new BMessage(M_SELECT_CATEGORY)); - fCategoryList->AddColumn(new BStringColumn(TRANSLATE("Category"), - fCategoryList->StringWidth(TRANSLATE("Category"))+20, - 10,300,B_TRUNCATE_END),0); - fCategoryList->AddColumn(new BStringColumn(TRANSLATE("Amount"), - fCategoryList->StringWidth(TRANSLATE("Amount"))+20, - 10,300,B_TRUNCATE_END,B_ALIGN_RIGHT),1); - fCategoryList->AddColumn(new BStringColumn(TRANSLATE("Frequency"), - fCategoryList->StringWidth(TRANSLATE("Frequency"))+20, - 10,300,B_TRUNCATE_END,B_ALIGN_RIGHT),2); + fCategoryList->AddColumn( + new BStringColumn( + TRANSLATE("Category"), fCategoryList->StringWidth(TRANSLATE("Category")) + 20, 10, 300, + B_TRUNCATE_END + ), + 0 + ); + fCategoryList->AddColumn( + new BStringColumn( + TRANSLATE("Amount"), fCategoryList->StringWidth(TRANSLATE("Amount")) + 20, 10, 300, + B_TRUNCATE_END, B_ALIGN_RIGHT + ), + 1 + ); + fCategoryList->AddColumn( + new BStringColumn( + TRANSLATE("Frequency"), fCategoryList->StringWidth(TRANSLATE("Frequency")) + 20, 10, + 300, B_TRUNCATE_END, B_ALIGN_RIGHT + ), + 2 + ); fCategoryList->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); fIncomeRow = new BRow(); fCategoryList->AddRow(fIncomeRow); fSpendingRow = new BRow(); fCategoryList->AddRow(fSpendingRow); - fIncomeRow->SetField(new BStringField(TRANSLATE("Income")),0); - fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")),0); - - fCategoryList->SetColor(B_COLOR_BACKGROUND,white); - fCategoryList->SetColor(B_COLOR_SELECTION,GetColor(BC_SELECTION_FOCUS)); - fCategoryList->SetColor(B_COLOR_NON_FOCUS_SELECTION,GetColor(BC_SELECTION_NOFOCUS)); - fCategoryList->SetColor(B_COLOR_SEPARATOR_BORDER,white); - fCategoryList->SetColor(B_COLOR_SEPARATOR_LINE,white); - fCategoryList->SetColor(B_COLOR_HEADER_BACKGROUND,GetColor(BC_GRID_HEADER)); + fIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); + fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); + + fCategoryList->SetColor(B_COLOR_BACKGROUND, white); + fCategoryList->SetColor(B_COLOR_SELECTION, GetColor(BC_SELECTION_FOCUS)); + fCategoryList->SetColor(B_COLOR_NON_FOCUS_SELECTION, GetColor(BC_SELECTION_NOFOCUS)); + fCategoryList->SetColor(B_COLOR_SEPARATOR_BORDER, white); + fCategoryList->SetColor(B_COLOR_SEPARATOR_LINE, white); + fCategoryList->SetColor(B_COLOR_HEADER_BACKGROUND, GetColor(BC_GRID_HEADER)); } diff --git a/src/BudgetWindow.h b/src/BudgetWindow.h index d026604..25b1d51 100644 --- a/src/BudgetWindow.h +++ b/src/BudgetWindow.h @@ -1,37 +1,36 @@ #ifndef BUDGETWIN_H #define BUDGETWIN_H -#include -#include -#include -#include -#include -#include -#include +#include "Budget.h" #include "ColumnListView.h" +#include "ReportGrid.h" +#include #include -#include +#include +#include #include +#include #include -#include #include -#include "ReportGrid.h" -#include "Budget.h" +#include +#include +#include +#include +#include class CurrencyBox; -class BudgetWindow : public BWindow -{ -public: +class BudgetWindow : public BWindow { + public: BudgetWindow(const BRect &frame); ~BudgetWindow(void); void MessageReceived(BMessage *msg); -private: + private: void BuildStatsAndEditor(void); void BuildBudgetSummary(void); void BuildCategoryList(void); - + void RefreshCategories(void); void RefreshBudgetSummary(void); void RefreshBudgetGrid(void); @@ -39,34 +38,25 @@ class BudgetWindow : public BWindow void CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg); void HandleCategorySelection(void); void SetPeriod(const BudgetPeriod &period); - + BMenuBar *fBar; BView *fBackView; - + BColumnListView *fCategoryList; - BRow *fIncomeRow, - *fSpendingRow; - + BRow *fIncomeRow, *fSpendingRow; + BColumnListView *fBudgetSummary; - BRow *fSummaryIncomeRow, - *fSummarySpendingRow, - *fSummaryTotalRow; - - BBox *fCatBox; - CurrencyBox *fAmountBox; - BStringView *fAmountLabel; - BRadioButton *fMonthly, - *fWeekly, - *fQuarterly, - *fAnnually; - + BRow *fSummaryIncomeRow, *fSummarySpendingRow, *fSummaryTotalRow; + + BBox *fCatBox; + CurrencyBox *fAmountBox; + BStringView *fAmountLabel; + BRadioButton *fMonthly, *fWeekly, *fQuarterly, *fAnnually; + BColumnListView *fCatStat; - BRow *fStatAverageRow, - *fStatHighestRow, - *fStatLowestRow; - - ReportGrid fIncomeGrid, - fSpendingGrid; + BRow *fStatAverageRow, *fStatHighestRow, *fStatLowestRow; + + ReportGrid fIncomeGrid, fSpendingGrid; }; #endif diff --git a/src/BuildOptions.h b/src/BuildOptions.h index d1c91ac..8edfc2e 100644 --- a/src/BuildOptions.h +++ b/src/BuildOptions.h @@ -4,16 +4,12 @@ #include // Uncomment DEMO_MODE to turn this into the demo package version -enum { -NORMAL_MODE=0, -PREVIEW_MODE, -BETA_MODE -}; +enum { NORMAL_MODE = 0, PREVIEW_MODE, BETA_MODE }; #define BUILD_MODE NORMAL_MODE // Uncomment ENTER_NAVIGATION to enable using the Enter key to navigate fields. // It copies Quicken, but it is also not consistent in its behavior, which is NOT good -//#define ENTER_NAVIGATION +// #define ENTER_NAVIGATION #endif diff --git a/src/CBLocale.h b/src/CBLocale.h index 6e3a1f3..845da59 100644 --- a/src/CBLocale.h +++ b/src/CBLocale.h @@ -1,68 +1,71 @@ #ifndef CBLOCALE_H #define CBLOCALE_H -#include -#include +#include "DAlert.h" +#include "Fixed.h" #include +#include #include -#include "Fixed.h" -#include "DAlert.h" +#include -typedef enum -{ -DATE_MDY=1, -DATE_DMY=2 -} date_format; +typedef enum { DATE_MDY = 1, DATE_DMY = 2 } date_format; -class Locale -{ -public: +class Locale { + public: Locale(void); ~Locale(void); - + bool operator==(const Locale &other) const; bool operator!=(const Locale &other) const; - + void Flatten(BFile *file); - + status_t CurrencyToString(const Fixed &amount, BString &string); status_t DateToString(time_t date, BString &string); status_t StringToCurrency(const char *string, Fixed &amount); status_t PremultipliedStringToCurrency(const char *string, Fixed &amount); status_t StringToDate(const char *instring, time_t &date); void NumberToCurrency(const Fixed &number, BString &string); - + void SetDateFormat(const date_format &format); + date_format DateFormat(void) const { return fDateFormat; } - + void SetCurrencySymbol(const char *symbol); + const char *CurrencySymbol(void) const { return fCurrencySymbol.String(); } - + void SetCurrencySeparator(const char *symbol); - const char *CurrencySeparator(void) const { return fCurrencySeparator.String(); } - + + const char *CurrencySeparator(void) const { return fCurrencySeparator.String(); } + void SetCurrencyDecimal(const char *symbol); + const char *CurrencyDecimal(void) const { return fCurrencyDecimal.String(); } - + void SetCurrencySymbolPrefix(const bool &value); + bool IsCurrencySymbolPrefix(void) const { return fPrefixSymbol; } - + void SetCurrencyDecimalPlace(const uint8 &place); + uint8 CurrencyDecimalPlace(void) const { return fCurrencyDecimalPlace; } - + void SetDateSeparator(const char *symbol); + const char *DateSeparator(void) const { return fDateSeparator.String(); } - + void SetDST(const bool &value); + bool UseDST(void) const { return fUseDST; } - -private: + + private: friend class CapitalBeParser; - + void SetDefaults(void); status_t ConstructDateStringMDY(const char *in, BString &out); status_t ConstructDateStringDMY(const char *in, BString &out); - + // Like BeFinancial, we just use two different date formats: mmddyyyy (0) and // ddmmyyyy (1) date_format fDateFormat; @@ -75,13 +78,19 @@ class Locale bool fUseDST; }; -void ShowAlert(const char *header, const char *message, - alert_type type=B_INFO_ALERT); -void ShowBug(const char *string); -void GetVersionString(BString &string); -void CapitalizeEachWord(BString &string); -const char *GetCurrencyOnlyMask(void); -const char *GetDateOnlyMask(void); -void IllegalCharsToEntities(BString *string); +void +ShowAlert(const char *header, const char *message, alert_type type = B_INFO_ALERT); +void +ShowBug(const char *string); +void +GetVersionString(BString &string); +void +CapitalizeEachWord(BString &string); +const char * +GetCurrencyOnlyMask(void); +const char * +GetDateOnlyMask(void); +void +IllegalCharsToEntities(BString *string); #endif diff --git a/src/CashFlowReport.cpp b/src/CashFlowReport.cpp index 022ef78..91f3e58 100644 --- a/src/CashFlowReport.cpp +++ b/src/CashFlowReport.cpp @@ -1,163 +1,147 @@ -#include "ReportWindow.h" #include "Account.h" #include "CBLocale.h" -#include "Database.h" -#include "ReportGrid.h" #include "ColumnListView.h" #include "ColumnTypes.h" +#include "Database.h" +#include "ReportGrid.h" +#include "ReportWindow.h" #include "TimeSupport.h" #include -void ReportWindow::ComputeCashFlow(void) -{ +void +ReportWindow::ComputeCashFlow(void) { // Calculate the number of columns and the starting date for each one - BObjectList timelist(20,true); - - for(time_t t = fStartDate; t timelist(20, true); + + for (time_t t = fStartDate; t < fEndDate;) { time_t *item = new time_t(t); timelist.AddItem(item); - - switch(fSubtotalMode) - { - case SUBTOTAL_MONTH: - { - t = IncrementDateByMonth(t); - break; - } - case SUBTOTAL_QUARTER: - { - t = IncrementDateByQuarter(t); - break; - } - case SUBTOTAL_YEAR: - { - t = IncrementDateByYear(t); - break; - } - default: - { - t = fEndDate; - break; - } + + switch (fSubtotalMode) { + case SUBTOTAL_MONTH: { + t = IncrementDateByMonth(t); + break; + } + case SUBTOTAL_QUARTER: { + t = IncrementDateByQuarter(t); + break; + } + case SUBTOTAL_YEAR: { + t = IncrementDateByYear(t); + break; + } + default: { + t = fEndDate; + break; + } } } timelist.AddItem(new time_t(fEndDate)); - - ReportGrid incomegrid(timelist.CountItems()-1,0), expensegrid(timelist.CountItems()-1,0); + + ReportGrid incomegrid(timelist.CountItems() - 1, 0), expensegrid(timelist.CountItems() - 1, 0); BString longestname(""); - - for(int32 i = 0; iCountItems(); i++) - { - BStringItem *catitem = (BStringItem*)fCategoryList->ItemAt(i); - if(!catitem || !catitem->IsSelected() || strlen(catitem->Text())<1) + + for (int32 i = 0; i < fCategoryList->CountItems(); i++) { + BStringItem *catitem = (BStringItem *)fCategoryList->ItemAt(i); + if (!catitem || !catitem->IsSelected() || strlen(catitem->Text()) < 1) continue; - - if((uint32)longestname.CountChars() < strlen(catitem->Text())) + + if ((uint32)longestname.CountChars() < strlen(catitem->Text())) longestname = catitem->Text(); - + BString escaped = EscapeIllegalCharacters(catitem->Text()); - + CppSQLite3Query query; - + BString command, expcommand; int32 accountcount = 0; -/* if(!query.eof()) - { - doincome = true; - incomegrid.AddItem(); - incomegrid.SetRowTitle(incomegrid.CountItems()-1,catitem->Text()); - } -*/ - -/* if(!query.eof()) - { - query.finalize(); - doexpense = true; - expensegrid.AddItem(); - expensegrid.SetRowTitle(expensegrid.CountItems()-1,catitem->Text()); - } -*/ - - int32 count = timelist.CountItems()-1; - for(int32 subtotal_index = 0; subtotal_indexText()); + } + */ + + /* if(!query.eof()) + { + query.finalize(); + doexpense = true; + expensegrid.AddItem(); + expensegrid.SetRowTitle(expensegrid.CountItems()-1,catitem->Text()); + } + */ + + int32 count = timelist.CountItems() - 1; + for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { + time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + accountcount = 0; command = expcommand = ""; - for(int32 i = 0; iCountItems();i++) - { - AccountItem *item = (AccountItem*)fAccountList->ItemAt(i); - if(!item || !item->IsSelected()) + for (int32 i = 0; i < fAccountList->CountItems(); i++) { + AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + if (!item || !item->IsSelected()) continue; - - if(accountcount>0) - { + + if (accountcount > 0) { command << " union all "; expcommand << " union all "; } - + command << "select sum(amount) from account_"; command << item->account->GetID() << " where category = '" << escaped - << "' and amount > 0 and date >= " << subtotal_start << " and date < " << subtotal_end; - + << "' and amount > 0 and date >= " << subtotal_start << " and date < " + << subtotal_end; + expcommand << "select sum(amount) from account_"; expcommand << item->account->GetID() << " where category = '" << escaped - << "' and amount < 0 and date >= " << subtotal_start << " and date < " << subtotal_end; - + << "' and amount < 0 and date >= " << subtotal_start << " and date < " + << subtotal_end; + accountcount++; } command << ";"; expcommand << ";"; - + // query for income in this category - query = gDatabase.DBQuery(command.String(),"ReportWindow::ComputeCashFlow:income"); - - if(!query.eof()) - { - Fixed inctotal,f; - - while(!query.eof()) - { + query = gDatabase.DBQuery(command.String(), "ReportWindow::ComputeCashFlow:income"); + + if (!query.eof()) { + Fixed inctotal, f; + + while (!query.eof()) { f.SetPremultiplied(query.getInt64Field(0)); inctotal += f; query.nextRow(); } - if(inctotal > 0) - { + if (inctotal > 0) { incomegrid.AddItem(); - incomegrid.SetRowTitle(incomegrid.CountItems()-1,catitem->Text()); - incomegrid.SetValue(subtotal_index,incomegrid.CountItems()-1,inctotal); + incomegrid.SetRowTitle(incomegrid.CountItems() - 1, catitem->Text()); + incomegrid.SetValue(subtotal_index, incomegrid.CountItems() - 1, inctotal); } - } - else - incomegrid.SetValue(subtotal_index,incomegrid.CountItems()-1,Fixed()); - + } else + incomegrid.SetValue(subtotal_index, incomegrid.CountItems() - 1, Fixed()); + // query for spending in this category - query = gDatabase.DBQuery(expcommand.String(),"ReportWindow::ComputeCashFlow:expense"); - - if(!query.eof()) - { - Fixed exptotal,f; - - while(!query.eof()) - { + query = gDatabase.DBQuery(expcommand.String(), "ReportWindow::ComputeCashFlow:expense"); + + if (!query.eof()) { + Fixed exptotal, f; + + while (!query.eof()) { f.SetPremultiplied(query.getInt64Field(0)); exptotal += f.AbsoluteValue(); query.nextRow(); } - if(exptotal > 0) - { + if (exptotal > 0) { expensegrid.AddItem(); - expensegrid.SetRowTitle(expensegrid.CountItems()-1,catitem->Text()); - expensegrid.SetValue(subtotal_index,expensegrid.CountItems()-1,exptotal); + expensegrid.SetRowTitle(expensegrid.CountItems() - 1, catitem->Text()); + expensegrid.SetValue(subtotal_index, expensegrid.CountItems() - 1, exptotal); } - } - else - expensegrid.SetValue(subtotal_index,expensegrid.CountItems()-1,Fixed()); - + } else + expensegrid.SetValue(subtotal_index, expensegrid.CountItems() - 1, Fixed()); + query.finalize(); } } @@ -165,115 +149,106 @@ void ReportWindow::ComputeCashFlow(void) expensegrid.Sort(); // Now that we have all the data, we need to set up the rows and columns for the report grid - BColumn *col = new BStringColumn(TRANSLATE("Category"),fGridView->StringWidth(longestname.String())+20,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,0); - + BColumn *col = new BStringColumn( + TRANSLATE("Category"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, + B_TRUNCATE_END + ); + fGridView->AddColumn(col, 0); + int32 i; - for(i = 0; itm_mon + 2) / 3)+1; - strftime(year,10,"%Y",timestruct); - sprintf(columntitle, "Q%d %s", quarternumber, year); - break; - } - case SUBTOTAL_YEAR: - { - strftime(columntitle,128,"%Y",timestruct); - break; - } - default: - { - sprintf(columntitle,TRANSLATE("Amount")); - break; - } + switch (fSubtotalMode) { + case SUBTOTAL_MONTH: { + strftime(columntitle, 128, "%b %Y", timestruct); + break; } - - col = new BStringColumn(columntitle,75,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,i+1); + case SUBTOTAL_QUARTER: { + char year[10]; + int quarternumber = ((timestruct->tm_mon + 2) / 3) + 1; + strftime(year, 10, "%Y", timestruct); + sprintf(columntitle, "Q%d %s", quarternumber, year); + break; + } + case SUBTOTAL_YEAR: { + strftime(columntitle, 128, "%Y", timestruct); + break; + } + default: { + sprintf(columntitle, TRANSLATE("Amount")); + break; + } + } + + col = new BStringColumn(columntitle, 75, 10, 300, B_TRUNCATE_END); + fGridView->AddColumn(col, i + 1); } - + fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Income")),0); + titlerow->SetField(new BStringField(TRANSLATE("Income")), 0); fGridView->AddRow(new BRow()); - - if(!fGridView->IsHidden()) - { + + if (!fGridView->IsHidden()) { // Now that the grid is set up, start adding data to the grid - for(i = 0; iAddRow(row); - + BStringField *catname = new BStringField(incomegrid.RowTitle(i)); - row->SetField(catname,0); - - for(int32 columnindex = 0; columnindexSetField(catname, 0); + + for (int32 columnindex = 0; columnindex < timelist.CountItems(); columnindex++) { BString temp; Fixed f; - - incomegrid.ValueAt(columnindex,i,f); - gCurrentLocale.CurrencyToString(f,temp); - + + incomegrid.ValueAt(columnindex, i, f); + gCurrentLocale.CurrencyToString(f, temp); + BStringField *amountfield = new BStringField(temp.String()); - row->SetField(amountfield,columnindex+1); + row->SetField(amountfield, columnindex + 1); } } - + fGridView->AddRow(new BRow()); titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Expense")),0); + titlerow->SetField(new BStringField(TRANSLATE("Expense")), 0); fGridView->AddRow(new BRow()); - - for(i = 0; iAddRow(row); - + BStringField *catname = new BStringField(expensegrid.RowTitle(i)); - row->SetField(catname,0); - - for(int32 columnindex = 0; columnindexSetField(catname, 0); + + for (int32 columnindex = 0; columnindex < timelist.CountItems(); columnindex++) { BString temp; Fixed f; - - expensegrid.ValueAt(columnindex,i,f); - gCurrentLocale.CurrencyToString(f,temp); - + + expensegrid.ValueAt(columnindex, i, f); + gCurrentLocale.CurrencyToString(f, temp); + BStringField *amountfield = new BStringField(temp.String()); - row->SetField(amountfield,columnindex+1); + row->SetField(amountfield, columnindex + 1); } } - } - else - { + } else { // Graph view is showing. Render the graph // TODO: Implement as line graph - -/* - The main point behind the graphs is to give the user a different way of looking - at the data in order to calculate a trend and also be able to look at quite a bit of data - for an extended period of time, which the report view doesn't do a very good job of showing. - - As such, what we need is a line graph view. -*/ + + /* + The main point behind the graphs is to give the user a different way of looking + at the data in order to calculate a trend and also be able to look at quite a bit of + data for an extended period of time, which the report view doesn't do a very good job of + showing. + + As such, what we need is a line graph view. + */ } } diff --git a/src/Category.cpp b/src/Category.cpp index 3e6741e..835f5ba 100644 --- a/src/Category.cpp +++ b/src/Category.cpp @@ -1,166 +1,153 @@ #include "Category.h" -#include -#include "Database.h" #include "CBLocale.h" -#include +#include "Database.h" #include +#include +#include -Category::Category(const char *string, const Fixed &fixed, const char *memo) -{ - fList = new BObjectList(20,true); - if(string) - fList->AddItem(new CatItem(string,fixed,memo)); +Category::Category(const char *string, const Fixed &fixed, const char *memo) { + fList = new BObjectList(20, true); + if (string) + fList->AddItem(new CatItem(string, fixed, memo)); } -Category::Category(const Category &from) -{ - fList = new BObjectList(20,true); - for(int32 i=0; iCountItems(); i++) - { +Category::Category(const Category &from) { + fList = new BObjectList(20, true); + for (int32 i = 0; i < from.fList->CountItems(); i++) { CatItem *item = from.fList->ItemAt(i); - if(item) + if (item) fList->AddItem(new CatItem(*item)); } } -Category::~Category(void) -{ - delete fList; -} +Category::~Category(void) { delete fList; } -void Category::SetNameAt(const int32 &index, const char *string) -{ +void +Category::SetNameAt(const int32 &index, const char *string) { CatItem *item = fList->ItemAt(index); - - if(item) - item->string=string; + + if (item) + item->string = string; } -void Category::SetAmountAt(const int32 &index, const Fixed &fixed) -{ +void +Category::SetAmountAt(const int32 &index, const Fixed &fixed) { CatItem *item = fList->ItemAt(index); - - if(item) + + if (item) item->amount = fixed; } -void Category::SetMemoAt(const int32 &index, const char *string) -{ +void +Category::SetMemoAt(const int32 &index, const char *string) { CatItem *item = fList->ItemAt(index); - - if(item) - item->memo=string; + + if (item) + item->memo = string; } -const char *Category::NameAt(const int32 &index) const -{ +const char * +Category::NameAt(const int32 &index) const { CatItem *item = fList->ItemAt(index); - + return item ? item->string.String() : NULL; } -Fixed Category::AmountAt(const int32 &index) const -{ +Fixed +Category::AmountAt(const int32 &index) const { CatItem *item = fList->ItemAt(index); - + return item ? item->amount : Fixed(0); } -const char *Category::MemoAt(const int32 &index) const -{ +const char * +Category::MemoAt(const int32 &index) const { CatItem *item = fList->ItemAt(index); - + return item ? item->memo.String() : NULL; } -bool Category::AddItem(const char *name, const Fixed &amount, const char *memo) -{ - if(!name) +bool +Category::AddItem(const char *name, const Fixed &amount, const char *memo) { + if (!name) return false; - + CatItem *item = fList->ItemAt(0); - if(item) - { - if(item->string.CountChars()==0) - { + if (item) { + if (item->string.CountChars() == 0) { fList->RemoveItemAt(0L); } } - fList->AddItem(new CatItem(name,amount,memo)); - + fList->AddItem(new CatItem(name, amount, memo)); + return true; } -bool Category::HasItem(const char *name) -{ +bool +Category::HasItem(const char *name) { // Prevent duplicates - for(int32 i=0; iCountItems(); i++) - { + for (int32 i = 0; i < fList->CountItems(); i++) { CatItem *data = fList->ItemAt(i); - if(data->string==name) + if (data->string == name) return true; } return false; } -bool Category::RemoveItem(const char *name) -{ - if(!name) +bool +Category::RemoveItem(const char *name) { + if (!name) return false; - + // Find item and remove - CatItem *item=NULL; - for(int32 i=0; iCountItems(); i++) - { + CatItem *item = NULL; + for (int32 i = 0; i < fList->CountItems(); i++) { CatItem *data = fList->ItemAt(i); - if(data->string==name) - { - item=data; + if (data->string == name) { + item = data; break; } } - + // owns item, so it does the delete fList->RemoveItem(item); return true; } -bool Category::RemoveItem(const int32 &index) -{ - CatItem *item=fList->RemoveItemAt(index); - if(!item) +bool +Category::RemoveItem(const int32 &index) { + CatItem *item = fList->RemoveItemAt(index); + if (!item) return false; - + delete item; return true; } -void Category::Flatten(BFile *file) -{ +void +Category::Flatten(BFile *file) { BString str("\t\t\n"); - - for(int32 i=0; iCountItems(); i++) - { + + for (int32 i = 0; i < fList->CountItems(); i++) { CatItem *data = fList->ItemAt(i); BString temp(data->string.String()); IllegalCharsToEntities(&temp); - str << "\t\t\tamount.AsFixed() << "\" />\n"; + str << "\t\t\tamount.AsFixed() + << "\" />\n"; } - + str << "\t\t\n"; - file->Write(str.String(),str.Length()); + file->Write(str.String(), str.Length()); } -void Category::PrintToStream(void) const -{ +void +Category::PrintToStream(void) const { BString str(" "); - - for(int32 i=0; iCountItems(); i++) - { + + for (int32 i = 0; i < fList->CountItems(); i++) { CatItem *data = fList->ItemAt(i); str << data->string.String() << " " << data->amount.AsFixed(); - if(i==fList->CountItems()-1) + if (i == fList->CountItems() - 1) str << " "; else str << "|"; @@ -169,46 +156,40 @@ void Category::PrintToStream(void) const printf(str.String()); } -Category &Category::operator=(const Category &from) -{ +Category & +Category::operator=(const Category &from) { fList->MakeEmpty(); - - for(int32 i=0; iItemAt(i); - fList->AddItem(new CatItem(item->string.String(),item->amount,item->memo.String())); + fList->AddItem(new CatItem(item->string.String(), item->amount, item->memo.String())); } return *this; } -void Category::MakeEmpty(void) -{ +void +Category::MakeEmpty(void) { fList->MakeEmpty(); } -void Category::Sort(void) -{ +void +Category::Sort(void) { fList->SortItems(CompareCatItem); } -int Category::CompareCatItem(const CatItem *item1, const CatItem *item2) -{ - if(!item1) - { - if(item2) +int +Category::CompareCatItem(const CatItem *item1, const CatItem *item2) { + if (!item1) { + if (item2) return 1; else return 0; - } - else - if(!item2) - { - if(item1) + } else if (!item2) { + if (item1) return -1; else return 0; } - + return item1->string.Compare(item2->string); } - diff --git a/src/Category.h b/src/Category.h index 48a7b54..19eaaa6 100644 --- a/src/Category.h +++ b/src/Category.h @@ -1,61 +1,59 @@ #ifndef TYPES_H #define TYPES_H -#include -#include #include "Fixed.h" #include "ObjectList.h" +#include +#include -class Category -{ -public: - Category(const char *string=NULL, const Fixed &fixed=0, const char *memo=NULL); +class Category { + public: + Category(const char *string = NULL, const Fixed &fixed = 0, const char *memo = NULL); Category(const Category &from); ~Category(void); - + void SetNameAt(const int32 &index, const char *string); void SetAmountAt(const int32 &index, const Fixed &fixed); void SetMemoAt(const int32 &index, const char *string); - + const char *NameAt(const int32 &index) const; const char *MemoAt(const int32 &index) const; Fixed AmountAt(const int32 &index) const; - - bool AddItem(const char *name, const Fixed &amount, const char *memo=NULL); + + bool AddItem(const char *name, const Fixed &amount, const char *memo = NULL); bool HasItem(const char *name); bool RemoveItem(const char *name); bool RemoveItem(const int32 &index); + int32 CountItems(void) const { return fList->CountItems(); } - + void Flatten(BFile *file); void PrintToStream(void) const; void Sort(void); - + Category &operator=(const Category &from); void MakeEmpty(void); - -private: - class CatItem - { - public: - CatItem(const char *str=NULL,const Fixed &fixed=0, const char *str2=NULL) - { + + private: + class CatItem { + public: + CatItem(const char *str = NULL, const Fixed &fixed = 0, const char *str2 = NULL) { string = str; amount = fixed; memo = str2; } - CatItem(const CatItem &from) - { + + CatItem(const CatItem &from) { string = from.string; amount = from.amount; memo = from.memo; } - + BString string; Fixed amount; BString memo; }; - + static int CompareCatItem(const CatItem *item1, const CatItem *item2); BObjectList *fList; }; diff --git a/src/CategoryBox.cpp b/src/CategoryBox.cpp index f36788e..3557346 100644 --- a/src/CategoryBox.cpp +++ b/src/CategoryBox.cpp @@ -4,84 +4,79 @@ #include "MsgDefs.h" #include "TimeSupport.h" -CategoryBoxFilter::CategoryBoxFilter(CategoryBox *box) - : AutoTextControlFilter(box) -{ -} +CategoryBoxFilter::CategoryBoxFilter(CategoryBox *box) : AutoTextControlFilter(box) {} -filter_result CategoryBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +CategoryBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB) - { - if(mod & B_SHIFT_KEY) + if (key == B_TAB) { + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; - - if(key<32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && - !(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) ) +#endif + + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; + + if (key < 32 || ((mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && !(mod & B_OPTION_KEY) && + !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - + Account *acc = gDatabase.CurrentAccount(); - if(!acc) + if (!acc) return B_DISPATCH_MESSAGE; - + int32 start, end; - TextControl()->TextView()->GetSelection(&start,&end); - if(end == (int32)strlen(TextControl()->Text())) - { - TextControl()->TextView()->Delete(start,end); - + TextControl()->TextView()->GetSelection(&start, &end); + if (end == (int32)strlen(TextControl()->Text())) { + TextControl()->TextView()->Delete(start, end); + BString string; - if(GetCurrentMessage()->FindString("bytes",&string)!=B_OK) - string=""; + if (GetCurrentMessage()->FindString("bytes", &string) != B_OK) + string = ""; string.Prepend(TextControl()->Text()); - + BString autocomplete = acc->AutocompleteCategory(string.String()); - - if(autocomplete.CountChars()>0) - { + + if (autocomplete.CountChars() > 0) { BMessage automsg(M_CATEGORY_AUTOCOMPLETE); - automsg.AddInt32("start",strlen(TextControl()->Text())+1); - automsg.AddString("string",autocomplete.String()); + automsg.AddInt32("start", strlen(TextControl()->Text()) + 1); + automsg.AddString("string", autocomplete.String()); SendMessage(&automsg); } } - + return B_DISPATCH_MESSAGE; } -CategoryBox::CategoryBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags) -{ +CategoryBox::CategoryBox( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : AutoTextControl(name, label, text, msg, flags) { SetFilter(new CategoryBoxFilter(this)); SetCharacterLimit(32); } -bool CategoryBox::Validate(void) -{ - if(strlen(Text())<1) - { - DAlert *alert = new DAlert("Category is missing.","Do you want to add this transaction " - "without a category?","Add","Cancel",NULL, - B_WIDTH_AS_USUAL,B_WARNING_ALERT); +bool +CategoryBox::Validate(void) { + if (strlen(Text()) < 1) { + DAlert *alert = new DAlert( + "Category is missing.", + "Do you want to add this transaction " + "without a category?", + "Add", "Cancel", NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT + ); int32 value = alert->Go(); - if(value == 0) + if (value == 0) SetText("Uncategorized"); else return false; diff --git a/src/CategoryBox.h b/src/CategoryBox.h index 346d196..6666dfd 100644 --- a/src/CategoryBox.h +++ b/src/CategoryBox.h @@ -5,28 +5,24 @@ class CategoryBox; -enum -{ - M_CATEGORY_AUTOCOMPLETE = 'cata' -}; +enum { M_CATEGORY_AUTOCOMPLETE = 'cata' }; -class CategoryBoxFilter : public AutoTextControlFilter -{ -public: +class CategoryBoxFilter : public AutoTextControlFilter { + public: CategoryBoxFilter(CategoryBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class CategoryBox : public AutoTextControl -{ -public: - CategoryBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class CategoryBox : public AutoTextControl { + public: + CategoryBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); bool Validate(void); - -private: + + private: friend CategoryBoxFilter; }; diff --git a/src/CategoryWindow.cpp b/src/CategoryWindow.cpp index 30003c8..c53f156 100644 --- a/src/CategoryWindow.cpp +++ b/src/CategoryWindow.cpp @@ -2,11 +2,11 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -19,9 +19,8 @@ #include "Preferences.h" #include "Translate.h" -enum -{ - M_SHOW_ADD_WINDOW='shaw', +enum { + M_SHOW_ADD_WINDOW = 'shaw', M_SHOW_REMOVE_WINDOW, M_SHOW_EDIT_WINDOW, M_EDIT_CATEGORY, @@ -30,517 +29,475 @@ enum M_NAME_CHANGED }; -class CategoryItem : public BStringItem -{ -public: +class CategoryItem : public BStringItem { + public: CategoryItem(const BString &name); void DrawItem(BView *owner, BRect frame, bool complete = false); }; -class CategoryView : public BView -{ -public: +class CategoryView : public BView { + public: CategoryView(const char *name, const int32 &flags); void AttachedToWindow(void); void MessageReceived(BMessage *msg); -private: + private: float RefreshCategoryList(void); - - BOutlineListView *fListView; - - BButton *fAddButton, - *fRemoveButton, - *fEditButton; - - CategoryItem *fIncomeItem, - *fSpendingItem; - float fBestWidth; + + BOutlineListView *fListView; + + BButton *fAddButton, *fRemoveButton, *fEditButton; + + CategoryItem *fIncomeItem, *fSpendingItem; + float fBestWidth; }; -class CategoryInputWindow : public BWindow -{ -public: +class CategoryInputWindow : public BWindow { + public: CategoryInputWindow(const BRect &frame, BView *target); void MessageReceived(BMessage *msg); -private: - AutoTextControl *fNameBox; - - BButton *fOKButton, - *fCancelButton; - - BCheckBox *fExpenseBox; - BView *fTarget; + private: + AutoTextControl *fNameBox; + + BButton *fOKButton, *fCancelButton; + + BCheckBox *fExpenseBox; + BView *fTarget; }; -class CategoryEditWindow : public BWindow -{ -public: +class CategoryEditWindow : public BWindow { + public: CategoryEditWindow(const BRect &frame, const char *oldname, BView *target); void MessageReceived(BMessage *msg); -private: - AutoTextControl *fNameBox; - - BButton *fOKButton, - *fCancelButton; - - BString fOldName; - - BView *fTarget; + private: + AutoTextControl *fNameBox; + + BButton *fOKButton, *fCancelButton; + + BString fOldName; + + BView *fTarget; }; -class CategoryRemoveWindow : public BWindow -{ -public: +class CategoryRemoveWindow : public BWindow { + public: CategoryRemoveWindow(const BRect &frame, const char *from, BView *target); void MessageReceived(BMessage *msg); void FrameResized(float w, float h); -private: - - BOutlineListView *fListView; - - CategoryItem *fIncomeItem, - *fSpendingItem; - - BTextView *fDirections; - - BButton *fOKButton, - *fCancelButton; - BView *fTarget; + + private: + BOutlineListView *fListView; + + CategoryItem *fIncomeItem, *fSpendingItem; + + BTextView *fDirections; + + BButton *fOKButton, *fCancelButton; + BView *fTarget; BScrollView *fScrollView; }; -CategoryView::CategoryView(const char *name, const int32 &flags) - : BView(name,flags) -{ +CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, flags) { BString temp; - SetViewColor(240,240,240); - + SetViewColor(240, 240, 240); + // the buttons - temp = TRANSLATE("Edit"); temp+="…"; - fEditButton = new BButton("editbutton",temp.String(), new BMessage(M_SHOW_EDIT_WINDOW)); - - temp = TRANSLATE("Remove"); temp+="…"; - fRemoveButton = new BButton("removebutton",temp.String(), new BMessage(M_SHOW_REMOVE_WINDOW)); - - temp = TRANSLATE("Add"); temp+="…"; - fAddButton = new BButton("addbutton",temp.String(), new BMessage(M_SHOW_ADD_WINDOW)); - + temp = TRANSLATE("Edit"); + temp += "…"; + fEditButton = new BButton("editbutton", temp.String(), new BMessage(M_SHOW_EDIT_WINDOW)); + + temp = TRANSLATE("Remove"); + temp += "…"; + fRemoveButton = new BButton("removebutton", temp.String(), new BMessage(M_SHOW_REMOVE_WINDOW)); + + temp = TRANSLATE("Add"); + temp += "…"; + fAddButton = new BButton("addbutton", temp.String(), new BMessage(M_SHOW_ADD_WINDOW)); + // the category list - fListView = new BOutlineListView("categorylist",B_SINGLE_SELECTION_LIST, - B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE); - BScrollView *sv = new BScrollView("scrollview",fListView,0,false,true); - + fListView = new BOutlineListView( + "categorylist", B_SINGLE_SELECTION_LIST, + B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE + ); + BScrollView *sv = new BScrollView("scrollview", fListView, 0, false, true); + fIncomeItem = new CategoryItem(TRANSLATE("Income")); fSpendingItem = new CategoryItem(TRANSLATE("Spending")); RefreshCategoryList(); - + BLayoutBuilder::Group<>(this, B_VERTICAL) .SetInsets(15, 15) .AddGrid(1.0f, 1.0f) - .Add(sv, 0, 0, 4) - .AddGrid(1.0f, 1.0f, 0, 1, 4) - .Add(fEditButton, 0, 0) - .Add(fRemoveButton, 1, 0) - .Add(fAddButton, 2, 0) - .AddGlue(3, 0) - .End() + .Add(sv, 0, 0, 4) + .AddGrid(1.0f, 1.0f, 0, 1, 4) + .Add(fEditButton, 0, 0) + .Add(fRemoveButton, 1, 0) + .Add(fAddButton, 2, 0) + .AddGlue(3, 0) .End() - .End(); + .End() + .End(); } -void CategoryView::AttachedToWindow(void) -{ +void +CategoryView::AttachedToWindow(void) { fListView->SetTarget(this); fEditButton->SetTarget(this); fAddButton->SetTarget(this); fRemoveButton->SetTarget(this); - + fListView->Select(0); - + fListView->MakeFocus(true); } -void CategoryView::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_SHOW_ADD_WINDOW: - { - BRect r(Window()->Frame()); - CategoryInputWindow *catwin = new CategoryInputWindow(BRect(100,100,300,225),this); - catwin->MoveTo(r.left + ((Bounds().Width()-catwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-catwin->Bounds().Height())/2) ); - catwin->Show(); +void +CategoryView::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_SHOW_ADD_WINDOW: { + BRect r(Window()->Frame()); + CategoryInputWindow *catwin = new CategoryInputWindow(BRect(100, 100, 300, 225), this); + catwin->MoveTo( + r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) + ); + catwin->Show(); + break; + } + case M_SHOW_REMOVE_WINDOW: { + int32 index = fListView->CurrentSelection(); + CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + + if (!item || item == fIncomeItem || item == fSpendingItem) break; - } - case M_SHOW_REMOVE_WINDOW: - { - int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem*)fListView->ItemAt(index); - - if(!item || item==fIncomeItem || item==fSpendingItem) - break; - - BRect r(Window()->Frame()); - CategoryRemoveWindow *catwin = new CategoryRemoveWindow(r,item->Text(),this); - catwin->MoveTo(r.left + ((Bounds().Width()-catwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-catwin->Bounds().Height())/2) ); - catwin->Show(); + + BRect r(Window()->Frame()); + CategoryRemoveWindow *catwin = new CategoryRemoveWindow(r, item->Text(), this); + catwin->MoveTo( + r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) + ); + catwin->Show(); + break; + } + case M_SHOW_EDIT_WINDOW: { + int32 index = fListView->CurrentSelection(); + CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + + if (!item || item == fIncomeItem || item == fSpendingItem) break; - } - case M_SHOW_EDIT_WINDOW: - { - int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem*)fListView->ItemAt(index); - - if(!item || item==fIncomeItem || item==fSpendingItem) - break; - - BRect r(Window()->Frame()); - CategoryEditWindow *catwin = new CategoryEditWindow(r,item->Text(),this); - catwin->MoveTo(r.left + ((Bounds().Width()-catwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-catwin->Bounds().Height())/2) ); - catwin->Show(); + + BRect r(Window()->Frame()); + CategoryEditWindow *catwin = new CategoryEditWindow(r, item->Text(), this); + catwin->MoveTo( + r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) + ); + catwin->Show(); + break; + } + case M_ADD_CATEGORY: { + BString name; + bool expense; + if (msg->FindString("name", &name) != B_OK || msg->FindBool("expense", &expense) != B_OK) break; - } - case M_ADD_CATEGORY: - { - BString name; - bool expense; - if(msg->FindString("name",&name)!=B_OK || - msg->FindBool("expense",&expense)!=B_OK) - break; - - if(name.ICompare(TRANSLATE("Income"))==0 || name.ICompare(TRANSLATE("Spending"))==0 || - name.ICompare(TRANSLATE("Split"))==0) - { - ShowAlert(TRANSLATE("Can't use this category name"), - TRANSLATE("Capital Be uses the words 'Income','Spending', and 'Split' " - "for managing categories, so you can't use them as category names. " - "Please choose a different name for your new category.")); - break; - } - - gDatabase.AddCategory(name.String(),expense); - RefreshCategoryList(); + + if (name.ICompare(TRANSLATE("Income")) == 0 || name.ICompare(TRANSLATE("Spending")) == 0 || + name.ICompare(TRANSLATE("Split")) == 0) { + ShowAlert( + TRANSLATE("Can't use this category name"), + TRANSLATE("Capital Be uses the words 'Income','Spending', and 'Split' " + "for managing categories, so you can't use them as category names. " + "Please choose a different name for your new category.") + ); break; } - case M_REMOVE_CATEGORY: - { - BString newcat; - if(msg->FindString("newcat",&newcat)!=B_OK) - break; - - int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem*)fListView->ItemAt(index); - - if(!item || item==fIncomeItem || item==fSpendingItem) - break; - - gDatabase.RecategorizeTransactions(item->Text(), newcat.String()); - gDatabase.RemoveCategory(item->Text()); - RefreshCategoryList(); - + + gDatabase.AddCategory(name.String(), expense); + RefreshCategoryList(); + break; + } + case M_REMOVE_CATEGORY: { + BString newcat; + if (msg->FindString("newcat", &newcat) != B_OK) break; - } - case M_EDIT_CATEGORY: - { - - BString newname; - if(msg->FindString("newname",&newname)!=B_OK) - break; - - int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem*)fListView->ItemAt(index); - - if(!item || item==fIncomeItem || item==fSpendingItem) - break; - - gDatabase.RecategorizeTransactions(item->Text(), newname.String()); - gDatabase.RemoveCategory(item->Text()); - RefreshCategoryList(); + + int32 index = fListView->CurrentSelection(); + CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + + if (!item || item == fIncomeItem || item == fSpendingItem) break; - } - default: - { - BView::MessageReceived(msg); + + gDatabase.RecategorizeTransactions(item->Text(), newcat.String()); + gDatabase.RemoveCategory(item->Text()); + RefreshCategoryList(); + + break; + } + case M_EDIT_CATEGORY: { + + BString newname; + if (msg->FindString("newname", &newname) != B_OK) break; - } + + int32 index = fListView->CurrentSelection(); + CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + + if (!item || item == fIncomeItem || item == fSpendingItem) + break; + + gDatabase.RecategorizeTransactions(item->Text(), newname.String()); + gDatabase.RemoveCategory(item->Text()); + RefreshCategoryList(); + break; + } + default: { + BView::MessageReceived(msg); + break; + } } } -float CategoryView::RefreshCategoryList(void) -{ - if(fListView->CountItems()>0) - { - if(fListView->HasItem(fIncomeItem)) +float +CategoryView::RefreshCategoryList(void) { + if (fListView->CountItems() > 0) { + if (fListView->HasItem(fIncomeItem)) fListView->RemoveItem(fIncomeItem); - if(fListView->HasItem(fSpendingItem)) + if (fListView->HasItem(fSpendingItem)) fListView->RemoveItem(fSpendingItem); - + fListView->MakeEmpty(); } fListView->AddItem(fIncomeItem); fListView->AddItem(fSpendingItem); - + int32 maxchars; float maxlength; - if(strlen(TRANSLATE("Income"))>strlen(TRANSLATE("Spending"))) - { + if (strlen(TRANSLATE("Income")) > strlen(TRANSLATE("Spending"))) { maxchars = strlen(TRANSLATE("Income")); maxlength = StringWidth(TRANSLATE("Income")); - } - else - { + } else { maxchars = strlen(TRANSLATE("Spending")); maxlength = StringWidth(TRANSLATE("Spending")); } - - CppSQLite3Query query = gDatabase.DBQuery("select * from categorylist order by name desc", - "CategoryView::CategoryView"); - while(!query.eof()) - { + + CppSQLite3Query query = gDatabase.DBQuery( + "select * from categorylist order by name desc", "CategoryView::CategoryView" + ); + while (!query.eof()) { int expense = query.getIntField(1); BString name = query.getStringField(0); - - if(expense==0) - fListView->AddUnder(new CategoryItem(DeescapeIllegalCharacters(name.String())), - fSpendingItem); + + if (expense == 0) + fListView->AddUnder( + new CategoryItem(DeescapeIllegalCharacters(name.String())), fSpendingItem + ); else - fListView->AddUnder(new CategoryItem(DeescapeIllegalCharacters(name.String())), - fIncomeItem); - - if(name.CountChars()>maxchars) - { + fListView->AddUnder( + new CategoryItem(DeescapeIllegalCharacters(name.String())), fIncomeItem + ); + + if (name.CountChars() > maxchars) { maxchars = name.CountChars(); maxlength = StringWidth(name.String()); } - + query.nextRow(); } - + return maxlength; } CategoryWindow::CategoryWindow(const BRect &frame) - : BWindow(frame,TRANSLATE("Categories"),B_DOCUMENT_WINDOW_LOOK,B_NORMAL_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) -{ + : BWindow( + frame, TRANSLATE("Categories"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ) { AddCommonFilter(new EscapeCancelFilter); - - CategoryView *view = new CategoryView("categoryview" ,B_WILL_DRAW); - - AddShortcut('A',B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW),view); - AddShortcut('R',B_COMMAND_KEY, new BMessage(M_REMOVE_CATEGORY),view); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(view) - .End(); -} + CategoryView *view = new CategoryView("categoryview", B_WILL_DRAW); -CategoryItem::CategoryItem(const BString &name) - : BStringItem(name.String()) -{ + AddShortcut('A', B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW), view); + AddShortcut('R', B_COMMAND_KEY, new BMessage(M_REMOVE_CATEGORY), view); + + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); } -void CategoryItem::DrawItem(BView *owner, BRect frame, bool complete) -{ - if(IsSelected()) - { +CategoryItem::CategoryItem(const BString &name) : BStringItem(name.String()) {} + +void +CategoryItem::DrawItem(BView *owner, BRect frame, bool complete) { + if (IsSelected()) { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); - } - else - { + } else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); } owner->FillRect(frame); - if(IsSelected()) - { + if (IsSelected()) { owner->SetHighColor(100, 100, 100); owner->StrokeRect(frame); } - - owner->SetHighColor(0,0,0); - + + owner->SetHighColor(0, 0, 0); + BRegion region(frame); owner->ConstrainClippingRegion(®ion); - owner->DrawString(Text(),BPoint(frame.left+1,frame.bottom-2)); + owner->DrawString(Text(), BPoint(frame.left + 1, frame.bottom - 2)); owner->ConstrainClippingRegion(NULL); } CategoryInputWindow::CategoryInputWindow(const BRect &frame, BView *target) - : BWindow(frame,TRANSLATE("Add Category"),B_FLOATING_WINDOW_LOOK,B_MODAL_APP_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | - B_NOT_V_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fTarget(target) -{ + : BWindow( + frame, TRANSLATE("Add Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_V_RESIZABLE | + B_AUTO_UPDATE_SIZE_LIMITS + ), + fTarget(target) { BString temp; AddCommonFilter(new EscapeCancelFilter); - AddShortcut('W',B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - - BView *view = new BView("background",B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(view) - .End(); - view->SetViewColor(240,240,240); - - temp = TRANSLATE("Category Name"); temp+=":"; - fNameBox = new AutoTextControl("namebox",temp.String(), - "",new BMessage(M_NAME_CHANGED)); + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + + BView *view = new BView("background", B_WILL_DRAW); + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); + view->SetViewColor(240, 240, 240); + + temp = TRANSLATE("Category Name"); + temp += ":"; + fNameBox = new AutoTextControl("namebox", temp.String(), "", new BMessage(M_NAME_CHANGED)); fNameBox->SetCharacterLimit(32); - - fExpenseBox = new BCheckBox("expensebox",TRANSLATE("Spending Category"),NULL); + + fExpenseBox = new BCheckBox("expensebox", TRANSLATE("Spending Category"), NULL); fExpenseBox->SetValue(B_CONTROL_ON); - - fOKButton = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_ADD_CATEGORY)); - fOKButton->SetLabel(TRANSLATE("OK")); + + fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_ADD_CATEGORY)); + fOKButton->SetLabel(TRANSLATE("OK")); fOKButton->MakeDefault(true); - fCancelButton = new BButton("cancelbutton",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); + fCancelButton = + new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); fNameBox->MakeFocus(true); - + BLayoutBuilder::Group<>(this, B_VERTICAL) .SetInsets(10) .Add(fNameBox) .Add(fExpenseBox) .AddGrid(1.0f, 1.0f) - .Add(fCancelButton, 0, 0) - .Add(fOKButton, 1, 0) + .Add(fCancelButton, 0, 0) + .Add(fOKButton, 1, 0) .End() - .End(); + .End(); } -void CategoryInputWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_NAME_CHANGED: - { - if(strlen(fNameBox->Text())>0) - { - if(!fOKButton->IsEnabled()) - fOKButton->SetEnabled(true); - } - else - { - if(fOKButton->IsEnabled()) - fOKButton->SetEnabled(false); - } - break; - } - case M_ADD_CATEGORY: - { - BMessenger msgr(fTarget); - msg->AddString("name",fNameBox->Text()); - msg->AddBool("expense",fExpenseBox->Value() == B_CONTROL_ON); - msgr.SendMessage(msg); - break; - } - default: - { - BWindow::MessageReceived(msg); - break; +void +CategoryInputWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_NAME_CHANGED: { + if (strlen(fNameBox->Text()) > 0) { + if (!fOKButton->IsEnabled()) + fOKButton->SetEnabled(true); + } else { + if (fOKButton->IsEnabled()) + fOKButton->SetEnabled(false); } + break; + } + case M_ADD_CATEGORY: { + BMessenger msgr(fTarget); + msg->AddString("name", fNameBox->Text()); + msg->AddBool("expense", fExpenseBox->Value() == B_CONTROL_ON); + msgr.SendMessage(msg); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, BView *target) - : BWindow(frame,TRANSLATE("Remove Category"),B_FLOATING_WINDOW_LOOK,B_MODAL_APP_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fTarget(target) -{ - rgb_color backcolor = {240,240,240,255}; - + : BWindow( + frame, TRANSLATE("Remove Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS + ), + fTarget(target) { + rgb_color backcolor = {240, 240, 240, 255}; + AddCommonFilter(new EscapeCancelFilter); - AddShortcut('W',B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *view = new BView("background",B_WILL_DRAW | B_FRAME_EVENTS); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(view) - .End(); + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + BView *view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(backcolor); - + fDirections = new BTextView("directions"); fDirections->MakeEditable(false); - + BString directions( TRANSLATE("Please choose a new category for all transactions currently in the " - "%%CATEGORY_NAME%% category.")); - directions.ReplaceFirst("%%CATEGORY_NAME%%",from); + "%%CATEGORY_NAME%% category.") + ); + directions.ReplaceFirst("%%CATEGORY_NAME%%", from); fDirections->SetText(directions.String()); fDirections->SetViewColor(backcolor); fDirections->SetWordWrap(true); - - fOKButton = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_REMOVE_CATEGORY)); - + + fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_REMOVE_CATEGORY)); + fOKButton->SetLabel(TRANSLATE("OK")); - fCancelButton = new BButton("cancelbutton",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); - - fListView = new BOutlineListView("categorylist",B_SINGLE_SELECTION_LIST, - B_WILL_DRAW | B_FRAME_EVENTS | - B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE); - fScrollView = new BScrollView("scrollview",fListView,0, - false,true); - + fCancelButton = + new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + + fListView = new BOutlineListView( + "categorylist", B_SINGLE_SELECTION_LIST, + B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE + ); + fScrollView = new BScrollView("scrollview", fListView, 0, false, true); + fIncomeItem = new CategoryItem(TRANSLATE("Income")); fSpendingItem = new CategoryItem(TRANSLATE("Spending")); fListView->AddItem(fIncomeItem); fListView->AddItem(fSpendingItem); - - CppSQLite3Query query = gDatabase.DBQuery("select * from categorylist order by name desc", - "CategoryView::CategoryView"); - + + CppSQLite3Query query = gDatabase.DBQuery( + "select * from categorylist order by name desc", "CategoryView::CategoryView" + ); + int32 maxchars; float maxlength; - if(strlen(TRANSLATE("Income"))>strlen(TRANSLATE("Spending"))) - { + if (strlen(TRANSLATE("Income")) > strlen(TRANSLATE("Spending"))) { maxchars = strlen(TRANSLATE("Income")); maxlength = view->StringWidth(TRANSLATE("Income")); - } - else - { + } else { maxchars = strlen(TRANSLATE("Spending")); maxlength = view->StringWidth(TRANSLATE("Spending")); } - - while(!query.eof()) - { + + while (!query.eof()) { int expense = query.getIntField(1); BString name = DeescapeIllegalCharacters(query.getStringField(0)); - - if(name.Compare(from)==0) - { + + if (name.Compare(from) == 0) { query.nextRow(); continue; } - - if(expense==0) - fListView->AddUnder(new CategoryItem(name.String()), - fSpendingItem); + + if (expense == 0) + fListView->AddUnder(new CategoryItem(name.String()), fSpendingItem); else - fListView->AddUnder(new CategoryItem(name.String()), - fIncomeItem); - - if(name.CountChars()>maxchars) - { + fListView->AddUnder(new CategoryItem(name.String()), fIncomeItem); + + if (name.CountChars() > maxchars) { maxchars = name.CountChars(); maxlength = view->StringWidth(name.String()); } - + query.nextRow(); } @@ -549,80 +506,72 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, .Add(fDirections, 1) .Add(fScrollView, 2) .AddGrid(1.0f, 1.0f) - .AddGlue(0, 0) - .Add(fCancelButton, 1, 0) - .Add(fOKButton, 2, 0) + .AddGlue(0, 0) + .Add(fCancelButton, 1, 0) + .Add(fOKButton, 2, 0) .End() - .End(); + .End(); } -void CategoryRemoveWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_REMOVE_CATEGORY: - { - int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem*)fListView->ItemAt(index); - - if(!item || item==fIncomeItem || item==fSpendingItem) - break; - - BMessenger msgr(fTarget); - msg->AddString("newcat",item->Text()); - msgr.SendMessage(msg); - - PostMessage(B_QUIT_REQUESTED); - break; - } - default: - { - BWindow::MessageReceived(msg); +void +CategoryRemoveWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_REMOVE_CATEGORY: { + int32 index = fListView->CurrentSelection(); + CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + + if (!item || item == fIncomeItem || item == fSpendingItem) break; - } - } -} -void CategoryRemoveWindow::FrameResized(float w, float h) -{ + BMessenger msgr(fTarget); + msg->AddString("newcat", item->Text()); + msgr.SendMessage(msg); + PostMessage(B_QUIT_REQUESTED); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } + } } +void +CategoryRemoveWindow::FrameResized(float w, float h) {} + CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, BView *target) - : BWindow(frame,TRANSLATE("Edit Category"),B_FLOATING_WINDOW_LOOK,B_MODAL_APP_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | - B_AUTO_UPDATE_SIZE_LIMITS), - fOldName(oldname), - fTarget(target) -{ + : BWindow( + frame, TRANSLATE("Edit Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | + B_AUTO_UPDATE_SIZE_LIMITS + ), + fOldName(oldname), fTarget(target) { BString temp; AddCommonFilter(new EscapeCancelFilter); - AddShortcut('W',B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - - BView *view = new BView("background",B_WILL_DRAW | B_FRAME_EVENTS); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(view) - .End(); - view->SetViewColor(240,240,240); - - temp = TRANSLATE("Category Name"); temp << ": " << fOldName; - BStringView *oldnameView = new BStringView("oldname",temp.String()); - - temp = TRANSLATE("New Category Name"); temp+=":"; - fNameBox = new AutoTextControl("namebox",temp.String(),"", - new BMessage(M_NAME_CHANGED)); + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + + BView *view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); + view->SetViewColor(240, 240, 240); + + temp = TRANSLATE("Category Name"); + temp << ": " << fOldName; + BStringView *oldnameView = new BStringView("oldname", temp.String()); + + temp = TRANSLATE("New Category Name"); + temp += ":"; + fNameBox = new AutoTextControl("namebox", temp.String(), "", new BMessage(M_NAME_CHANGED)); fNameBox->SetCharacterLimit(32); - - fOKButton = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_EDIT_CATEGORY)); + + fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_CATEGORY)); fOKButton->SetFlags(fOKButton->Flags() | B_FRAME_EVENTS); fOKButton->SetLabel(TRANSLATE("OK")); fOKButton->MakeDefault(true); - fCancelButton = new BButton("cancelbutton",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); - + fCancelButton = + new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + fOKButton->SetEnabled(false); fNameBox->MakeFocus(true); @@ -631,42 +580,35 @@ CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, .Add(oldnameView) .Add(fNameBox) .AddGrid(1.0f, 1.0f) - .Add(fCancelButton, 0, 0) - .Add(fOKButton, 1, 0) + .Add(fCancelButton, 0, 0) + .Add(fOKButton, 1, 0) .End() - .End(); + .End(); } -void CategoryEditWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_NAME_CHANGED: - { - if(strlen(fNameBox->Text())>0) - { - if(!fOKButton->IsEnabled()) - fOKButton->SetEnabled(true); - } - else - { - if(fOKButton->IsEnabled()) - fOKButton->SetEnabled(false); - } - break; - } - case M_EDIT_CATEGORY: - { - BMessenger msgr(fTarget); - msg->AddString("newname",fNameBox->Text()); - msgr.SendMessage(msg); - PostMessage(B_QUIT_REQUESTED); - break; - } - default: - { - BWindow::MessageReceived(msg); - break; +void +CategoryEditWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_NAME_CHANGED: { + if (strlen(fNameBox->Text()) > 0) { + if (!fOKButton->IsEnabled()) + fOKButton->SetEnabled(true); + } else { + if (fOKButton->IsEnabled()) + fOKButton->SetEnabled(false); } + break; + } + case M_EDIT_CATEGORY: { + BMessenger msgr(fTarget); + msg->AddString("newname", fNameBox->Text()); + msgr.SendMessage(msg); + PostMessage(B_QUIT_REQUESTED); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } diff --git a/src/CategoryWindow.h b/src/CategoryWindow.h index e8757f7..e84b323 100644 --- a/src/CategoryWindow.h +++ b/src/CategoryWindow.h @@ -3,9 +3,8 @@ #include -class CategoryWindow : public BWindow -{ -public: +class CategoryWindow : public BWindow { + public: CategoryWindow(const BRect &frame); }; diff --git a/src/CheckNumBox.cpp b/src/CheckNumBox.cpp index b5c3e3b..4d9e4a9 100644 --- a/src/CheckNumBox.cpp +++ b/src/CheckNumBox.cpp @@ -5,117 +5,100 @@ #include "TimeSupport.h" #include "Translate.h" -CheckNumBoxFilter::CheckNumBoxFilter(CheckNumBox *box) - : AutoTextControlFilter(box) -{ -} +CheckNumBoxFilter::CheckNumBoxFilter(CheckNumBox *box) : AutoTextControlFilter(box) {} -filter_result CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB) - { - if(mod & B_SHIFT_KEY) + if (key == B_TAB) { + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; +#endif + + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; - if(key<32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && - !(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) ) + if (key < 32 || ((mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && !(mod & B_OPTION_KEY) && + !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - + Account *acc = gDatabase.CurrentAccount(); - if(!acc) + if (!acc) return B_DISPATCH_MESSAGE; - + int32 start, end; - TextControl()->TextView()->GetSelection(&start,&end); + TextControl()->TextView()->GetSelection(&start, &end); BString string, autocomplete; int32 length = strlen(TextControl()->Text()); - + BString keystring; - GetCurrentMessage()->FindString("bytes",&keystring); - - if(keystring=="+") - { - if(strlen(TextControl()->Text())>0) - { + GetCurrentMessage()->FindString("bytes", &keystring); + + if (keystring == "+") { + if (strlen(TextControl()->Text()) > 0) { uint16 num = acc->LastCheckNumber() + 1; acc->SetLastCheckNumber(num); - - string << (num+1); - } - else + + string << (num + 1); + } else string << acc->LastCheckNumber() + 1; - + TextControl()->SetText(string.String()); TextControl()->TextView()->SelectAll(); return B_SKIP_MESSAGE; - } - else - if(keystring=="-") - { -// if(strlen(TextControl()->Text())>0) - if(length>0) - { + } else if (keystring == "-") { + // if(strlen(TextControl()->Text())>0) + if (length > 0) { uint16 num = acc->LastCheckNumber() - 1; acc->SetLastCheckNumber(num); - - string << (num+1); - } - else + + string << (num + 1); + } else string << acc->LastCheckNumber() + 1; - + TextControl()->SetText(string.String()); TextControl()->TextView()->SelectAll(); return B_SKIP_MESSAGE; - } - else -// if(end == (int32)strlen(TextControl()->Text())) - if(end == length) - { - TextControl()->TextView()->Delete(start,end); - - if(GetCurrentMessage()->FindString("bytes",&string)!=B_OK) - string=""; - string.Prepend(TextControl()->Text()); - - autocomplete = acc->AutocompleteType(string.String()); - if(autocomplete.CountChars()>0) - { - BMessage automsg(M_TYPE_AUTOCOMPLETE); - automsg.AddInt32("start",strlen(TextControl()->Text())+1); - automsg.AddString("string",autocomplete.String()); - SendMessage(&automsg); + } else + // if(end == (int32)strlen(TextControl()->Text())) + if (end == length) { + TextControl()->TextView()->Delete(start, end); + + if (GetCurrentMessage()->FindString("bytes", &string) != B_OK) + string = ""; + string.Prepend(TextControl()->Text()); + + autocomplete = acc->AutocompleteType(string.String()); + if (autocomplete.CountChars() > 0) { + BMessage automsg(M_TYPE_AUTOCOMPLETE); + automsg.AddInt32("start", strlen(TextControl()->Text()) + 1); + automsg.AddString("string", autocomplete.String()); + SendMessage(&automsg); + } } - } - + return B_DISPATCH_MESSAGE; } -CheckNumBox::CheckNumBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags) -{ +CheckNumBox::CheckNumBox( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : AutoTextControl(name, label, text, msg, flags) { SetFilter(new CheckNumBoxFilter(this)); - const char type_disallowed[]="`~!@#$%^&*()_-+={[}]|\\;:'\"<>?"; - int32 i=0; - while(type_disallowed[i]) - { + const char type_disallowed[] = "`~!@#$%^&*()_-+={[}]|\\;:'\"<>?"; + int32 i = 0; + while (type_disallowed[i]) { TextView()->DisallowChar(type_disallowed[i]); i++; } @@ -123,14 +106,15 @@ CheckNumBox::CheckNumBox(const char *name, const char *label, SetCharacterLimit(8); } -bool CheckNumBox::Validate(void) -{ - if(strlen(Text())<1) - { - ShowAlert(TRANSLATE("Transaction type is missing."), - TRANSLATE("You need to enter a check number or transaction type, such as " - "ATM (for debit card transactions and the like), DEP (for deposits), " - "or your own code for some other kind of expense.")); +bool +CheckNumBox::Validate(void) { + if (strlen(Text()) < 1) { + ShowAlert( + TRANSLATE("Transaction type is missing."), + TRANSLATE("You need to enter a check number or transaction type, such as " + "ATM (for debit card transactions and the like), DEP (for deposits), " + "or your own code for some other kind of expense.") + ); MakeFocus(true); return false; } diff --git a/src/CheckNumBox.h b/src/CheckNumBox.h index 5f3ced7..27a2f97 100644 --- a/src/CheckNumBox.h +++ b/src/CheckNumBox.h @@ -3,29 +3,26 @@ #include "AutoTextControl.h" -enum -{ - M_TYPE_AUTOCOMPLETE='tyac' -}; +enum { M_TYPE_AUTOCOMPLETE = 'tyac' }; class CheckNumBox; -class CheckNumBoxFilter : public AutoTextControlFilter -{ -public: +class CheckNumBoxFilter : public AutoTextControlFilter { + public: CheckNumBoxFilter(CheckNumBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class CheckNumBox : public AutoTextControl -{ -public: - CheckNumBox(const char *name, const char *label, const char *text, - BMessage *msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE); - +class CheckNumBox : public AutoTextControl { + public: + CheckNumBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); + bool Validate(void); - -private: + + private: friend CheckNumBoxFilter; }; diff --git a/src/CheckView.cpp b/src/CheckView.cpp index f5a119f..6a0666e 100644 --- a/src/CheckView.cpp +++ b/src/CheckView.cpp @@ -19,83 +19,76 @@ #include "NavTextBox.h" #include "PayeeBox.h" #include "Preferences.h" +#include "TimeSupport.h" #include "TransactionData.h" #include "Translate.h" -#include "TimeSupport.h" -enum -{ - M_ENTER_TRANSACTION='entr' -}; - -CheckView::CheckView(const char *name, int32 flags) - : BView(name,flags | B_FRAME_EVENTS) -{ - fDateLabel = new BStringView("datelabel",TRANSLATE("Date")); - fDate = new DateBox("dateentry","",NULL,new BMessage(M_DATE_CHANGED)); - - fTypeLabel=new BStringView("typelabel",TRANSLATE("Type")); - fType = new CheckNumBox("typeentry","",NULL,new BMessage(M_TYPE_CHANGED)); - - fPayeeLabel = new BStringView("payeelabel",TRANSLATE("Payee")); - fPayee = new PayeeBox("payeeentry","",NULL,new BMessage(M_PAYEE_CHANGED)); - - fAmountLabel = new BStringView("amountlabel",TRANSLATE("Amount")); - fAmount = new CurrencyBox("amountentry","","",new BMessage(M_AMOUNT_CHANGED)); - - fCategoryLabel = new BStringView("categorylabel",TRANSLATE("Category")); - fCategory = new CategoryBox("categoryentry","",NULL,new BMessage(M_CATEGORY_CHANGED)); - - fMemoLabel = new BStringView("memolabel",TRANSLATE("Memo")); - fMemo = new NavTextBox("memoentry","",NULL,new BMessage(M_MEMO_CHANGED)); +enum { M_ENTER_TRANSACTION = 'entr' }; + +CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { + fDateLabel = new BStringView("datelabel", TRANSLATE("Date")); + fDate = new DateBox("dateentry", "", NULL, new BMessage(M_DATE_CHANGED)); + + fTypeLabel = new BStringView("typelabel", TRANSLATE("Type")); + fType = new CheckNumBox("typeentry", "", NULL, new BMessage(M_TYPE_CHANGED)); + + fPayeeLabel = new BStringView("payeelabel", TRANSLATE("Payee")); + fPayee = new PayeeBox("payeeentry", "", NULL, new BMessage(M_PAYEE_CHANGED)); + + fAmountLabel = new BStringView("amountlabel", TRANSLATE("Amount")); + fAmount = new CurrencyBox("amountentry", "", "", new BMessage(M_AMOUNT_CHANGED)); + + fCategoryLabel = new BStringView("categorylabel", TRANSLATE("Category")); + fCategory = new CategoryBox("categoryentry", "", NULL, new BMessage(M_CATEGORY_CHANGED)); + + fMemoLabel = new BStringView("memolabel", TRANSLATE("Memo")); + fMemo = new NavTextBox("memoentry", "", NULL, new BMessage(M_MEMO_CHANGED)); fMemo->TextView()->DisallowChar(B_ESCAPE); fMemo->SetCharacterLimit(21); - + prefsLock.Lock(); BString rechelp = gAppPath; prefsLock.Unlock(); rechelp << "helpfiles/" << gCurrentLanguage->Name() << "/Main Window Help"; - fHelpButton = new HelpButton("rechelp",rechelp.String()); - - fEnter = new BButton("enterbutton",TRANSLATE("Enter"),new BMessage(M_ENTER_TRANSACTION)); - - #ifndef ENTER_NAVIGATION + fHelpButton = new HelpButton("rechelp", rechelp.String()); + + fEnter = new BButton("enterbutton", TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); + +#ifndef ENTER_NAVIGATION fEnter->MakeDefault(true); - #endif - -// #ifndef ENTER_NAVIGATION -// fEnter->MoveBy(0,-8); -// #endif - +#endif + + // #ifndef ENTER_NAVIGATION + // fEnter->MoveBy(0,-8); + // #endif + gDatabase.AddObserver(this); - + BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .SetInsets(0) .AddGrid(1.0f, 0.0f) - .Add(fDateLabel, 0, 0) - .Add(fDate, 0, 1, 2) - .Add(fTypeLabel, 2, 0) - .Add(fType, 2, 1) - .Add(fPayeeLabel, 3, 0) - .Add(fPayee, 3, 1, 2) - .Add(fAmountLabel, 5, 0) - .Add(fAmount, 5, 1, 2) - .Add(fCategoryLabel, 0, 2) - .Add(fCategory, 0, 3, 3) - .Add(fMemoLabel, 3, 2) - .Add(fMemo, 3, 3, 4) - .Add(fHelpButton, 0, 5) - .Add(fEnter, 6, 5) + .Add(fDateLabel, 0, 0) + .Add(fDate, 0, 1, 2) + .Add(fTypeLabel, 2, 0) + .Add(fType, 2, 1) + .Add(fPayeeLabel, 3, 0) + .Add(fPayee, 3, 1, 2) + .Add(fAmountLabel, 5, 0) + .Add(fAmount, 5, 1, 2) + .Add(fCategoryLabel, 0, 2) + .Add(fCategory, 0, 3, 3) + .Add(fMemoLabel, 3, 2) + .Add(fMemo, 3, 3, 4) + .Add(fHelpButton, 0, 5) + .Add(fEnter, 6, 5) .End() - .End(); + .End(); } -CheckView::~CheckView(void) -{ -} +CheckView::~CheckView(void) {} -void CheckView::AttachedToWindow(void) -{ +void +CheckView::AttachedToWindow(void) { SetViewColor(Parent()->ViewColor()); fDate->GetFilter()->SetMessenger(new BMessenger(this)); fPayee->GetFilter()->SetMessenger(new BMessenger(this)); @@ -103,166 +96,147 @@ void CheckView::AttachedToWindow(void) fAmount->GetFilter()->SetMessenger(new BMessenger(this)); fCategory->GetFilter()->SetMessenger(new BMessenger(this)); fMemo->GetFilter()->SetMessenger(new BMessenger(this)); - + fEnter->SetTarget(this); } -void CheckView::MessageReceived(BMessage *msg) -{ +void +CheckView::MessageReceived(BMessage *msg) { int32 start; BString string; - switch(msg->what) - { - case M_TYPE_AUTOCOMPLETE: - { - msg->FindInt32("start",&start); - msg->FindString("string",&string); - fType->SetText(string.String()); - fType->TextView()->Select(start,string.CountChars()); + switch (msg->what) { + case M_TYPE_AUTOCOMPLETE: { + msg->FindInt32("start", &start); + msg->FindString("string", &string); + fType->SetText(string.String()); + fType->TextView()->Select(start, string.CountChars()); + break; + } + case M_PAYEE_AUTOCOMPLETE: { + msg->FindInt32("start", &start); + msg->FindString("string", &string); + fPayee->SetText(string.String()); + fPayee->TextView()->Select(start, string.CountChars()); + break; + } + case M_CATEGORY_AUTOCOMPLETE: { + msg->FindInt32("start", &start); + msg->FindString("string", &string); + fCategory->SetText(string.String()); + fCategory->TextView()->Select(start, string.CountChars()); + break; + } + +#ifdef ENTER_NAVIGATION + + case M_ENTER_NAVIGATION: { + if (!fMemo->ChildAt(0)->IsFocus()) { + DoNextField(); break; } - case M_PAYEE_AUTOCOMPLETE: - { - msg->FindInt32("start",&start); - msg->FindString("string",&string); - fPayee->SetText(string.String()); - fPayee->TextView()->Select(start,string.CountChars()); + + // fall through to the next case + } + +#endif + + case M_ENTER_TRANSACTION: { + // The text filter sends this message whenever the user hits Enter + // from the Memo field. The CheckView instance should do whatever is + // needed to post the transaction into the register + +#ifdef DEMO_MODE + Account *demoacc = gDatabase.CurrentAccount(); + if (demoacc && demoacc->CountTransactions() >= 25) { + ShowAlert( + TRANSLATE("Demo Mode Limit"), + TRANSLATE( + "The Demo Mode limit has been reached on this account.", + "You can manually enter up to 25 transactions per " + "account. We hope that you like Capital Be and will " + "purchase the full version. Have a nice day!" + ), + B_IDEA_ALERT + ); + MakeEmpty(); break; } - case M_CATEGORY_AUTOCOMPLETE: - { - msg->FindInt32("start",&start); - msg->FindString("string",&string); - fCategory->SetText(string.String()); - fCategory->TextView()->Select(start,string.CountChars()); + +#endif + + if (!fDate->Validate() || !fType->Validate() || !fPayee->Validate() || + !fAmount->Validate() || !fCategory->Validate()) break; - } - - #ifdef ENTER_NAVIGATION - - case M_ENTER_NAVIGATION: - { - if(!fMemo->ChildAt(0)->IsFocus()) - { - DoNextField(); - break; - } - - // fall through to the next case - } - - #endif - - case M_ENTER_TRANSACTION: - { - // The text filter sends this message whenever the user hits Enter - // from the Memo field. The CheckView instance should do whatever is - // needed to post the transaction into the register - - #ifdef DEMO_MODE - Account *demoacc=gDatabase.CurrentAccount(); - if(demoacc && demoacc->CountTransactions()>=25) - { - ShowAlert(TRANSLATE("Demo Mode Limit"), - TRANSLATE( - "The Demo Mode limit has been reached on this account.", - "You can manually enter up to 25 transactions per " - "account. We hope that you like Capital Be and will " - "purchase the full version. Have a nice day!"), - B_IDEA_ALERT); - MakeEmpty(); - break; - } - - #endif - - if( !fDate->Validate() || !fType->Validate() || - !fPayee->Validate() || !fAmount->Validate() || - !fCategory->Validate() ) - break; - - Account *acc=gDatabase.CurrentAccount(); - if(!acc) - break; - - TransactionData trans(acc,fDate->Text(),fType->Text(), - fPayee->Text(),fAmount->Text(),fCategory->Text(),fMemo->Text(), - real_time_clock_usecs()); - - - gDatabase.AddTransaction(trans); - acc->SetCurrentTransaction(trans.GetID()); - - if(trans.Type().TypeCode() == TRANS_NUMERIC) - acc->SetLastCheckNumber(atol(trans.Type().Type())); - - MakeEmpty(); - - gDatabase.GetTransaction(trans.GetID(),trans); - fDate->SetDate(trans.Date()); - - BString str; - gDefaultLocale.DateToString(fDate->GetDate(),str); - fDate->SetText(str.String()); - fDate->MakeFocus(true); + + Account *acc = gDatabase.CurrentAccount(); + if (!acc) break; - } - case M_PREVIOUS_FIELD: - { - if(fDate->ChildAt(0)->IsFocus()) - { - if(fDate->Validate(false)) - { - if(gDatabase.CurrentAccount() && strlen(fDate->Text())>0) - { - time_t date; - gDefaultLocale.StringToDate(fDate->Text(),date); - fDate->SetDate(date); - } - fMemo->MakeFocus(true); + + TransactionData trans( + acc, fDate->Text(), fType->Text(), fPayee->Text(), fAmount->Text(), fCategory->Text(), + fMemo->Text(), real_time_clock_usecs() + ); + + + gDatabase.AddTransaction(trans); + acc->SetCurrentTransaction(trans.GetID()); + + if (trans.Type().TypeCode() == TRANS_NUMERIC) + acc->SetLastCheckNumber(atol(trans.Type().Type())); + + MakeEmpty(); + + gDatabase.GetTransaction(trans.GetID(), trans); + fDate->SetDate(trans.Date()); + + BString str; + gDefaultLocale.DateToString(fDate->GetDate(), str); + fDate->SetText(str.String()); + fDate->MakeFocus(true); + break; + } + case M_PREVIOUS_FIELD: { + if (fDate->ChildAt(0)->IsFocus()) { + if (fDate->Validate(false)) { + if (gDatabase.CurrentAccount() && strlen(fDate->Text()) > 0) { + time_t date; + gDefaultLocale.StringToDate(fDate->Text(), date); + fDate->SetDate(date); } - break; - } - else - if(fType->ChildAt(0)->IsFocus()) - fDate->MakeFocus(true); - else - if(fPayee->ChildAt(0)->IsFocus()) - { - if(fPayee->Validate(false)) - fType->MakeFocus(true); + fMemo->MakeFocus(true); } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - if(fAmount->Validate(false)) - fPayee->MakeFocus(true); - } - else - if(fCategory->ChildAt(0)->IsFocus()) - { -// if(fCategory->Validate()) - fAmount->MakeFocus(true); - } - if(fMemo->ChildAt(0)->IsFocus()) - fCategory->MakeFocus(true); - break; - } - case M_NEXT_FIELD: - { - DoNextField(); break; + } else if (fType->ChildAt(0)->IsFocus()) + fDate->MakeFocus(true); + else if (fPayee->ChildAt(0)->IsFocus()) { + if (fPayee->Validate(false)) + fType->MakeFocus(true); + } else if (fAmount->ChildAt(0)->IsFocus()) { + if (fAmount->Validate(false)) + fPayee->MakeFocus(true); + } else if (fCategory->ChildAt(0)->IsFocus()) { + // if(fCategory->Validate()) + fAmount->MakeFocus(true); } - default: - { - BView::MessageReceived(msg); - } + if (fMemo->ChildAt(0)->IsFocus()) + fCategory->MakeFocus(true); + break; + } + case M_NEXT_FIELD: { + DoNextField(); + break; + } + default: { + BView::MessageReceived(msg); + } } } -void CheckView::SetFields(const char *date,const char *type, const char *payee, - const char *amount,const char *category,const char *memo) -{ +void +CheckView::SetFields( + const char *date, const char *type, const char *payee, const char *amount, const char *category, + const char *memo +) { fDate->SetText(date); fType->SetText(type); fPayee->SetText(payee); @@ -271,63 +245,51 @@ void CheckView::SetFields(const char *date,const char *type, const char *payee, fMemo->SetText(memo); } -void CheckView::HandleNotify(const uint64 &value, const BMessage *msg) -{ - if(value & WATCH_SELECT) - { - if(value & WATCH_ACCOUNT) - { +void +CheckView::HandleNotify(const uint64 &value, const BMessage *msg) { + if (value & WATCH_SELECT) { + if (value & WATCH_ACCOUNT) { MakeEmpty(); - + Account *account; - if(msg->FindPointer("item",(void**)&account)==B_OK) - { - if(account && !account->HasObserver(this)) + if (msg->FindPointer("item", (void **)&account) == B_OK) { + if (account && !account->HasObserver(this)) account->AddObserver(this); } - - if(!account) - { + + if (!account) { // This happens when the last account is deleted -- there // is no longer a current account fDate->MakeFocus(true); return; } - - - if(account->CountTransactions()>0) - { + + + if (account->CountTransactions() > 0) { TransactionData data; - gDatabase.GetTransaction(account->GetID(),data); + gDatabase.GetTransaction(account->GetID(), data); fDate->SetDate(data.Date()); - + BString text; - gDefaultLocale.DateToString(data.Date(),text); + gDefaultLocale.DateToString(data.Date(), text); fDate->SetText(text.String()); - } - else - { + } else { BString text; - gDefaultLocale.DateToString(GetCurrentDate(),text); + gDefaultLocale.DateToString(GetCurrentDate(), text); fDate->SetText(text.String()); } - + fDate->MakeFocus(true); - } - else - if(value & WATCH_TRANSACTION) - { + } else if (value & WATCH_TRANSACTION) { uint32 id; - if(msg->FindInt32("id",(int32*)&id)==B_OK) - { - if(gDatabase.CurrentAccount()) - { + if (msg->FindInt32("id", (int32 *)&id) == B_OK) { + if (gDatabase.CurrentAccount()) { TransactionData data; - gDatabase.GetTransaction(id,data); + gDatabase.GetTransaction(id, data); fDate->SetDate(data.Date()); - + BString text; - gDefaultLocale.DateToString(data.Date(),text); + gDefaultLocale.DateToString(data.Date(), text); fDate->SetText(text.String()); } } @@ -335,8 +297,8 @@ void CheckView::HandleNotify(const uint64 &value, const BMessage *msg) } } -void CheckView::MakeEmpty(void) -{ +void +CheckView::MakeEmpty(void) { fDate->SetText(""); fType->SetText(""); fPayee->SetText(""); @@ -345,66 +307,46 @@ void CheckView::MakeEmpty(void) fMemo->SetText(""); } -void CheckView::MakeFocus(bool value) -{ +void +CheckView::MakeFocus(bool value) { fDate->MakeFocus(value); } -void CheckView::FrameResized(float width, float height) -{ -} +void +CheckView::FrameResized(float width, float height) {} -void CheckView::DoNextField(void) -{ - if(fDate->ChildAt(0)->IsFocus()) - { - if(fDate->Validate(false)) - { - if(gDatabase.CurrentAccount() && strlen(fDate->Text())>0) - { +void +CheckView::DoNextField(void) { + if (fDate->ChildAt(0)->IsFocus()) { + if (fDate->Validate(false)) { + if (gDatabase.CurrentAccount() && strlen(fDate->Text()) > 0) { time_t date; - gDefaultLocale.StringToDate(fDate->Text(),date); + gDefaultLocale.StringToDate(fDate->Text(), date); fDate->SetDate(date); } } fType->MakeFocus(true); - } - else - if(fType->ChildAt(0)->IsFocus()) + } else if (fType->ChildAt(0)->IsFocus()) fPayee->MakeFocus(true); - else - if(fPayee->ChildAt(0)->IsFocus()) - { - if(fPayee->Validate(false)) + else if (fPayee->ChildAt(0)->IsFocus()) { + if (fPayee->Validate(false)) fAmount->MakeFocus(true); - } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - if(fAmount->Validate(false)) + } else if (fAmount->ChildAt(0)->IsFocus()) { + if (fAmount->Validate(false)) fCategory->MakeFocus(true); - } - else - if(fCategory->ChildAt(0)->IsFocus()) - { + } else if (fCategory->ChildAt(0)->IsFocus()) { // TODO: don't force entering a transaction when going to the // split window via key editing - if(strcmp(fCategory->Text(),"Split")==0) - { - Window()->PostMessage(M_ENTER_TRANSACTION,this); + if (strcmp(fCategory->Text(), "Split") == 0) { + Window()->PostMessage(M_ENTER_TRANSACTION, this); Window()->PostMessage(M_EDIT_TRANSACTION); - return; + return; } - + fMemo->MakeFocus(true); - } - else - if(fMemo->ChildAt(0)->IsFocus()) - { + } else if (fMemo->ChildAt(0)->IsFocus()) { fEnter->MakeFocus(true); - } - else - { + } else { // We should *never* be here ShowBug("M_NEXT_FIELD received for unknown view in CheckView"); } diff --git a/src/CheckView.h b/src/CheckView.h index 771efc5..277982a 100644 --- a/src/CheckView.h +++ b/src/CheckView.h @@ -1,26 +1,25 @@ #ifndef CHECKVIEW_H #define CHECKVIEW_H -#include -#include -#include #include -#include #include +#include +#include +#include +#include #include -#include "Notifier.h" #include "Account.h" #include "HelpButton.h" +#include "Notifier.h" -enum -{ - M_DATE_CHANGED='dtch', - M_TYPE_CHANGED='tych', - M_PAYEE_CHANGED='pych', - M_AMOUNT_CHANGED='amch', - M_CATEGORY_CHANGED='ctch', - M_MEMO_CHANGED='mmch' +enum { + M_DATE_CHANGED = 'dtch', + M_TYPE_CHANGED = 'tych', + M_PAYEE_CHANGED = 'pych', + M_AMOUNT_CHANGED = 'amch', + M_CATEGORY_CHANGED = 'ctch', + M_MEMO_CHANGED = 'mmch' }; class CheckViewFilter; @@ -31,35 +30,35 @@ class DateBox; class NavTextBox; class PayeeBox; -class CheckView : public BView, public Observer -{ -public: +class CheckView : public BView, public Observer { + public: CheckView(const char *name, int32 flags); ~CheckView(void); void AttachedToWindow(void); void MessageReceived(BMessage *msg); - void SetFields(const char *date,const char *type, const char *payee, - const char *amount,const char *category,const char *memo); - + void SetFields( + const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo + ); + void HandleNotify(const uint64 &value, const BMessage *msg); void MakeEmpty(void); - void MakeFocus(bool value=true); + void MakeFocus(bool value = true); void FrameResized(float width, float height); - -private: + + private: void DoNextField(void); - + DateBox *fDate; CheckNumBox *fType; PayeeBox *fPayee; CurrencyBox *fAmount; CategoryBox *fCategory; NavTextBox *fMemo; - - BStringView *fDateLabel,*fTypeLabel,*fPayeeLabel,*fAmountLabel, - *fCategoryLabel,*fMemoLabel; + + BStringView *fDateLabel, *fTypeLabel, *fPayeeLabel, *fAmountLabel, *fCategoryLabel, *fMemoLabel; BButton *fEnter, *fTransfer; - + HelpButton *fHelpButton; }; diff --git a/src/CppSQLite3.cpp b/src/CppSQLite3.cpp index 9032be6..23969ba 100644 --- a/src/CppSQLite3.cpp +++ b/src/CppSQLite3.cpp @@ -2,11 +2,11 @@ // CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library. // // Copyright (c) 2004..2007 Rob Groves. All Rights Reserved. rob.groves@btinternet.com -// +// // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written -// agreement, is hereby granted, provided that the above copyright notice, -// this paragraph and the following two paragraphs appear in all copies, +// agreement, is hereby granted, provided that the above copyright notice, +// this paragraph and the following two paragraphs appear in all copies, // modifications, and distributions. // // IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, @@ -39,122 +39,129 @@ // Named constant for passing to CppSQLite3Exception when passing it a string // that cannot be deleted. -static const bool DONT_DELETE_MSG=false; +static const bool DONT_DELETE_MSG = false; //////////////////////////////////////////////////////////////////////////////// // Prototypes for SQLite functions not included in SQLite DLL, but copied below // from SQLite encode.c //////////////////////////////////////////////////////////////////////////////// -int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out); -int sqlite3_decode_binary(const unsigned char *in, unsigned char *out); +int +sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out); +int +sqlite3_decode_binary(const unsigned char *in, unsigned char *out); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Exception::CppSQLite3Exception(const int nErrCode, - char* szErrMess, - bool bDeleteMsg/*=true*/) : - mnErrCode(nErrCode) -{ - mpszErrMess = sqlite3_mprintf("%s[%d]: %s", - errorCodeAsString(nErrCode), - nErrCode, - szErrMess ? szErrMess : ""); - - if (bDeleteMsg && szErrMess) - { +CppSQLite3Exception:: + CppSQLite3Exception(const int nErrCode, char *szErrMess, bool bDeleteMsg /*=true*/) + : mnErrCode(nErrCode) { + mpszErrMess = sqlite3_mprintf( + "%s[%d]: %s", errorCodeAsString(nErrCode), nErrCode, szErrMess ? szErrMess : "" + ); + + if (bDeleteMsg && szErrMess) { sqlite3_free(szErrMess); } } - -CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception& e) : - mnErrCode(e.mnErrCode) -{ +CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception &e) : mnErrCode(e.mnErrCode) { mpszErrMess = 0; - if (e.mpszErrMess) - { + if (e.mpszErrMess) { mpszErrMess = sqlite3_mprintf("%s", e.mpszErrMess); } } - -const char* CppSQLite3Exception::errorCodeAsString(int nErrCode) -{ - switch (nErrCode) - { - case SQLITE_OK : return "SQLITE_OK"; - case SQLITE_ERROR : return "SQLITE_ERROR"; - case SQLITE_INTERNAL : return "SQLITE_INTERNAL"; - case SQLITE_PERM : return "SQLITE_PERM"; - case SQLITE_ABORT : return "SQLITE_ABORT"; - case SQLITE_BUSY : return "SQLITE_BUSY"; - case SQLITE_LOCKED : return "SQLITE_LOCKED"; - case SQLITE_NOMEM : return "SQLITE_NOMEM"; - case SQLITE_READONLY : return "SQLITE_READONLY"; - case SQLITE_INTERRUPT : return "SQLITE_INTERRUPT"; - case SQLITE_IOERR : return "SQLITE_IOERR"; - case SQLITE_CORRUPT : return "SQLITE_CORRUPT"; - case SQLITE_NOTFOUND : return "SQLITE_NOTFOUND"; - case SQLITE_FULL : return "SQLITE_FULL"; - case SQLITE_CANTOPEN : return "SQLITE_CANTOPEN"; - case SQLITE_PROTOCOL : return "SQLITE_PROTOCOL"; - case SQLITE_EMPTY : return "SQLITE_EMPTY"; - case SQLITE_SCHEMA : return "SQLITE_SCHEMA"; - case SQLITE_TOOBIG : return "SQLITE_TOOBIG"; - case SQLITE_CONSTRAINT : return "SQLITE_CONSTRAINT"; - case SQLITE_MISMATCH : return "SQLITE_MISMATCH"; - case SQLITE_MISUSE : return "SQLITE_MISUSE"; - case SQLITE_NOLFS : return "SQLITE_NOLFS"; - case SQLITE_AUTH : return "SQLITE_AUTH"; - case SQLITE_FORMAT : return "SQLITE_FORMAT"; - case SQLITE_RANGE : return "SQLITE_RANGE"; - case SQLITE_ROW : return "SQLITE_ROW"; - case SQLITE_DONE : return "SQLITE_DONE"; - case CPPSQLITE_ERROR : return "CPPSQLITE_ERROR"; - default: return "UNKNOWN_ERROR"; - } -} - - -CppSQLite3Exception::~CppSQLite3Exception() -{ - if (mpszErrMess) - { +const char * +CppSQLite3Exception::errorCodeAsString(int nErrCode) { + switch (nErrCode) { + case SQLITE_OK: + return "SQLITE_OK"; + case SQLITE_ERROR: + return "SQLITE_ERROR"; + case SQLITE_INTERNAL: + return "SQLITE_INTERNAL"; + case SQLITE_PERM: + return "SQLITE_PERM"; + case SQLITE_ABORT: + return "SQLITE_ABORT"; + case SQLITE_BUSY: + return "SQLITE_BUSY"; + case SQLITE_LOCKED: + return "SQLITE_LOCKED"; + case SQLITE_NOMEM: + return "SQLITE_NOMEM"; + case SQLITE_READONLY: + return "SQLITE_READONLY"; + case SQLITE_INTERRUPT: + return "SQLITE_INTERRUPT"; + case SQLITE_IOERR: + return "SQLITE_IOERR"; + case SQLITE_CORRUPT: + return "SQLITE_CORRUPT"; + case SQLITE_NOTFOUND: + return "SQLITE_NOTFOUND"; + case SQLITE_FULL: + return "SQLITE_FULL"; + case SQLITE_CANTOPEN: + return "SQLITE_CANTOPEN"; + case SQLITE_PROTOCOL: + return "SQLITE_PROTOCOL"; + case SQLITE_EMPTY: + return "SQLITE_EMPTY"; + case SQLITE_SCHEMA: + return "SQLITE_SCHEMA"; + case SQLITE_TOOBIG: + return "SQLITE_TOOBIG"; + case SQLITE_CONSTRAINT: + return "SQLITE_CONSTRAINT"; + case SQLITE_MISMATCH: + return "SQLITE_MISMATCH"; + case SQLITE_MISUSE: + return "SQLITE_MISUSE"; + case SQLITE_NOLFS: + return "SQLITE_NOLFS"; + case SQLITE_AUTH: + return "SQLITE_AUTH"; + case SQLITE_FORMAT: + return "SQLITE_FORMAT"; + case SQLITE_RANGE: + return "SQLITE_RANGE"; + case SQLITE_ROW: + return "SQLITE_ROW"; + case SQLITE_DONE: + return "SQLITE_DONE"; + case CPPSQLITE_ERROR: + return "CPPSQLITE_ERROR"; + default: + return "UNKNOWN_ERROR"; + } +} + +CppSQLite3Exception::~CppSQLite3Exception() { + if (mpszErrMess) { sqlite3_free(mpszErrMess); mpszErrMess = 0; } } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Buffer::CppSQLite3Buffer() -{ - mpBuf = 0; -} - - -CppSQLite3Buffer::~CppSQLite3Buffer() -{ - clear(); -} +CppSQLite3Buffer::CppSQLite3Buffer() { mpBuf = 0; } +CppSQLite3Buffer::~CppSQLite3Buffer() { clear(); } -void CppSQLite3Buffer::clear() -{ - if (mpBuf) - { +void +CppSQLite3Buffer::clear() { + if (mpBuf) { sqlite3_free(mpBuf); mpBuf = 0; } - } - -const char* CppSQLite3Buffer::format(const char* szFormat, ...) -{ +const char * +CppSQLite3Buffer::format(const char *szFormat, ...) { clear(); va_list va; va_start(va, szFormat); @@ -163,58 +170,40 @@ const char* CppSQLite3Buffer::format(const char* szFormat, ...) return mpBuf; } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Binary::CppSQLite3Binary() : - mpBuf(0), - mnBinaryLen(0), - mnBufferLen(0), - mnEncodedLen(0), - mbEncoded(false) -{ -} +CppSQLite3Binary::CppSQLite3Binary() + : mpBuf(0), mnBinaryLen(0), mnBufferLen(0), mnEncodedLen(0), mbEncoded(false) {} +CppSQLite3Binary::~CppSQLite3Binary() { clear(); } -CppSQLite3Binary::~CppSQLite3Binary() -{ - clear(); -} - - -void CppSQLite3Binary::setBinary(const unsigned char* pBuf, int nLen) -{ +void +CppSQLite3Binary::setBinary(const unsigned char *pBuf, int nLen) { mpBuf = allocBuffer(nLen); memcpy(mpBuf, pBuf, nLen); } - -void CppSQLite3Binary::setEncoded(const unsigned char* pBuf) -{ +void +CppSQLite3Binary::setEncoded(const unsigned char *pBuf) { clear(); - mnEncodedLen = strlen((const char*)pBuf); + mnEncodedLen = strlen((const char *)pBuf); mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator - mpBuf = (unsigned char*)malloc(mnBufferLen); + mpBuf = (unsigned char *)malloc(mnBufferLen); - if (!mpBuf) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Cannot allocate memory", - DONT_DELETE_MSG); + if (!mpBuf) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Cannot allocate memory", DONT_DELETE_MSG); } memcpy(mpBuf, pBuf, mnBufferLen); mbEncoded = true; } - -const unsigned char* CppSQLite3Binary::getEncoded() -{ - if (!mbEncoded) - { - unsigned char* ptmp = (unsigned char*)malloc(mnBinaryLen); +const unsigned char * +CppSQLite3Binary::getEncoded() { + if (!mbEncoded) { + unsigned char *ptmp = (unsigned char *)malloc(mnBinaryLen); memcpy(ptmp, mpBuf, mnBinaryLen); mnEncodedLen = sqlite3_encode_binary(ptmp, mnBinaryLen, mpBuf); free(ptmp); @@ -224,19 +213,14 @@ const unsigned char* CppSQLite3Binary::getEncoded() return mpBuf; } - -const unsigned char* CppSQLite3Binary::getBinary() -{ - if (mbEncoded) - { +const unsigned char * +CppSQLite3Binary::getBinary() { + if (mbEncoded) { // in/out buffers can be the same mnBinaryLen = sqlite3_decode_binary(mpBuf, mpBuf); - if (mnBinaryLen == -1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Cannot decode binary", - DONT_DELETE_MSG); + if (mnBinaryLen == -1) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Cannot decode binary", DONT_DELETE_MSG); } mbEncoded = false; @@ -245,31 +229,26 @@ const unsigned char* CppSQLite3Binary::getBinary() return mpBuf; } - -int CppSQLite3Binary::getBinaryLength() -{ +int +CppSQLite3Binary::getBinaryLength() { getBinary(); return mnBinaryLen; } - -unsigned char* CppSQLite3Binary::allocBuffer(int nLen) -{ +unsigned char * +CppSQLite3Binary::allocBuffer(int nLen) { clear(); // Allow extra space for encoded binary as per comments in // SQLite encode.c See bottom of this file for implementation // of SQLite functions use 3 instead of 2 just to be sure ;-) mnBinaryLen = nLen; - mnBufferLen = 3 + (257*nLen)/254; + mnBufferLen = 3 + (257 * nLen) / 254; - mpBuf = (unsigned char*)malloc(mnBufferLen); + mpBuf = (unsigned char *)malloc(mnBufferLen); - if (!mpBuf) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Cannot allocate memory", - DONT_DELETE_MSG); + if (!mpBuf) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Cannot allocate memory", DONT_DELETE_MSG); } mbEncoded = false; @@ -277,11 +256,9 @@ unsigned char* CppSQLite3Binary::allocBuffer(int nLen) return mpBuf; } - -void CppSQLite3Binary::clear() -{ - if (mpBuf) - { +void +CppSQLite3Binary::clear() { + if (mpBuf) { mnBinaryLen = 0; mnBufferLen = 0; free(mpBuf); @@ -289,34 +266,26 @@ void CppSQLite3Binary::clear() } } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Query::CppSQLite3Query() -{ +CppSQLite3Query::CppSQLite3Query() { mpVM = 0; mbEof = true; mnCols = 0; mbOwnVM = false; } - -CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery) -{ +CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query &rQuery) { mpVM = rQuery.mpVM; // Only one object can own the VM - const_cast(rQuery).mpVM = 0; + const_cast(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; } - -CppSQLite3Query::CppSQLite3Query(sqlite3* pDB, - sqlite3_stmt* pVM, - bool bEof, - bool bOwnVM/*=true*/) -{ +CppSQLite3Query:: + CppSQLite3Query(sqlite3 *pDB, sqlite3_stmt *pVM, bool bEof, bool bOwnVM /*=true*/) { mpDB = pDB; mpVM = pVM; mbEof = bEof; @@ -324,756 +293,581 @@ CppSQLite3Query::CppSQLite3Query(sqlite3* pDB, mbOwnVM = bOwnVM; } - -CppSQLite3Query::~CppSQLite3Query() -{ - try - { +CppSQLite3Query::~CppSQLite3Query() { + try { finalize(); - } - catch (...) - { + } catch (...) { } } - -CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery) -{ - try - { +CppSQLite3Query & +CppSQLite3Query::operator=(const CppSQLite3Query &rQuery) { + try { finalize(); - } - catch (...) - { + } catch (...) { } mpVM = rQuery.mpVM; // Only one object can own the VM - const_cast(rQuery).mpVM = 0; + const_cast(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; return *this; } - -int CppSQLite3Query::numFields() -{ +int +CppSQLite3Query::numFields() { checkVM(); return mnCols; } - -const char* CppSQLite3Query::fieldValue(int nField) -{ +const char * +CppSQLite3Query::fieldValue(int nField) { checkVM(); - if (nField < 0 || nField > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nField < 0 || nField > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } - return (const char*)sqlite3_column_text(mpVM, nField); + return (const char *)sqlite3_column_text(mpVM, nField); } - -const char* CppSQLite3Query::fieldValue(const char* szField) -{ +const char * +CppSQLite3Query::fieldValue(const char *szField) { int nField = fieldIndex(szField); - return (const char*)sqlite3_column_text(mpVM, nField); + return (const char *)sqlite3_column_text(mpVM, nField); } - -int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/) -{ - if (fieldDataType(nField) == SQLITE_NULL) - { +int +CppSQLite3Query::getIntField(int nField, int nNullValue /*=0*/) { + if (fieldDataType(nField) == SQLITE_NULL) { return nNullValue; - } - else - { + } else { return sqlite3_column_int(mpVM, nField); } } - -int CppSQLite3Query::getIntField(const char* szField, int nNullValue/*=0*/) -{ +int +CppSQLite3Query::getIntField(const char *szField, int nNullValue /*=0*/) { int nField = fieldIndex(szField); return getIntField(nField, nNullValue); } - -sqlite_int64 CppSQLite3Query::getInt64Field(int nField, sqlite_int64 nNullValue/*=0*/) -{ - if (fieldDataType(nField) == SQLITE_NULL) - { +sqlite_int64 +CppSQLite3Query::getInt64Field(int nField, sqlite_int64 nNullValue /*=0*/) { + if (fieldDataType(nField) == SQLITE_NULL) { return nNullValue; - } - else - { + } else { return sqlite3_column_int64(mpVM, nField); } } - -sqlite_int64 CppSQLite3Query::getInt64Field(const char* szField, sqlite_int64 nNullValue/*=0*/) -{ +sqlite_int64 +CppSQLite3Query::getInt64Field(const char *szField, sqlite_int64 nNullValue /*=0*/) { int nField = fieldIndex(szField); return getInt64Field(nField, nNullValue); } - -double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/) -{ - if (fieldDataType(nField) == SQLITE_NULL) - { +double +CppSQLite3Query::getFloatField(int nField, double fNullValue /*=0.0*/) { + if (fieldDataType(nField) == SQLITE_NULL) { return fNullValue; - } - else - { + } else { return sqlite3_column_double(mpVM, nField); } } - -double CppSQLite3Query::getFloatField(const char* szField, double fNullValue/*=0.0*/) -{ +double +CppSQLite3Query::getFloatField(const char *szField, double fNullValue /*=0.0*/) { int nField = fieldIndex(szField); return getFloatField(nField, fNullValue); } - -const char* CppSQLite3Query::getStringField(int nField, const char* szNullValue/*=""*/) -{ - if (fieldDataType(nField) == SQLITE_NULL) - { +const char * +CppSQLite3Query::getStringField(int nField, const char *szNullValue /*=""*/) { + if (fieldDataType(nField) == SQLITE_NULL) { return szNullValue; - } - else - { - return (const char*)sqlite3_column_text(mpVM, nField); + } else { + return (const char *)sqlite3_column_text(mpVM, nField); } } - -const char* CppSQLite3Query::getStringField(const char* szField, const char* szNullValue/*=""*/) -{ +const char * +CppSQLite3Query::getStringField(const char *szField, const char *szNullValue /*=""*/) { int nField = fieldIndex(szField); return getStringField(nField, szNullValue); } - -const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen) -{ +const unsigned char * +CppSQLite3Query::getBlobField(int nField, int &nLen) { checkVM(); - if (nField < 0 || nField > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nField < 0 || nField > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } nLen = sqlite3_column_bytes(mpVM, nField); - return (const unsigned char*)sqlite3_column_blob(mpVM, nField); + return (const unsigned char *)sqlite3_column_blob(mpVM, nField); } - -const unsigned char* CppSQLite3Query::getBlobField(const char* szField, int& nLen) -{ +const unsigned char * +CppSQLite3Query::getBlobField(const char *szField, int &nLen) { int nField = fieldIndex(szField); return getBlobField(nField, nLen); } - -bool CppSQLite3Query::fieldIsNull(int nField) -{ +bool +CppSQLite3Query::fieldIsNull(int nField) { return (fieldDataType(nField) == SQLITE_NULL); } - -bool CppSQLite3Query::fieldIsNull(const char* szField) -{ +bool +CppSQLite3Query::fieldIsNull(const char *szField) { int nField = fieldIndex(szField); return (fieldDataType(nField) == SQLITE_NULL); } - -int CppSQLite3Query::fieldIndex(const char* szField) -{ +int +CppSQLite3Query::fieldIndex(const char *szField) { checkVM(); - if (szField) - { - for (int nField = 0; nField < mnCols; nField++) - { - const char* szTemp = sqlite3_column_name(mpVM, nField); + if (szField) { + for (int nField = 0; nField < mnCols; nField++) { + const char *szTemp = sqlite3_column_name(mpVM, nField); - if (strcmp(szField, szTemp) == 0) - { + if (strcmp(szField, szTemp) == 0) { return nField; } } } - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field name requested", - DONT_DELETE_MSG); + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid field name requested", DONT_DELETE_MSG); } - -const char* CppSQLite3Query::fieldName(int nCol) -{ +const char * +CppSQLite3Query::fieldName(int nCol) { checkVM(); - if (nCol < 0 || nCol > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nCol < 0 || nCol > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } return sqlite3_column_name(mpVM, nCol); } - -const char* CppSQLite3Query::fieldDeclType(int nCol) -{ +const char * +CppSQLite3Query::fieldDeclType(int nCol) { checkVM(); - if (nCol < 0 || nCol > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nCol < 0 || nCol > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } return sqlite3_column_decltype(mpVM, nCol); } - -int CppSQLite3Query::fieldDataType(int nCol) -{ +int +CppSQLite3Query::fieldDataType(int nCol) { checkVM(); - if (nCol < 0 || nCol > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nCol < 0 || nCol > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } return sqlite3_column_type(mpVM, nCol); } - -bool CppSQLite3Query::eof() -{ +bool +CppSQLite3Query::eof() { checkVM(); return mbEof; } - -void CppSQLite3Query::nextRow() -{ +void +CppSQLite3Query::nextRow() { checkVM(); int nRet = sqlite3_step(mpVM); - if (nRet == SQLITE_DONE) - { + if (nRet == SQLITE_DONE) { // no rows mbEof = true; - } - else if (nRet == SQLITE_ROW) - { + } else if (nRet == SQLITE_ROW) { // more rows, nothing to do - } - else - { + } else { nRet = sqlite3_finalize(mpVM); mpVM = 0; - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, - (char*)szError, - DONT_DELETE_MSG); + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } - -void CppSQLite3Query::finalize() -{ - if (mpVM && mbOwnVM) - { +void +CppSQLite3Query::finalize() { + if (mpVM && mbOwnVM) { int nRet = sqlite3_finalize(mpVM); mpVM = 0; - if (nRet != SQLITE_OK) - { - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + if (nRet != SQLITE_OK) { + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } } - -void CppSQLite3Query::checkVM() -{ - if (mpVM == 0) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Null Virtual Machine pointer", - DONT_DELETE_MSG); +void +CppSQLite3Query::checkVM() { + if (mpVM == 0) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Virtual Machine pointer", DONT_DELETE_MSG); } } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Table::CppSQLite3Table() -{ +CppSQLite3Table::CppSQLite3Table() { mpaszResults = 0; mnRows = 0; mnCols = 0; mnCurrentRow = 0; } - -CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table& rTable) -{ +CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table &rTable) { mpaszResults = rTable.mpaszResults; // Only one object can own the results - const_cast(rTable).mpaszResults = 0; + const_cast(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; } - -CppSQLite3Table::CppSQLite3Table(char** paszResults, int nRows, int nCols) -{ +CppSQLite3Table::CppSQLite3Table(char **paszResults, int nRows, int nCols) { mpaszResults = paszResults; mnRows = nRows; mnCols = nCols; mnCurrentRow = 0; } - -CppSQLite3Table::~CppSQLite3Table() -{ - try - { +CppSQLite3Table::~CppSQLite3Table() { + try { finalize(); - } - catch (...) - { + } catch (...) { } } - -CppSQLite3Table& CppSQLite3Table::operator=(const CppSQLite3Table& rTable) -{ - try - { +CppSQLite3Table & +CppSQLite3Table::operator=(const CppSQLite3Table &rTable) { + try { finalize(); - } - catch (...) - { + } catch (...) { } mpaszResults = rTable.mpaszResults; // Only one object can own the results - const_cast(rTable).mpaszResults = 0; + const_cast(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; return *this; } - -void CppSQLite3Table::finalize() -{ - if (mpaszResults) - { +void +CppSQLite3Table::finalize() { + if (mpaszResults) { sqlite3_free_table(mpaszResults); mpaszResults = 0; } } - -int CppSQLite3Table::numFields() -{ +int +CppSQLite3Table::numFields() { checkResults(); return mnCols; } - -int CppSQLite3Table::numRows() -{ +int +CppSQLite3Table::numRows() { checkResults(); return mnRows; } - -const char* CppSQLite3Table::fieldValue(int nField) -{ +const char * +CppSQLite3Table::fieldValue(int nField) { checkResults(); - if (nField < 0 || nField > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nField < 0 || nField > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } - int nIndex = (mnCurrentRow*mnCols) + mnCols + nField; + int nIndex = (mnCurrentRow * mnCols) + mnCols + nField; return mpaszResults[nIndex]; } - -const char* CppSQLite3Table::fieldValue(const char* szField) -{ +const char * +CppSQLite3Table::fieldValue(const char *szField) { checkResults(); - if (szField) - { - for (int nField = 0; nField < mnCols; nField++) - { - if (strcmp(szField, mpaszResults[nField]) == 0) - { - int nIndex = (mnCurrentRow*mnCols) + mnCols + nField; + if (szField) { + for (int nField = 0; nField < mnCols; nField++) { + if (strcmp(szField, mpaszResults[nField]) == 0) { + int nIndex = (mnCurrentRow * mnCols) + mnCols + nField; return mpaszResults[nIndex]; } } } - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field name requested", - DONT_DELETE_MSG); + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid field name requested", DONT_DELETE_MSG); } - -int CppSQLite3Table::getIntField(int nField, int nNullValue/*=0*/) -{ - if (fieldIsNull(nField)) - { +int +CppSQLite3Table::getIntField(int nField, int nNullValue /*=0*/) { + if (fieldIsNull(nField)) { return nNullValue; - } - else - { + } else { return atoi(fieldValue(nField)); } } - -int CppSQLite3Table::getIntField(const char* szField, int nNullValue/*=0*/) -{ - if (fieldIsNull(szField)) - { +int +CppSQLite3Table::getIntField(const char *szField, int nNullValue /*=0*/) { + if (fieldIsNull(szField)) { return nNullValue; - } - else - { + } else { return atoi(fieldValue(szField)); } } - -double CppSQLite3Table::getFloatField(int nField, double fNullValue/*=0.0*/) -{ - if (fieldIsNull(nField)) - { +double +CppSQLite3Table::getFloatField(int nField, double fNullValue /*=0.0*/) { + if (fieldIsNull(nField)) { return fNullValue; - } - else - { + } else { return atof(fieldValue(nField)); } } - -double CppSQLite3Table::getFloatField(const char* szField, double fNullValue/*=0.0*/) -{ - if (fieldIsNull(szField)) - { +double +CppSQLite3Table::getFloatField(const char *szField, double fNullValue /*=0.0*/) { + if (fieldIsNull(szField)) { return fNullValue; - } - else - { + } else { return atof(fieldValue(szField)); } } - -const char* CppSQLite3Table::getStringField(int nField, const char* szNullValue/*=""*/) -{ - if (fieldIsNull(nField)) - { +const char * +CppSQLite3Table::getStringField(int nField, const char *szNullValue /*=""*/) { + if (fieldIsNull(nField)) { return szNullValue; - } - else - { + } else { return fieldValue(nField); } } - -const char* CppSQLite3Table::getStringField(const char* szField, const char* szNullValue/*=""*/) -{ - if (fieldIsNull(szField)) - { +const char * +CppSQLite3Table::getStringField(const char *szField, const char *szNullValue /*=""*/) { + if (fieldIsNull(szField)) { return szNullValue; - } - else - { + } else { return fieldValue(szField); } } - -bool CppSQLite3Table::fieldIsNull(int nField) -{ +bool +CppSQLite3Table::fieldIsNull(int nField) { checkResults(); return (fieldValue(nField) == 0); } - -bool CppSQLite3Table::fieldIsNull(const char* szField) -{ +bool +CppSQLite3Table::fieldIsNull(const char *szField) { checkResults(); return (fieldValue(szField) == 0); } - -const char* CppSQLite3Table::fieldName(int nCol) -{ +const char * +CppSQLite3Table::fieldName(int nCol) { checkResults(); - if (nCol < 0 || nCol > mnCols-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid field index requested", - DONT_DELETE_MSG); + if (nCol < 0 || nCol > mnCols - 1) { + throw CppSQLite3Exception( + CPPSQLITE_ERROR, "Invalid field index requested", DONT_DELETE_MSG + ); } return mpaszResults[nCol]; } - -void CppSQLite3Table::setRow(int nRow) -{ +void +CppSQLite3Table::setRow(int nRow) { checkResults(); - if (nRow < 0 || nRow > mnRows-1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid row index requested", - DONT_DELETE_MSG); + if (nRow < 0 || nRow > mnRows - 1) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid row index requested", DONT_DELETE_MSG); } mnCurrentRow = nRow; } - -void CppSQLite3Table::checkResults() -{ - if (mpaszResults == 0) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Null Results pointer", - DONT_DELETE_MSG); +void +CppSQLite3Table::checkResults() { + if (mpaszResults == 0) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Results pointer", DONT_DELETE_MSG); } } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Statement::CppSQLite3Statement() -{ +CppSQLite3Statement::CppSQLite3Statement() { mpDB = 0; mpVM = 0; } - -CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement) -{ +CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement &rStatement) { mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM - const_cast(rStatement).mpVM = 0; + const_cast(rStatement).mpVM = 0; } - -CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM) -{ +CppSQLite3Statement::CppSQLite3Statement(sqlite3 *pDB, sqlite3_stmt *pVM) { mpDB = pDB; mpVM = pVM; } - -CppSQLite3Statement::~CppSQLite3Statement() -{ - try - { +CppSQLite3Statement::~CppSQLite3Statement() { + try { finalize(); - } - catch (...) - { + } catch (...) { } } - -CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement) -{ +CppSQLite3Statement & +CppSQLite3Statement::operator=(const CppSQLite3Statement &rStatement) { mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM - const_cast(rStatement).mpVM = 0; + const_cast(rStatement).mpVM = 0; return *this; } - -int CppSQLite3Statement::execDML() -{ +int +CppSQLite3Statement::execDML() { checkDB(); checkVM(); - const char* szError=0; + const char *szError = 0; int nRet = sqlite3_step(mpVM); - if (nRet == SQLITE_DONE) - { + if (nRet == SQLITE_DONE) { int nRowsChanged = sqlite3_changes(mpDB); nRet = sqlite3_reset(mpVM); - if (nRet != SQLITE_OK) - { + if (nRet != SQLITE_OK) { szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } return nRowsChanged; - } - else - { + } else { nRet = sqlite3_reset(mpVM); szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } - -CppSQLite3Query CppSQLite3Statement::execQuery() -{ +CppSQLite3Query +CppSQLite3Statement::execQuery() { checkDB(); checkVM(); int nRet = sqlite3_step(mpVM); - if (nRet == SQLITE_DONE) - { + if (nRet == SQLITE_DONE) { // no rows - return CppSQLite3Query(mpDB, mpVM, true/*eof*/, false); - } - else if (nRet == SQLITE_ROW) - { + return CppSQLite3Query(mpDB, mpVM, true /*eof*/, false); + } else if (nRet == SQLITE_ROW) { // at least 1 row - return CppSQLite3Query(mpDB, mpVM, false/*eof*/, false); - } - else - { + return CppSQLite3Query(mpDB, mpVM, false /*eof*/, false); + } else { nRet = sqlite3_reset(mpVM); - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } - -void CppSQLite3Statement::bind(int nParam, const char* szValue) -{ +void +CppSQLite3Statement::bind(int nParam, const char *szValue) { checkVM(); int nRes = sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT); - if (nRes != SQLITE_OK) - { - throw CppSQLite3Exception(nRes, - "Error binding string param", - DONT_DELETE_MSG); + if (nRes != SQLITE_OK) { + throw CppSQLite3Exception(nRes, "Error binding string param", DONT_DELETE_MSG); } } - -void CppSQLite3Statement::bind(int nParam, const int nValue) -{ +void +CppSQLite3Statement::bind(int nParam, const int nValue) { checkVM(); int nRes = sqlite3_bind_int(mpVM, nParam, nValue); - if (nRes != SQLITE_OK) - { - throw CppSQLite3Exception(nRes, - "Error binding int param", - DONT_DELETE_MSG); + if (nRes != SQLITE_OK) { + throw CppSQLite3Exception(nRes, "Error binding int param", DONT_DELETE_MSG); } } - -void CppSQLite3Statement::bind(int nParam, const double dValue) -{ +void +CppSQLite3Statement::bind(int nParam, const double dValue) { checkVM(); int nRes = sqlite3_bind_double(mpVM, nParam, dValue); - if (nRes != SQLITE_OK) - { - throw CppSQLite3Exception(nRes, - "Error binding double param", - DONT_DELETE_MSG); + if (nRes != SQLITE_OK) { + throw CppSQLite3Exception(nRes, "Error binding double param", DONT_DELETE_MSG); } } - -void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen) -{ +void +CppSQLite3Statement::bind(int nParam, const unsigned char *blobValue, int nLen) { checkVM(); - int nRes = sqlite3_bind_blob(mpVM, nParam, - (const void*)blobValue, nLen, SQLITE_TRANSIENT); + int nRes = sqlite3_bind_blob(mpVM, nParam, (const void *)blobValue, nLen, SQLITE_TRANSIENT); - if (nRes != SQLITE_OK) - { - throw CppSQLite3Exception(nRes, - "Error binding blob param", - DONT_DELETE_MSG); + if (nRes != SQLITE_OK) { + throw CppSQLite3Exception(nRes, "Error binding blob param", DONT_DELETE_MSG); } } - -void CppSQLite3Statement::bindNull(int nParam) -{ +void +CppSQLite3Statement::bindNull(int nParam) { checkVM(); int nRes = sqlite3_bind_null(mpVM, nParam); - if (nRes != SQLITE_OK) - { - throw CppSQLite3Exception(nRes, - "Error binding NULL param", - DONT_DELETE_MSG); + if (nRes != SQLITE_OK) { + throw CppSQLite3Exception(nRes, "Error binding NULL param", DONT_DELETE_MSG); } } - -int CppSQLite3Statement::bindParameterIndex(const char* szParam) -{ +int +CppSQLite3Statement::bindParameterIndex(const char *szParam) { checkVM(); int nParam = sqlite3_bind_parameter_index(mpVM, szParam); -int nn = sqlite3_bind_parameter_count(mpVM); -const char* sz1 = sqlite3_bind_parameter_name(mpVM, 1); -const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2); + int nn = sqlite3_bind_parameter_count(mpVM); + const char *sz1 = sqlite3_bind_parameter_name(mpVM, 1); + const char *sz2 = sqlite3_bind_parameter_name(mpVM, 2); - if (!nParam) - { + if (!nParam) { char buf[128]; sprintf(buf, "Parameter '%s' is not valid for this statement", szParam); throw CppSQLite3Exception(CPPSQLITE_ERROR, buf, DONT_DELETE_MSG); @@ -1082,318 +876,250 @@ const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2); return nParam; } - -void CppSQLite3Statement::bind(const char* szParam, const char* szValue) -{ +void +CppSQLite3Statement::bind(const char *szParam, const char *szValue) { int nParam = bindParameterIndex(szParam); bind(nParam, szValue); } - -void CppSQLite3Statement::bind(const char* szParam, const int nValue) -{ +void +CppSQLite3Statement::bind(const char *szParam, const int nValue) { int nParam = bindParameterIndex(szParam); bind(nParam, nValue); } -void CppSQLite3Statement::bind(const char* szParam, const double dwValue) -{ +void +CppSQLite3Statement::bind(const char *szParam, const double dwValue) { int nParam = bindParameterIndex(szParam); bind(nParam, dwValue); } -void CppSQLite3Statement::bind(const char* szParam, const unsigned char* blobValue, int nLen) -{ +void +CppSQLite3Statement::bind(const char *szParam, const unsigned char *blobValue, int nLen) { int nParam = bindParameterIndex(szParam); bind(nParam, blobValue, nLen); } - -void CppSQLite3Statement::bindNull(const char* szParam) -{ +void +CppSQLite3Statement::bindNull(const char *szParam) { int nParam = bindParameterIndex(szParam); bindNull(nParam); } - -void CppSQLite3Statement::reset() -{ - if (mpVM) - { +void +CppSQLite3Statement::reset() { + if (mpVM) { int nRet = sqlite3_reset(mpVM); - if (nRet != SQLITE_OK) - { - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + if (nRet != SQLITE_OK) { + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } } - -void CppSQLite3Statement::finalize() -{ - if (mpVM) - { +void +CppSQLite3Statement::finalize() { + if (mpVM) { int nRet = sqlite3_finalize(mpVM); mpVM = 0; - if (nRet != SQLITE_OK) - { - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + if (nRet != SQLITE_OK) { + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } } - -void CppSQLite3Statement::checkDB() -{ - if (mpDB == 0) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Database not open", - DONT_DELETE_MSG); +void +CppSQLite3Statement::checkDB() { + if (mpDB == 0) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Database not open", DONT_DELETE_MSG); } } - -void CppSQLite3Statement::checkVM() -{ - if (mpVM == 0) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Null Virtual Machine pointer", - DONT_DELETE_MSG); +void +CppSQLite3Statement::checkVM() { + if (mpVM == 0) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Virtual Machine pointer", DONT_DELETE_MSG); } } - //////////////////////////////////////////////////////////////////////////////// -CppSQLite3DB::CppSQLite3DB() -{ +CppSQLite3DB::CppSQLite3DB() { mpDB = 0; mnBusyTimeoutMs = 60000; // 60 seconds } - -CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db) -{ +CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB &db) { mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds } - -CppSQLite3DB::~CppSQLite3DB() -{ - try - { +CppSQLite3DB::~CppSQLite3DB() { + try { close(); - } - catch (...) - { + } catch (...) { } } - -CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db) -{ +CppSQLite3DB & +CppSQLite3DB::operator=(const CppSQLite3DB &db) { mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds return *this; } - -void CppSQLite3DB::open(const char* szFile) -{ +void +CppSQLite3DB::open(const char *szFile) { int nRet = sqlite3_open(szFile, &mpDB); - if (nRet != SQLITE_OK) - { - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + if (nRet != SQLITE_OK) { + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } setBusyTimeout(mnBusyTimeoutMs); } - -void CppSQLite3DB::close() -{ - if (mpDB) - { - if (sqlite3_close(mpDB) == SQLITE_OK) - { +void +CppSQLite3DB::close() { + if (mpDB) { + if (sqlite3_close(mpDB) == SQLITE_OK) { mpDB = 0; - } - else - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Unable to close database", - DONT_DELETE_MSG); + } else { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Unable to close database", DONT_DELETE_MSG); } } } - -CppSQLite3Statement CppSQLite3DB::compileStatement(const char* szSQL) -{ +CppSQLite3Statement +CppSQLite3DB::compileStatement(const char *szSQL) { checkDB(); - sqlite3_stmt* pVM = compile(szSQL); + sqlite3_stmt *pVM = compile(szSQL); return CppSQLite3Statement(mpDB, pVM); } - -bool CppSQLite3DB::tableExists(const char* szTable) -{ +bool +CppSQLite3DB::tableExists(const char *szTable) { char szSQL[256]; - sprintf(szSQL, - "select count(*) from sqlite_master where type='table' and name='%s'", - szTable); + sprintf(szSQL, "select count(*) from sqlite_master where type='table' and name='%s'", szTable); int nRet = execScalar(szSQL); return (nRet > 0); } - -int CppSQLite3DB::execDML(const char* szSQL) -{ +int +CppSQLite3DB::execDML(const char *szSQL) { checkDB(); - char* szError=0; + char *szError = 0; int nRet = sqlite3_exec(mpDB, szSQL, 0, 0, &szError); - if (nRet == SQLITE_OK) - { + if (nRet == SQLITE_OK) { return sqlite3_changes(mpDB); - } - else - { + } else { throw CppSQLite3Exception(nRet, szError); } } - -CppSQLite3Query CppSQLite3DB::execQuery(const char* szSQL) -{ +CppSQLite3Query +CppSQLite3DB::execQuery(const char *szSQL) { checkDB(); - sqlite3_stmt* pVM = compile(szSQL); + sqlite3_stmt *pVM = compile(szSQL); int nRet = sqlite3_step(pVM); - if (nRet == SQLITE_DONE) - { + if (nRet == SQLITE_DONE) { // no rows - return CppSQLite3Query(mpDB, pVM, true/*eof*/); - } - else if (nRet == SQLITE_ROW) - { + return CppSQLite3Query(mpDB, pVM, true /*eof*/); + } else if (nRet == SQLITE_ROW) { // at least 1 row - return CppSQLite3Query(mpDB, pVM, false/*eof*/); - } - else - { + return CppSQLite3Query(mpDB, pVM, false /*eof*/); + } else { nRet = sqlite3_finalize(pVM); - const char* szError= sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } } - -int CppSQLite3DB::execScalar(const char* szSQL, int nNullValue/*=0*/) -{ +int +CppSQLite3DB::execScalar(const char *szSQL, int nNullValue /*=0*/) { CppSQLite3Query q = execQuery(szSQL); - if (q.eof() || q.numFields() < 1) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Invalid scalar query", - DONT_DELETE_MSG); + if (q.eof() || q.numFields() < 1) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid scalar query", DONT_DELETE_MSG); } return q.getIntField(0, nNullValue); } - -CppSQLite3Table CppSQLite3DB::getTable(const char* szSQL) -{ +CppSQLite3Table +CppSQLite3DB::getTable(const char *szSQL) { checkDB(); - char* szError=0; - char** paszResults=0; + char *szError = 0; + char **paszResults = 0; int nRet; int nRows(0); int nCols(0); nRet = sqlite3_get_table(mpDB, szSQL, &paszResults, &nRows, &nCols, &szError); - if (nRet == SQLITE_OK) - { + if (nRet == SQLITE_OK) { return CppSQLite3Table(paszResults, nRows, nCols); - } - else - { + } else { throw CppSQLite3Exception(nRet, szError); } } - -sqlite_int64 CppSQLite3DB::lastRowId() -{ +sqlite_int64 +CppSQLite3DB::lastRowId() { return sqlite3_last_insert_rowid(mpDB); } - -void CppSQLite3DB::setBusyTimeout(int nMillisecs) -{ +void +CppSQLite3DB::setBusyTimeout(int nMillisecs) { mnBusyTimeoutMs = nMillisecs; sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs); } - -void CppSQLite3DB::checkDB() -{ - if (!mpDB) - { - throw CppSQLite3Exception(CPPSQLITE_ERROR, - "Database not open", - DONT_DELETE_MSG); +void +CppSQLite3DB::checkDB() { + if (!mpDB) { + throw CppSQLite3Exception(CPPSQLITE_ERROR, "Database not open", DONT_DELETE_MSG); } } - -sqlite3_stmt* CppSQLite3DB::compile(const char* szSQL) -{ +sqlite3_stmt * +CppSQLite3DB::compile(const char *szSQL) { checkDB(); - const char* szTail=0; - sqlite3_stmt* pVM; + const char *szTail = 0; + sqlite3_stmt *pVM; int nRet = sqlite3_prepare_v2(mpDB, szSQL, -1, &pVM, &szTail); - if (nRet != SQLITE_OK) - { - const char* szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, - (char*)szError, - DONT_DELETE_MSG); + if (nRet != SQLITE_OK) { + const char *szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); } return pVM; } -bool CppSQLite3DB::IsAutoCommitOn() -{ +bool +CppSQLite3DB::IsAutoCommitOn() { checkDB(); return sqlite3_get_autocommit(mpDB) ? true : false; } //////////////////////////////////////////////////////////////////////////////// // SQLite encode.c reproduced here, containing implementation notes and source -// for sqlite3_encode_binary() and sqlite3_decode_binary() +// for sqlite3_encode_binary() and sqlite3_decode_binary() //////////////////////////////////////////////////////////////////////////////// /* @@ -1440,7 +1166,7 @@ bool CppSQLite3DB::IsAutoCommitOn() ** We would prefer to keep the size of the encoded string smaller than ** this. ** -** To minimize the encoding size, we first add a fixed offset value to each +** To minimize the encoding size, we first add a fixed offset value to each ** byte in the sequence. The addition is modulo 256. (That is to say, if ** the sum of the original character value and the offset exceeds 256, then ** the higher order bits are truncated.) The offset is chosen to minimize @@ -1449,7 +1175,7 @@ bool CppSQLite3DB::IsAutoCommitOn() ** characters, the offset might be 0x01. Each of the 0x27 characters would ** then be converted into an 0x28 character which would not need to be ** escaped at all and so the 100 character input string would be converted -** into just 100 characters of output. Actually 101 characters of output - +** into just 100 characters of output. Actually 101 characters of output - ** we have to record the offset used as the first byte in the sequence so ** that the string can be decoded. Since the offset value is stored as ** part of the output string and the output string is not allowed to contain @@ -1472,7 +1198,7 @@ bool CppSQLite3DB::IsAutoCommitOn() ** ** Decoding is obvious: ** -** (5) Copy encoded characters except the first into the decode +** (5) Copy encoded characters except the first into the decode ** buffer. Set the first encoded character aside for use as ** the offset in step 7 below. ** @@ -1498,7 +1224,7 @@ bool CppSQLite3DB::IsAutoCommitOn() /* ** Encode a binary buffer "in" of size n bytes so that it contains -** no instances of characters '\'' or '\000'. The output is +** no instances of characters '\'' or '\000'. The output is ** null-terminated and can be used as a string value in an INSERT ** or UPDATE statement. Use sqlite3_decode_binary() to convert the ** string back into its original binary. @@ -1512,46 +1238,51 @@ bool CppSQLite3DB::IsAutoCommitOn() ** The return value is the number of characters in the encoded ** string, excluding the "\000" terminator. */ -int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){ - int i, j, e, m; - int cnt[256]; - if( n<=0 ){ - out[0] = 'x'; - out[1] = 0; - return 1; - } - memset(cnt, 0, sizeof(cnt)); - for(i=n-1; i>=0; i--){ cnt[in[i]]++; } - m = n; - for(i=1; i<256; i++){ - int sum; - if( i=='\'' ) continue; - sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff]; - if( sum= 0; i--) { + cnt[in[i]]++; + } + m = n; + for (i = 1; i < 256; i++) { + int sum; + if (i == '\'') + continue; + sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff]; + if (sum < m) { + m = sum; + e = i; + if (m == 0) + break; + } + } + out[0] = e; + j = 1; + for (i = 0; i < n; i++) { + int c = (in[i] - e) & 0xff; + if (c == 0) { + out[j++] = 1; + out[j++] = 1; + } else if (c == 1) { + out[j++] = 1; + out[j++] = 2; + } else if (c == '\'') { + out[j++] = 1; + out[j++] = 3; + } else { + out[j++] = c; + } + } + out[j] = 0; + return j; } /* @@ -1564,24 +1295,25 @@ int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){ ** The "in" and "out" parameters may point to the same buffer in order ** to decode a string in place. */ -int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){ - int i, c, e; - e = *(in++); - i = 0; - while( (c = *(in++))!=0 ){ - if( c==1 ){ - c = *(in++); - if( c==1 ){ - c = 0; - }else if( c==2 ){ - c = 1; - }else if( c==3 ){ - c = '\''; - }else{ - return -1; - } - } - out[i++] = (c + e)&0xff; - } - return i; +int +sqlite3_decode_binary(const unsigned char *in, unsigned char *out) { + int i, c, e; + e = *(in++); + i = 0; + while ((c = *(in++)) != 0) { + if (c == 1) { + c = *(in++); + if (c == 1) { + c = 0; + } else if (c == 2) { + c = 1; + } else if (c == 3) { + c = '\''; + } else { + return -1; + } + } + out[i++] = (c + e) & 0xff; + } + return i; } diff --git a/src/CppSQLite3.h b/src/CppSQLite3.h index c573a78..7ba12c8 100644 --- a/src/CppSQLite3.h +++ b/src/CppSQLite3.h @@ -2,11 +2,11 @@ // CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library. // // Copyright (c) 2004..2007 Rob Groves. All Rights Reserved. rob.groves@btinternet.com -// +// // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written -// agreement, is hereby granted, provided that the above copyright notice, -// this paragraph and the following two paragraphs appear in all copies, +// agreement, is hereby granted, provided that the above copyright notice, +// this paragraph and the following two paragraphs appear in all copies, // modifications, and distributions. // // IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, @@ -39,288 +39,259 @@ #define CPPSQLITE_ERROR 1000 -class CppSQLite3Exception -{ -public: - - CppSQLite3Exception(const int nErrCode, - char* szErrMess, - bool bDeleteMsg=true); - - CppSQLite3Exception(const CppSQLite3Exception& e); +class CppSQLite3Exception { + public: + CppSQLite3Exception(const int nErrCode, char *szErrMess, bool bDeleteMsg = true); - virtual ~CppSQLite3Exception(); + CppSQLite3Exception(const CppSQLite3Exception &e); - const int errorCode() { return mnErrCode; } + virtual ~CppSQLite3Exception(); - const char* errorMessage() { return mpszErrMess; } + const int errorCode() { return mnErrCode; } - static const char* errorCodeAsString(int nErrCode); + const char *errorMessage() { return mpszErrMess; } -private: + static const char *errorCodeAsString(int nErrCode); - int mnErrCode; - char* mpszErrMess; + private: + int mnErrCode; + char *mpszErrMess; }; +class CppSQLite3Buffer { + public: + CppSQLite3Buffer(); -class CppSQLite3Buffer -{ -public: - - CppSQLite3Buffer(); - - ~CppSQLite3Buffer(); - - const char* format(const char* szFormat, ...); + ~CppSQLite3Buffer(); - operator const char*() { return mpBuf; } + const char *format(const char *szFormat, ...); - void clear(); + operator const char *() { return mpBuf; } -private: + void clear(); - char* mpBuf; + private: + char *mpBuf; }; +class CppSQLite3Binary { + public: + CppSQLite3Binary(); -class CppSQLite3Binary -{ -public: + ~CppSQLite3Binary(); - CppSQLite3Binary(); + void setBinary(const unsigned char *pBuf, int nLen); + void setEncoded(const unsigned char *pBuf); - ~CppSQLite3Binary(); + const unsigned char *getEncoded(); + const unsigned char *getBinary(); - void setBinary(const unsigned char* pBuf, int nLen); - void setEncoded(const unsigned char* pBuf); + int getBinaryLength(); - const unsigned char* getEncoded(); - const unsigned char* getBinary(); + unsigned char *allocBuffer(int nLen); - int getBinaryLength(); + void clear(); - unsigned char* allocBuffer(int nLen); - - void clear(); - -private: - - unsigned char* mpBuf; - int mnBinaryLen; - int mnBufferLen; - int mnEncodedLen; - bool mbEncoded; + private: + unsigned char *mpBuf; + int mnBinaryLen; + int mnBufferLen; + int mnEncodedLen; + bool mbEncoded; }; +class CppSQLite3Query { + public: + CppSQLite3Query(); -class CppSQLite3Query -{ -public: - - CppSQLite3Query(); - - CppSQLite3Query(const CppSQLite3Query& rQuery); + CppSQLite3Query(const CppSQLite3Query &rQuery); - CppSQLite3Query(sqlite3* pDB, - sqlite3_stmt* pVM, - bool bEof, - bool bOwnVM=true); + CppSQLite3Query(sqlite3 *pDB, sqlite3_stmt *pVM, bool bEof, bool bOwnVM = true); - CppSQLite3Query& operator=(const CppSQLite3Query& rQuery); + CppSQLite3Query &operator=(const CppSQLite3Query &rQuery); - virtual ~CppSQLite3Query(); + virtual ~CppSQLite3Query(); - int numFields(); + int numFields(); - int fieldIndex(const char* szField); - const char* fieldName(int nCol); + int fieldIndex(const char *szField); + const char *fieldName(int nCol); - const char* fieldDeclType(int nCol); - int fieldDataType(int nCol); + const char *fieldDeclType(int nCol); + int fieldDataType(int nCol); - const char* fieldValue(int nField); - const char* fieldValue(const char* szField); + const char *fieldValue(int nField); + const char *fieldValue(const char *szField); - int getIntField(int nField, int nNullValue=0); - int getIntField(const char* szField, int nNullValue=0); + int getIntField(int nField, int nNullValue = 0); + int getIntField(const char *szField, int nNullValue = 0); - sqlite_int64 getInt64Field(int nField, sqlite_int64 nNullValue=0); - sqlite_int64 getInt64Field(const char* szField, sqlite_int64 nNullValue=0); + sqlite_int64 getInt64Field(int nField, sqlite_int64 nNullValue = 0); + sqlite_int64 getInt64Field(const char *szField, sqlite_int64 nNullValue = 0); - double getFloatField(int nField, double fNullValue=0.0); - double getFloatField(const char* szField, double fNullValue=0.0); + double getFloatField(int nField, double fNullValue = 0.0); + double getFloatField(const char *szField, double fNullValue = 0.0); - const char* getStringField(int nField, const char* szNullValue=""); - const char* getStringField(const char* szField, const char* szNullValue=""); + const char *getStringField(int nField, const char *szNullValue = ""); + const char *getStringField(const char *szField, const char *szNullValue = ""); - const unsigned char* getBlobField(int nField, int& nLen); - const unsigned char* getBlobField(const char* szField, int& nLen); + const unsigned char *getBlobField(int nField, int &nLen); + const unsigned char *getBlobField(const char *szField, int &nLen); bool fieldIsNull(int nField); - bool fieldIsNull(const char* szField); + bool fieldIsNull(const char *szField); - bool eof(); + bool eof(); - void nextRow(); + void nextRow(); - void finalize(); + void finalize(); -private: + private: + void checkVM(); - void checkVM(); - - sqlite3* mpDB; - sqlite3_stmt* mpVM; - bool mbEof; - int mnCols; - bool mbOwnVM; + sqlite3 *mpDB; + sqlite3_stmt *mpVM; + bool mbEof; + int mnCols; + bool mbOwnVM; }; +class CppSQLite3Table { + public: + CppSQLite3Table(); -class CppSQLite3Table -{ -public: - - CppSQLite3Table(); - - CppSQLite3Table(const CppSQLite3Table& rTable); + CppSQLite3Table(const CppSQLite3Table &rTable); - CppSQLite3Table(char** paszResults, int nRows, int nCols); + CppSQLite3Table(char **paszResults, int nRows, int nCols); - virtual ~CppSQLite3Table(); + virtual ~CppSQLite3Table(); - CppSQLite3Table& operator=(const CppSQLite3Table& rTable); + CppSQLite3Table &operator=(const CppSQLite3Table &rTable); - int numFields(); + int numFields(); - int numRows(); + int numRows(); - const char* fieldName(int nCol); + const char *fieldName(int nCol); - const char* fieldValue(int nField); - const char* fieldValue(const char* szField); + const char *fieldValue(int nField); + const char *fieldValue(const char *szField); - int getIntField(int nField, int nNullValue=0); - int getIntField(const char* szField, int nNullValue=0); + int getIntField(int nField, int nNullValue = 0); + int getIntField(const char *szField, int nNullValue = 0); - double getFloatField(int nField, double fNullValue=0.0); - double getFloatField(const char* szField, double fNullValue=0.0); + double getFloatField(int nField, double fNullValue = 0.0); + double getFloatField(const char *szField, double fNullValue = 0.0); - const char* getStringField(int nField, const char* szNullValue=""); - const char* getStringField(const char* szField, const char* szNullValue=""); + const char *getStringField(int nField, const char *szNullValue = ""); + const char *getStringField(const char *szField, const char *szNullValue = ""); - bool fieldIsNull(int nField); - bool fieldIsNull(const char* szField); - - void setRow(int nRow); + bool fieldIsNull(int nField); + bool fieldIsNull(const char *szField); - void finalize(); + void setRow(int nRow); -private: + void finalize(); - void checkResults(); + private: + void checkResults(); - int mnCols; - int mnRows; - int mnCurrentRow; - char** mpaszResults; + int mnCols; + int mnRows; + int mnCurrentRow; + char **mpaszResults; }; +class CppSQLite3Statement { + public: + CppSQLite3Statement(); -class CppSQLite3Statement -{ -public: + CppSQLite3Statement(const CppSQLite3Statement &rStatement); - CppSQLite3Statement(); + CppSQLite3Statement(sqlite3 *pDB, sqlite3_stmt *pVM); - CppSQLite3Statement(const CppSQLite3Statement& rStatement); + virtual ~CppSQLite3Statement(); - CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM); + CppSQLite3Statement &operator=(const CppSQLite3Statement &rStatement); - virtual ~CppSQLite3Statement(); + int execDML(); - CppSQLite3Statement& operator=(const CppSQLite3Statement& rStatement); + CppSQLite3Query execQuery(); - int execDML(); + void bind(int nParam, const char *szValue); + void bind(int nParam, const int nValue); + void bind(int nParam, const double dwValue); + void bind(int nParam, const unsigned char *blobValue, int nLen); + void bindNull(int nParam); - CppSQLite3Query execQuery(); - - void bind(int nParam, const char* szValue); - void bind(int nParam, const int nValue); - void bind(int nParam, const double dwValue); - void bind(int nParam, const unsigned char* blobValue, int nLen); - void bindNull(int nParam); - - int bindParameterIndex(const char* szParam); - void bind(const char* szParam, const char* szValue); - void bind(const char* szParam, const int nValue); - void bind(const char* szParam, const double dwValue); - void bind(const char* szParam, const unsigned char* blobValue, int nLen); - void bindNull(const char* szParam); + int bindParameterIndex(const char *szParam); + void bind(const char *szParam, const char *szValue); + void bind(const char *szParam, const int nValue); + void bind(const char *szParam, const double dwValue); + void bind(const char *szParam, const unsigned char *blobValue, int nLen); + void bindNull(const char *szParam); void reset(); - void finalize(); - -private: + void finalize(); - void checkDB(); - void checkVM(); + private: + void checkDB(); + void checkVM(); - sqlite3* mpDB; - sqlite3_stmt* mpVM; + sqlite3 *mpDB; + sqlite3_stmt *mpVM; }; +class CppSQLite3DB { + public: + CppSQLite3DB(); -class CppSQLite3DB -{ -public: + virtual ~CppSQLite3DB(); - CppSQLite3DB(); + void open(const char *szFile); - virtual ~CppSQLite3DB(); + void close(); - void open(const char* szFile); + bool tableExists(const char *szTable); - void close(); + int execDML(const char *szSQL); - bool tableExists(const char* szTable); + CppSQLite3Query execQuery(const char *szSQL); - int execDML(const char* szSQL); + int execScalar(const char *szSQL, int nNullValue = 0); - CppSQLite3Query execQuery(const char* szSQL); + CppSQLite3Table getTable(const char *szSQL); - int execScalar(const char* szSQL, int nNullValue=0); + CppSQLite3Statement compileStatement(const char *szSQL); - CppSQLite3Table getTable(const char* szSQL); + sqlite_int64 lastRowId(); - CppSQLite3Statement compileStatement(const char* szSQL); + void interrupt() { sqlite3_interrupt(mpDB); } - sqlite_int64 lastRowId(); + void setBusyTimeout(int nMillisecs); - void interrupt() { sqlite3_interrupt(mpDB); } + static const char *SQLiteVersion() { return SQLITE_VERSION; } - void setBusyTimeout(int nMillisecs); + static const char *SQLiteHeaderVersion() { return SQLITE_VERSION; } - static const char* SQLiteVersion() { return SQLITE_VERSION; } - static const char* SQLiteHeaderVersion() { return SQLITE_VERSION; } - static const char* SQLiteLibraryVersion() { return sqlite3_libversion(); } - static int SQLiteLibraryVersionNumber() { return sqlite3_libversion_number(); } + static const char *SQLiteLibraryVersion() { return sqlite3_libversion(); } - bool IsAutoCommitOn(); + static int SQLiteLibraryVersionNumber() { return sqlite3_libversion_number(); } -private: + bool IsAutoCommitOn(); - CppSQLite3DB(const CppSQLite3DB& db); - CppSQLite3DB& operator=(const CppSQLite3DB& db); + private: + CppSQLite3DB(const CppSQLite3DB &db); + CppSQLite3DB &operator=(const CppSQLite3DB &db); - sqlite3_stmt* compile(const char* szSQL); + sqlite3_stmt *compile(const char *szSQL); - void checkDB(); + void checkDB(); - sqlite3* mpDB; - int mnBusyTimeoutMs; + sqlite3 *mpDB; + int mnBusyTimeoutMs; }; #endif diff --git a/src/CurrencyBox.cpp b/src/CurrencyBox.cpp index d3e1301..ba211ab 100644 --- a/src/CurrencyBox.cpp +++ b/src/CurrencyBox.cpp @@ -5,78 +5,69 @@ #include "TimeSupport.h" #include "Translate.h" -CurrencyBoxFilter::CurrencyBoxFilter(CurrencyBox *box) - : NavTextBoxFilter(box) -{ -} +CurrencyBoxFilter::CurrencyBoxFilter(CurrencyBox *box) : NavTextBoxFilter(box) {} -filter_result CurrencyBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +CurrencyBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB && ((NavTextBox*)TextControl())->IsTabFiltering()) - { - if(mod & B_SHIFT_KEY) + if (key == B_TAB && ((NavTextBox *)TextControl())->IsTabFiltering()) { + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; +#endif + + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; return B_DISPATCH_MESSAGE; } -CurrencyBox::CurrencyBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : NavTextBox(name,label,text,msg,flags) -{ +CurrencyBox::CurrencyBox( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : NavTextBox(name, label, text, msg, flags) { SetFilter(new CurrencyBoxFilter(this)); - const char amount_disallowed[]=" `~!@#%^&*()_-+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" - "ZXCVBNM<>?/qwertyuiopasdfghjklzxcvbnm"; - int32 i=0; - while(amount_disallowed[i]) - { + const char amount_disallowed[] = " `~!@#%^&*()_-+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" + "ZXCVBNM<>?/qwertyuiopasdfghjklzxcvbnm"; + int32 i = 0; + while (amount_disallowed[i]) { TextView()->DisallowChar(amount_disallowed[i]); i++; } SetCharacterLimit(20); } - -bool CurrencyBox::Validate(bool alert) -{ - if(strlen(Text())<1) +bool +CurrencyBox::Validate(bool alert) { + if (strlen(Text()) < 1) SetText("0"); Fixed amount; - if(gCurrentLocale.StringToCurrency(Text(),amount)!=B_OK) - { - if(alert) - { - ShowAlert(TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.")); + if (gCurrentLocale.StringToCurrency(Text(), amount) != B_OK) { + if (alert) { + ShowAlert( + TRANSLATE("Capital Be didn't understand the amount."), + TRANSLATE("There may be a typo or the wrong kind of currency symbol " + "for this account.") + ); MakeFocus(true); } return false; - } - else - { + } else { BString string; - gCurrentLocale.CurrencyToString(amount,string); + gCurrentLocale.CurrencyToString(amount, string); SetText(string.String()); } - + return true; } diff --git a/src/CurrencyBox.h b/src/CurrencyBox.h index 81b098a..a2a54dd 100644 --- a/src/CurrencyBox.h +++ b/src/CurrencyBox.h @@ -5,23 +5,22 @@ class CurrencyBox; -class CurrencyBoxFilter : public NavTextBoxFilter -{ -public: +class CurrencyBoxFilter : public NavTextBoxFilter { + public: CurrencyBoxFilter(CurrencyBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class CurrencyBox : public NavTextBox -{ -public: - CurrencyBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class CurrencyBox : public NavTextBox { + public: + CurrencyBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); bool Validate(bool alert = true); - -private: + + private: friend CurrencyBoxFilter; }; diff --git a/src/DAlert.cpp b/src/DAlert.cpp index 91dbf80..c1173cc 100644 --- a/src/DAlert.cpp +++ b/src/DAlert.cpp @@ -40,16 +40,16 @@ #include #include +#include #include #include #include #include -#include #include #include -//#define DEBUG_ALERT +// #define DEBUG_ALERT #ifdef DEBUG_ALERT #define FTRACE(x) fprintf(x) #else @@ -57,8 +57,8 @@ #endif // Default size of the Alert window. -#define DEFAULT_RECT BRect(0, 0, 310, 75) -#define max(LHS, RHS) ((LHS) > (RHS) ? (LHS) : (RHS)) +#define DEFAULT_RECT BRect(0, 0, 310, 75) +#define max(LHS, RHS) ((LHS) > (RHS) ? (LHS) : (RHS)) // Globals --------------------------------------------------------------------- static const unsigned int kAlertButtonMsg = 'ALTB'; @@ -88,25 +88,26 @@ static const int kTextBottomOffset = 45; //------------------------------------------------------------------------------ class TAlertView : public BView { - public: - TAlertView(BRect frame); - TAlertView(BMessage* archive); - ~TAlertView(); + public: + TAlertView(BRect frame); + TAlertView(BMessage *archive); + ~TAlertView(); - static TAlertView* Instantiate(BMessage* archive); - status_t Archive(BMessage* archive, bool deep = true); + static TAlertView *Instantiate(BMessage *archive); + status_t Archive(BMessage *archive, bool deep = true); - virtual void Draw(BRect updateRect); + virtual void Draw(BRect updateRect); - // These functions (or something analogous) are missing from libbe.so's - // dump. I can only assume that the bitmap is a public var in the - // original implementation -- or DAlert is a friend of TAlertView. - // Neither one is necessary, since I can just add these. - void SetBitmap(BBitmap* Icon) { fIconBitmap = Icon; } - BBitmap* Bitmap() { return fIconBitmap; } + // These functions (or something analogous) are missing from libbe.so's + // dump. I can only assume that the bitmap is a public var in the + // original implementation -- or DAlert is a friend of TAlertView. + // Neither one is necessary, since I can just add these. + void SetBitmap(BBitmap *Icon) { fIconBitmap = Icon; } - private: - BBitmap* fIconBitmap; + BBitmap *Bitmap() { return fIconBitmap; } + + private: + BBitmap *fIconBitmap; }; //------------------------------------------------------------------------------ @@ -115,69 +116,64 @@ class TAlertView : public BView { // TextEntryAlert does it, but there are clearly no message filtering functions // on DAlert so here we go. class _DAlertFilter_ : public BMessageFilter { - public: - _DAlertFilter_(DAlert* Alert); - ~_DAlertFilter_(); + public: + _DAlertFilter_(DAlert *Alert); + ~_DAlertFilter_(); - virtual filter_result Filter(BMessage* msg, BHandler** target); + virtual filter_result Filter(BMessage *msg, BHandler **target); - private: - DAlert* fAlert; + private: + DAlert *fAlert; }; - static float -width_from_label(BButton *button) -{ +width_from_label(BButton *button) { // BButton::GetPreferredSize() does not return the minimum width // required to fit the label. Thus, the width is computed here. return button->StringWidth(button->Label()) + 20.0f; } - // #pragma mark - DAlert -DAlert::DAlert(const char *title, const char *text, const char *button1, - const char *button2, const char *button3, button_width width, - alert_type type) - : BWindow(DEFAULT_RECT, title, B_MODAL_WINDOW, - B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS) -{ +DAlert::DAlert( + const char *title, const char *text, const char *button1, const char *button2, + const char *button3, button_width width, alert_type type +) + : BWindow( + DEFAULT_RECT, title, B_MODAL_WINDOW, + B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS + ) { InitObject(text, button1, button2, button3, width, B_EVEN_SPACING, type); } - -DAlert::DAlert(const char *title, const char *text, const char *button1, - const char *button2, const char *button3, button_width width, - button_spacing spacing, alert_type type) - : BWindow(DEFAULT_RECT, title, B_MODAL_WINDOW, - B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS) -{ +DAlert::DAlert( + const char *title, const char *text, const char *button1, const char *button2, + const char *button3, button_width width, button_spacing spacing, alert_type type +) + : BWindow( + DEFAULT_RECT, title, B_MODAL_WINDOW, + B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS + ) { InitObject(text, button1, button2, button3, width, spacing, type); } - -DAlert::~DAlert() -{ +DAlert::~DAlert() { // Probably not necessary, but it makes me feel better. if (fAlertSem >= B_OK) delete_sem(fAlertSem); } - -DAlert::DAlert(BMessage* data) - : BWindow(data) -{ +DAlert::DAlert(BMessage *data) : BWindow(data) { fInvoker = NULL; fAlertSem = -1; fAlertVal = -1; - fTextView = (BTextView*)FindView("_tv_"); + fTextView = (BTextView *)FindView("_tv_"); - fButtons[0] = (BButton*)FindView("_b0_"); - fButtons[1] = (BButton*)FindView("_b1_"); - fButtons[2] = (BButton*)FindView("_b2_"); + fButtons[0] = (BButton *)FindView("_b0_"); + fButtons[1] = (BButton *)FindView("_b1_"); + fButtons[2] = (BButton *)FindView("_b2_"); if (fButtons[2]) SetDefaultButton(fButtons[2]); @@ -186,14 +182,14 @@ DAlert::DAlert(BMessage* data) else if (fButtons[0]) SetDefaultButton(fButtons[0]); - TAlertView* master = (TAlertView*)FindView("_master_"); + TAlertView *master = (TAlertView *)FindView("_master_"); if (master) master->SetBitmap(InitIcon()); // Get keys char key; for (int32 i = 0; i < 3; ++i) { - if (data->FindInt8("_but_key", i, (int8*)&key) == B_OK) + if (data->FindInt8("_but_key", i, (int8 *)&key) == B_OK) fKeys[i] = key; } @@ -209,20 +205,16 @@ DAlert::DAlert(BMessage* data) AddCommonFilter(new _DAlertFilter_(this)); } - -BArchivable* -DAlert::Instantiate(BMessage* data) -{ +BArchivable * +DAlert::Instantiate(BMessage *data) { if (!validate_instantiation(data, "DAlert")) return NULL; return new DAlert(data); } - status_t -DAlert::Archive(BMessage* data, bool deep) const -{ +DAlert::Archive(BMessage *data, bool deep) const { status_t ret = BWindow::Archive(data, deep); // Stow the text @@ -252,28 +244,22 @@ DAlert::Archive(BMessage* data, bool deep) const return ret; } - void -DAlert::SetShortcut(int32 index, char key) -{ +DAlert::SetShortcut(int32 index, char key) { if (index >= 0 && index < 3) fKeys[index] = key; } - char -DAlert::Shortcut(int32 index) const -{ +DAlert::Shortcut(int32 index) const { if (index >= 0 && index < 3) return fKeys[index]; return 0; } - int32 -DAlert::Go() -{ +DAlert::Go() { fAlertSem = create_sem(0, "AlertSem"); if (fAlertSem < B_OK) { Quit(); @@ -281,8 +267,7 @@ DAlert::Go() } // Get the originating window, if it exists - BWindow* window = - dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); + BWindow *window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); Show(); @@ -292,8 +277,7 @@ DAlert::Go() status_t err; for (;;) { do { - err = acquire_sem_etc(fAlertSem, 1, B_RELATIVE_TIMEOUT, - kSemTimeOut); + err = acquire_sem_etc(fAlertSem, 1, B_RELATIVE_TIMEOUT, kSemTimeOut); // We've (probably) had our time slice taken away from us } while (err == B_INTERRUPTED); @@ -317,19 +301,15 @@ DAlert::Go() return value; } - status_t -DAlert::Go(BInvoker* invoker) -{ +DAlert::Go(BInvoker *invoker) { fInvoker = invoker; Show(); return B_OK; } - void -DAlert::MessageReceived(BMessage* msg) -{ +DAlert::MessageReceived(BMessage *msg) { if (msg->what != kAlertButtonMsg) return BWindow::MessageReceived(msg); @@ -338,9 +318,9 @@ DAlert::MessageReceived(BMessage* msg) if (fAlertSem < B_OK) { // Semaphore hasn't been created; we're running asynchronous if (fInvoker) { - BMessage* out = fInvoker->Message(); - if (out && (out->ReplaceInt32("which", which) == B_OK - || out->AddInt32("which", which) == B_OK)) + BMessage *out = fInvoker->Message(); + if (out && (out->ReplaceInt32("which", which) == B_OK || + out->AddInt32("which", which) == B_OK)) fInvoker->Invoke(); } PostMessage(B_QUIT_REQUESTED); @@ -359,79 +339,61 @@ DAlert::MessageReceived(BMessage* msg) } } - void -DAlert::FrameResized(float newWidth, float newHeight) -{ +DAlert::FrameResized(float newWidth, float newHeight) { BWindow::FrameResized(newWidth, newHeight); } - -BButton* -DAlert::ButtonAt(int32 index) const -{ +BButton * +DAlert::ButtonAt(int32 index) const { if (index >= 0 && index < 3) return fButtons[index]; return NULL; } - -BTextView* -DAlert::TextView() const -{ +BTextView * +DAlert::TextView() const { return fTextView; } - -BHandler* -DAlert::ResolveSpecifier(BMessage* msg, int32 index, - BMessage* specifier, int32 form, const char* property) -{ +BHandler * +DAlert::ResolveSpecifier( + BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property +) { return BWindow::ResolveSpecifier(msg, index, specifier, form, property); } - status_t -DAlert::GetSupportedSuites(BMessage* data) -{ +DAlert::GetSupportedSuites(BMessage *data) { return BWindow::GetSupportedSuites(data); } - void -DAlert::DispatchMessage(BMessage* msg, BHandler* handler) -{ +DAlert::DispatchMessage(BMessage *msg, BHandler *handler) { BWindow::DispatchMessage(msg, handler); } - void -DAlert::Quit() -{ +DAlert::Quit() { BWindow::Quit(); } - bool -DAlert::QuitRequested() -{ +DAlert::QuitRequested() { return BWindow::QuitRequested(); } - BPoint -DAlert::AlertPosition(float width, float height) -{ +DAlert::AlertPosition(float width, float height) { BPoint result(100, 100); - BWindow* window = - dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); + BWindow *window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); BScreen screen(window); - BRect screenFrame(0, 0, 640, 480); - if (screen.IsValid()) - screenFrame = screen.Frame(); + BRect screenFrame(0, 0, 640, 480); + if (screen.IsValid()) + screenFrame = screen.Frame(); // Horizontally, we're smack in the middle result.x = screenFrame.left + (screenFrame.Width() / 2.0) - (width / 2.0); @@ -442,24 +404,25 @@ DAlert::AlertPosition(float width, float height) return result; } - status_t -DAlert::Perform(perform_code d, void* arg) -{ +DAlert::Perform(perform_code d, void *arg) { return BWindow::Perform(d, arg); } +void +DAlert::_ReservedAlert1() {} -void DAlert::_ReservedAlert1() {} -void DAlert::_ReservedAlert2() {} -void DAlert::_ReservedAlert3() {} +void +DAlert::_ReservedAlert2() {} +void +DAlert::_ReservedAlert3() {} -void -DAlert::InitObject(const char* text, const char* button0, const char* button1, - const char* button2, button_width width, button_spacing spacing, - alert_type type) -{ +void +DAlert::InitObject( + const char *text, const char *button0, const char *button1, const char *button2, + button_width width, button_spacing spacing, alert_type type +) { fInvoker = NULL; fAlertSem = -1; fAlertVal = -1; @@ -470,7 +433,7 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, fButtonWidth = width; // Set up the "_master_" view - TAlertView* masterView = new TAlertView(Bounds()); + TAlertView *masterView = new TAlertView(Bounds()); AddChild(masterView); masterView->SetBitmap(InitIcon()); @@ -484,23 +447,28 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, protoMsg.AddInt32("which", 0); // Set up the buttons int buttonCount = 0; - fButtons[buttonCount] = new BButton(BRect(0, 0, 0, 0), "_b0_", button0, - new BMessage(protoMsg), B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM); + fButtons[buttonCount] = new BButton( + BRect(0, 0, 0, 0), "_b0_", button0, new BMessage(protoMsg), B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM + ); masterView->AddChild(fButtons[buttonCount]); ++buttonCount; if (button1) { protoMsg.ReplaceInt32("which", 1); - fButtons[buttonCount] = new BButton(BRect(0, 0, 0, 0), "_b1_", button1, - new BMessage(protoMsg), B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM); + fButtons[buttonCount] = new BButton( + BRect(0, 0, 0, 0), "_b1_", button1, new BMessage(protoMsg), + B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM + ); masterView->AddChild(fButtons[buttonCount]); ++buttonCount; } if (button2) { protoMsg.ReplaceInt32("which", 2); - fButtons[buttonCount] = new BButton(BRect(0, 0, 0, 0), "_b2_", button2, - new BMessage(protoMsg), B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM); + fButtons[buttonCount] = new BButton( + BRect(0, 0, 0, 0), "_b2_", button2, new BMessage(protoMsg), + B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM + ); masterView->AddChild(fButtons[buttonCount]); ++buttonCount; @@ -518,7 +486,7 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, } for (int i = buttonCount - 1; i >= 0; --i) { - // Determine the button's size + // Determine the button's size float buttonWidth = 0, buttonHeight = 0; fButtons[i]->GetPreferredSize(&buttonWidth, &buttonHeight); if (fButtonWidth == B_WIDTH_FROM_WIDEST) @@ -534,18 +502,17 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, buttonY = Bounds().bottom - buttonHeight; if (i == buttonCount - 1) { // The right-most button - buttonX = Bounds().right - fButtons[i]->Frame().Width() - - kButtonRightOffset; - + buttonX = Bounds().right - fButtons[i]->Frame().Width() - kButtonRightOffset; + // This hack is put in place because placement under Zeta looks goofy // because there is no border around default buttons anymore - if(B_BEOS_VERSION > 0x0510) + if (B_BEOS_VERSION > 0x0510) buttonY -= kButtonBottomOffset; else buttonY -= kDefButtonBottomOffset; } else { - buttonX = fButtons[i + 1]->Frame().left - - fButtons[i]->Frame().Width() - kButtonSpaceOffset; + buttonX = + fButtons[i + 1]->Frame().left - fButtons[i]->Frame().Width() - kButtonSpaceOffset; buttonY -= kButtonBottomOffset; if (i == 0) { if (spacing == B_OFFSET_SPACING) { @@ -555,17 +522,15 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, // If there are two buttons, the left wall of // button0 needs to line up with the left wall // of the TextView. - buttonX = (masterView->Bitmap()) ? - kTextIconOffset : kTextLeftOffset; - if (fButtons[i + 1]->Frame().left - - (buttonX + fButtons[i]->Frame().Width()) < - kButtonMinOffsetSpaceOffset) { - // Recompute buttonX using min offset space - // if using the current buttonX would not - // provide enough space or cause an overlap. - buttonX = fButtons[i + 1]->Frame().left - - fButtons[i]->Frame().Width() - - kButtonMinOffsetSpaceOffset; + buttonX = (masterView->Bitmap()) ? kTextIconOffset : kTextLeftOffset; + if (fButtons[i + 1]->Frame().left - + (buttonX + fButtons[i]->Frame().Width()) < + kButtonMinOffsetSpaceOffset) { + // Recompute buttonX using min offset space + // if using the current buttonX would not + // provide enough space or cause an overlap. + buttonX = fButtons[i + 1]->Frame().left - fButtons[i]->Frame().Width() - + kButtonMinOffsetSpaceOffset; } } } else if (buttonCount == 3) @@ -577,8 +542,7 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, // Adjust the window's width, if necessary float totalWidth = kButtonRightOffset; - totalWidth += fButtons[buttonCount - 1]->Frame().right - - fButtons[0]->Frame().left; + totalWidth += fButtons[buttonCount - 1]->Frame().right - fButtons[0]->Frame().left; if (masterView->Bitmap()) totalWidth += kIconStripeWidth + kWindowIconOffset; else @@ -597,29 +561,31 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, ResizeTo(totalWidth, Bounds().Height()); // Set up the text view - BRect textViewRect(kTextLeftOffset, kTextTopOffset, - Bounds().right - kTextRightOffset, - Bounds().bottom - kTextBottomOffset); + BRect textViewRect( + kTextLeftOffset, kTextTopOffset, Bounds().right - kTextRightOffset, + Bounds().bottom - kTextBottomOffset + ); if (masterView->Bitmap()) textViewRect.left = kTextIconOffset; - fTextView = new BTextView(textViewRect, "_tv_", textViewRect, - B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW); + fTextView = new BTextView( + textViewRect, "_tv_", textViewRect, B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW + ); masterView->AddChild(fTextView); -// fTextView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); - fTextView->SetViewColor(240,240,240); + // fTextView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); + fTextView->SetViewColor(240, 240, 240); fTextView->MakeEditable(false); fTextView->SetStylable(true); fTextView->MakeSelectable(true); fTextView->SetWordWrap(true); - + // Set up text - boldface the title, skip a line, and then show the message. BFont font(be_bold_font); font.SetSize(be_plain_font->Size() + 3.0); fTextView->SetFontAndColor(&font); fTextView->Insert(Title()); - fTextView->Insert("\n\n",2); + fTextView->Insert("\n\n", 2); fTextView->SetFontAndColor(be_plain_font); fTextView->Insert(text); @@ -637,32 +603,30 @@ DAlert::InitObject(const char* text, const char* button0, const char* button1, MoveTo(AlertPosition(Frame().Width(), Frame().Height())); } - -BBitmap* -DAlert::InitIcon() -{ +BBitmap * +DAlert::InitIcon() { BBitmap *icon = NULL; - + switch (fMsgType) { - case B_INFO_ALERT: - icon = BTranslationUtils::GetBitmap('PNG ',"cb_info_icon.png"); - break; - case B_IDEA_ALERT: - icon = BTranslationUtils::GetBitmap('PNG ',"cb_idea_icon.png"); - break; - case B_WARNING_ALERT: - icon = BTranslationUtils::GetBitmap('PNG ',"cb_warning_icon.png"); - break; - case B_STOP_ALERT: - icon = BTranslationUtils::GetBitmap('PNG ',"cb_stop_icon.png"); - break; - - default: - // Alert type is either invalid or B_EMPTY_ALERT; - // either way, we're not going to load an icon - return NULL; + case B_INFO_ALERT: + icon = BTranslationUtils::GetBitmap('PNG ', "cb_info_icon.png"); + break; + case B_IDEA_ALERT: + icon = BTranslationUtils::GetBitmap('PNG ', "cb_idea_icon.png"); + break; + case B_WARNING_ALERT: + icon = BTranslationUtils::GetBitmap('PNG ', "cb_warning_icon.png"); + break; + case B_STOP_ALERT: + icon = BTranslationUtils::GetBitmap('PNG ', "cb_stop_icon.png"); + break; + + default: + // Alert type is either invalid or B_EMPTY_ALERT; + // either way, we're not going to load an icon + return NULL; } - + if (!icon) { // If there's no icon, it's an empty alert indeed. fMsgType = B_EMPTY_ALERT; @@ -671,91 +635,62 @@ DAlert::InitIcon() return icon; } - //------------------------------------------------------------------------------ // #pragma mark - TAlertView TAlertView::TAlertView(BRect frame) - : BView(frame, "TAlertView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW), - fIconBitmap(NULL) -{ -// SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); - SetViewColor(240,240,240); + : BView(frame, "TAlertView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW), fIconBitmap(NULL) { + // SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); + SetViewColor(240, 240, 240); } +TAlertView::TAlertView(BMessage *archive) : BView(archive), fIconBitmap(NULL) {} -TAlertView::TAlertView(BMessage* archive) - : BView(archive), - fIconBitmap(NULL) -{ -} - +TAlertView::~TAlertView() { delete fIconBitmap; } -TAlertView::~TAlertView() -{ - delete fIconBitmap; -} - - -TAlertView* -TAlertView::Instantiate(BMessage* archive) -{ +TAlertView * +TAlertView::Instantiate(BMessage *archive) { if (!validate_instantiation(archive, "TAlertView")) return NULL; return new TAlertView(archive); } - status_t -TAlertView::Archive(BMessage* archive, bool deep) -{ +TAlertView::Archive(BMessage *archive, bool deep) { return BView::Archive(archive, deep); } - void -TAlertView::Draw(BRect updateRect) -{ +TAlertView::Draw(BRect updateRect) { // Here's the fun stuff if (fIconBitmap) { -/* BRect stripeRect = Bounds(); - stripeRect.right = kIconStripeWidth; -// SetHighColor(tint_color(ViewColor(), B_DARKEN_1_TINT)); - SetHighColor(220,220,220); - FillRect(stripeRect); -*/ + /* BRect stripeRect = Bounds(); + stripeRect.right = kIconStripeWidth; + // SetHighColor(tint_color(ViewColor(), B_DARKEN_1_TINT)); + SetHighColor(220,220,220); + FillRect(stripeRect); + */ SetDrawingMode(B_OP_OVER); DrawBitmapAsync(fIconBitmap, BPoint(5, 10)); SetDrawingMode(B_OP_COPY); } - } - //------------------------------------------------------------------------------ // #pragma mark - _DAlertFilter_ -_DAlertFilter_::_DAlertFilter_(DAlert* alert) - : BMessageFilter(B_KEY_DOWN), - fAlert(alert) -{ -} - - -_DAlertFilter_::~_DAlertFilter_() -{ -} +_DAlertFilter_::_DAlertFilter_(DAlert *alert) : BMessageFilter(B_KEY_DOWN), fAlert(alert) {} +_DAlertFilter_::~_DAlertFilter_() {} filter_result -_DAlertFilter_::Filter(BMessage* msg, BHandler** target) -{ +_DAlertFilter_::Filter(BMessage *msg, BHandler **target) { if (msg->what == B_KEY_DOWN) { char byte; - if (msg->FindInt8("byte", (int8*)&byte) == B_OK) { + if (msg->FindInt8("byte", (int8 *)&byte) == B_OK) { for (int i = 0; i < 3; ++i) { if (byte == fAlert->Shortcut(i) && fAlert->ButtonAt(i)) { char space = ' '; @@ -769,4 +704,3 @@ _DAlertFilter_::Filter(BMessage* msg, BHandler** target) return B_DISPATCH_MESSAGE; } - diff --git a/src/DAlert.h b/src/DAlert.h index 4ae27fc..0fc47b9 100644 --- a/src/DAlert.h +++ b/src/DAlert.h @@ -23,16 +23,16 @@ // Author: Erik Jaesler (erik@cgsoftware.com) // Description: DAlert displays a modal alert window. //------------------------------------------------------------------------------ - -#ifndef _ALERT_H -#define _ALERT_H + +#ifndef _ALERT_H +#define _ALERT_H // Standard Includes ----------------------------------------------------------- // System Includes ------------------------------------------------------------- +#include #include #include -#include // Project Includes ------------------------------------------------------------ @@ -48,104 +48,84 @@ class BInvoker; class BTextView; // enum for flavors of alert --------------------------------------------------- -enum alert_type { - B_EMPTY_ALERT = 0, - B_INFO_ALERT, - B_IDEA_ALERT, - B_WARNING_ALERT, - B_STOP_ALERT -}; +enum alert_type { B_EMPTY_ALERT = 0, B_INFO_ALERT, B_IDEA_ALERT, B_WARNING_ALERT, B_STOP_ALERT }; - -enum button_spacing { - B_EVEN_SPACING = 0, - B_OFFSET_SPACING -}; +enum button_spacing { B_EVEN_SPACING = 0, B_OFFSET_SPACING }; // DAlert class ---------------------------------------------------------------- -class DAlert : public BWindow -{ -public: - - DAlert( const char *title, - const char *text, - const char *button1, - const char *button2 = NULL, - const char *button3 = NULL, - button_width width = B_WIDTH_AS_USUAL, - alert_type type = B_INFO_ALERT); - DAlert( const char *title, - const char *text, - const char *button1, - const char *button2, - const char *button3, - button_width width, - button_spacing spacing, - alert_type type = B_INFO_ALERT); -virtual ~DAlert(); - -// Archiving - DAlert(BMessage *data); -static BArchivable *Instantiate(BMessage *data); -virtual status_t Archive(BMessage *data, bool deep = true) const; - -// DAlert guts - void SetShortcut(int32 button_index, char key); - char Shortcut(int32 button_index) const; - - int32 Go(); - status_t Go(BInvoker *invoker); - -virtual void MessageReceived(BMessage *an_event); -virtual void FrameResized(float new_width, float new_height); - BButton *ButtonAt(int32 index) const; - BTextView *TextView() const; - -virtual BHandler *ResolveSpecifier(BMessage *msg, - int32 index, - BMessage *specifier, - int32 form, - const char *property); -virtual status_t GetSupportedSuites(BMessage *data); - -virtual void DispatchMessage(BMessage *msg, BHandler *handler); -virtual void Quit(); -virtual bool QuitRequested(); - -static BPoint AlertPosition(float width, float height); - -// Private or reserved --------------------------------------------------------- -virtual status_t Perform(perform_code d, void *arg); - -private: -friend class _DAlertFilter_; - -virtual void _ReservedAlert1(); -virtual void _ReservedAlert2(); -virtual void _ReservedAlert3(); - - void InitObject(const char *text, - const char *button1, - const char *button2 = NULL, - const char *button3 = NULL, - button_width width = B_WIDTH_AS_USUAL, - button_spacing spacing = B_EVEN_SPACING, - alert_type type = B_INFO_ALERT); - BBitmap *InitIcon(); - - sem_id fAlertSem; - int32 fAlertVal; - BButton *fButtons[3]; - BTextView *fTextView; - char fKeys[3]; - alert_type fMsgType; - button_width fButtonWidth; - BInvoker *fInvoker; - uint32 _reserved[4]; +class DAlert : public BWindow { + public: + DAlert( + const char *title, const char *text, const char *button1, const char *button2 = NULL, + const char *button3 = NULL, button_width width = B_WIDTH_AS_USUAL, + alert_type type = B_INFO_ALERT + ); + DAlert( + const char *title, const char *text, const char *button1, const char *button2, + const char *button3, button_width width, button_spacing spacing, + alert_type type = B_INFO_ALERT + ); + virtual ~DAlert(); + + // Archiving + DAlert(BMessage *data); + static BArchivable *Instantiate(BMessage *data); + virtual status_t Archive(BMessage *data, bool deep = true) const; + + // DAlert guts + void SetShortcut(int32 button_index, char key); + char Shortcut(int32 button_index) const; + + int32 Go(); + status_t Go(BInvoker *invoker); + + virtual void MessageReceived(BMessage *an_event); + virtual void FrameResized(float new_width, float new_height); + BButton *ButtonAt(int32 index) const; + BTextView *TextView() const; + + virtual BHandler *ResolveSpecifier( + BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property + ); + virtual status_t GetSupportedSuites(BMessage *data); + + virtual void DispatchMessage(BMessage *msg, BHandler *handler); + virtual void Quit(); + virtual bool QuitRequested(); + + static BPoint AlertPosition(float width, float height); + + // Private or reserved --------------------------------------------------------- + virtual status_t Perform(perform_code d, void *arg); + + private: + friend class _DAlertFilter_; + + virtual void _ReservedAlert1(); + virtual void _ReservedAlert2(); + virtual void _ReservedAlert3(); + + void InitObject( + const char *text, const char *button1, const char *button2 = NULL, + const char *button3 = NULL, button_width width = B_WIDTH_AS_USUAL, + button_spacing spacing = B_EVEN_SPACING, alert_type type = B_INFO_ALERT + ); + BBitmap *InitIcon(); + + sem_id fAlertSem; + int32 fAlertVal; + BButton *fButtons[3]; + BTextView *fTextView; + char fKeys[3]; + alert_type fMsgType; + button_width fButtonWidth; + BInvoker *fInvoker; + uint32 _reserved[4]; }; + //------------------------------------------------------------------------------ -#endif // _ALERT_H +#endif // _ALERT_H /* * $Log $ @@ -153,4 +133,3 @@ virtual void _ReservedAlert3(); * $Id $ * */ - diff --git a/src/DStringList.cpp b/src/DStringList.cpp index 3f486f4..eb66be4 100644 --- a/src/DStringList.cpp +++ b/src/DStringList.cpp @@ -1,125 +1,113 @@ -#include #include "DStringList.h" +#include -DStringList::DStringList(int32 itemsPerBlock, bool owner) - : fList(itemsPerBlock), - fOwner(owner) -{ -} +DStringList::DStringList(int32 itemsPerBlock, bool owner) : fList(itemsPerBlock), fOwner(owner) {} -DStringList::~DStringList() -{ - MakeEmpty(fOwner); -} +DStringList::~DStringList() { MakeEmpty(fOwner); } -bool DStringList::AddItem(const char *string) -{ - if(!string) +bool +DStringList::AddItem(const char *string) { + if (!string) return false; - + return fList.AddItem(new BString(string)); } -bool DStringList::AddItem(const char *string, int32 atIndex) -{ - if(!string) +bool +DStringList::AddItem(const char *string, int32 atIndex) { + if (!string) return false; - - return fList.AddItem(new BString(string),atIndex); + + return fList.AddItem(new BString(string), atIndex); } -bool DStringList::AddList(DStringList *newItems) -{ - if(!newItems) +bool +DStringList::AddList(DStringList *newItems) { + if (!newItems) return false; - for(int32 i=0; iCountItems(); i++) + for (int32 i = 0; i < newItems->CountItems(); i++) fList.AddItem(newItems->ItemAtFast(i)); return true; } -bool DStringList::AddList(DStringList *newItems, int32 atIndex) -{ - if(!newItems) +bool +DStringList::AddList(DStringList *newItems, int32 atIndex) { + if (!newItems) return false; - for(int32 i=0; iCountItems(); i++) - fList.AddItem(newItems->ItemAtFast(i),atIndex); + for (int32 i = 0; i < newItems->CountItems(); i++) + fList.AddItem(newItems->ItemAtFast(i), atIndex); return true; } -bool DStringList::RemoveItem(BString *item) -{ +bool +DStringList::RemoveItem(BString *item) { return fList.RemoveItem(item); } -BString *DStringList::RemoveItem(int32 index) -{ - return (BString*)fList.RemoveItem(index); +BString * +DStringList::RemoveItem(int32 index) { + return (BString *)fList.RemoveItem(index); } -bool DStringList::RemoveItems(int32 index, int32 count) -{ - return (BString*)fList.RemoveItems(index,count); +bool +DStringList::RemoveItems(int32 index, int32 count) { + return (BString *)fList.RemoveItems(index, count); } -bool DStringList::ReplaceItem(int32 index, BString *newItem) -{ - return fList.ReplaceItem(index,newItem); +bool +DStringList::ReplaceItem(int32 index, BString *newItem) { + return fList.ReplaceItem(index, newItem); } -bool DStringList::HasItem(const char *string) const -{ - if(!string) +bool +DStringList::HasItem(const char *string) const { + if (!string) return false; - - for(int32 i=0; iCompare(string)==0) + + for (int32 i = 0; i < CountItems(); i++) { + BString *item = ItemAt(i); + if (item->Compare(string) == 0) return true; } return false; } -BString *DStringList::FindItem(const char *string) const -{ - if(!string) +BString * +DStringList::FindItem(const char *string) const { + if (!string) return NULL; - - for(int32 i=0; iCompare(string)==0) + + for (int32 i = 0; i < CountItems(); i++) { + BString *item = ItemAt(i); + if (item->Compare(string) == 0) return item; } return NULL; } -void DStringList::MakeEmpty(bool freemem) -{ - if(freemem) - { +void +DStringList::MakeEmpty(bool freemem) { + if (freemem) { BString *str; - for(int32 i=0; iString():NULL); + + printf("DStringList: %ld items\n", fList.CountItems()); + + for (int32 i = 0; i < fList.CountItems(); i++) { + str = ItemAt(i); + printf("%ld: %s\n", i, (str) ? str->String() : NULL); } } diff --git a/src/DStringList.h b/src/DStringList.h index 1823214..2938e32 100644 --- a/src/DStringList.h +++ b/src/DStringList.h @@ -1,52 +1,61 @@ -#ifndef _DSTRINGLIST_H -#define _DSTRINGLIST_H +#ifndef _DSTRINGLIST_H +#define _DSTRINGLIST_H #include -#include #include #include +#include -class DStringList -{ -public: +class DStringList { + public: DStringList(int32 itemsPerBlock = 20, bool owner = true); - virtual ~DStringList(); - - bool AddItem(const char *string); - bool AddItem(const char *string, int32 atIndex); - bool AddList(DStringList *newItems); - bool AddList(DStringList *newItems, int32 atIndex); - bool RemoveItem(BString *item); + virtual ~DStringList(); + + bool AddItem(const char *string); + bool AddItem(const char *string, int32 atIndex); + bool AddList(DStringList *newItems); + bool AddList(DStringList *newItems, int32 atIndex); + bool RemoveItem(BString *item); BString *RemoveItem(int32 index); - bool RemoveItems(int32 index, int32 count); - bool ReplaceItem(int32 index, BString *newItem); - void MakeEmpty(bool freemem=false); - -// void SortItems(void); - bool SwapItems(int32 indexA, int32 indexB) { return fList.SwapItems(indexA,indexB); } - bool MoveItem(int32 fromIndex, int32 toIndex) { return fList.MoveItem(fromIndex,toIndex); } - + bool RemoveItems(int32 index, int32 count); + bool ReplaceItem(int32 index, BString *newItem); + void MakeEmpty(bool freemem = false); + + // void SortItems(void); + bool SwapItems(int32 indexA, int32 indexB) { return fList.SwapItems(indexA, indexB); } + + bool MoveItem(int32 fromIndex, int32 toIndex) { return fList.MoveItem(fromIndex, toIndex); } + BString *FindItem(const char *string) const; - BString *ItemAt(int32 index) const { return (BString*)fList.ItemAtFast(index); } - BString *ItemAtFast(int32 index) const { return (BString*)fList.ItemAtFast(index); } - BString *FirstItem() const { return (BString*)fList.FirstItem(); } - BString *LastItem() const { return (BString*)fList.LastItem(); } - BString *Items() const { return (BString*)fList.Items(); } - - bool HasItem(const char *string) const; - bool HasItem(BString *item) const { return fList.HasItem(item); } - int32 IndexOf(BString *item) const { return fList.IndexOf(item); } - int32 CountItems() const { return fList.CountItems(); } - bool IsEmpty() const { return fList.IsEmpty(); } - + + BString *ItemAt(int32 index) const { return (BString *)fList.ItemAtFast(index); } + + BString *ItemAtFast(int32 index) const { return (BString *)fList.ItemAtFast(index); } + + BString *FirstItem() const { return (BString *)fList.FirstItem(); } + + BString *LastItem() const { return (BString *)fList.LastItem(); } + + BString *Items() const { return (BString *)fList.Items(); } + + bool HasItem(const char *string) const; + + bool HasItem(BString *item) const { return fList.HasItem(item); } + + int32 IndexOf(BString *item) const { return fList.IndexOf(item); } + + int32 CountItems() const { return fList.CountItems(); } + + bool IsEmpty() const { return fList.IsEmpty(); } + void PrintToStream(void); - -// void DoForEach(bool (*func)(void *)); -// void DoForEach(bool (*func)(void *, void *), void *); -private: + // void DoForEach(bool (*func)(void *)); + // void DoForEach(bool (*func)(void *, void *), void *); + + private: BList fList; - bool fOwner; + bool fOwner; }; #endif diff --git a/src/Database.cpp b/src/Database.cpp index 7f171ee..7bb6574 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -1,18 +1,18 @@ #include "Database.h" -#include #include +#include #include -#include "DStringList.h" #include "Budget.h" +#include "DStringList.h" #include "Fixed.h" #include "Import.h" +#include "ScheduledTransData.h" #include "TimeSupport.h" #include "Transaction.h" #include "TransactionData.h" -#include "ScheduledTransData.h" -//#define LOCK_DATABASE +// #define LOCK_DATABASE #ifdef LOCK_DATABASE #define LOCK fLocker.Lock() #define UNLOCK fLocker.Unlock() @@ -31,362 +31,370 @@ Locale gCurrentLocale; // This global is used to hold all financial data for Capital Be. Database gDatabase; -Database::Database(const char *path) - : fCurrent(NULL), - fList(20,true), - fPath(path) -{ -} +Database::Database(const char *path) : fCurrent(NULL), fList(20, true), fPath(path) {} -Database::~Database(void) -{ -} +Database::~Database(void) {} -void Database::CloseAccount(Account *item) -{ - if(!item) +void +Database::CloseAccount(Account *item) { + if (!item) return; - - LOCK; + + LOCK; BString command = "update accountlist set status = 'Closed' where accountid = "; command << item->GetID() << ";"; - DBCommand(command.String(),"Database::CloseAccount"); + DBCommand(command.String(), "Database::CloseAccount"); item->SetClosed(true); - + BMessage msg; - msg.AddPointer("item",(void*)item); - Notify(WATCH_CHANGE | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)item); + Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } -void Database::RenameAccount(Account *item, const char *name) -{ - if(item && name) - { +void +Database::RenameAccount(Account *item, const char *name) { + if (item && name) { LOCK; BString command = "update accountlist set name = '"; command << EscapeIllegalCharacters(name) << "' where accountid = "; command << item->GetID() << ";"; - DBCommand(command.String(),"Database::RenameAccount"); - + DBCommand(command.String(), "Database::RenameAccount"); + item->SetName(name); - + BMessage msg; - msg.AddPointer("item",(void*)item); - Notify(WATCH_CHANGE | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)item); + Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } } -void Database::ReopenAccount(Account *item) -{ - if(!item) +void +Database::ReopenAccount(Account *item) { + if (!item) return; - + LOCK; BString command = "update accountlist set status = 'Open' where accountid = "; command << item->GetID() << ";"; - DBCommand(command.String(),"Database::ReopenAccount"); + DBCommand(command.String(), "Database::ReopenAccount"); item->SetClosed(false); BMessage msg; - msg.AddPointer("item",(void*)item); - Notify(WATCH_CHANGE | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)item); + Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } -void Database::CreateFile(const char *path) -{ - if(!path) +void +Database::CreateFile(const char *path) { + if (!path) return; - + LOCK; fDB.close(); fPath = path; - - try - { + + try { fDB.open(path); - } - catch(...) - { + } catch (...) { BString error = "Couldn't create database file '"; error << path << "'."; ShowBug(error.String()); UNLOCK; return; } - + // Character-Entry Limits: // Category names: 32 // Account names: 32 // Currency/Date separators: 2 // Transaction Status: 10 // Currency Symbol/Decimal: 2 - - DBCommand("create table accountlist (accountid int primary key, name varchar(96), " - "type varchar(12), status varchar(30));","Database::CreateFile:create accountlist"); - DBCommand("create table accountlocale (accountid int primary key, dateformat varchar(8), " - "dateseparator char(6), currencysymbol char(6), " - "currencyseparator char(6), currencydecimal char(6), " - "currencyprefix char(1));","Database::CreateFile:create accountlocale"); - DBCommand("create table memorizedlist (transactionid int);","Database::CreateFile:create memorizedlist"); - DBCommand("create table scheduledlist (timestamp int primary key, accountid int, transid int," - "date int, type varchar(24), payee varchar(96), amount int," - "category varchar(96),memo varchar(63), interval int, count int," - "nextdate int);", - "Database::CreateFile:create scheduledlist"); - DBCommand("create table budgetlist (entryid int primary key, category varchar(96), " - "amount int, period int(2), isexpense int(1));","Database::CreateFile:create budgetlist"); - DBCommand("create table transactionlist (timestamp int primary key, transid int, " - "category varchar(96), accountid int);","Database::CreateFile:create transactionlist"); - DBCommand("create table categorylist (name varchar(96), type int(2));", - "Database::CreateFile:create categorylist"); - + + DBCommand( + "create table accountlist (accountid int primary key, name varchar(96), " + "type varchar(12), status varchar(30));", + "Database::CreateFile:create accountlist" + ); + DBCommand( + "create table accountlocale (accountid int primary key, dateformat varchar(8), " + "dateseparator char(6), currencysymbol char(6), " + "currencyseparator char(6), currencydecimal char(6), " + "currencyprefix char(1));", + "Database::CreateFile:create accountlocale" + ); + DBCommand( + "create table memorizedlist (transactionid int);", + "Database::CreateFile:create memorizedlist" + ); + DBCommand( + "create table scheduledlist (timestamp int primary key, accountid int, transid int," + "date int, type varchar(24), payee varchar(96), amount int," + "category varchar(96),memo varchar(63), interval int, count int," + "nextdate int);", + "Database::CreateFile:create scheduledlist" + ); + DBCommand( + "create table budgetlist (entryid int primary key, category varchar(96), " + "amount int, period int(2), isexpense int(1));", + "Database::CreateFile:create budgetlist" + ); + DBCommand( + "create table transactionlist (timestamp int primary key, transid int, " + "category varchar(96), accountid int);", + "Database::CreateFile:create transactionlist" + ); + DBCommand( + "create table categorylist (name varchar(96), type int(2));", + "Database::CreateFile:create categorylist" + ); + // now that the tables have all been created, create the default locale - DBCommand("create table defaultlocale (dateformat varchar(8), " - "dateseparator char(6), currencysymbol char(6), " - "currencyseparator char(6), currencydecimal char(6), " - "currencyprefix char(1));","Database::CreateFile:create defaultlocale"); - DBCommand("insert into defaultlocale values('mmddyyyy', '/', '$', ',', '.', 'true');", - "Database::CreateFile insert defaultlocale values"); + DBCommand( + "create table defaultlocale (dateformat varchar(8), " + "dateseparator char(6), currencysymbol char(6), " + "currencyseparator char(6), currencydecimal char(6), " + "currencyprefix char(1));", + "Database::CreateFile:create defaultlocale" + ); + DBCommand( + "insert into defaultlocale values('mmddyyyy', '/', '$', ',', '.', 'true');", + "Database::CreateFile insert defaultlocale values" + ); UNLOCK; } -status_t Database::OpenFile(const char *path) -{ - if(!path) +status_t +Database::OpenFile(const char *path) { + if (!path) return B_ERROR; - + BEntry entry(path); - if(entry.InitCheck()!=B_OK) + if (entry.InitCheck() != B_OK) return entry.InitCheck(); - - if(!entry.Exists()) + + if (!entry.Exists()) return B_NAME_NOT_FOUND; - + LOCK; fDB.close(); fPath = path; - - try - { + + try { fDB.open(path); - } - catch(...) - { + } catch (...) { UNLOCK; - ShowAlert("Couldn't open account data.","Capital Be couldn't open your financial data. " - "If your data is in the old storage format from the Preview Edition 1.0, you " - "will need to run the conversion program before you can use your data."); + ShowAlert( + "Couldn't open account data.", + "Capital Be couldn't open your financial data. " + "If your data is in the old storage format from the Preview Edition 1.0, you " + "will need to run the conversion program before you can use your data." + ); return B_ERROR; } - + // Populate account list - CppSQLite3Query query = DBQuery("select * from accountlist","Database::OpenFile:get accounts from list"); - - while(!query.eof()) - { + CppSQLite3Query query = + DBQuery("select * from accountlist", "Database::OpenFile:get accounts from list"); + + while (!query.eof()) { uint32 id = query.getIntField(0); BString name = DeescapeIllegalCharacters(query.getStringField(1)); -// BString type = query.getStringField(2); + // BString type = query.getStringField(2); BString status = DeescapeIllegalCharacters(query.getStringField(3)); - - Account *account = new Account(name.String(), status.ICompare("open")!=0); + + Account *account = new Account(name.String(), status.ICompare("open") != 0); account->SetID(id); - if(UsesDefaultLocale(id)) - { + if (UsesDefaultLocale(id)) { account->UseDefaultLocale(false); account->SetLocale(LocaleForAccount(id)); } fList.AddItem(account); - + BMessage msg; - msg.AddPointer("item",(void*)account); - Notify(WATCH_CREATE | WATCH_ACCOUNT,&msg); - + msg.AddPointer("item", (void *)account); + Notify(WATCH_CREATE | WATCH_ACCOUNT, &msg); + query.nextRow(); } query.finalize(); - + // Set the current transaction and last check number for each account - for(int32 i=0; iGetID() << " order by date,transid;"; - - query = DBQuery(command.String(),"Database::OpenFile:set current transaction"); - if(!query.eof()) + + query = DBQuery(command.String(), "Database::OpenFile:set current transaction"); + if (!query.eof()) acc->SetCurrentTransaction(query.getInt64Field(0)); query.finalize(); - + acc->SetLastCheckNumber(acc->LookupLastCheckNumber()); } - + gDefaultLocale = GetDefaultLocale(); - - fCurrent = (Account*)fList.ItemAt(0); + + fCurrent = (Account *)fList.ItemAt(0); UNLOCK; return B_OK; - } -void Database::CloseFile(void) -{ +void +Database::CloseFile(void) { LOCK; fDB.close(); UNLOCK; } -bool Database::ImportFile(const entry_ref &ref) -{ +bool +Database::ImportFile(const entry_ref &ref) { LOCK; - Notify(WATCH_MASS_EDIT,NULL); + Notify(WATCH_MASS_EDIT, NULL); bool value = ImportQIF(ref); - Notify(WATCH_MASS_EDIT,NULL); + Notify(WATCH_MASS_EDIT, NULL); UNLOCK; - + return value; } -bool Database::ExportFile(const entry_ref &ref) -{ +bool +Database::ExportFile(const entry_ref &ref) { LOCK; bool value = ExportQIF(ref); UNLOCK; - + return value; } -Account *Database::SetCurrentAccount(const int32 &index) -{ +Account * +Database::SetCurrentAccount(const int32 &index) { // We actually permit a NULL pointer here because sometimes we don't *have* an account // to operate on LOCK; - Account *acc = (Account*)fList.ItemAt(index); + Account *acc = (Account *)fList.ItemAt(index); fCurrent = acc; - + BMessage msg; - msg.AddPointer("item",(void*)acc); - Notify(WATCH_SELECT | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)acc); + Notify(WATCH_SELECT | WATCH_ACCOUNT, &msg); UNLOCK; - + return acc; } -int32 Database::SetCurrentAccount(Account *account) -{ - if(!account) - { +int32 +Database::SetCurrentAccount(Account *account) { + if (!account) { LOCK; SetCurrentAccount(-1); UNLOCK; return -1; } - + // We actually permit a NULL pointer here because sometimes we don't *have* an account // to operate on - if(!fList.HasItem(account)) + if (!fList.HasItem(account)) return -1; - + LOCK; fCurrent = account; - + BMessage msg; - msg.AddPointer("item",(void*)account); - Notify(WATCH_SELECT | WATCH_ACCOUNT,&msg); - + msg.AddPointer("item", (void *)account); + Notify(WATCH_SELECT | WATCH_ACCOUNT, &msg); + int32 value = fList.IndexOf(account); UNLOCK; return value; } -Account *Database::AddAccount(const char *name, const AccountType &type, const char *status, - const Locale *locale) -{ - if(!name || !status) +Account * +Database::AddAccount( + const char *name, const AccountType &type, const char *status, const Locale *locale +) { + if (!name || !status) return NULL; - + LOCK; - BString ename,estatus; + BString ename, estatus; ename = EscapeIllegalCharacters(name); estatus = EscapeIllegalCharacters(status); - - int32 id = GetLastKey("accountlist","accountid"); + + int32 id = GetLastKey("accountlist", "accountid"); id++; - + BString command; - command << "insert into accountlist values(" << id << ", '" << ename << "', '" + command << "insert into accountlist values(" << id << ", '" << ename << "', '" << AccountTypeToString(type) << "', '" << estatus << "');"; - DBCommand(command.String(),"Database::AddAccount:insert accountlist"); - - if(locale) + DBCommand(command.String(), "Database::AddAccount:insert accountlist"); + + if (locale) SetAccountLocale(id, *locale); else SetAccountLocale(id, gDefaultLocale); - + command = ""; command << "create table account_" << id << " (timestamp int primary key, transid int, date int, type varchar(24), " - "payee varchar(96), amount int, category varchar(96), memo varchar(63), " - "status char(21));"; - - DBCommand(command.String(),"Database::AddAccount:create account"); - + "payee varchar(96), amount int, category varchar(96), memo varchar(63), " + "status char(21));"; + + DBCommand(command.String(), "Database::AddAccount:create account"); + Account *account = new Account(name); account->SetID(id); - if(strcmp(status,"closed")==0) + if (strcmp(status, "closed") == 0) account->SetClosed(true); fList.AddItem(account); - - if(fList.CountItems()==1) + + if (fList.CountItems() == 1) fCurrent = account; - + BMessage msg; - msg.AddPointer("item",(void*)account); - Notify(WATCH_CREATE | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)account); + Notify(WATCH_CREATE | WATCH_ACCOUNT, &msg); UNLOCK; - + return account; } -bool Database::RemoveAccount(const int &accountid) -{ +bool +Database::RemoveAccount(const int &accountid) { LOCK; BString command; command << "select accountid from accountlist where accountid = " << accountid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::RemoveAccount:accountid check"); - - if(!query.eof()) - { + CppSQLite3Query query = DBQuery(command.String(), "Database::RemoveAccount:accountid check"); + + if (!query.eof()) { query.finalize(); - + Account *item = AccountByID(accountid); - if(item) - { + if (item) { BMessage msg; - msg.AddPointer("item",(void*)item); - Notify(WATCH_DELETE | WATCH_ACCOUNT,&msg); + msg.AddPointer("item", (void *)item); + Notify(WATCH_DELETE | WATCH_ACCOUNT, &msg); } - + command = "delete from accountlist where accountid = "; command << accountid << ";"; - DBCommand(command.String(),"Database::RemoveAccount:delete accountlist item"); - + DBCommand(command.String(), "Database::RemoveAccount:delete accountlist item"); + command = "delete from accountlocale where accountid = "; command << accountid << ";"; - DBCommand(command.String(),"Database::RemoveAccount:delete accountlocale item"); - + DBCommand(command.String(), "Database::RemoveAccount:delete accountlocale item"); + command = "drop table account_"; command << accountid; - DBCommand(command.String(),"Database::RemoveAccount:drop account table"); - + DBCommand(command.String(), "Database::RemoveAccount:drop account table"); + fList.RemoveItem(item); - if(fList.CountItems()==0) + if (fList.CountItems() == 0) fCurrent = 0; - + UNLOCK; return true; } @@ -395,491 +403,465 @@ bool Database::RemoveAccount(const int &accountid) return false; } -void Database::RemoveAccount(Account *account) -{ - if(account) +void +Database::RemoveAccount(Account *account) { + if (account) RemoveAccount(account->GetID()); } -Account *Database::AccountByName(const char *name) -{ - if(!name) +Account * +Database::AccountByName(const char *name) { + if (!name) return NULL; - - for(int32 i=0; iName() && strcmp(name,acc->Name())==0) + if (acc && acc->Name() && strcmp(name, acc->Name()) == 0) return acc; } return NULL; } -Account *Database::AccountByID(const uint32 &accountid) -{ - for(int32 i=0; iGetID()==accountid) + if (acc && acc->GetID() == accountid) return acc; } return NULL; } -void Database::AddBudgetEntry(const BudgetEntry &entry) -{ - if(entry.name.CountChars()<1 || !HasCategory(entry.name.String())) +void +Database::AddBudgetEntry(const BudgetEntry &entry) { + if (entry.name.CountChars() < 1 || !HasCategory(entry.name.String())) return; - + LOCK; BString ecategory = EscapeIllegalCharacters(entry.name.String()); - + // See if the budget list already has the category and if it does, update the entry // to the new value. Otherwise, add the entry to the list BString command; - command << "select entryid from budgetlist where category = '" << ecategory << "';"; - CppSQLite3Query query = DBQuery(command.String(),"Database::AddBudgetEntry:check existing"); - + command << "select entryid from budgetlist where category = '" << ecategory << "';"; + CppSQLite3Query query = DBQuery(command.String(), "Database::AddBudgetEntry:check existing"); + int value = -1; - if(!query.eof()) + if (!query.eof()) value = query.getIntField(0); query.finalize(); - - if(value >= 0) - { + + if (value >= 0) { command = "update budgetlist set amount = "; command << entry.amount.AsFixed() << " where entryid = " << value << ";"; - DBCommand(command.String(),"Database::AddBudgetEntry:update budgetlist amount"); + DBCommand(command.String(), "Database::AddBudgetEntry:update budgetlist amount"); command = "update budgetlist set period = "; command << (int)entry.period << " where entryid = " << value << ";"; - DBCommand(command.String(),"Database::AddBudgetEntry:update budgetlist period"); + DBCommand(command.String(), "Database::AddBudgetEntry:update budgetlist period"); return; } - + // We got this far, so we just add the entry to the list - value = GetLastKey("budgetlist","entryid"); + value = GetLastKey("budgetlist", "entryid"); value++; command = "insert into budgetlist values("; - command << value << ", '" << ecategory << "', " << entry.amount.AsFixed() - << ", " << (int)entry.period << ", " << (entry.isexpense ? 1 : 0) << ");"; - DBCommand(command.String(),"Database::AddBudgetEntry:insert into budgetlist"); + command << value << ", '" << ecategory << "', " << entry.amount.AsFixed() << ", " + << (int)entry.period << ", " << (entry.isexpense ? 1 : 0) << ");"; + DBCommand(command.String(), "Database::AddBudgetEntry:insert into budgetlist"); UNLOCK; } -bool Database::RemoveBudgetEntry(const char *category) -{ - if(!category || !HasBudgetEntry(category)) +bool +Database::RemoveBudgetEntry(const char *category) { + if (!category || !HasBudgetEntry(category)) return false; - + LOCK; BString ecategory = EscapeIllegalCharacters(category); - + BString command; command << "delete from budgetlist where category = '" << ecategory << "';"; - DBCommand(command.String(),"Database::RemoveBudgetEntry"); + DBCommand(command.String(), "Database::RemoveBudgetEntry"); UNLOCK; return true; } -bool Database::HasBudgetEntry(const char *category) -{ - if(!category) +bool +Database::HasBudgetEntry(const char *category) { + if (!category) return false; - + LOCK; BString ecategory = EscapeIllegalCharacters(category); BString command; - command << "select entryid from budgetlist where category = '" << ecategory - << "' order by 1;"; - CppSQLite3Query query = DBQuery(command.String(),"Database::HasBudgetEntry"); - + command << "select entryid from budgetlist where category = '" << ecategory << "' order by 1;"; + CppSQLite3Query query = DBQuery(command.String(), "Database::HasBudgetEntry"); + bool value = query.eof(); UNLOCK; return value; } -bool Database::GetBudgetEntry(const char *name, BudgetEntry &entry) -{ - if(!name) +bool +Database::GetBudgetEntry(const char *name, BudgetEntry &entry) { + if (!name) return false; - + BString escaped = EscapeIllegalCharacters(name); BString command = "select amount,period,isexpense from budgetlist where category = '"; command << escaped << "';"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"Database::GetBudgetEntry"); - - if(!query.eof()) - { + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Database::GetBudgetEntry"); + + if (!query.eof()) { entry.name = name; entry.amount.SetPremultiplied(query.getInt64Field(0)); - entry.period=(BudgetPeriod)query.getIntField(1); - entry.isexpense = (query.getIntField(2)==1); + entry.period = (BudgetPeriod)query.getIntField(1); + entry.isexpense = (query.getIntField(2) == 1); return true; } return false; } -int32 Database::CountBudgetEntries(void) -{ - CppSQLite3Query query = gDatabase.DBQuery("select category from budgetlist", - "Database::CountBudgetEntries"); - - int32 count=0; - while(!query.eof()) - { +int32 +Database::CountBudgetEntries(void) { + CppSQLite3Query query = + gDatabase.DBQuery("select category from budgetlist", "Database::CountBudgetEntries"); + + int32 count = 0; + while (!query.eof()) { count++; query.nextRow(); } return count; } -void Database::SetAccountLocale(const uint32 &accountid, const Locale &data) -{ +void +Database::SetAccountLocale(const uint32 &accountid, const Locale &data) { LOCK; BString command("select accountid from accountlocale where accountid = "); command << accountid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::SetAccountLocale:find accountid"); - - if(query.eof()) - { + CppSQLite3Query query = DBQuery(command.String(), "Database::SetAccountLocale:find accountid"); + + if (query.eof()) { command << "insert into accountlocale values(" << accountid << ",'" - << (data.DateFormat()==DATE_DMY ? "ddmmyyyy": "mmddyyyy") << "','" + << (data.DateFormat() == DATE_DMY ? "ddmmyyyy" : "mmddyyyy") << "','" << data.DateSeparator() << "','" << data.CurrencySymbol() << "','" << data.CurrencySeparator() << "','" << data.CurrencyDecimal() << "','" - << (data.IsCurrencySymbolPrefix() ? "true" : "false" ) << "');"; - DBCommand(command.String(),"Database::SetAccountLocale:insert into accountlocale"); + << (data.IsCurrencySymbolPrefix() ? "true" : "false") << "');"; + DBCommand(command.String(), "Database::SetAccountLocale:insert into accountlocale"); UNLOCK; return; } - + query.finalize(); - + // This already has the locale data in the table, so we'll just update it and return - command << "update accountlocale set dateformat = '" + command << "update accountlocale set dateformat = '" << (data.DateFormat() == 1 ? "ddmmyyyy" : "mmddyyyy") << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update dateformat"); - + DBCommand(command.String(), "Database::SetAccountLocale:update dateformat"); + command << "update accountlocale set dateseparator = '" << data.DateSeparator() << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update dateseparator"); - + DBCommand(command.String(), "Database::SetAccountLocale:update dateseparator"); + command << "update accountlocale set currencysymbol = '" << data.CurrencySymbol() << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencysymbol"); - + DBCommand(command.String(), "Database::SetAccountLocale:update currencysymbol"); + command << "update accountlocale set currencyseparator = '" << data.CurrencySeparator() << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencyseparator"); - + DBCommand(command.String(), "Database::SetAccountLocale:update currencyseparator"); + command << "update accountlocale set currencydecimal = '" << data.CurrencyDecimal() << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencydecimal"); - - command << "update accountlocale set currencyprefix = '" + DBCommand(command.String(), "Database::SetAccountLocale:update currencydecimal"); + + command << "update accountlocale set currencyprefix = '" << (data.IsCurrencySymbolPrefix() ? "true" : "false") << "' where accountid = " << accountid << ";"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencyprefix"); + DBCommand(command.String(), "Database::SetAccountLocale:update currencyprefix"); UNLOCK; } -Locale Database::LocaleForAccount(const uint32 &id) -{ +Locale +Database::LocaleForAccount(const uint32 &id) { LOCK; BString command; command << "select * from accountlocale where accountid = " << id << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::LocaleForAccount:find account"); - + CppSQLite3Query query = DBQuery(command.String(), "Database::LocaleForAccount:find account"); + Locale locale; - if(query.eof()) - { + if (query.eof()) { UNLOCK; return locale; } - + BString temp = query.getStringField(1); - locale.SetDateFormat( (temp.Compare("ddmmyyyy")==0) ? DATE_DMY : DATE_MDY ); - locale.SetDateSeparator( query.getStringField(2) ); - locale.SetCurrencySymbol( query.getStringField(3) ); - locale.SetCurrencySeparator( query.getStringField(4) ); - locale.SetCurrencyDecimal( query.getStringField(5) ); - + locale.SetDateFormat((temp.Compare("ddmmyyyy") == 0) ? DATE_DMY : DATE_MDY); + locale.SetDateSeparator(query.getStringField(2)); + locale.SetCurrencySymbol(query.getStringField(3)); + locale.SetCurrencySeparator(query.getStringField(4)); + locale.SetCurrencyDecimal(query.getStringField(5)); + temp = query.getStringField(6); - locale.SetCurrencySymbolPrefix( temp.Compare("true")==0 ? true : false ); + locale.SetCurrencySymbolPrefix(temp.Compare("true") == 0 ? true : false); UNLOCK; return locale; } -void Database::SetDefaultLocale(const Locale &data) -{ +void +Database::SetDefaultLocale(const Locale &data) { LOCK; BString command; - + // This already has the locale data in the table, so we'll just update it and return - command << "update defaultlocale set dateformat = '" - << (data.DateFormat() == DATE_MDY ? "mmddyyyy" : "ddmmyyyy") - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update dateformat"); - - command << "update defaultlocale set dateseparator = '" << data.DateSeparator() - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update dateseparator"); - - command << "update defaultlocale set currencysymbol = '" << data.CurrencySymbol() - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencysymbol"); - - command << "update defaultlocale set currencyseparator = '" << data.CurrencySeparator() - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencyseparator"); - - command << "update defaultlocale set currencydecimal = '" << data.CurrencyDecimal() - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencydecimal"); - - command << "update defaultlocale set currencyprefix = '" - << (data.IsCurrencySymbolPrefix() ? "true" : "false") - << "';"; - DBCommand(command.String(),"Database::SetAccountLocale:update currencyprefix"); + command << "update defaultlocale set dateformat = '" + << (data.DateFormat() == DATE_MDY ? "mmddyyyy" : "ddmmyyyy") << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update dateformat"); + + command << "update defaultlocale set dateseparator = '" << data.DateSeparator() << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update dateseparator"); + + command << "update defaultlocale set currencysymbol = '" << data.CurrencySymbol() << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update currencysymbol"); + + command << "update defaultlocale set currencyseparator = '" << data.CurrencySeparator() << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update currencyseparator"); + + command << "update defaultlocale set currencydecimal = '" << data.CurrencyDecimal() << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update currencydecimal"); + + command << "update defaultlocale set currencyprefix = '" + << (data.IsCurrencySymbolPrefix() ? "true" : "false") << "';"; + DBCommand(command.String(), "Database::SetAccountLocale:update currencyprefix"); BMessage msg; - msg.AddPointer("locale",&gDefaultLocale); - Notify(WATCH_LOCALE | WATCH_CHANGE,&msg); + msg.AddPointer("locale", &gDefaultLocale); + Notify(WATCH_LOCALE | WATCH_CHANGE, &msg); UNLOCK; } -Locale Database::GetDefaultLocale(void) -{ +Locale +Database::GetDefaultLocale(void) { LOCK; - CppSQLite3Query query = DBQuery("select * from defaultlocale;", - "Database::GetDefaultLocale"); - + CppSQLite3Query query = DBQuery("select * from defaultlocale;", "Database::GetDefaultLocale"); + Locale locale; - if(query.eof()) - { + if (query.eof()) { UNLOCK; return locale; } - + BString temp = query.getStringField(0); - locale.SetDateFormat( (temp.Compare("ddmmyyyy")==0) ? DATE_DMY : DATE_MDY ); - locale.SetDateSeparator( query.getStringField(1) ); - locale.SetCurrencySymbol( query.getStringField(2) ); - locale.SetCurrencySeparator( query.getStringField(3) ); - locale.SetCurrencyDecimal( query.getStringField(4) ); - + locale.SetDateFormat((temp.Compare("ddmmyyyy") == 0) ? DATE_DMY : DATE_MDY); + locale.SetDateSeparator(query.getStringField(1)); + locale.SetCurrencySymbol(query.getStringField(2)); + locale.SetCurrencySeparator(query.getStringField(3)); + locale.SetCurrencyDecimal(query.getStringField(4)); + temp = query.getStringField(5); - locale.SetCurrencySymbolPrefix( temp.Compare("true")==0 ? true : false ); + locale.SetCurrencySymbolPrefix(temp.Compare("true") == 0 ? true : false); UNLOCK; return locale; } -bool Database::UsesDefaultLocale(const uint32 &id) -{ +bool +Database::UsesDefaultLocale(const uint32 &id) { LOCK; - + BString command = "select accountid from accountlocale where accountid = "; command << id << ";"; - - CppSQLite3Query query = DBQuery(command.String(), - "Database::UsesDefaultLocale"); + + CppSQLite3Query query = DBQuery(command.String(), "Database::UsesDefaultLocale"); return query.eof(); - + UNLOCK; } -bool Database::AddTransaction(const uint32 &accountid, const uint32 &id, - const time_t &date, const TransactionType &type, - const char *payee, const Fixed &amount, - const char *category, const char *memo, const uint8 &status) -{ - if(!payee || !category) +bool +Database::AddTransaction( + const uint32 &accountid, const uint32 &id, const time_t &date, const TransactionType &type, + const char *payee, const Fixed &amount, const char *category, const char *memo, + const uint8 &status +) { + if (!payee || !category) return false; - + LOCK; bigtime_t timestamp = real_time_clock_usecs(); - - AddCategory(category,amount.IsNegative()); - + + AddCategory(category, amount.IsNegative()); + BString ecategory = EscapeIllegalCharacters(category); BString epayee = EscapeIllegalCharacters(payee); BString ememo = EscapeIllegalCharacters(memo); - + BString command = "insert into transactionlist values("; command << timestamp << ", " << id << ", '" << ecategory << "', " << accountid << ");"; - DBCommand(command.String(),"Database::AddTransaction:insert into transactionlist"); - + DBCommand(command.String(), "Database::AddTransaction:insert into transactionlist"); + command = "insert into account_"; - command << accountid << " values(" << timestamp << ", " << id << ", " - << date << ",'" << type.Type() << "', '" - << epayee << "', " << amount.AsFixed() << ", '" << ecategory; - if(memo) + command << accountid << " values(" << timestamp << ", " << id << ", " << date << ",'" + << type.Type() << "', '" << epayee << "', " << amount.AsFixed() << ", '" << ecategory; + if (memo) command << "', '" << ememo << "', '"; else command << "', '', "; - - if(status==TRANS_CLEARED) + + if (status == TRANS_CLEARED) command << "cleared');"; - else - if(status==TRANS_RECONCILED) + else if (status == TRANS_RECONCILED) command << "reconciled');"; else command << "open');"; - - DBCommand(command.String(),"Database::AddTransaction:insert into account"); - + + DBCommand(command.String(), "Database::AddTransaction:insert into account"); + Account *account = AccountByID(accountid); - if(account) - { - if(account->CurrentTransaction()==0) - { + if (account) { + if (account->CurrentTransaction() == 0) { // It appears that the account is empty. Make sure and, if so, set the just-added // transaction to the current one command = "select * from account_"; command << accountid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::AddTransaction:get current transaction"); - if(query.eof()) - { + CppSQLite3Query query = + DBQuery(command.String(), "Database::AddTransaction:get current transaction"); + if (query.eof()) { // account is empty. make it the current one. account->SetCurrentTransaction(id); } } } - - if(IsNotifying()) - { + + if (IsNotifying()) { BMessage msg; TransactionData data; - GetTransaction(id,data); - msg.AddInt32("accountid",accountid); - msg.AddPointer("item",(void*)&data); - Notify(WATCH_CREATE | WATCH_TRANSACTION,&msg); + GetTransaction(id, data); + msg.AddInt32("accountid", accountid); + msg.AddPointer("item", (void *)&data); + Notify(WATCH_CREATE | WATCH_TRANSACTION, &msg); } UNLOCK; - + return true; } -bool Database::AddTransaction(TransactionData &data, const bool &newid) -{ - if(!data.IsValid()) +bool +Database::AddTransaction(TransactionData &data, const bool &newid) { + if (!data.IsValid()) return false; - + LOCK; - uint32 id=0; - - if(data.CountCategories()==1) - { - if(newid) + uint32 id = 0; + + if (data.CountCategories() == 1) { + if (newid) id = NextTransactionID(); else id = data.GetID(); - - AddTransaction(data.GetAccount()->GetID(), id, data.Date(), data.Type(), - data.Payee(), data.Amount(), data.NameAt(0), data.Memo(), - data.Status()); - } - else - { - if(newid) - { + + AddTransaction( + data.GetAccount()->GetID(), id, data.Date(), data.Type(), data.Payee(), data.Amount(), + data.NameAt(0), data.Memo(), data.Status() + ); + } else { + if (newid) { id = NextTransactionID(); data.SetID(id); } - + // We are disabling notifications for the moment so that we don't end up with // multiple single-category transaction entries in the transaction view. SetNotify(false); - for(int32 i=0; iGetID(), id, data.Date(), data.Type(), - data.Payee(), data.AmountAt(i), data.NameAt(i), data.MemoAt(i), - data.Status()); + AddTransaction( + data.GetAccount()->GetID(), id, data.Date(), data.Type(), data.Payee(), + data.AmountAt(i), data.NameAt(i), data.MemoAt(i), data.Status() + ); } - + // We now re-enable notifications and add the final transaction entry. This will // cause everyone to be notified of what really is just 1 transaction that has // multiple categories SetNotify(true); - int32 index = data.CountCategories()-1; - AddTransaction(data.GetAccount()->GetID(), id, data.Date(), data.Type(), - data.Payee(), data.AmountAt(index), data.NameAt(index), - data.MemoAt(index),data.Status()); + int32 index = data.CountCategories() - 1; + AddTransaction( + data.GetAccount()->GetID(), id, data.Date(), data.Type(), data.Payee(), + data.AmountAt(index), data.NameAt(index), data.MemoAt(index), data.Status() + ); } UNLOCK; return true; } -bool Database::RemoveTransaction(const uint32 &transid) -{ - if(!HasTransaction(transid)) +bool +Database::RemoveTransaction(const uint32 &transid) { + if (!HasTransaction(transid)) return false; - + // Timestamps are not used. They are used as unique identifiers for each transaction, // but transid's are not unique. This is because a transaction that the user has entered // in may be split across multiple categories and the transid is what links them all together. - + LOCK; DStringList stringlist; BString command; - BObjectList idlist(20,true); - + BObjectList idlist(20, true); + command << "select accountid from transactionlist where transid = " << transid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::RemoveTransaction:find transaction"); - - while(!query.eof()) - { + CppSQLite3Query query = + DBQuery(command.String(), "Database::RemoveTransaction:find transaction"); + + while (!query.eof()) { idlist.AddItem(new uint32(query.getInt64Field(0))); query.nextRow(); } - + query.finalize(); - - if(idlist.CountItems()<1) - { + + if (idlist.CountItems() < 1) { UNLOCK; return false; } - - for(int32 i=0; iSetCurrentTransaction(0); query.finalize(); } } - + command = "delete from transactionlist where transid = "; command << transid << ";"; - DBCommand(command.String(),"Database::RemoveTransaction:delete from transactionlist"); - + DBCommand(command.String(), "Database::RemoveTransaction:delete from transactionlist"); + UNLOCK; return true; } -uint32 Database::NextTransactionID(void) -{ +uint32 +Database::NextTransactionID(void) { LOCK; uint32 key = GetLastKey("transactionlist", "transid"); key++; @@ -887,255 +869,245 @@ uint32 Database::NextTransactionID(void) return key; } -bool Database::HasTransaction(const uint32 &transid) -{ - if(transid < 0) +bool +Database::HasTransaction(const uint32 &transid) { + if (transid < 0) return false; - + LOCK; BString command; command << "select transid from transactionlist where transid = " << transid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::HasTransaction"); - + CppSQLite3Query query = DBQuery(command.String(), "Database::HasTransaction"); + bool value = !query.eof(); UNLOCK; return value; } -bool Database::GetTransaction(const uint32 &transid, const uint32 &accountid, - TransactionData &data) -{ +bool +Database::GetTransaction(const uint32 &transid, const uint32 &accountid, TransactionData &data) { LOCK; - + BString command; CppSQLite3Query query; - + command = "select date,payee,amount,category,memo,type,timestamp from account_"; command << accountid << " where transid = " << transid << ";"; - query = DBQuery(command.String(),"Database::GetTransaction:get transaction data"); - - if(query.eof()) - { + query = DBQuery(command.String(), "Database::GetTransaction:get transaction data"); + + if (query.eof()) { UNLOCK; return false; } - + Locale loc = LocaleForAccount(accountid); - + data.MakeEmpty(); data.SetAccount(AccountByID(accountid)); data.SetDate(atol(query.getStringField(0))); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(1)).String()); data.SetType(DeescapeIllegalCharacters(query.getStringField(5)).String()); data.SetID(transid); - while(!query.eof()) - { + while (!query.eof()) { Fixed f; f.SetPremultiplied(atol(query.getStringField(2))); - - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(3)).String(),f,true); - - if(!query.fieldIsNull(4)) - data.SetMemoAt(data.CountCategories()-1,query.getStringField(4)); - + + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(3)).String(), f, true); + + if (!query.fieldIsNull(4)) + data.SetMemoAt(data.CountCategories() - 1, query.getStringField(4)); + query.nextRow(); } - - if( (data.CountCategories() == 1) && strlen(data.MemoAt(0))>0) + + if ((data.CountCategories() == 1) && strlen(data.MemoAt(0)) > 0) data.SetMemo(data.MemoAt(0)); - + UNLOCK; return true; } -bool Database::GetTransaction(const uint32 &transid, TransactionData &data) -{ +bool +Database::GetTransaction(const uint32 &transid, TransactionData &data) { LOCK; - + BString command; CppSQLite3Query query; - + command << "select accountid from transactionlist where transid = " << transid << ";"; - query = DBQuery(command.String(),"Database::GetTransaction:get accountid"); - + query = DBQuery(command.String(), "Database::GetTransaction:get accountid"); + uint32 accountid = query.getIntField(0); query.finalize(); UNLOCK; - - return GetTransaction(transid,accountid,data); + + return GetTransaction(transid, accountid, data); } -void Database::SetTransactionStatus(const uint32 &transid, const uint8 &status) -{ +void +Database::SetTransactionStatus(const uint32 &transid, const uint8 &status) { LOCK; - + BString command; command << "select accountid from transactionlist where transid = " << transid << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::SetTransactionStatus:get accountid"); - + CppSQLite3Query query = + DBQuery(command.String(), "Database::SetTransactionStatus:get accountid"); + uint32 accountid = query.getIntField(0); query.finalize(); - + command = "update account_"; command << accountid << " set status = "; - - if(status == TRANS_OPEN) + + if (status == TRANS_OPEN) command << "'Open' "; + else if (status == TRANS_RECONCILED) + command << "'Reconciled' "; else - if(status == TRANS_RECONCILED) - command << "'Reconciled' " ; - else - command << "'Cleared'" ; - + command << "'Cleared'"; + command << "where transid = " << transid << ";"; - DBCommand(command.String(),"Database::SetTransactionStatus:set status"); - + DBCommand(command.String(), "Database::SetTransactionStatus:set status"); + BMessage msg; TransactionData data; - GetTransaction(transid,data); - msg.AddInt32("accountid",accountid); - msg.AddPointer("item",(void*)&data); - Notify(WATCH_CHANGE | WATCH_TRANSACTION,&msg); - + GetTransaction(transid, data); + msg.AddInt32("accountid", accountid); + msg.AddPointer("item", (void *)&data); + Notify(WATCH_CHANGE | WATCH_TRANSACTION, &msg); + UNLOCK; } -bool Database::GetTransferCounterpart(const uint32 &transid, TransactionData &data) -{ +bool +Database::GetTransferCounterpart(const uint32 &transid, TransactionData &data) { LOCK; - + BString command; command << "select accountid from transactionlist where transid = " << transid << " and " << "accountid != " << data.GetAccount()->GetID() << ";"; - CppSQLite3Query query = DBQuery(command.String(),"Database::SetTransferCounterpart:get accountid"); - + CppSQLite3Query query = + DBQuery(command.String(), "Database::SetTransferCounterpart:get accountid"); + uint32 accountid = query.getIntField(0); query.finalize(); - + UNLOCK; - + data.SetAccount(AccountByID(accountid)); - - return GetTransaction(transid,data); + + return GetTransaction(transid, data); } -void Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &newid) -{ - if(!data.IsValid()) +void +Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &newid) { + if (!data.IsValid()) return; - + LOCK; - + uint32 id; - if(newid) - { + if (newid) { id = GetLastKey("scheduledlist", "transid"); id++; - } - else + } else id = data.GetID(); - + time_t nextdate = data.GetNextDueDate(); - if(nextdate==0) - { - switch(data.GetInterval()) - { - case SCHEDULED_MONTHLY: - { - nextdate = IncrementDateByMonth(data.Date()); - break; - } - case SCHEDULED_WEEKLY: - { - // TODO: Add weekly scheduling support -// data.SetNextDueDate(IncrementDateByMonth(data.Date())); - ShowBug("Unimplemented Weekly scheduling support in Database::AddScheduledTransaction()"); - break; - } - case SCHEDULED_QUARTERLY: - { - nextdate = IncrementDateByQuarter(data.Date()); - break; - } - case SCHEDULED_ANNUALLY: - { - nextdate = IncrementDateByYear(data.Date()); - break; - } - default: - { - ShowBug("Unknown scheduled value in Database::AddScheduledTransaction()"); - break; - } + if (nextdate == 0) { + switch (data.GetInterval()) { + case SCHEDULED_MONTHLY: { + nextdate = IncrementDateByMonth(data.Date()); + break; + } + case SCHEDULED_WEEKLY: { + // TODO: Add weekly scheduling support + // data.SetNextDueDate(IncrementDateByMonth(data.Date())); + ShowBug("Unimplemented Weekly scheduling support in Database::AddScheduledTransaction()" + ); + break; + } + case SCHEDULED_QUARTERLY: { + nextdate = IncrementDateByQuarter(data.Date()); + break; + } + case SCHEDULED_ANNUALLY: { + nextdate = IncrementDateByYear(data.Date()); + break; + } + default: { + ShowBug("Unknown scheduled value in Database::AddScheduledTransaction()"); + break; + } } } - - if(data.CountCategories()==1) - { - InsertSchedTransaction(id, data.GetAccount()->GetID(), data.Date(), data.Type(), - data.Payee(), data.Amount(), data.NameAt(0), data.Memo(), - data.GetInterval(), nextdate, data.GetCount()); - } - else - { + + if (data.CountCategories() == 1) { + InsertSchedTransaction( + id, data.GetAccount()->GetID(), data.Date(), data.Type(), data.Payee(), data.Amount(), + data.NameAt(0), data.Memo(), data.GetInterval(), nextdate, data.GetCount() + ); + } else { // We are disabling notifications for the moment so that we don't end up with // multiple single-category transaction entries in the transaction view. SetNotify(false); - for(int32 i=0; iGetID(), data.Date(), data.Type(), - data.Payee(), data.AmountAt(i), data.NameAt(i), - data.MemoAt(i), data.GetInterval(), nextdate, data.GetCount()); + InsertSchedTransaction( + id, data.GetAccount()->GetID(), data.Date(), data.Type(), data.Payee(), + data.AmountAt(i), data.NameAt(i), data.MemoAt(i), data.GetInterval(), nextdate, + data.GetCount() + ); } - + // We now re-enable notifications and add the final transaction entry. This will // cause everyone to be notified of what really is just 1 transaction that has // multiple categories SetNotify(true); - int32 index = data.CountCategories()-1; - InsertSchedTransaction(id, data.GetAccount()->GetID(), data.Date(), data.Type(), - data.Payee(), data.AmountAt(index), data.NameAt(index), - data.MemoAt(index), data.GetInterval(), nextdate, data.GetCount()); + int32 index = data.CountCategories() - 1; + InsertSchedTransaction( + id, data.GetAccount()->GetID(), data.Date(), data.Type(), data.Payee(), + data.AmountAt(index), data.NameAt(index), data.MemoAt(index), data.GetInterval(), + nextdate, data.GetCount() + ); } UNLOCK; } -void Database::RemoveScheduledTransaction(const uint32 &id) -{ +void +Database::RemoveScheduledTransaction(const uint32 &id) { LOCK; BString command = "delete from scheduledlist where transid = "; command << id << ";"; - DBCommand(command.String(),"Database::RemoveScheduledTransactionStatus"); - + DBCommand(command.String(), "Database::RemoveScheduledTransactionStatus"); + // TODO: add notification? - + UNLOCK; } -bool Database::GetScheduledTransaction(const uint32 &transid, ScheduledTransData &data) -{ +bool +Database::GetScheduledTransaction(const uint32 &transid, ScheduledTransData &data) { LOCK; - + BString command; CppSQLite3Query query; - + command = "select accountid,date,payee,amount,category,memo,type,nextdate," - "count,interval from scheduledlist where transid = "; + "count,interval from scheduledlist where transid = "; command << transid << ";"; - query = DBQuery(command.String(),"Database::GetScheduledTransaction:get transaction data"); - - if(query.eof()) - { + query = DBQuery(command.String(), "Database::GetScheduledTransaction:get transaction data"); + + if (query.eof()) { UNLOCK; return false; } - + data.MakeEmpty(); data.SetAccount(AccountByID(query.getIntField(0))); Locale loc = LocaleForAccount(data.GetAccount()->GetID()); - + data.SetID(transid); data.SetDate(query.getInt64Field(1)); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(2)).String()); @@ -1143,351 +1115,338 @@ bool Database::GetScheduledTransaction(const uint32 &transid, ScheduledTransData data.SetNextDueDate(query.getInt64Field(7)); data.SetCount(query.getIntField(8)); data.SetInterval((TransactionInterval)query.getIntField(9)); - while(!query.eof()) - { + while (!query.eof()) { Fixed f; f.SetPremultiplied(atol(query.getStringField(3))); - - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(4)).String(),f,true); - - if(!query.fieldIsNull(4)) - data.SetMemoAt(data.CountCategories()-1,query.getStringField(5)); - + + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(4)).String(), f, true); + + if (!query.fieldIsNull(4)) + data.SetMemoAt(data.CountCategories() - 1, query.getStringField(5)); + query.nextRow(); } - - if( (data.CountCategories() == 1) && strlen(data.MemoAt(0))>0) + + if ((data.CountCategories() == 1) && strlen(data.MemoAt(0)) > 0) data.SetMemo(data.MemoAt(0)); - + UNLOCK; return true; } -uint32 Database::CountScheduledTransactions(void) -{ - CppSQLite3Query query = gDatabase.DBQuery("select count(*) from scheduledlist", - "ScheduleListView::RefreshScheduleList: count transactions"); - if(query.eof()) +uint32 +Database::CountScheduledTransactions(void) { + CppSQLite3Query query = gDatabase.DBQuery( + "select count(*) from scheduledlist", + "ScheduleListView::RefreshScheduleList: count transactions" + ); + if (query.eof()) return 0; - + return query.getInt64Field(0); } -bool Database::InsertSchedTransaction(const uint32 &id, const uint32 &accountid, - const time_t &startdate, const TransactionType &type, - const char *payee, const Fixed &amount, const char *category, - const char *memo, const TransactionInterval &interval, - const time_t &nextdate, const int32 &count) -{ +bool +Database::InsertSchedTransaction( + const uint32 &id, const uint32 &accountid, const time_t &startdate, const TransactionType &type, + const char *payee, const Fixed &amount, const char *category, const char *memo, + const TransactionInterval &interval, const time_t &nextdate, const int32 &count +) { // Internal method. No locking required - if(!payee || !category) + if (!payee || !category) return false; - + LOCK; bigtime_t timestamp = real_time_clock_usecs(); - + BString ecategory = EscapeIllegalCharacters(category); BString epayee = EscapeIllegalCharacters(payee); BString ememo = EscapeIllegalCharacters(memo); - + BString command = "insert into scheduledlist values("; - command << timestamp << ", " << accountid << ", " << id << ", " - << startdate << ",'" << type.Type() << "', '" - << epayee << "', " << amount.AsFixed() << ", '" << ecategory; - if(memo) + command << timestamp << ", " << accountid << ", " << id << ", " << startdate << ",'" + << type.Type() << "', '" << epayee << "', " << amount.AsFixed() << ", '" << ecategory; + if (memo) command << "', '" << ememo << "', "; else command << "', '', "; - + command << (int)interval << ", " << count << ", " << nextdate << ");"; - - DBCommand(command.String(),"Database::InsertSchedTransaction:insert into table"); - - return true; + + DBCommand(command.String(), "Database::InsertSchedTransaction:insert into table"); + + return true; } -int32 Database::GetLastKey(const char *table, const char *column) -{ +int32 +Database::GetLastKey(const char *table, const char *column) { // Internal method. No locking required - if(!table || !column) + if (!table || !column) return B_ERROR; - + BString command; command << "select " << column << " from " << table << " order by 1;"; - CppSQLite3Query query = DBQuery(command.String(),"Database::GetLastKey"); - + CppSQLite3Query query = DBQuery(command.String(), "Database::GetLastKey"); + int value = B_ERROR; - while(!query.eof()) - { + while (!query.eof()) { value = query.getIntField(0); query.nextRow(); } return value; } -void Database::AddCategory(const char *name, const bool &isexpense) -{ - if(!name || HasCategory(name)) +void +Database::AddCategory(const char *name, const bool &isexpense) { + if (!name || HasCategory(name)) return; - - if(strcasecmp(name,"split")==0) + + if (strcasecmp(name, "split") == 0) return; - + BString command("insert into categorylist values('"); command << EscapeIllegalCharacters(name) << "', " << (isexpense ? 0 : 1) << ");"; - DBCommand(command.String(),"Database::AddCategory"); + DBCommand(command.String(), "Database::AddCategory"); } -void Database::RemoveCategory(const char *name) -{ - if(!name || !HasCategory(name)) +void +Database::RemoveCategory(const char *name) { + if (!name || !HasCategory(name)) return; - + BString command("delete from categorylist where name = '"); command << EscapeIllegalCharacters(name) << "';"; - DBCommand(command.String(),"Database::RemoveCategory"); + DBCommand(command.String(), "Database::RemoveCategory"); } -bool Database::RenameCategory(const char *oldname, const char *newname) -{ - if( (!oldname && !newname) || strcmp(oldname,newname) == 0) +bool +Database::RenameCategory(const char *oldname, const char *newname) { + if ((!oldname && !newname) || strcmp(oldname, newname) == 0) return false; - - if(!HasCategory(oldname) || HasCategory(newname) ) + + if (!HasCategory(oldname) || HasCategory(newname)) return false; - + BString command("update categorylist set name = '"); - if(newname) + if (newname) command << EscapeIllegalCharacters(newname); - + command << "' where name = '"; - - if(oldname) + + if (oldname) command << EscapeIllegalCharacters(oldname); - + command << "';"; - - DBCommand(command.String(),"Database::RenameCategory"); + + DBCommand(command.String(), "Database::RenameCategory"); return true; } -bool Database::HasCategory(const char *name) -{ +bool +Database::HasCategory(const char *name) { BString command; CppSQLite3Query query; - - if(!name || strlen(name)==0) - { + + if (!name || strlen(name) == 0) { command = "select * from categorylist;"; - query = DBQuery(command.String(),"Database::HasCategory:find category"); - - while(!query.eof()) - { + query = DBQuery(command.String(), "Database::HasCategory:find category"); + + while (!query.eof()) { BString cat = query.getStringField(0); - if(cat.CountChars()==0) + if (cat.CountChars() == 0) return true; - + query.nextRow(); } - + return false; } - - command << "select name from categorylist where name = '" - << EscapeIllegalCharacters(name) << "';"; - query = DBQuery(command.String(),"Database::HasCategory:find category"); - + + command << "select name from categorylist where name = '" << EscapeIllegalCharacters(name) + << "';"; + query = DBQuery(command.String(), "Database::HasCategory:find category"); + return !query.eof(); } -bool Database::IsCategoryExpense(const char *name) -{ - if(!name) +bool +Database::IsCategoryExpense(const char *name) { + if (!name) return false; - - if(!HasCategory(name)) + + if (!HasCategory(name)) ShowBug("Called IsCategoryExpense on a nonexistent category"); - + BString command("select type from categorylist where name = '"); command << EscapeIllegalCharacters(name) << "';"; - CppSQLite3Query query = DBQuery(command.String(),"Database::IsCategoryExpense"); - - if(query.eof()) + CppSQLite3Query query = DBQuery(command.String(), "Database::IsCategoryExpense"); + + if (query.eof()) ShowBug("Called IsCategoryExpense and search had no results"); - + int value = query.getIntField(0); return (value == 0); } -void Database::SetCategoryExpense(const char *name, const bool &isexpense) -{ - if(!name || !HasCategory(name)) +void +Database::SetCategoryExpense(const char *name, const bool &isexpense) { + if (!name || !HasCategory(name)) return; - + BString command("update categorylist set type = "); command << (isexpense ? 0 : 1) << " where name = '" << EscapeIllegalCharacters(name) << "';"; command << EscapeIllegalCharacters(name) << "';"; - DBCommand(command.String(),"Database::SetCategoryExpense"); + DBCommand(command.String(), "Database::SetCategoryExpense"); } -void Database::RecategorizeTransactions(const char *from, const char *to) -{ - if(!HasCategory(from)) +void +Database::RecategorizeTransactions(const char *from, const char *to) { + if (!HasCategory(from)) return; - - if(!HasCategory(to)) - AddCategory(to,IsCategoryExpense(from)); - - Notify(WATCH_MASS_EDIT,NULL); - + + if (!HasCategory(to)) + AddCategory(to, IsCategoryExpense(from)); + + Notify(WATCH_MASS_EDIT, NULL); + BString command; - for(int32 i=0; iGetID() << " set category = '"; - - if(to) + + if (to) command << EscapeIllegalCharacters(to); - command << "' where category = '"; - - if(from) - command<< EscapeIllegalCharacters(from); + command << "' where category = '"; + + if (from) + command << EscapeIllegalCharacters(from); command << "';"; - DBCommand(command.String(),"Database::RecategorizeTransactions"); + DBCommand(command.String(), "Database::RecategorizeTransactions"); } - - Notify(WATCH_MASS_EDIT,NULL); + + Notify(WATCH_MASS_EDIT, NULL); } -BString AccountTypeToString(const AccountType &type) -{ - switch(type) - { - case ACCOUNT_BANK: - return BString("Bank"); - case ACCOUNT_CREDIT: - return BString("Credit"); - default: - return BString("Unknown"); +BString +AccountTypeToString(const AccountType &type) { + switch (type) { + case ACCOUNT_BANK: + return BString("Bank"); + case ACCOUNT_CREDIT: + return BString("Credit"); + default: + return BString("Unknown"); } } // This will prevent SQL injection attacks -static const char *sIllegalCharacters[] = - { "!","@","#","$","%","^","&","*","(",")","-","+","=","{","}","[","]","\\", - "|",";",":","'","\"","<",">",",",".","/","?","`","~"," ", NULL - }; -static const char *sReplacementCharacters[] = - { "£21£","£40£","£23£","£24£","£25£","£5e£","£26£","£2a£","£28£","£29£","£2d£", - "£2b£","£3d£","£7b£","£7d£","£5b£","£5d£","£5c£","£7c£","£3b£","£3a£","£27£", - "£22£","£3c£","£3e£","£2c£","£2e£","£2f£","£3f£","£60£","£7e£","£20£", NULL - }; - -static const char *sIllegalWords[]= - { " select "," drop "," create "," delete "," where "," update "," order "," by ", - " and "," or "," in "," between "," aliases "," join "," union "," alter ", - " functions "," group "," into ", " view ", NULL }; -static const char *sReplacementWords[]= - { " ¥select "," ¥drop "," ¥create "," ¥delete "," ¥where "," ¥update "," ¥order "," ¥by ", - " ¥and "," ¥or "," ¥in "," ¥between "," ¥aliases "," ¥join "," ¥union "," ¥alter ", - " ¥functions "," ¥group "," ¥into ", " ¥view ", NULL }; - -BString EscapeIllegalCharacters(const char *instr) -{ +static const char *sIllegalCharacters[] = {"!", "@", "#", "$", "%", "^", "&", "*", "(", + ")", "-", "+", "=", "{", "}", "[", "]", "\\", + "|", ";", ":", "'", "\"", "<", ">", ",", ".", + "/", "?", "`", "~", " ", NULL}; +static const char *sReplacementCharacters[] = { + "£21£", "£40£", "£23£", "£24£", "£25£", "£5e£", "£26£", "£2a£", "£28£", "£29£", "£2d£", + "£2b£", "£3d£", "£7b£", "£7d£", "£5b£", "£5d£", "£5c£", "£7c£", "£3b£", "£3a£", "£27£", + "£22£", "£3c£", "£3e£", "£2c£", "£2e£", "£2f£", "£3f£", "£60£", "£7e£", "£20£", NULL +}; + +static const char *sIllegalWords[] = {" select ", " drop ", " create ", " delete ", " where ", + " update ", " order ", " by ", " and ", " or ", + " in ", " between ", " aliases ", " join ", " union ", + " alter ", " functions ", " group ", " into ", " view ", + NULL}; +static const char *sReplacementWords[] = { + " ¥select ", " ¥drop ", " ¥create ", " ¥delete ", " ¥where ", " ¥update ", " ¥order ", + " ¥by ", " ¥and ", " ¥or ", " ¥in ", " ¥between ", " ¥aliases ", " ¥join ", + " ¥union ", " ¥alter ", " ¥functions ", " ¥group ", " ¥into ", " ¥view ", NULL +}; + +BString +EscapeIllegalCharacters(const char *instr) { // Because the £ symbol isn't allowed in a category but is a valid database character, // we'll use it as the escape character for illegal characters - + BString string(instr); - if(string.CountChars()<1) + if (string.CountChars() < 1) return string; - + string.RemoveAll("£"); string.RemoveAll("¥"); - - int32 i=0; - while(sIllegalCharacters[i]) - { - string.ReplaceAll(sIllegalCharacters[i],sReplacementCharacters[i]); + + int32 i = 0; + while (sIllegalCharacters[i]) { + string.ReplaceAll(sIllegalCharacters[i], sReplacementCharacters[i]); i++; } - + // Just to make sure that reserved words aren't used, we'll prefix them with the ¥ character // for the same reasons that we used £ with bad characters - i=0; - while(sIllegalWords[i]) - { - string.ReplaceAll(sIllegalWords[i],sReplacementWords[i]); + i = 0; + while (sIllegalWords[i]) { + string.ReplaceAll(sIllegalWords[i], sReplacementWords[i]); i++; } return string; } -BString DeescapeIllegalCharacters(const char *instr) -{ +BString +DeescapeIllegalCharacters(const char *instr) { BString string(instr); - if(string.CountChars()<1) + if (string.CountChars() < 1) return string; - - int32 i=0; - while(sIllegalCharacters[i]) - { - string.ReplaceAll(sReplacementCharacters[i],sIllegalCharacters[i]); + + int32 i = 0; + while (sIllegalCharacters[i]) { + string.ReplaceAll(sReplacementCharacters[i], sIllegalCharacters[i]); i++; } - + // Just to make sure that reserved words aren't used, we'll prefix them with the ¥ character // for the same reasons that we used £ with bad characters - i=0; - while(sIllegalWords[i]) - { - string.ReplaceAll(sReplacementWords[i],sIllegalWords[i]); + i = 0; + while (sIllegalWords[i]) { + string.ReplaceAll(sReplacementWords[i], sIllegalWords[i]); i++; } return string; } -void Database::DBCommand(const char *command, const char *functionname) -{ - if(!command) +void +Database::DBCommand(const char *command, const char *functionname) { + if (!command) ShowBug("NULL database command in Database::DBCommand"); - if(!functionname) + if (!functionname) ShowBug("NULL function name in Database::DBCommand"); - - try - { + + try { fDB.execDML(command); - } - catch(CppSQLite3Exception &e) - { + } catch (CppSQLite3Exception &e) { BString msg("Database Exception in "); - msg << functionname << ".\n\n" << e.errorMessage() - << "\n\nDatabase Exception Command: " << command << "\n"; + msg << functionname << ".\n\n" + << e.errorMessage() << "\n\nDatabase Exception Command: " << command << "\n"; printf(msg.String()); ShowBug(msg.String()); } } -CppSQLite3Query Database::DBQuery(const char *query, const char *functionname) -{ - if(!query) +CppSQLite3Query +Database::DBQuery(const char *query, const char *functionname) { + if (!query) ShowBug("NULL database command in Database::DBQuery"); - if(!functionname) + if (!functionname) ShowBug("NULL function name in Database::DBQuery"); - - try - { + + try { return fDB.execQuery(query); - } - catch(CppSQLite3Exception &e) - { + } catch (CppSQLite3Exception &e) { BString msg("Database Exception in "); - msg << functionname << ".\n\n" << e.errorMessage() - << "\n\nDatabase Exception Query: " << query << "\n"; + msg << functionname << ".\n\n" + << e.errorMessage() << "\n\nDatabase Exception Query: " << query << "\n"; printf(msg.String()); ShowBug(msg.String()); } diff --git a/src/Database.h b/src/Database.h index 540a339..d0e7469 100644 --- a/src/Database.h +++ b/src/Database.h @@ -1,14 +1,14 @@ #ifndef DATABASE_H #define DATABASE_H +#include "Account.h" +#include "CBLocale.h" +#include "CppSQLite3.h" +#include "Notifier.h" +#include "ObjectList.h" #include #include #include -#include "Notifier.h" -#include "ObjectList.h" -#include "CppSQLite3.h" -#include "Account.h" -#include "CBLocale.h" class Fixed; class BudgetEntry; @@ -16,77 +16,86 @@ class TransactionType; class TransactionData; class ScheduledTransData; -BString AccountTypeToString(const AccountType &type); +BString +AccountTypeToString(const AccountType &type); -class Database : public Notifier -{ -public: - Database(const char *file=NULL); +class Database : public Notifier { + public: + Database(const char *file = NULL); ~Database(void); - -// --------------------------------------------------------------------------- -// Old API functions (list-based) -// --------------------------------------------------------------------------- + + // --------------------------------------------------------------------------- + // Old API functions (list-based) + // --------------------------------------------------------------------------- Account *SetCurrentAccount(const int32 &index); int32 SetCurrentAccount(Account *account); + Account *CurrentAccount(void) const { return fCurrent; } + Account *AccountAt(int32 index) { return fList.ItemAt(index); } + Account *AccountByName(const char *name); Account *AccountByID(const uint32 &accountid); + int32 CountAccounts(void) { return fList.CountItems(); } + void PrintToStream(void) const; + int32 IndexOf(Account *acc) { return fList.IndexOf(acc); } + void CloseAccount(Account *item); void ReopenAccount(Account *item); - + bool ImportFile(const entry_ref &ref); bool ExportFile(const entry_ref &ref); - -// --------------------------------------------------------------------------- -// SQLite-based functions -// --------------------------------------------------------------------------- + + // --------------------------------------------------------------------------- + // SQLite-based functions + // --------------------------------------------------------------------------- void CreateFile(const char *path); status_t OpenFile(const char *path); void CloseFile(void); - - Account *AddAccount(const char *name, const AccountType &type, - const char *status="Open", const Locale *locale=NULL); + + Account *AddAccount( + const char *name, const AccountType &type, const char *status = "Open", + const Locale *locale = NULL + ); bool RemoveAccount(const int &accountid); void RemoveAccount(Account *item); void RenameAccount(Account *item, const char *name); - + void AddBudgetEntry(const BudgetEntry &entry); bool RemoveBudgetEntry(const char *category); bool HasBudgetEntry(const char *category); bool GetBudgetEntry(const char *name, BudgetEntry &entry); int32 CountBudgetEntries(void); - + void SetAccountLocale(const uint32 &accountid, const Locale &data); Locale LocaleForAccount(const uint32 &id); void SetDefaultLocale(const Locale &data); Locale GetDefaultLocale(void); bool UsesDefaultLocale(const uint32 &id); - - bool AddTransaction(const uint32 &accountid, const uint32 &id, const time_t &date, - const TransactionType &type, - const char *payee, const Fixed &amount, - const char *category, const char *memo, const uint8 &status=TRANS_OPEN); + + bool AddTransaction( + const uint32 &accountid, const uint32 &id, const time_t &date, const TransactionType &type, + const char *payee, const Fixed &amount, const char *category, const char *memo, + const uint8 &status = TRANS_OPEN + ); bool AddTransaction(TransactionData &data, const bool &newid = true); bool RemoveTransaction(const uint32 &transid); uint32 NextTransactionID(void); bool HasTransaction(const uint32 &transid); bool GetTransaction(const uint32 &transid, TransactionData &data); - bool GetTransaction(const uint32 &transid, const uint32 &accountid, - TransactionData &data); + bool GetTransaction(const uint32 &transid, const uint32 &accountid, TransactionData &data); void SetTransactionStatus(const uint32 &transid, const uint8 &status); - + bool GetTransferCounterpart(const uint32 &transid, TransactionData &data); - + void AddScheduledTransaction(const ScheduledTransData &data, const bool &newid = true); void RemoveScheduledTransaction(const uint32 &id); bool GetScheduledTransaction(const uint32 &transid, ScheduledTransData &data); uint32 CountScheduledTransactions(void); - + void AddCategory(const char *name, const bool &isexpense); void RemoveCategory(const char *name); bool RenameCategory(const char *oldname, const char *newname); @@ -94,33 +103,33 @@ class Database : public Notifier bool IsCategoryExpense(const char *name); void SetCategoryExpense(const char *name, const bool &isexpense); void RecategorizeTransactions(const char *from, const char *to); - + void DBCommand(const char *command, const char *functionname); CppSQLite3Query DBQuery(const char *query, const char *functionname); - -private: + + private: int32 GetLastKey(const char *table, const char *column); - + // Used to allow split scheduled transactions - bool InsertSchedTransaction(const uint32 &id, const uint32 &accountid, - const time_t &startdate, - const TransactionType &type, - const char *payee, const Fixed &amount, - const char *category, const char *memo, - const TransactionInterval &interval, - const time_t &nextdate, - const int32 &count=-1); - + bool InsertSchedTransaction( + const uint32 &id, const uint32 &accountid, const time_t &startdate, + const TransactionType &type, const char *payee, const Fixed &amount, const char *category, + const char *memo, const TransactionInterval &interval, const time_t &nextdate, + const int32 &count = -1 + ); + Account *fCurrent; - BObjectListfList; - + BObjectList fList; + BLocker fLocker; BString fPath; CppSQLite3DB fDB; }; -BString EscapeIllegalCharacters(const char *string); -BString DeescapeIllegalCharacters(const char *string); +BString +EscapeIllegalCharacters(const char *string); +BString +DeescapeIllegalCharacters(const char *string); extern Locale gDefaultLocale; extern Locale gCurrentLocale; diff --git a/src/DateBox.cpp b/src/DateBox.cpp index f86c1c9..5bffe33 100644 --- a/src/DateBox.cpp +++ b/src/DateBox.cpp @@ -5,157 +5,130 @@ #include "TimeSupport.h" #include "Translate.h" -DateBoxFilter::DateBoxFilter(DateBox *box) - : AutoTextControlFilter(box) -{ -} +DateBoxFilter::DateBoxFilter(DateBox *box) : AutoTextControlFilter(box) {} -filter_result DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB) - { - if(!((DateBox*)TextControl())->IsTabFiltering()) + if (key == B_TAB) { + if (!((DateBox *)TextControl())->IsTabFiltering()) return B_DISPATCH_MESSAGE; - - if(mod & B_SHIFT_KEY) + + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; - +#endif + + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; + // Weed out navigation keys - if((key<32 && key!=B_PAGE_UP && key!=B_PAGE_DOWN)) + if ((key < 32 && key != B_PAGE_UP && key != B_PAGE_DOWN)) return B_DISPATCH_MESSAGE; - + int32 start, end; - DateBox *box = (DateBox*)TextControl(); - box->TextView()->GetSelection(&start,&end); - + DateBox *box = (DateBox *)TextControl(); + box->TextView()->GetSelection(&start, &end); + BString keystring; - GetCurrentMessage()->FindString("bytes",&keystring); - + GetCurrentMessage()->FindString("bytes", &keystring); + BString string; - if(keystring=="+") - { - if(strlen(box->Text())>0) + if (keystring == "+") { + if (strlen(box->Text()) > 0) box->fCurrentDate = IncrementDateByDay(box->fCurrentDate); - - gDefaultLocale.DateToString(box->fCurrentDate,string); + + gDefaultLocale.DateToString(box->fCurrentDate, string); box->SetText(string.String()); box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } - else - if(keystring=="-") - { - if(strlen(box->Text())>0) + } else if (keystring == "-") { + if (strlen(box->Text()) > 0) box->fCurrentDate = DecrementDateByDay(box->fCurrentDate); - gDefaultLocale.DateToString(box->fCurrentDate,string); + gDefaultLocale.DateToString(box->fCurrentDate, string); box->SetText(string.String()); box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } - else - if(key==B_PAGE_UP) - { - if(strlen(box->Text())>0) - { - if(mod & B_SHIFT_KEY) + } else if (key == B_PAGE_UP) { + if (strlen(box->Text()) > 0) { + if (mod & B_SHIFT_KEY) box->fCurrentDate = IncrementDateByYear(box->fCurrentDate); else box->fCurrentDate = IncrementDateByMonth(box->fCurrentDate); } - gDefaultLocale.DateToString(box->fCurrentDate,string); + gDefaultLocale.DateToString(box->fCurrentDate, string); box->SetText(string.String()); box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } - else - if(key==B_PAGE_DOWN) - { - if(strlen(box->Text())>0) - { - if(mod & B_SHIFT_KEY) + } else if (key == B_PAGE_DOWN) { + if (strlen(box->Text()) > 0) { + if (mod & B_SHIFT_KEY) box->fCurrentDate = DecrementDateByYear(box->fCurrentDate); else box->fCurrentDate = DecrementDateByMonth(box->fCurrentDate); } - gDefaultLocale.DateToString(box->fCurrentDate,string); + gDefaultLocale.DateToString(box->fCurrentDate, string); box->SetText(string.String()); box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; } - + return B_DISPATCH_MESSAGE; } -DateBox::DateBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags), - fFilterTab(true) -{ +DateBox::DateBox(const char *name, const char *label, const char *text, BMessage *msg, uint32 flags) + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) { SetFilter(new DateBoxFilter(this)); fCurrentDate = GetCurrentDate(); - const char date_disallowed[]="`~!@#$%^&*()_=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" - "ZXCVBNM,.<>?qwertyuiopasdfghjklzxcvbnm"; - int32 i=0; - while(date_disallowed[i]) - { + const char date_disallowed[] = "`~!@#$%^&*()_=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" + "ZXCVBNM,.<>?qwertyuiopasdfghjklzxcvbnm"; + int32 i = 0; + while (date_disallowed[i]) { TextView()->DisallowChar(date_disallowed[i]); i++; } - + // Even though dates should have a limit of 10 characters, we want to give // the user a little elbow room. ;^) SetCharacterLimit(15); } - -bool DateBox::Validate(const bool &alert) -{ +bool +DateBox::Validate(const bool &alert) { BString date; time_t tdate; - if(strlen(Text())<1) - { + if (strlen(Text()) < 1) { BString date; - gDefaultLocale.DateToString(fCurrentDate,date); + gDefaultLocale.DateToString(fCurrentDate, date); SetText(date.String()); - } - else - if(gDefaultLocale.StringToDate(Text(),tdate)!=B_OK) - { - if(alert) - { - ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE("Capital Be understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.")); + } else if (gDefaultLocale.StringToDate(Text(), tdate) != B_OK) { + if (alert) { + ShowAlert( + TRANSLATE("Capital Be didn't understand the date you entered."), + TRANSLATE("Capital Be understands lots of different ways of entering dates. " + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") + ); MakeFocus(true); } return false; - } - else - { + } else { fCurrentDate = tdate; - gDefaultLocale.DateToString(fCurrentDate,date); + gDefaultLocale.DateToString(fCurrentDate, date); SetText(date.String()); } return true; diff --git a/src/DateBox.h b/src/DateBox.h index e913ede..6df39fe 100644 --- a/src/DateBox.h +++ b/src/DateBox.h @@ -5,27 +5,30 @@ class DateBox; -class DateBoxFilter : public AutoTextControlFilter -{ -public: +class DateBoxFilter : public AutoTextControlFilter { + public: DateBoxFilter(DateBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class DateBox : public AutoTextControl -{ -public: - DateBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class DateBox : public AutoTextControl { + public: + DateBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); void SetDate(const time_t &date) { fCurrentDate = date; } + time_t GetDate(void) const { return fCurrentDate; } - bool Validate(const bool &alert=true); - + + bool Validate(const bool &alert = true); + void UseTabFiltering(const bool &value) { fFilterTab = value; } + bool IsTabFiltering(void) const { return fFilterTab; } -private: + + private: friend DateBoxFilter; time_t fCurrentDate; bool fFilterTab; diff --git a/src/EscapeCancelFilter.h b/src/EscapeCancelFilter.h index cbf2ac1..139f98c 100644 --- a/src/EscapeCancelFilter.h +++ b/src/EscapeCancelFilter.h @@ -3,25 +3,22 @@ // This is for any window which doesn't already have an AutoTextControl in it. -#include #include +#include + +class EscapeCancelFilter : public BMessageFilter { + public: + EscapeCancelFilter(void) : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN) {} -class EscapeCancelFilter : public BMessageFilter -{ -public: - EscapeCancelFilter(void) - : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE,B_KEY_DOWN) {} ~EscapeCancelFilter(void) {} - filter_result Filter(BMessage *msg, BHandler **target) - { + + filter_result Filter(BMessage *msg, BHandler **target) { int32 rawchar; - msg->FindInt32("raw_char",&rawchar); - - if(rawchar == B_ESCAPE) - { + msg->FindInt32("raw_char", &rawchar); + + if (rawchar == B_ESCAPE) { BLooper *loop = (*target)->Looper(); - if(loop) - { + if (loop) { BMessenger msgr(loop); msgr.SendMessage(B_QUIT_REQUESTED); return B_SKIP_MESSAGE; @@ -29,9 +26,7 @@ class EscapeCancelFilter : public BMessageFilter } return B_DISPATCH_MESSAGE; } - }; #endif - diff --git a/src/Fixed.cpp b/src/Fixed.cpp index 77b3ccc..f48786d 100644 --- a/src/Fixed.cpp +++ b/src/Fixed.cpp @@ -1,232 +1,218 @@ #include "Fixed.h" -Fixed::Fixed(void) -{ - fValue = 0; -} - -Fixed::Fixed(double val) -{ - fValue = (int32)(val * 100.0); -} +Fixed::Fixed(void) { fValue = 0; } -Fixed::Fixed(long val, bool premult) -{ - fValue = premult ? val : val * 100; -} +Fixed::Fixed(double val) { fValue = (int32)(val * 100.0); } -Fixed::Fixed(int val) -{ - fValue = val * 100; -} +Fixed::Fixed(long val, bool premult) { fValue = premult ? val : val * 100; } +Fixed::Fixed(int val) { fValue = val * 100; } -float Fixed::AsFloat(void) const -{ +float +Fixed::AsFloat(void) const { return float(fValue / 100.0); } -double Fixed::AsDouble(void) const -{ +double +Fixed::AsDouble(void) const { return double(fValue / 100.0); } - -long Fixed::AsLong(void) const -{ +long +Fixed::AsLong(void) const { return fValue / 100; } -long Fixed::AsFixed(void) const -{ +long +Fixed::AsFixed(void) const { return fValue; } -long Fixed::IntegerPart(void) const -{ +long +Fixed::IntegerPart(void) const { return fValue / 100; } -double Fixed::DecimalPart(void) const -{ +double +Fixed::DecimalPart(void) const { return (fValue / 100.0) - (double)(fValue / 100); } -Fixed Fixed::AbsoluteValue(void) const -{ +Fixed +Fixed::AbsoluteValue(void) const { Fixed f(*this); - if(f.IsNegative()) + if (f.IsNegative()) f.Invert(); return f; } -void Fixed::Round(void) -{ +void +Fixed::Round(void) { int32 integerpart = (fValue / 100) * 100; int32 decimalpart; - + decimalpart = fValue - integerpart; fValue -= decimalpart; - if(fValue > 0) - { - if(decimalpart > 49) + if (fValue > 0) { + if (decimalpart > 49) fValue += 100; - } - else - { - if(decimalpart < -49) + } else { + if (decimalpart < -49) fValue -= 100; } } -void Fixed::SetPremultiplied(long value) -{ - fValue=value; +void +Fixed::SetPremultiplied(long value) { + fValue = value; } -void Fixed::AddPremultiplied(long value) -{ - fValue+=value; +void +Fixed::AddPremultiplied(long value) { + fValue += value; } -void Fixed::SubtractPremultiplied(long value) -{ - fValue+=value; +void +Fixed::SubtractPremultiplied(long value) { + fValue += value; } -Fixed Fixed::InvertAsCopy(void) const -{ - Fixed f; f.SetPremultiplied(-fValue); return f; +Fixed +Fixed::InvertAsCopy(void) const { + Fixed f; + f.SetPremultiplied(-fValue); + return f; } -void Fixed::Invert(void) -{ +void +Fixed::Invert(void) { fValue = -fValue; } - -bool Fixed::IsNegative(void) const -{ - return fValue<0; +bool +Fixed::IsNegative(void) const { + return fValue < 0; } -bool Fixed::IsPositive(void) const -{ - return fValue>0; +bool +Fixed::IsPositive(void) const { + return fValue > 0; } -bool Fixed::IsZero(void) const -{ - return fValue==0; +bool +Fixed::IsZero(void) const { + return fValue == 0; } -bool Fixed::operator!=(const Fixed &from) const -{ +bool +Fixed::operator!=(const Fixed &from) const { return (fValue != from.fValue); } -bool Fixed::operator==(const Fixed &from) const -{ +bool +Fixed::operator==(const Fixed &from) const { return (fValue == from.fValue); } -Fixed Fixed::operator+(const Fixed &from) -{ - return Fixed( fValue + from.fValue, true ); +Fixed +Fixed::operator+(const Fixed &from) { + return Fixed(fValue + from.fValue, true); } -Fixed Fixed::operator-(const Fixed &from) -{ - return Fixed( fValue - from.fValue, true ); +Fixed +Fixed::operator-(const Fixed &from) { + return Fixed(fValue - from.fValue, true); } -Fixed Fixed::operator+(const double &from) -{ - return Fixed( (double(fValue)/100.0) + from); +Fixed +Fixed::operator+(const double &from) { + return Fixed((double(fValue) / 100.0) + from); } -Fixed Fixed::operator-(const double &from) -{ - return Fixed( (double(fValue)/100.0) - from); +Fixed +Fixed::operator-(const double &from) { + return Fixed((double(fValue) / 100.0) - from); } -Fixed Fixed::operator+=(const double &from) -{ +Fixed +Fixed::operator+=(const double &from) { return Fixed(fValue += int32(from * 100)); } -Fixed Fixed::operator-=(const double &from) -{ +Fixed +Fixed::operator-=(const double &from) { return Fixed(fValue -= int32(from * 100)); } -Fixed Fixed::operator*=(const double &from) -{ +Fixed +Fixed::operator*=(const double &from) { // Use 64-bit processing to prevent out-of-range errors int64 start = fValue * 100; int64 mult = int64(from); - + fValue = int32((start * mult) / 100); return *this; } -Fixed Fixed::operator/=(const double &from) -{ +Fixed +Fixed::operator/=(const double &from) { // Use 64-bit processing to prevent out-of-range errors int64 start = fValue * 100; int64 div = int64(from * 100.0); - + fValue = int32(start / div); return *this; } -bool Fixed::operator<(const long &from) const -{ - return fValue<(from*100); +bool +Fixed::operator<(const long &from) const { + return fValue < (from * 100); } -bool Fixed::operator>(const long &from) const -{ - return fValue>(from*100); +bool +Fixed::operator>(const long &from) const { + return fValue > (from * 100); } -bool Fixed::operator<(const Fixed &from) const -{ +bool +Fixed::operator<(const Fixed &from) const { return fValue < from.fValue; } -bool Fixed::operator>(const Fixed &from) const -{ +bool +Fixed::operator>(const Fixed &from) const { return fValue > from.fValue; } -bool Fixed::operator<=(const Fixed &from) const -{ +bool +Fixed::operator<=(const Fixed &from) const { return fValue <= from.fValue; } -bool Fixed::operator>=(const Fixed &from) const -{ +bool +Fixed::operator>=(const Fixed &from) const { return fValue >= from.fValue; } -bool Fixed::operator==(const long &from) const -{ - return fValue==(from*100); +bool +Fixed::operator==(const long &from) const { + return fValue == (from * 100); } -Fixed &Fixed::operator+=(const Fixed &from) -{ - fValue+=from.fValue; return *this; +Fixed & +Fixed::operator+=(const Fixed &from) { + fValue += from.fValue; + return *this; } -Fixed &Fixed::operator-=(const Fixed &from) -{ - fValue-=from.fValue; return *this; +Fixed & +Fixed::operator-=(const Fixed &from) { + fValue -= from.fValue; + return *this; } -Fixed &Fixed::operator=(const long &from) -{ - fValue=from*100; return *this; +Fixed & +Fixed::operator=(const long &from) { + fValue = from * 100; + return *this; } - diff --git a/src/Fixed.h b/src/Fixed.h index 9f900c3..721fe40 100644 --- a/src/Fixed.h +++ b/src/Fixed.h @@ -5,14 +5,13 @@ // Fixed point class accurate to 2 decimal places -class Fixed -{ -public: +class Fixed { + public: Fixed(void); Fixed(double val); - Fixed(long val, bool premult=false); + Fixed(long val, bool premult = false); Fixed(int val); - + float AsFloat(void) const; double AsDouble(void) const; long AsLong(void) const; @@ -26,11 +25,11 @@ class Fixed void Invert(void); Fixed AbsoluteValue(void) const; void Round(void); - + bool IsNegative(void) const; bool IsPositive(void) const; bool IsZero(void) const; - + Fixed operator+(const Fixed &from); Fixed operator-(const Fixed &from); bool operator<(const Fixed &from) const; @@ -49,11 +48,12 @@ class Fixed bool operator<(const long &from) const; bool operator>(const long &from) const; bool operator==(const long &from) const; - + Fixed &operator+=(const Fixed &from); Fixed &operator-=(const Fixed &from); Fixed &operator=(const long &from); -private: + + private: int32 fValue; }; diff --git a/src/HelpButton.cpp b/src/HelpButton.cpp index 87e470e..d2f0e4a 100644 --- a/src/HelpButton.cpp +++ b/src/HelpButton.cpp @@ -1,72 +1,66 @@ #include "HelpButton.h" #include "Preferences.h" -#include -#include -#include -#include +#include "Translate.h" #include +#include #include -#include "Translate.h" +#include +#include +#include + +class HelpButtonWindow : public BWindow { + public: + HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref); -class HelpButtonWindow : public BWindow -{ -public: - HelpButtonWindow(const BRect &frame,const entry_ref &helpfileref); -private: + private: BTextView *fTextView; }; HelpButton::HelpButton(const char *name, const char *path) - : BButton(name, "", new BMessage(M_HELPBUTTON_PRESSED)) { - get_ref_for_path(path,&fRef); - SetIcon(BTranslationUtils::GetBitmap('PNG ',"HelpButtonUp.png")); + : BButton(name, "", new BMessage(M_HELPBUTTON_PRESSED)) { + get_ref_for_path(path, &fRef); + SetIcon(BTranslationUtils::GetBitmap('PNG ', "HelpButtonUp.png")); } -HelpButton::~HelpButton(void) { - -} +HelpButton::~HelpButton(void) {} -void HelpButton::AttachedToWindow() { +void +HelpButton::AttachedToWindow() { SetTarget(this); BButton::AttachedToWindow(); } -void HelpButton::MessageReceived(BMessage *msg) -{ - if(msg->what==M_HELPBUTTON_PRESSED) { +void +HelpButton::MessageReceived(BMessage *msg) { + if (msg->what == M_HELPBUTTON_PRESSED) { BRect frame = Window()->Frame(); - HelpButtonWindow *help = new HelpButtonWindow(frame,fRef); + HelpButtonWindow *help = new HelpButtonWindow(frame, fRef); help->Show(); - } - else { + } else { BButton::MessageReceived(msg); } } -HelpButtonWindow::HelpButtonWindow(const BRect &frame,const entry_ref &helpfileref) - : BWindow(frame,TRANSLATE("Help"),B_DOCUMENT_WINDOW_LOOK, - B_FLOATING_APP_WINDOW_FEEL,B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) -{ - BView *view = new BView("back",B_WILL_DRAW | B_FRAME_EVENTS); - view->SetViewColor(235,235,255); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .Add(view) - .End(); - - fTextView = new BTextView("textview",B_WILL_DRAW); +HelpButtonWindow::HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref) + : BWindow( + frame, TRANSLATE("Help"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ) { + BView *view = new BView("back", B_WILL_DRAW | B_FRAME_EVENTS); + view->SetViewColor(235, 235, 255); + BLayoutBuilder::Group<>(this, B_VERTICAL).Add(view).End(); + + fTextView = new BTextView("textview", B_WILL_DRAW); fTextView->MakeEditable(false); fTextView->SetStylable(true); fTextView->SetWordWrap(true); - - BScrollView *sv = new BScrollView("scrollview",fTextView,B_FRAME_EVENTS,false,true); - - BFile file(&helpfileref,B_READ_ONLY); + + BScrollView *sv = new BScrollView("scrollview", fTextView, B_FRAME_EVENTS, false, true); + + BFile file(&helpfileref, B_READ_ONLY); SetTitle(helpfileref.name); - BTranslationUtils::GetStyledText(&file,fTextView); + BTranslationUtils::GetStyledText(&file, fTextView); fTextView->MakeFocus(true); - BLayoutBuilder::Group<>(view, B_VERTICAL) - .SetInsets(10) - .Add(sv) - .End(); + BLayoutBuilder::Group<>(view, B_VERTICAL).SetInsets(10).Add(sv).End(); } diff --git a/src/HelpButton.h b/src/HelpButton.h index c75ee0b..b5c183b 100644 --- a/src/HelpButton.h +++ b/src/HelpButton.h @@ -7,15 +7,15 @@ #define M_HELPBUTTON_PRESSED 'hbpr' -class HelpButton : public BButton -{ -public: +class HelpButton : public BButton { + public: HelpButton(const char *name, const char *path); ~HelpButton(void); virtual void AttachedToWindow(); virtual void MessageReceived(BMessage *msg); -private: + + private: entry_ref fRef; }; diff --git a/src/Import.cpp b/src/Import.cpp index db42f00..2735fc0 100644 --- a/src/Import.cpp +++ b/src/Import.cpp @@ -1,29 +1,29 @@ #include "Import.h" -#include -#include -#include -#include -#include -#include "TextFile.h" -#include "DStringList.h" +#include "Account.h" #include "Budget.h" -#include "ObjectList.h" +#include "CBLocale.h" +#include "Category.h" +#include "DStringList.h" #include "Database.h" -#include "Account.h" +#include "ObjectList.h" +#include "TextFile.h" #include "Transaction.h" #include "TransactionData.h" -#include "Category.h" -#include "CBLocale.h" +#include +#include +#include +#include +#include #define DEBUG_IMPORT #ifdef DEBUG_IMPORT - #define STRACE(x) printf x +#define STRACE(x) printf x #else - #define STRACE(x) /* */ +#define STRACE(x) /* */ #endif -bool debuggerflag=false; +bool debuggerflag = false; // These functions are called by the global database object to remove all the // messy import code from the rest of the otherwise-clean OOP code. This code is @@ -36,506 +36,465 @@ bool debuggerflag=false; All I know is that they exist when Business Lists are exported from Q2004. */ -BString ReadCategories(BObjectList &list, TextFile &file); -BString ReadTransactions(Account *account, TextFile &file); -BString ReadAccounts(BObjectList &list, TextFile &file); +BString +ReadCategories(BObjectList &list, TextFile &file); +BString +ReadTransactions(Account *account, TextFile &file); +BString +ReadAccounts(BObjectList &list, TextFile &file); -BString DateToQIFDate(const time_t &date); -BString MakeCategoryString(const DStringList &list, const bool &isexpense); +BString +DateToQIFDate(const time_t &date); +BString +MakeCategoryString(const DStringList &list, const bool &isexpense); -bool ImportQIF(const entry_ref &ref) -{ - TextFile file(ref,B_READ_ONLY); +bool +ImportQIF(const entry_ref &ref) { + TextFile file(ref, B_READ_ONLY); STRACE(("Importing QIF file\n")); BObjectList catlist(20); BObjectList accountlist(20); - int32 accountindex=0; - + int32 accountindex = 0; + BString string = file.ReadLine(); - - while(!file.IsEOF()) - { + + while (!file.IsEOF()) { Account *currentaccount; BString accountname; - - if(string.CountChars()<1) + + if (string.CountChars() < 1) break; - + string.RemoveAll("\r"); - - if(string.FindFirst("!Type:Cat")!=B_ERROR) - { + + if (string.FindFirst("!Type:Cat") != B_ERROR) { string = ReadCategories(catlist, file); - } - else - if(string.FindFirst("!Type:Bank")!=B_ERROR) - { + } else if (string.FindFirst("!Type:Bank") != B_ERROR) { STRACE(("Bank Account\n")); accountindex++; accountname = "Bank Account "; accountname << accountindex; - - currentaccount = gDatabase.AddAccount(accountname.String(),ACCOUNT_BANK,"open"); - string = ReadTransactions(currentaccount,file); - } - else - if(string.FindFirst("!Type:Cash")!=B_ERROR) - { + + currentaccount = gDatabase.AddAccount(accountname.String(), ACCOUNT_BANK, "open"); + string = ReadTransactions(currentaccount, file); + } else if (string.FindFirst("!Type:Cash") != B_ERROR) { accountindex++; accountname = "Cash Account "; accountname << accountindex; - - currentaccount = gDatabase.AddAccount(accountname.String(),ACCOUNT_CASH,"open"); - string = ReadTransactions(currentaccount,file); - } - else - if(string.FindFirst("!Type:CCard")!=B_ERROR) - { + + currentaccount = gDatabase.AddAccount(accountname.String(), ACCOUNT_CASH, "open"); + string = ReadTransactions(currentaccount, file); + } else if (string.FindFirst("!Type:CCard") != B_ERROR) { accountindex++; accountname = "Credit Card Account "; accountname << accountindex; - - currentaccount = gDatabase.AddAccount(accountname.String(),ACCOUNT_CREDIT,"open"); - string = ReadTransactions(currentaccount,file); - } -/* else - if(string=="!Account") - { - if(accountlist.CountItems()<1) - string = ReadAccounts(accountlist,file); - else - { - string = ReadTransactions(accountlist.ItemAt(accountindex),file); - accountindex++; - } + currentaccount = gDatabase.AddAccount(accountname.String(), ACCOUNT_CREDIT, "open"); + string = ReadTransactions(currentaccount, file); } - else - if(string=="!Type:Memorized") - { - printf("DEBUG: importing Memorized transactions unimplemented\n"); - string = file.ReadLine(); - } -*/ else - { -// STRACE(("Line %s\n",string.String())); + /* else + if(string=="!Account") + { + if(accountlist.CountItems()<1) + string = ReadAccounts(accountlist,file); + else + { + string = ReadTransactions(accountlist.ItemAt(accountindex),file); + accountindex++; + } + + } + else + if(string=="!Type:Memorized") + { + printf("DEBUG: importing Memorized transactions unimplemented\n"); + string = file.ReadLine(); + } + */ + else { + // STRACE(("Line %s\n",string.String())); string = file.ReadLine(); } } - + return true; } -BString ReadCategories(BObjectList &list, TextFile &file) -{ +BString +ReadCategories(BObjectList &list, TextFile &file) { STRACE(("Importing category list\n")); BString catdata = file.ReadLine(); catdata.RemoveAll("\r"); - + Category *cat = new Category(); - while(catdata.ByteAt(0)!='!' && !file.IsEOF() ) - { -/* switch(catdata.ByteAt(0)) - { - case 'N': - { - // Name - cat->SetNameAt(0,catdata.String()+1); - break; - } - case 'B': - { - // Budget amounts are listed in the file in order - // and for any category which is used for budgeting - - // TODO: Implement Budget amounts in QIF import - break; - } - case '^': - { - list.AddItem(cat); - cat = new Category(); - break; - } - case '!': - { - STRACE(("Added %ld categories\n",list.CountItems())); - delete cat; - return catdata; - break; - } - default: - break; - } -*/ catdata = file.ReadLine(); + while (catdata.ByteAt(0) != '!' && !file.IsEOF()) { + /* switch(catdata.ByteAt(0)) + { + case 'N': + { + // Name + cat->SetNameAt(0,catdata.String()+1); + break; + } + case 'B': + { + // Budget amounts are listed in the file in order + // and for any category which is used for budgeting + + // TODO: Implement Budget amounts in QIF import + break; + } + case '^': + { + list.AddItem(cat); + cat = new Category(); + break; + } + case '!': + { + STRACE(("Added %ld categories\n",list.CountItems())); + delete cat; + return catdata; + break; + } + default: + break; + } + */ + catdata = file.ReadLine(); catdata.RemoveAll("\r"); } delete cat; - - STRACE(("Added %ld categories\n",list.CountItems())); + + STRACE(("Added %ld categories\n", list.CountItems())); return catdata; } -BString ReadAccounts(BObjectList &list, TextFile &file) -{ +BString +ReadAccounts(BObjectList &list, TextFile &file) { STRACE(("Importing accounts\n")); BString accdata = file.ReadLine(); - - BString accname=""; - - while(accdata.ByteAt(0)!='!' && !file.IsEOF()) - { + + BString accname = ""; + + while (accdata.ByteAt(0) != '!' && !file.IsEOF()) { accdata.RemoveAll("\r"); - switch(accdata.ByteAt(0)) - { - case 'N': - { - accname = accdata.String()+1; - break; - } - case '^': - { - if(accname.CountChars()<1) - break; - - Account *acc = gDatabase.AddAccount(accname.String(),ACCOUNT_BANK); - list.AddItem(acc); - accname = ""; - break; - } - default: + switch (accdata.ByteAt(0)) { + case 'N': { + accname = accdata.String() + 1; + break; + } + case '^': { + if (accname.CountChars() < 1) break; + + Account *acc = gDatabase.AddAccount(accname.String(), ACCOUNT_BANK); + list.AddItem(acc); + accname = ""; + break; + } + default: + break; } - + accdata = file.ReadLine(); } return accdata; } -BString ReadTransactions(Account *account, TextFile &file) -{ +BString +ReadTransactions(Account *account, TextFile &file) { gDatabase.SetNotify(false); - gDatabase.DBCommand("BEGIN EXCLUSIVE","Import:Turn off autocommit"); - STRACE(("Importing bank transactions to %s\n",account?account->Name():"")); - + gDatabase.DBCommand("BEGIN EXCLUSIVE", "Import:Turn off autocommit"); + STRACE(("Importing bank transactions to %s\n", account ? account->Name() : "")); + time_t date; TransactionData data; data.SetAccount(account); - + BString transdata = file.ReadLine(); - + bool splitmode = false; - while(transdata.ByteAt(0)!='!' && !file.IsEOF()) - { + while (transdata.ByteAt(0) != '!' && !file.IsEOF()) { transdata.RemoveAll("\r"); - - switch(transdata.ByteAt(0)) - { - case 'D': - { - // Date. Note that there are two formats. - // The antequated format is immediately compatible with - // StringToDate - MM/DD/YY. The other is downright - // funky: MM/DD/' F . F is an offset from the year 2000, - // so a line reading D1/23' 5 is 1/23/2005. - transdata.ReplaceFirst("' ","/200"); - if(gDefaultLocale.StringToDate(transdata.String()+1,date)==B_OK) - data.SetDate(date); - break; - - } - case 'C': - { - // apparently a check can be cleared or not - no reconciliation - // done :/ - data.SetStatus(TRANS_RECONCILED); - break; - } - case 'M': - { - data.SetMemo(transdata.String()+1); - break; + + switch (transdata.ByteAt(0)) { + case 'D': { + // Date. Note that there are two formats. + // The antequated format is immediately compatible with + // StringToDate - MM/DD/YY. The other is downright + // funky: MM/DD/' F . F is an offset from the year 2000, + // so a line reading D1/23' 5 is 1/23/2005. + transdata.ReplaceFirst("' ", "/200"); + if (gDefaultLocale.StringToDate(transdata.String() + 1, date) == B_OK) + data.SetDate(date); + break; + } + case 'C': { + // apparently a check can be cleared or not - no reconciliation + // done :/ + data.SetStatus(TRANS_RECONCILED); + break; + } + case 'M': { + data.SetMemo(transdata.String() + 1); + break; + } + case 'N': { + data.SetType(transdata.String() + 1); + break; + } + case 'P': { + // Payee + data.SetPayee(transdata.String() + 1); + break; + } + case 'S': { + if (splitmode == false) { + data.SetCategory(""); + splitmode = true; } - case 'N': - { - data.SetType(transdata.String()+1); - break; + + BString splitamount = file.ReadLine(); + BString splitmemo; + if (splitamount.ByteAt(0) == 'E') { + splitmemo = splitamount.String() + 1; + splitmemo.RemoveAll("\r"); + + splitamount = file.ReadLine(); + splitamount.RemoveAll("\r"); } - case 'P': - { - // Payee - data.SetPayee(transdata.String()+1); + + if (splitamount.ByteAt(0) != '$') break; - } - case 'S': - { - if(splitmode == false) - { - data.SetCategory(""); - splitmode = true; - } - - BString splitamount = file.ReadLine(); - BString splitmemo; - if(splitamount.ByteAt(0)=='E') - { - splitmemo = splitamount.String()+1; - splitmemo.RemoveAll("\r"); - - splitamount = file.ReadLine(); - splitamount.RemoveAll("\r"); - } - - if(splitamount.ByteAt(0)!='$') - break; - Fixed splitfixed; - if(gCurrentLocale.StringToCurrency(splitamount.String()+1,splitfixed)!=B_OK) - break; - - data.AddCategory(transdata.String()+1,splitfixed,false); - if(splitmemo.CountChars()>0) - data.SetMemoAt(data.CountCategories()-1,splitmemo.String()); - + Fixed splitfixed; + if (gCurrentLocale.StringToCurrency(splitamount.String() + 1, splitfixed) != B_OK) break; + + data.AddCategory(transdata.String() + 1, splitfixed, false); + if (splitmemo.CountChars() > 0) + data.SetMemoAt(data.CountCategories() - 1, splitmemo.String()); + + break; + } + case 'U': + case 'T': { + Fixed amount; + if (gCurrentLocale.StringToCurrency(transdata.String() + 1, amount) == B_OK) + data.SetAmount(amount); + + if (amount.IsPositive()) + data.SetType("DEP"); + else { + if (data.Type().TypeCode() == TRANS_INIT) + data.SetType("ATM"); } - case 'U': - case 'T': - { - Fixed amount; - if(gCurrentLocale.StringToCurrency(transdata.String()+1,amount)==B_OK) - data.SetAmount(amount); - - if(amount.IsPositive()) - data.SetType("DEP"); + break; + } + case 'L': { + // Category + data.SetCategory(transdata.String() + 1); + break; + } + case '^': { + if (strlen(data.Payee()) < 1) { + // There shouldn't be a transaction without a payee. Apparently, though, + // things aren't so pretty, necessarily. We will handle this with + // two conditions - skip the thing entirely if the amount is 0 + // and use [No Payee Entered] otherwise + if (data.Amount().AsLong() == 0) + break; else - { - if(data.Type().TypeCode()==TRANS_INIT) - data.SetType("ATM"); - } - break; - } - case 'L': - { - // Category - data.SetCategory(transdata.String()+1); - break; - } - case '^': - { - if(strlen(data.Payee())<1) - { - // There shouldn't be a transaction without a payee. Apparently, though, - // things aren't so pretty, necessarily. We will handle this with - // two conditions - skip the thing entirely if the amount is 0 - // and use [No Payee Entered] otherwise - if(data.Amount().AsLong()==0) - break; - else - data.SetPayee("[No Payee Entered]"); - } - - if(data.CountCategories()<1) - data.SetCategory("Uncategorized"); - - - gDatabase.AddTransaction(data); - STRACE(("Added transaction %s\n",data.Payee())); - data.MakeEmpty(); - data.SetAccount(account); - splitmode=false; - break; + data.SetPayee("[No Payee Entered]"); } - default: - break; + + if (data.CountCategories() < 1) + data.SetCategory("Uncategorized"); + + + gDatabase.AddTransaction(data); + STRACE(("Added transaction %s\n", data.Payee())); + data.MakeEmpty(); + data.SetAccount(account); + splitmode = false; + break; + } + default: + break; } transdata = file.ReadLine(); } gDatabase.SetNotify(true); - gDatabase.DBCommand("COMMIT","turn on autocommit"); + gDatabase.DBCommand("COMMIT", "turn on autocommit"); return transdata; } -bool ExportQIF(const entry_ref &ref) -{ - BFile file(&ref,B_CREATE_FILE | B_READ_WRITE | B_FAIL_IF_EXISTS); - if(file.InitCheck()!=B_OK) +bool +ExportQIF(const entry_ref &ref) { + BFile file(&ref, B_CREATE_FILE | B_READ_WRITE | B_FAIL_IF_EXISTS); + if (file.InitCheck() != B_OK) return false; - + BString text; CppSQLite3Query query; BString command; - + // Export categories and budget - DStringList incomelist,expenselist; - query = gDatabase.DBQuery("select * from categorylist order by name", - "ExportQIF:get category list"); - while(!query.eof()) - { - if(query.getIntField(1) == 1) + DStringList incomelist, expenselist; + query = gDatabase.DBQuery( + "select * from categorylist order by name", "ExportQIF:get category list" + ); + while (!query.eof()) { + if (query.getIntField(1) == 1) incomelist.AddItem(query.getStringField(0)); else expenselist.AddItem(query.getStringField(0)); query.nextRow(); } query.finalize(); - - if(incomelist.CountItems()>0 || expenselist.CountItems()>0) + + if (incomelist.CountItems() > 0 || expenselist.CountItems() > 0) text << "!Type:Cat\n"; - - text << MakeCategoryString(incomelist,false); - text << MakeCategoryString(expenselist,true); - - if(text.CountChars()>0) - file.Write(text.String(),text.CountChars()); + + text << MakeCategoryString(incomelist, false); + text << MakeCategoryString(expenselist, true); + + if (text.CountChars() > 0) + file.Write(text.String(), text.CountChars()); text = ""; - + // Export account list text << "!Account\n"; - for(int32 i=0; iName() << "\nBank\n^\n"; } - - file.Write(text.String(),text.CountChars()); + + file.Write(text.String(), text.CountChars()); text = ""; - + // Export accounts text << "!Account\n"; - for(int32 i=0; iName() << "\nTBank\n^\n!Type:Bank\n"; - + command = "select * from account_"; command << account->GetID() << " order by date;"; query = gDatabase.DBQuery(command.String(), "ExportQIF:get transactions from accounts"); - - while(!query.eof()) - { + + while (!query.eof()) { time_t date = query.getInt64Field(2); text << "D" << DateToQIFDate(date) << "\n"; - + int32 amount = query.getInt64Field(5); - Fixed fixed(amount,true); + Fixed fixed(amount, true); BString temp; - gDefaultLocale.CurrencyToString(fixed,temp); + gDefaultLocale.CurrencyToString(fixed, temp); temp.RemoveFirst(gDefaultLocale.CurrencySymbol()); text << "U" << temp << "\nT" << temp << "\n"; - + text << "N" << DeescapeIllegalCharacters(query.getStringField(3)) << "\n"; text << "P" << DeescapeIllegalCharacters(query.getStringField(4)) << "\n"; - + temp = DeescapeIllegalCharacters(query.getStringField(7)); - if(temp.CountChars()>0) + if (temp.CountChars() > 0) text << "M" << temp << "\n"; - + text << "L" << DeescapeIllegalCharacters(query.getStringField(6)) << "\n^\n"; query.nextRow(); } - - file.Write(text.String(),text.CountChars()); + + file.Write(text.String(), text.CountChars()); text = ""; } query.finalize(); - + // TODO: Export memorized transactions - + return true; } -BString DateToQIFDate(const time_t &date) -{ +BString +DateToQIFDate(const time_t &date) { struct tm *timestruct; - + timestruct = localtime(&date); - + BString qifdate; - if(timestruct) - { - if(timestruct->tm_year < 100) - { - qifdate << (timestruct->tm_mon + 1) << "/" << timestruct->tm_mday - << "/" << timestruct->tm_year; - } - else - { + if (timestruct) { + if (timestruct->tm_year < 100) { + qifdate << (timestruct->tm_mon + 1) << "/" << timestruct->tm_mday << "/" + << timestruct->tm_year; + } else { qifdate << (timestruct->tm_mon + 1) << "/"; - - if(timestruct->tm_mday < 10) + + if (timestruct->tm_mday < 10) qifdate += " "; qifdate << timestruct->tm_mday << "'"; - - if( (timestruct->tm_year - 100) < 10) + + if ((timestruct->tm_year - 100) < 10) qifdate += " "; qifdate << (timestruct->tm_year - 100); } } - + return qifdate; } -BString MakeCategoryString(const DStringList &list, const bool &isexpense) -{ +BString +MakeCategoryString(const DStringList &list, const bool &isexpense) { BString text; CppSQLite3Query query; - - for(int32 i=0; iString())); - text << "N" << unescaped << "\nD" << unescaped << "\n" << (isexpense?"E":"I") << "\n"; - + text << "N" << unescaped << "\nD" << unescaped << "\n" << (isexpense ? "E" : "I") << "\n"; + // See if the category is in the budget and, if so, write it to disk if nonzero BudgetEntry entry; - if(gDatabase.GetBudgetEntry(unescaped.String(),entry)) - { + if (gDatabase.GetBudgetEntry(unescaped.String(), entry)) { Fixed f = entry.amount; - + bool error = false; - switch(entry.period) - { - case BUDGET_WEEKLY: - { - f *= 52; - f /= 12; - break; - } - case BUDGET_MONTHLY: - { - break; - } - case BUDGET_QUARTERLY: - { - f /= 3; - break; - } - case BUDGET_ANNUALLY: - { - f /= 12; - break; - } - default: - { - error = true; - break; - } + switch (entry.period) { + case BUDGET_WEEKLY: { + f *= 52; + f /= 12; + break; + } + case BUDGET_MONTHLY: { + break; + } + case BUDGET_QUARTERLY: { + f /= 3; + break; + } + case BUDGET_ANNUALLY: { + f /= 12; + break; + } + default: { + error = true; + break; + } } - + BString temp; - gDefaultLocale.CurrencyToString(f,temp); + gDefaultLocale.CurrencyToString(f, temp); temp.RemoveFirst(gDefaultLocale.CurrencySymbol()); temp.Prepend("B"); temp += "\n"; - - for(int32 i=0; i<12; i++) + + for (int32 i = 0; i < 12; i++) text += temp; } - + text << "^\n"; } - + return text; } diff --git a/src/Import.h b/src/Import.h index 458ae4c..036a72f 100644 --- a/src/Import.h +++ b/src/Import.h @@ -3,7 +3,9 @@ #include -bool ImportQIF(const entry_ref &ref); -bool ExportQIF(const entry_ref &ref); +bool +ImportQIF(const entry_ref &ref); +bool +ExportQIF(const entry_ref &ref); #endif diff --git a/src/Language.cpp b/src/Language.cpp index 334fbc6..3e91f87 100644 --- a/src/Language.cpp +++ b/src/Language.cpp @@ -1,10 +1,10 @@ -#include -#include -#include -#include -#include "TextFile.h" #include "Language.h" #include "BuildOptions.h" +#include "TextFile.h" +#include +#include +#include +#include /* This class is probably the complete wrong way to go about adding @@ -12,146 +12,116 @@ to be rewritten or replaced later. */ -Language::Language(const entry_ref &ref) - : fInit(false), - fName(ref.name), - fFileRef(ref) -{ -} +Language::Language(const entry_ref &ref) : fInit(false), fName(ref.name), fFileRef(ref) {} -Language::Language(void) - : fInit(false) -{ -} +Language::Language(void) : fInit(false) {} -Language::~Language(void) -{ -} +Language::~Language(void) {} -void Language::Initialize(void) -{ +void +Language::Initialize(void) { // Here we load the dictionary file for the app - - fInit=true; - - if(fName.CountChars()<1) - { - fName="English"; + + fInit = true; + + if (fName.CountChars() < 1) { + fName = "English"; return; } - + // Read in the dictionary file into a BString - TextFile file(fFileRef,B_READ_ONLY); - + TextFile file(fFileRef, B_READ_ONLY); + // At this point, we'll read in all the data about the translation - + // Now read in the translation strings - bool nextline=false; - - while(1) - { - BString line=file.ReadLine(),key="",value=""; - - if(line.CountChars()==0) + bool nextline = false; + + while (1) { + BString line = file.ReadLine(), key = "", value = ""; + + if (line.CountChars() == 0) break; - - int32 i=0; - - for(i=0;i0) + + BString str = fEntryList[instring]; + if (str.CountChars() > 0) return str; - + return BString(instring); } - LanguageLogger::LanguageLogger(const entry_ref &ref) - : Language(ref), - fFile(&ref,B_CREATE_FILE | B_ERASE_FILE | B_READ_WRITE) + : Language(ref), fFile(&ref, B_CREATE_FILE | B_ERASE_FILE | B_READ_WRITE) { SetInitialized(true); } -LanguageLogger::~LanguageLogger(void) -{ - fFile.Unset(); -} +LanguageLogger::~LanguageLogger(void) { fFile.Unset(); } -void LanguageLogger::Initialize(void) -{ -} +void +LanguageLogger::Initialize(void) {} -BString LanguageLogger::Translate(const char *instring) -{ - if(!instring) +BString +LanguageLogger::Translate(const char *instring) { + if (!instring) return BString(); - - if(fLogList[instring].CountChars()==0) - { + + if (fLogList[instring].CountChars() == 0) { BString outstring(instring); outstring << "\t" << BString(instring).ToUpper() << "\n"; - - fFile.Write(outstring.String(),outstring.Length()); - - fLogList[instring]=instring; + + fFile.Write(outstring.String(), outstring.Length()); + + fLogList[instring] = instring; } - + return BString(instring); } diff --git a/src/Language.h b/src/Language.h index 31ab76c..5ffecdd 100644 --- a/src/Language.h +++ b/src/Language.h @@ -1,34 +1,34 @@ #ifndef LANGUAGE_H #define LANGUAGE_H -#include -#include -#include +#include "BuildOptions.h" #include #include -#include "BuildOptions.h" +#include +#include +#include -typedef std::map LanguageEntryList; +typedef std::map LanguageEntryList; -class Language -{ -public: +class Language { + public: Language(const entry_ref &ref); Language(void); - + virtual ~Language(void); - + virtual void Initialize(void); + bool IsInitialized(void) const { return fInit; } - + const char *Name(void) { return fName.String(); } - + virtual BString Translate(const char *instring); -protected: + protected: void SetInitialized(bool value) { fInit = value; } - -private: + + private: LanguageEntryList fEntryList; bool fInit; BString fName; @@ -36,14 +36,13 @@ class Language }; // Debugging class used to generate language files quickly -class LanguageLogger : public Language -{ -public: +class LanguageLogger : public Language { + public: LanguageLogger(const entry_ref &ref); ~LanguageLogger(void); void Initialize(void); BString Translate(const char *instring); - + LanguageEntryList fLogList; BFile fFile; }; diff --git a/src/LanguageRoster.cpp b/src/LanguageRoster.cpp index 8ca80b2..569c7f6 100644 --- a/src/LanguageRoster.cpp +++ b/src/LanguageRoster.cpp @@ -1,94 +1,85 @@ #include "LanguageRoster.h" #include #include -//#include "Preferences.h" +// #include "Preferences.h" #include "BuildOptions.h" -//#define BUILD_LOGFILE +// #define BUILD_LOGFILE -LanguageRoster *language_roster=NULL; +LanguageRoster *language_roster = NULL; LanguageRoster::LanguageRoster(const char *path) - : fLanguagePath(path), - fCurrentLanguage(NULL), - fDefaultLanguage(NULL) -{ + : fLanguagePath(path), fCurrentLanguage(NULL), fDefaultLanguage(NULL) { BDirectory dir(fLanguagePath.String()); - - if(dir.InitCheck()!=B_OK) - create_directory(fLanguagePath.String(),0777); - + + if (dir.InitCheck() != B_OK) + create_directory(fLanguagePath.String(), 0777); + entry_ref ref; - #ifdef BUILD_LOGFILE +#ifdef BUILD_LOGFILE BEntry entry("LoggedTranslationFile"); entry.GetRef(&ref); fCurrentLanguage = fDefaultLanguage = new LanguageLogger(ref); - #else +#else fCurrentLanguage = fDefaultLanguage = new Language(); - #endif - +#endif + fCurrentLanguage->Initialize(); fLanguageList.AddItem(fDefaultLanguage); - while(dir.GetNextRef(&ref)==B_OK) - { - Language *loc=new Language(ref); + while (dir.GetNextRef(&ref) == B_OK) { + Language *loc = new Language(ref); fLanguageList.AddItem(loc); } } -LanguageRoster::~LanguageRoster(void) -{ - for(int32 i=0; iIsInitialized()) +void +LanguageRoster::SetLanguage(Language *language) { + if (language) { + if (!language->IsInitialized()) language->Initialize(); - + fCurrentLanguage = language; - + return; } - + fCurrentLanguage = fDefaultLanguage; } -bool LanguageRoster::SetLanguage(const char *name) -{ - if(!name) +bool +LanguageRoster::SetLanguage(const char *name) { + if (!name) return false; - - for(int32 i=0; iName(),name)==0) - { + + for (int32 i = 0; i < fLanguageList.CountItems(); i++) { + Language *language = (Language *)fLanguageList.ItemAt(i); + if (language && strcmp(language->Name(), name) == 0) { SetLanguage(language); return true; } diff --git a/src/LanguageRoster.h b/src/LanguageRoster.h index a376cb7..d0aeeba 100644 --- a/src/LanguageRoster.h +++ b/src/LanguageRoster.h @@ -1,24 +1,24 @@ #ifndef LANGUAGE_ROSTER_H #define LANGUAGE_ROSTER_H -#include #include "Language.h" +#include -class LanguageRoster -{ -public: +class LanguageRoster { + public: LanguageRoster(const char *path); ~LanguageRoster(void); - + int32 CountLanguages(void) const; Language *LanguageAt(const int32 &index); - + void SetLanguage(const int32 &index); void SetLanguage(Language *language); bool SetLanguage(const char *name); + Language *GetLanguage(void) { return fCurrentLanguage; } -private: + private: BString fLanguagePath; BList fLanguageList; Language *fCurrentLanguage; diff --git a/src/Locale.cpp b/src/Locale.cpp index 8ed09bc..f727369 100644 --- a/src/Locale.cpp +++ b/src/Locale.cpp @@ -1,825 +1,726 @@ +#include "App.h" #include "CBLocale.h" -#include #include -#include -#include #include #include -#include #include -#include -#include +#include +#include +#include #include -#include "App.h" +#include +#include +#include -Locale::Locale(void) -{ - SetDefaults(); -} +Locale::Locale(void) { SetDefaults(); } -Locale::~Locale(void) -{ -} +Locale::~Locale(void) {} -bool Locale::operator!=(const Locale &other) const -{ - return !(*this==other); +bool +Locale::operator!=(const Locale &other) const { + return !(*this == other); } -bool Locale::operator==(const Locale &other) const -{ - if( fDateFormat != other.fDateFormat || - fCurrencySymbol != other.fCurrencySymbol || - fPrefixSymbol != other.fPrefixSymbol || - fCurrencySeparator != other.fCurrencySeparator || - fCurrencyDecimal != other.fCurrencyDecimal || - fDateSeparator != other.fDateSeparator || - fCurrencyDecimalPlace != fCurrencyDecimalPlace || - fUseDST != other.fUseDST ) +bool +Locale::operator==(const Locale &other) const { + if (fDateFormat != other.fDateFormat || fCurrencySymbol != other.fCurrencySymbol || + fPrefixSymbol != other.fPrefixSymbol || fCurrencySeparator != other.fCurrencySeparator || + fCurrencyDecimal != other.fCurrencyDecimal || fDateSeparator != other.fDateSeparator || + fCurrencyDecimalPlace != fCurrencyDecimalPlace || fUseDST != other.fUseDST) return false; return true; } -void Locale::Flatten(BFile *file) -{ +void +Locale::Flatten(BFile *file) { BString str("\t\n"); - - if(fDateFormat == DATE_MDY) + + if (fDateFormat == DATE_MDY) str << "\t\t\n"; else str << "\t\t\n"; - + str << "\t\t\n"; str << "\t\t\n"; str << "\t\t\n"; str << "\t\t\n"; - - if(!fPrefixSymbol) + + if (!fPrefixSymbol) str << "\t\t\n"; - if(fUseDST) + if (fUseDST) str << "\t\t\n"; str << "\t\n"; - - file->Write(str.String(),str.Length()); + + file->Write(str.String(), str.Length()); } -status_t Locale::CurrencyToString(const Fixed &amount, BString &string) -{ +status_t +Locale::CurrencyToString(const Fixed &amount, BString &string) { string = ""; - + BString dollars; - dollars << ( amount.IsPositive() ? amount.AsLong() : -amount.AsLong() ); - + dollars << (amount.IsPositive() ? amount.AsLong() : -amount.AsLong()); + char cents[20]; BString formatstring("%."); - formatstring << (int) fCurrencyDecimalPlace << "f"; - sprintf(cents,formatstring.String(),amount.DecimalPart()); - - string = cents + ( (amount.IsNegative() && amount.DecimalPart() != 0) ? 2 : 1 ); - if(fCurrencyDecimal!=".") - string.ReplaceSet(".",fCurrencyDecimal.String()); - - for(int32 i=dollars.CountChars()-3; i>0; i-=3) - dollars.Insert(fCurrencySeparator,i); - + formatstring << (int)fCurrencyDecimalPlace << "f"; + sprintf(cents, formatstring.String(), amount.DecimalPart()); + + string = cents + ((amount.IsNegative() && amount.DecimalPart() != 0) ? 2 : 1); + if (fCurrencyDecimal != ".") + string.ReplaceSet(".", fCurrencyDecimal.String()); + + for (int32 i = dollars.CountChars() - 3; i > 0; i -= 3) + dollars.Insert(fCurrencySeparator, i); + string.Prepend(dollars); - if(fPrefixSymbol) + if (fPrefixSymbol) string.Prepend(fCurrencySymbol); else string.Append(fCurrencySymbol); - - if(amount<0) + + if (amount < 0) string.Prepend("-"); - + return B_OK; } -status_t Locale::StringToCurrency(const char *string, Fixed &amount) -{ +status_t +Locale::StringToCurrency(const char *string, Fixed &amount) { // This is going to be a royal pain. We have to deal with separators (or lack // thereof) and the mere possibility of a cents separator. Yuck. - - if(!string) + + if (!string) return B_ERROR; - - BString dollars(string),cents; - + + BString dollars(string), cents; + dollars.RemoveAll(fCurrencySymbol); dollars.RemoveAll(fCurrencySeparator); - + int32 index = dollars.FindFirst(fCurrencyDecimal); - if(index < 0) - { + if (index < 0) { // We're working with whole dollars here. :) cents = "00"; - } - else - { + } else { cents = dollars.String() + index + 1; dollars.Truncate(index); - if(dollars=="-0") + if (dollars == "-0") cents.Prepend("-"); } - + amount = atol(dollars.String()); float temp = atol(cents.String()); - if(amount<0) + if (amount < 0) temp = -temp; - + amount.AddPremultiplied(temp); return B_OK; } -status_t Locale::PremultipliedStringToCurrency(const char *string, Fixed &amount) -{ +status_t +Locale::PremultipliedStringToCurrency(const char *string, Fixed &amount) { // This function is an optimized version of StringToCurrency which expects // the input string to represent the premultiplied version of a Fixed value. // As a result, everything which is not a number is stripped out, converted // to a number and added to the amount parameter - if(!string) + if (!string) return B_ERROR; - + // TODO: See if using the string set version of RemoveAll would be faster - + BString valuestr(string); valuestr.RemoveAll(fCurrencySymbol); valuestr.RemoveAll(fCurrencySeparator); valuestr.RemoveAll(fCurrencyDecimal); - + int32 value = atoi(valuestr.String()); amount.SetPremultiplied(value); return B_OK; } -status_t Locale::DateToString(time_t date, BString &string) -{ +status_t +Locale::DateToString(time_t date, BString &string) { char buffer[10]; - struct tm* timestruct = localtime(&date); + struct tm *timestruct = localtime(&date); BString datestr; - - if(fDateFormat == DATE_MDY) + + if (fDateFormat == DATE_MDY) strftime(buffer, 10, "%m", timestruct); - else - if(fDateFormat == DATE_DMY) + else if (fDateFormat == DATE_DMY) strftime(buffer, 10, "%d", timestruct); - + datestr += buffer; datestr += fDateSeparator; - if(fDateFormat == DATE_MDY) + if (fDateFormat == DATE_MDY) strftime(buffer, 10, "%d", timestruct); - else - if(fDateFormat == DATE_DMY) + else if (fDateFormat == DATE_DMY) strftime(buffer, 10, "%m", timestruct); - + datestr += buffer; datestr += fDateSeparator; strftime(buffer, 10, "%Y", timestruct); datestr += buffer; string = datestr; - + return B_OK; } -status_t Locale::ConstructDateStringDMY(const char *in, BString &out) -{ +status_t +Locale::ConstructDateStringDMY(const char *in, BString &out) { // This constructs a proper date string given a list of numbers - if(!in) + if (!in) return B_ERROR; - + int32 length = strlen(in); - int num=0, num2=0; + int num = 0, num2 = 0; char charstring[3]; charstring[1] = '\0'; charstring[2] = '\0'; - - switch(length) + + switch (length) { + case 2: // DM { - case 2: // DM - { - out = in; - out.Insert(fDateSeparator,1); - break; - } - case 3: - case 5: - case 7: - { - // DDM - 0: 0-3, 1: 0-9 (0-1 if digit 0 == 3), 2: 1-9 - // DMM - 0: 1-9, 1: 0-1, 2: 0-9 (0-2 if digit 1 == 1) - // DDMYYYY - see above + year - // DMMYYYY - see above + year - bool ddm=false; - charstring[0] = in[0]; - num = atoi(charstring); - - if(num > 3) - ddm = false; - else - if(num < 1) - ddm = true; - else - { - // [1-3]xx. - charstring[0] = in[1]; - num2 = atoi(charstring); - - if(num == 3) - { - if(num2>1) - ddm = false; - else - ddm = true; - } + out = in; + out.Insert(fDateSeparator, 1); + break; + } + case 3: + case 5: + case 7: { + // DDM - 0: 0-3, 1: 0-9 (0-1 if digit 0 == 3), 2: 1-9 + // DMM - 0: 1-9, 1: 0-1, 2: 0-9 (0-2 if digit 1 == 1) + // DDMYYYY - see above + year + // DMMYYYY - see above + year + bool ddm = false; + charstring[0] = in[0]; + num = atoi(charstring); + + if (num > 3) + ddm = false; + else if (num < 1) + ddm = true; + else { + // [1-3]xx. + charstring[0] = in[1]; + num2 = atoi(charstring); + + if (num == 3) { + if (num2 > 1) + ddm = false; else - if(num2 > 1) ddm = true; - else - if(num2 == 0) - { - // Although we can't say for sure, it's unlikely that the user entered a leading zero for - // the month. + } else if (num2 > 1) + ddm = true; + else if (num2 == 0) { + // Although we can't say for sure, it's unlikely that the user entered a leading + // zero for the month. + ddm = true; + } else { + // [1-2][0-1]x. + charstring[0] = in[2]; + num = atoi(charstring); + + if (num == 0) + ddm = false; + else if (num > 2) + ddm = true; + else { + // Getting this far means that [1-2]1[1-2] or stuff like 1/12, 2/12, 11/2, or + // 21/2 As a result, we will choose the earlier result - ddm. ddm = true; - } - else - { - // [1-2][0-1]x. - charstring[0] = in[2]; - num = atoi(charstring); - - if(num == 0) - ddm = false; - else - if(num>2) - ddm = true; - else - { - // Getting this far means that [1-2]1[1-2] or stuff like 1/12, 2/12, 11/2, or 21/2 - // As a result, we will choose the earlier result - ddm. - ddm = true; - } } } - - out = in; - if(ddm) - out.Insert(fDateSeparator,2); - else - out.Insert(fDateSeparator,1); - break; } - case 4: - { - // DDMM - 0: 0-3, 1: 0-9 (0-1, if digit 0 is 3), 2: 0-1, 3: 0-9 - // DMYY - 0: 1-9, 1: 1-9, 2-3: 0-9 - bool ddmm=false; - charstring[0] = in[0]; - num = atoi(charstring); - - if(num > 3) - ddmm = false; - else - if(num == 0) - ddmm = true; - else - { - charstring[0] = in[1]; - num2 = atoi(charstring); - - if(num == 3) - { - if(num2 > 1) - ddmm = false; - else - ddmm = true; - } + + out = in; + if (ddm) + out.Insert(fDateSeparator, 2); + else + out.Insert(fDateSeparator, 1); + break; + } + case 4: { + // DDMM - 0: 0-3, 1: 0-9 (0-1, if digit 0 is 3), 2: 0-1, 3: 0-9 + // DMYY - 0: 1-9, 1: 1-9, 2-3: 0-9 + bool ddmm = false; + charstring[0] = in[0]; + num = atoi(charstring); + + if (num > 3) + ddmm = false; + else if (num == 0) + ddmm = true; + else { + charstring[0] = in[1]; + num2 = atoi(charstring); + + if (num == 3) { + if (num2 > 1) + ddmm = false; else - if(num2 == 0) ddmm = true; + } else if (num2 == 0) + ddmm = true; + else { + // [1-2][1-2]xx + charstring[0] = in[2]; + num = atoi(charstring); + + // at this point, it's tough to figure which, but it's more likely that + // if digit 2 is 0 or 9, it's a year and DDMM otherwise + if (num == 0 || num == 9) + ddmm = false; else - { - // [1-2][1-2]xx - charstring[0] = in[2]; - num = atoi(charstring); - - // at this point, it's tough to figure which, but it's more likely that - // if digit 2 is 0 or 9, it's a year and DDMM otherwise - if(num == 0 || num == 9) - ddmm = false; - else - ddmm = true; - } - } - - out = in; - if(ddmm) - out.Insert(fDateSeparator,2); - else - { - out.Insert(fDateSeparator,1); - out.Insert(fDateSeparator,2); + ddmm = true; } - - break; } - case 6: - { - // DDMMYY - 0: 0-3, 1: 0-9 (0-1 if digit 0 == 3), 2: 0-1, 3: 0-9 (0-2 if digit 2 == 1), - // 4-5: 0-9 - // DMYYYY - 0: 1-9, 1: 1-9, 2-5: 0-9 - bool ddmm = false; - charstring[0] = in[0]; - num = atoi(charstring); - - if(num == 0) - ddmm = false; - else - { - charstring[0] = in[1]; - num2 = atoi(charstring); - - if(num == 3) - { - if(num2 > 1) + + out = in; + if (ddmm) + out.Insert(fDateSeparator, 2); + else { + out.Insert(fDateSeparator, 1); + out.Insert(fDateSeparator, 2); + } + + break; + } + case 6: { + // DDMMYY - 0: 0-3, 1: 0-9 (0-1 if digit 0 == 3), 2: 0-1, 3: 0-9 (0-2 if digit 2 == 1), + // 4-5: 0-9 + // DMYYYY - 0: 1-9, 1: 1-9, 2-5: 0-9 + bool ddmm = false; + charstring[0] = in[0]; + num = atoi(charstring); + + if (num == 0) + ddmm = false; + else { + charstring[0] = in[1]; + num2 = atoi(charstring); + + if (num == 3) { + if (num2 > 1) + ddmm = false; + else if (num2 == 0) + ddmm = true; + else { + // We're in one of those "can't really tell" places, but we can + // guess based on the the next two numbers. If they are '19' or '20', + // we'll go with dmyyyy. + if ((in[2] == '1' && in[3] == '9') || (in[2] == '2' && in[3] == '0')) { ddmm = false; - else - if(num2 == 0) + } else ddmm = true; - else - { - // We're in one of those "can't really tell" places, but we can - // guess based on the the next two numbers. If they are '19' or '20', - // we'll go with dmyyyy. - if( (in[2]=='1' && in[3]=='9') || - (in[2]=='2' && in[3]=='0') ) - { + } + } else { + // Getting this far, we know that [1-9][1-9]xxxx + charstring[0] = in[2]; + num = atoi(charstring); + if (num > 1) + ddmm = false; + else { + charstring[0] = in[3]; + num2 = atoi(charstring); + + if (num == 1) { + if (num2 > 2) ddmm = false; - } else ddmm = true; - } - } - else - { - // Getting this far, we know that [1-9][1-9]xxxx - charstring[0] = in[2]; - num = atoi(charstring); - if(num > 1) - ddmm = false; - else - { - charstring[0] = in[3]; - num2 = atoi(charstring); - - if(num == 1) - { - if(num2 > 2) - ddmm = false; - else - ddmm = true; - } + } else { + // At this point, we have [1-9][1-9]0xxx. We'll check to see if + // digit 3 is 0, but if it happens to be nonzero, it's a little + // hard to definitively know which the user meant. Of course, it + // is probably ddmmyy format. + if (num2 == 0) + ddmm = false; else - { - // At this point, we have [1-9][1-9]0xxx. We'll check to see if - // digit 3 is 0, but if it happens to be nonzero, it's a little - // hard to definitively know which the user meant. Of course, it - // is probably ddmmyy format. - if(num2 == 0) - ddmm = false; - else - ddmm = true; - } - + ddmm = true; } } } - - out = in; - if(ddmm) - { - out.Insert(fDateSeparator,2); - out.Insert(fDateSeparator,5); - } - else - { - out.Insert(fDateSeparator,1); - out.Insert(fDateSeparator,3); - } - break; - } - case 8: // DDMMYYYY. Simple to handle - { - out = in; - out.Insert(fDateSeparator,2); - out.Insert(fDateSeparator,5); - break; } - default: - { - return B_ERROR; - break; + + out = in; + if (ddmm) { + out.Insert(fDateSeparator, 2); + out.Insert(fDateSeparator, 5); + } else { + out.Insert(fDateSeparator, 1); + out.Insert(fDateSeparator, 3); } + break; + } + case 8: // DDMMYYYY. Simple to handle + { + out = in; + out.Insert(fDateSeparator, 2); + out.Insert(fDateSeparator, 5); + break; + } + default: { + return B_ERROR; + break; + } } return B_OK; } -status_t Locale::ConstructDateStringMDY(const char *in, BString &out) -{ +status_t +Locale::ConstructDateStringMDY(const char *in, BString &out) { // This constructs a proper date string given a list of numbers - if(!in) + if (!in) return B_ERROR; - + int32 length = strlen(in); - -/* - Possible date formats (with numbers only): - - M, D - almost impossible to differentiate. Not supported - DD - impossible to differentiate from MD. Not supported. - - MD - all dates acceptable. Very easy. - - MDD - 0: 1-9, 1: 1-3, 2: 0-9 (0-1 when digit 1 is 3) - MMD - 0: 0-1, 1: 0-2, 2: 1-9 - - MMDD - 0: 0-1, 1: 0-2, 3: 1-3, 4: 0-9 - MDYY - 0: 1-9, 1: 1-9, 3: 0-9, 4: 0-9 - - MDDYY - MMDYY - - MMDDYY - MDYYYY - - MDDYYYY - MMDYYYY - - MMDDYYYY -*/ - int num=0; + + /* + Possible date formats (with numbers only): + + M, D - almost impossible to differentiate. Not supported + DD - impossible to differentiate from MD. Not supported. + + MD - all dates acceptable. Very easy. + + MDD - 0: 1-9, 1: 1-3, 2: 0-9 (0-1 when digit 1 is 3) + MMD - 0: 0-1, 1: 0-2, 2: 1-9 + + MMDD - 0: 0-1, 1: 0-2, 3: 1-3, 4: 0-9 + MDYY - 0: 1-9, 1: 1-9, 3: 0-9, 4: 0-9 + + MDDYY + MMDYY + + MMDDYY + MDYYYY + + MDDYYYY + MMDYYYY + + MMDDYYYY + */ + int num = 0; char charstring[3]; charstring[1] = '\0'; charstring[2] = '\0'; - + out = in; - - switch(length) + + switch (length) { + case 2: // MD { - case 2: // MD - { - out.Insert(fDateSeparator,1); - break; - } - case 3: // MDD, MMD. Overlap when [1][1-2][0-9]. When there is overlap, assume the earlier date. - case 5: // MDDYY, MMDYY - case 7: // MMDYYYY, MDDYYYY - { - // MDD - 0: 1-9, 1: 1-3, 2: 0-9 (0-1 if digit 1 == 3) - // MMD - 0: 0-1, 1: 0-9 (1-9 if digit 0 == 0), 2: 0-9 - bool mdd=false; - charstring[0] = in[0]; + out.Insert(fDateSeparator, 1); + break; + } + case 3: // MDD, MMD. Overlap when [1][1-2][0-9]. When there is overlap, assume the earlier date. + case 5: // MDDYY, MMDYY + case 7: // MMDYYYY, MDDYYYY + { + // MDD - 0: 1-9, 1: 1-3, 2: 0-9 (0-1 if digit 1 == 3) + // MMD - 0: 0-1, 1: 0-9 (1-9 if digit 0 == 0), 2: 0-9 + bool mdd = false; + charstring[0] = in[0]; + num = atoi(charstring); + + if (num > 1) + mdd = true; + else if (num < 1) + mdd = false; + else { + // So far, the first digit is a one, so it could be either. + charstring[0] = in[1]; num = atoi(charstring); - - if(num>1) - mdd = true; - else - if(num<1) + + if (num == 0) mdd = false; - else - { - // So far, the first digit is a one, so it could be either. - charstring[0] = in[1]; - num = atoi(charstring); - - if(num == 0) - mdd = false; - else - if(num == 3) - mdd = true; - else - { - // We got this far, so there is no possible way to know for sure which it is. - // Possible dates: 1/1x, 1/2x, 11/x, 12/x - // As a result, we will choose the earlier date, which means mdd=true. - mdd = true; - } + else if (num == 3) + mdd = true; + else { + // We got this far, so there is no possible way to know for sure which it is. + // Possible dates: 1/1x, 1/2x, 11/x, 12/x + // As a result, we will choose the earlier date, which means mdd=true. + mdd = true; } - - if(mdd) - out.Insert(fDateSeparator,1); - else - out.Insert(fDateSeparator,2); - - break; } - case 4: // MDYY, MMDD - { - // MMDD - 0: 0-1, 1: 0-2, 3: 1-3, 4: 0-9 (0-1 if digit 3 == 3) - // MDYY - 0: 1-9, 1: 1-9, 3: 0-9, 4: 0-9 - bool mdyy=false; - - charstring[0] = in[0]; + + if (mdd) + out.Insert(fDateSeparator, 1); + else + out.Insert(fDateSeparator, 2); + + break; + } + case 4: // MDYY, MMDD + { + // MMDD - 0: 0-1, 1: 0-2, 3: 1-3, 4: 0-9 (0-1 if digit 3 == 3) + // MDYY - 0: 1-9, 1: 1-9, 3: 0-9, 4: 0-9 + bool mdyy = false; + + charstring[0] = in[0]; + num = atoi(charstring); + + if (num > 1) + mdyy = true; + else if (num == 0) + mdyy = false; + else { + // First number = 1 + charstring[0] = in[1]; num = atoi(charstring); - - if(num > 1) - mdyy=true; - else - if(num == 0) - mdyy=false; - else - { - // First number = 1 - charstring[0] = in[1]; + + if (num > 2) + mdyy = true; + else if (num == 0) + mdyy = false; + else { + // Second number is 1 or 2. + charstring[0] = in[2]; num = atoi(charstring); - - if(num>2) - mdyy=true; - else - if(num==0) - mdyy=false; - else - { - // Second number is 1 or 2. - charstring[0] = in[2]; + if (num == 0 || num > 3) + mdyy = true; + else if (num == 3) { + // Date is 1[1,2]3x. Chances are that we can't tell, but if x>1, it's mdyy. + charstring[0] = in[3]; num = atoi(charstring); - if(num==0 || num>3) - mdyy=true; - else - if(num==3) - { - // Date is 1[1,2]3x. Chances are that we can't tell, but if x>1, it's mdyy. - charstring[0] = in[3]; - num = atoi(charstring); - if(num>1) - mdyy = true; - else - { - // Getting this far means we can't tell. Date is in format 1[1,2]3[0,1] - // This means we have no idea. Considering the liklihood that the user - // is entering a date in the year 1930 or 1931 is relatively small, we choose mmdd - mdyy=false; - } - } - else - { - - // Getting this far means we can't tell. Date is in format 1[1,2][1,2]x - // Example dates: 1124 could be either 1/1/24 or 11/24. Just as above, the user - // probably means MM/DD because of when this code is written. - mdyy=false; + if (num > 1) + mdyy = true; + else { + // Getting this far means we can't tell. Date is in format 1[1,2]3[0,1] + // This means we have no idea. Considering the liklihood that the user + // is entering a date in the year 1930 or 1931 is relatively small, we + // choose mmdd + mdyy = false; } + } else { + + // Getting this far means we can't tell. Date is in format 1[1,2][1,2]x + // Example dates: 1124 could be either 1/1/24 or 11/24. Just as above, the user + // probably means MM/DD because of when this code is written. + mdyy = false; } } - - if(mdyy) - { - out.Insert(fDateSeparator,1); - out.Insert(fDateSeparator,3); - } - else - out.Insert(fDateSeparator,2); - break; } - case 6: // MDYYYY, MMDDYY - { - // MDYYYY - 0: 1-9, 1: 1-9, 2-5: 0-9 - // MMDDYY - 0: 0-1, 1: 0-9 (1-9 if digit 0 == 0), 2: 0-3, 3: 0-9 (0-1 if digit 2 == 3), 4-5: 0-9 - bool mmddyy=false; - charstring[0] = in[0]; + + if (mdyy) { + out.Insert(fDateSeparator, 1); + out.Insert(fDateSeparator, 3); + } else + out.Insert(fDateSeparator, 2); + break; + } + case 6: // MDYYYY, MMDDYY + { + // MDYYYY - 0: 1-9, 1: 1-9, 2-5: 0-9 + // MMDDYY - 0: 0-1, 1: 0-9 (1-9 if digit 0 == 0), 2: 0-3, 3: 0-9 (0-1 if digit 2 == 3), 4-5: + // 0-9 + bool mmddyy = false; + charstring[0] = in[0]; + num = atoi(charstring); + + if (num > 1) + mmddyy = false; + else { + // [0-1]xxxxx + charstring[0] = in[1]; num = atoi(charstring); - - if(num > 1) - mmddyy = false; - else - { - // [0-1]xxxxx - charstring[0] = in[1]; + + if (num == 0) + mmddyy = true; + else { + // At this point we're dealing with 01xxxx or 11xxxx. We need to see if digits 2 & 3 + // are a date. + charstring[0] = in[2]; num = atoi(charstring); - - if(num == 0) - mmddyy = true; - else - { - // At this point we're dealing with 01xxxx or 11xxxx. We need to see if digits 2 & 3 are a date. - charstring[0] = in[2]; + if (num > 3) + mmddyy = false; + else if (num == 3) { + // Either 013xxx or 113xxx. If digit 3 > 1, then it's mdyyyy + charstring[0] = in[3]; num = atoi(charstring); - if(num > 3) + if (num > 1) mmddyy = false; else - if(num==3) - { - // Either 013xxx or 113xxx. If digit 3 > 1, then it's mdyyyy - charstring[0] = in[3]; - num = atoi(charstring); - if(num > 1) + mmddyy = true; + } else if (num == 0) { + // It's *much* less likely that the user will type in a year with a leading + // zero, so choose mmddyy + mmddyy = true; + } else { + // 01[1-2]xxx or 11[1-2]xxx. At this point, it's not possible to tell for sure + // which it is, but probability points to x119xx or x120xx if it's a year. + // Otherwise, we'll assume mmddyy + charstring[0] = in[3]; + uint8 num2 = atoi(charstring); + if (num == 1) { + if (num2 == 9) mmddyy = false; else mmddyy = true; - } - else - if(num==0) - { - // It's *much* less likely that the user will type in a year with a leading zero, so choose - // mmddyy - mmddyy = true; - } - else - { - // 01[1-2]xxx or 11[1-2]xxx. At this point, it's not possible to tell for sure which it is, - // but probability points to x119xx or x120xx if it's a year. Otherwise, we'll assume - // mmddyy - charstring[0] = in[3]; - uint8 num2 = atoi(charstring); - if(num == 1) - { - if(num2 == 9) - mmddyy = false; - else - mmddyy = true; - } - else - if(num == 2) - { - if(num2 == 0) - mmddyy = false; - else - mmddyy = true; - } + } else if (num == 2) { + if (num2 == 0) + mmddyy = false; else mmddyy = true; - } + } else + mmddyy = true; } } - - if(mmddyy) - { - out.Insert(fDateSeparator,2); - out.Insert(fDateSeparator,5); - } - else - { - out.Insert(fDateSeparator,1); - out.Insert(fDateSeparator,4); - } - break; } - case 8: // MMDDYYYY. Simple to handle - { - out = in; - out.Insert(fDateSeparator,2); - out.Insert(fDateSeparator,5); - break; - } - default: // M, D, other unsupported lengths - { - return B_ERROR; - break; + + if (mmddyy) { + out.Insert(fDateSeparator, 2); + out.Insert(fDateSeparator, 5); + } else { + out.Insert(fDateSeparator, 1); + out.Insert(fDateSeparator, 4); } + break; } - + case 8: // MMDDYYYY. Simple to handle + { + out = in; + out.Insert(fDateSeparator, 2); + out.Insert(fDateSeparator, 5); + break; + } + default: // M, D, other unsupported lengths + { + return B_ERROR; + break; + } + } + return B_OK; } -status_t Locale::StringToDate(const char *instring, time_t &date) -{ +status_t +Locale::StringToDate(const char *instring, time_t &date) { // Input recognized for MM/DD/YY: // 1) MM/DD // 2) MM/DD/YYYY // 3) MM/DD//YY // 4) M/D/YY // 5) M/DD/YYYY - - if(!instring || (fDateFormat!=DATE_MDY && fDateFormat!=DATE_DMY) ) + + if (!instring || (fDateFormat != DATE_MDY && fDateFormat != DATE_DMY)) return B_BAD_VALUE; - - BString monthstr,daystr,yearstr,string=instring; + + BString monthstr, daystr, yearstr, string = instring; int32 index; - if(fDateFormat==DATE_MDY) - { - monthstr=string; + if (fDateFormat == DATE_MDY) { + monthstr = string; index = monthstr.FindFirst(fDateSeparator); - if(index<0) - { - ConstructDateStringMDY(instring,string); + if (index < 0) { + ConstructDateStringMDY(instring, string); monthstr = string; index = monthstr.FindFirst(fDateSeparator); - if(index < 0) + if (index < 0) return index; } - + monthstr.Truncate(index); - + daystr = string.String() + index + 1; index = daystr.FindFirst(fDateSeparator); - if(index<0) - { + if (index < 0) { // This probably means that the user didn't tack the year // onto the end. Check to see if there are 1 or 2 characters // beyond the point of the last separator. If so, then chances are // that it is a valid date using the current year. - if(daystr.CountChars()!=1 && daystr.CountChars()!=2) + if (daystr.CountChars() != 1 && daystr.CountChars() != 2) return B_ERROR; - yearstr=""; - } - else - { + yearstr = ""; + } else { daystr.Truncate(index); yearstr = daystr.String() + index + 1; } - } - else - { + } else { daystr = string; index = daystr.FindFirst(fDateSeparator); - if(index<0) - { - ConstructDateStringDMY(instring,string); + if (index < 0) { + ConstructDateStringDMY(instring, string); monthstr = string; index = monthstr.FindFirst(fDateSeparator); - if(index < 0) + if (index < 0) return index; } - + daystr.Truncate(index); - + monthstr = string.String() + index + 1; index = monthstr.FindFirst(fDateSeparator); - if(index<0) - { + if (index < 0) { // This probably means that the user didn't tack the year // onto the end. Check to see if there are 1 or 2 characters // beyond the point of the last separator. If so, then chances are // that it is a valid date using the current year. - if(monthstr.CountChars()!=1 && monthstr.CountChars()!=2) + if (monthstr.CountChars() != 1 && monthstr.CountChars() != 2) return B_ERROR; - yearstr=""; - } - else - { + yearstr = ""; + } else { yearstr = monthstr.String() + index + 1; monthstr.Truncate(index); } } - + struct tm timestruct; - + time_t rawtime; time(&rawtime); timestruct = *localtime(&rawtime); - - if(yearstr.Length()>0) - { - if(yearstr.CountChars() <= 2) - { + + if (yearstr.Length() > 0) { + if (yearstr.CountChars() <= 2) { timestruct.tm_year = atoi(yearstr.String()); - if(timestruct.tm_year < 10) + if (timestruct.tm_year < 10) timestruct.tm_year += 100; - } - else + } else timestruct.tm_year = atoi(yearstr.String()) - 1900; } timestruct.tm_sec = 1; - timestruct.tm_min = 1; + timestruct.tm_min = 1; timestruct.tm_hour = 1; timestruct.tm_mon = atoi(monthstr.String()) - 1; timestruct.tm_mday = atoi(daystr.String()); - timestruct.tm_isdst = (fUseDST)?1:0; + timestruct.tm_isdst = (fUseDST) ? 1 : 0; time_t datestruct = mktime(×truct); - - if(datestruct == -1) - { -// debugger("Error handling for StringToDate unimplemented"); + + if (datestruct == -1) { + // debugger("Error handling for StringToDate unimplemented"); return B_ERROR; } - + date = datestruct; return B_OK; } -void Locale::NumberToCurrency(const Fixed &number, BString &string) -{ +void +Locale::NumberToCurrency(const Fixed &number, BString &string) { string = ""; string << number.IntegerPart(); - - for(int32 i=string.CountChars()-3; i>0; i-=3) - string.Insert(fCurrencySeparator,i); - + + for (int32 i = string.CountChars() - 3; i > 0; i -= 3) + string.Insert(fCurrencySeparator, i); + string << fCurrencyDecimal; - + // We have to do this to eliminate the leading zero and the decimal point BString decimal; decimal << (float)number.DecimalPart(); - - if(number.IsNegative()) - string += decimal.String()+3; + + if (number.IsNegative()) + string += decimal.String() + 3; else - string += decimal.String()+2; + string += decimal.String() + 2; } -void Locale::SetDefaults(void) -{ +void +Locale::SetDefaults(void) { fDateFormat = DATE_MDY; - fCurrencySymbol = "$"; + fCurrencySymbol = "$"; fPrefixSymbol = true; fCurrencySeparator = ","; fCurrencyDecimal = "."; @@ -828,48 +729,47 @@ void Locale::SetDefaults(void) fUseDST = false; } -void ShowAlert(const char *header, const char *message, alert_type type) -{ - DAlert *alert = new DAlert(header,message,"OK",NULL,NULL,B_WIDTH_AS_USUAL,type); +void +ShowAlert(const char *header, const char *message, alert_type type) { + DAlert *alert = new DAlert(header, message, "OK", NULL, NULL, B_WIDTH_AS_USUAL, type); alert->Go(); } -void GetVersionString(BString &string) -{ +void +GetVersionString(BString &string) { app_info ai; version_info vi; be_app->GetAppInfo(&ai); - BFile file(&ai.ref,B_READ_ONLY); + BFile file(&ai.ref, B_READ_ONLY); BAppFileInfo appinfo(&file); - appinfo.GetVersionInfo(&vi,B_APP_VERSION_KIND); + appinfo.GetVersionInfo(&vi, B_APP_VERSION_KIND); BString variety; - switch(vi.variety) - { - case 0: - variety="Development"; - break; - case 1: - variety="Alpha"; - break; - case 2: - variety="Beta"; - break; - case 3: - variety="Gamma"; - break; - case 4: - variety="Release Candidate"; - break; - default: - variety="Final"; - break; + switch (vi.variety) { + case 0: + variety = "Development"; + break; + case 1: + variety = "Alpha"; + break; + case 2: + variety = "Beta"; + break; + case 3: + variety = "Gamma"; + break; + case 4: + variety = "Release Candidate"; + break; + default: + variety = "Final"; + break; } - - string=""; + + string = ""; string << vi.major << "." << vi.middle << " "; - - if(variety!="Final") + + if (variety != "Final") string << variety << " " << vi.internal; else string << "Final"; @@ -877,68 +777,63 @@ void GetVersionString(BString &string) // This function saves typing and makes debug messages more friendly and easier to // test -void ShowBug(const char *string) -{ - BString message="Capital Be has run into a bug. This shouldn't happen, but it has.\n" - "Would you like to:\n\n1) Have Capital Be make an e-mail to send to Support\n" - "2) Save the bug to a text file for e-mailing later\n" - "3) Just quit and do nothing\n"; - - DAlert *alert = new DAlert("Agh! Bug!",message.String(),"Make an E-mail", - "Save to File","Quit"); - int32 value=alert->Go(); - - if(value==0) - { +void +ShowBug(const char *string) { + BString message = "Capital Be has run into a bug. This shouldn't happen, but it has.\n" + "Would you like to:\n\n1) Have Capital Be make an e-mail to send to Support\n" + "2) Save the bug to a text file for e-mailing later\n" + "3) Just quit and do nothing\n"; + + DAlert *alert = + new DAlert("Agh! Bug!", message.String(), "Make an E-mail", "Save to File", "Quit"); + int32 value = alert->Go(); + + if (value == 0) { be_app->PostMessage(M_QUIT_NOW); return; } - + // Generate the report text - message="Capital Be Bug Report\n\n"; - + message = "Capital Be Bug Report\n\n"; + BString version; GetVersionString(version); message << "Version: " << version << "\n"; message << "Error: " << string << "\n"; - - if(value==0) - { + + if (value == 0) { // Make an e-mail to myself. :D - + BString cmdstring("/boot/beos/apps/BeMail mailto:support@capitalbe.com "); cmdstring << "-subject 'Capital Be Bug Report' -body '" << message << "'"; cmdstring << " &"; system(cmdstring.String()); - } - else - if(value==1) - { + } else if (value == 1) { // Generate a text file of the bug on the Desktop BString filename("/boot/home/Desktop/Capital Be Bug Report "); filename << real_time_clock() << ".txt"; - BFile file(filename.String(),B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); - file.Write(message.String(),message.Length()); + BFile file(filename.String(), B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); + file.Write(message.String(), message.Length()); file.Unset(); } - + be_app->PostMessage(M_QUIT_NOW); } // Code from Haiku's String.cpp -void CapitalizeEachWord(BString &string) -{ - if(string.CountChars()<1) +void +CapitalizeEachWord(BString &string) { + if (string.CountChars() < 1) return; - + char *index = string.LockBuffer(string.Length()); - + int32 count = 0; int32 length = string.Length(); - + do { // Find the first alphabetical character... - for(; count < length; count++) { + for (; count < length; count++) { if (isalpha(index[count])) { // ...found! Convert it to uppercase. index[count] = toupper(index[count]); @@ -948,79 +843,81 @@ void CapitalizeEachWord(BString &string) } // Now find the first non-alphabetical character, // and meanwhile, turn to lowercase all the alphabetical ones - for(; count < length; count++) { + for (; count < length; count++) { if (isalpha(index[count])) index[count] = tolower(index[count]); else break; } } while (count < length); - + string.UnlockBuffer(); } -void Locale::SetDateFormat(const date_format &format) -{ +void +Locale::SetDateFormat(const date_format &format) { fDateFormat = format; } -void Locale::SetCurrencySymbol(const char *symbol) -{ - if(symbol) +void +Locale::SetCurrencySymbol(const char *symbol) { + if (symbol) fCurrencySymbol = symbol; } -void Locale::SetCurrencySeparator(const char *symbol) -{ - if(symbol) +void +Locale::SetCurrencySeparator(const char *symbol) { + if (symbol) fCurrencySeparator = symbol; } -void Locale::SetCurrencyDecimal(const char *symbol) -{ - if(symbol) +void +Locale::SetCurrencyDecimal(const char *symbol) { + if (symbol) fCurrencyDecimal = symbol; } -void Locale::SetCurrencySymbolPrefix(const bool &value) -{ +void +Locale::SetCurrencySymbolPrefix(const bool &value) { fPrefixSymbol = value; } -void Locale::SetCurrencyDecimalPlace(const uint8 &place) -{ +void +Locale::SetCurrencyDecimalPlace(const uint8 &place) { fCurrencyDecimalPlace = place; } -void Locale::SetDateSeparator(const char *symbol) -{ - if(symbol) +void +Locale::SetDateSeparator(const char *symbol) { + if (symbol) fDateSeparator = symbol; } -void Locale::SetDST(const bool &value) -{ +void +Locale::SetDST(const bool &value) { fUseDST = value; } -const char *GetCurrencyOnlyMask(void) -{ - return "zxcvbnm/<>?asdfghjkl;':\"qwertyuiop[]\\{}|`-=~!@#%^&*()_à¡™∞ô¶•«»–≠œ∑鮆øπ‘¬å∫∂ƒ©Ωfi∆◊æäñ≈ç√ßñµ…÷"; +const char * +GetCurrencyOnlyMask(void) { + return "zxcvbnm/" + "<>?asdfghjkl;':\"qwertyuiop[]\\{}|`-=~!@#%^&*()_" + "à¡™∞ô¶•«»–≠œ∑鮆øπ‘¬å∫∂ƒ©Ωfi∆◊æäñ≈ç√ßñµ…÷"; } -const char *GetDateOnlyMask(void) -{ +const char * +GetDateOnlyMask(void) { return "`~!@#$%^&*()_=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"ZXCVBNM,.<>?qwertyuiopasdfghjklzxcvbnm"; } -void IllegalCharsToEntities(BString *string) -{ - if(!string) +void +IllegalCharsToEntities(BString *string) { + if (!string) return; - - string->ReplaceAll("<","<"); - string->ReplaceAll(">",">"); - string->ReplaceAll("&","&"); - string->ReplaceAll("'","'"); - string->ReplaceAll("\"","""); + + string->ReplaceAll("<", "<"); + string->ReplaceAll(">", ">"); + string->ReplaceAll("&", "&"); + string->ReplaceAll("'", "'"); + string->ReplaceAll("\"", """); } diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 6960cb8..150a88d 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -1,27 +1,27 @@ #include "MainWindow.h" #include "RegisterView.h" +#include +#include #include #include #include -#include -#include -#include +#include #include #include -#include +#include #include #include "AccountSettingsWindow.h" #include "BudgetWindow.h" #include "BuildOptions.h" +#include "CBLocale.h" #include "CategoryWindow.h" #include "DAlert.h" -#include "Layout.h" -#include "CBLocale.h" #include "LanguageRoster.h" -#include "Preferences.h" +#include "Layout.h" #include "PrefWindow.h" +#include "Preferences.h" #include "ReconcileWindow.h" #include "ReportWindow.h" #include "ScheduleAddWindow.h" @@ -33,8 +33,8 @@ #include "TransferWindow.h" #include "Translate.h" -//#define TEST -//#define NOSAVE +// #define TEST +// #define NOSAVE // Internal definition of the Haiku services daemon #define B_SERVICES_DAEMON_RESTART 'SDRS' @@ -44,206 +44,214 @@ Language *gCurrentLanguage = NULL; int32 gTextViewHeight = 20; int32 gStringViewHeight = 20; -MainWindow::MainWindow(BRect frame) - : BWindow(frame,"",B_DOCUMENT_WINDOW, 0) -{ +MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BString temp; // Main window title changes in demo mode - if(BUILD_MODE == PREVIEW_MODE) + if (BUILD_MODE == PREVIEW_MODE) SetTitle(TRANSLATE("Capital Be Preview Edition")); - else - if(BUILD_MODE == BETA_MODE) + else if (BUILD_MODE == BETA_MODE) SetTitle("Capital Be: Beta"); else SetTitle("Capital Be"); - - // These chunks of code will save a lot of headache later on -- + + // These chunks of code will save a lot of headache later on -- // we cache the preferred size of BTextControls to make control layout *much* easier. // If it gets much more complicated than these couple of chunks, then it should // be moved into its own init function that is called from here. float pw, ph; - BTextControl *temptc = new BTextControl(BRect(0,0,1,1),"temptc","","",NULL); + BTextControl *temptc = new BTextControl(BRect(0, 0, 1, 1), "temptc", "", "", NULL); AddChild(temptc); - temptc->GetPreferredSize(&pw,&ph); + temptc->GetPreferredSize(&pw, &ph); gTextViewHeight = (int32)ph; RemoveChild(temptc); delete temptc; - - BStringView *tempsv = new BStringView(BRect(0,0,1,1),"tempsv","Foo"); + + BStringView *tempsv = new BStringView(BRect(0, 0, 1, 1), "tempsv", "Foo"); AddChild(tempsv); - tempsv->GetPreferredSize(&pw,&ph); + tempsv->GetPreferredSize(&pw, &ph); gStringViewHeight = (int32)ph; RemoveChild(tempsv); delete tempsv; - + ReadLanguageSettings(); - if(fLanguage.CountChars()>0) - { + if (fLanguage.CountChars() > 0) { language_roster->SetLanguage(fLanguage.String()); gCurrentLanguage = language_roster->GetLanguage(); } - if(!gCurrentLanguage) + if (!gCurrentLanguage) gCurrentLanguage = language_roster->GetLanguage(); - + fLoadError = false; InitSettings(); - - AddShortcut(B_HOME,B_COMMAND_KEY, new BMessage(M_FIRST_TRANSACTION)); - AddShortcut(B_END,B_COMMAND_KEY, new BMessage(M_LAST_TRANSACTION)); - - SetSizeLimits(520,30000,260,30000); - if(frame.Width() < 520) - ResizeBy(520 - frame.Width(),0); - if(frame.Height() < 260) - ResizeBy(0,260 - frame.Height()); - + + AddShortcut(B_HOME, B_COMMAND_KEY, new BMessage(M_FIRST_TRANSACTION)); + AddShortcut(B_END, B_COMMAND_KEY, new BMessage(M_LAST_TRANSACTION)); + + SetSizeLimits(520, 30000, 260, 30000); + if (frame.Width() < 520) + ResizeBy(520 - frame.Width(), 0); + if (frame.Height() < 260) + ResizeBy(0, 260 - frame.Height()); + BRect r(Bounds()); - r.bottom=20; + r.bottom = 20; BMenuBar *bar = new BMenuBar("keybar"); - - #ifdef BETA_MODE - temp = TRANSLATE("Report a Bug"); temp += "…"; - bar->AddItem(new BMenuItem(temp.String(), - new BMessage(M_REPORT_BUG))); - #endif + +#ifdef BETA_MODE + temp = TRANSLATE("Report a Bug"); + temp += "…"; + bar->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_BUG))); +#endif BMenu *menu = new BMenu(TRANSLATE("Program")); - #ifdef DEMO_MODE - menu->AddItem(new BMenuItem(TRANSLATE("Buy Capital Be"), - new BMessage(M_PURCHASE_FULL_VERSION))); +#ifdef DEMO_MODE + menu->AddItem(new BMenuItem(TRANSLATE("Buy Capital Be"), new BMessage(M_PURCHASE_FULL_VERSION)) + ); menu->AddSeparatorItem(); - #endif - - temp = TRANSLATE("Options"); temp += "…"; - menu->AddItem(new BMenuItem(temp.String(), - new BMessage(M_SHOW_OPTIONS_WINDOW),',')); - +#endif + + temp = TRANSLATE("Options"); + temp += "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_OPTIONS_WINDOW), ',')); + // Set up language support. Note that we only show the menu at all if there is // more than one language available - if(language_roster->CountLanguages()>1) - { + if (language_roster->CountLanguages() > 1) { menu->AddSeparatorItem(); - fLanguageMenu=new BMenu(TRANSLATE("Language")); + fLanguageMenu = new BMenu(TRANSLATE("Language")); fLanguageMenu->SetRadioMode(true); - for(int32 i=0; iCountLanguages(); i++) - { - Language *language=language_roster->LanguageAt(i); - BMessage *langmsg=new BMessage(M_SET_LANGUAGE); - langmsg->AddInt32("index",i); - fLanguageMenu->AddItem(new BMenuItem(language->Name(),langmsg)); + for (int32 i = 0; i < language_roster->CountLanguages(); i++) { + Language *language = language_roster->LanguageAt(i); + BMessage *langmsg = new BMessage(M_SET_LANGUAGE); + langmsg->AddInt32("index", i); + fLanguageMenu->AddItem(new BMenuItem(language->Name(), langmsg)); } menu->AddItem(fLanguageMenu); - - BMenuItem *markeditem=fLanguageMenu->FindItem(fLanguage.String()); - if(markeditem) + + BMenuItem *markeditem = fLanguageMenu->FindItem(fLanguage.String()); + if (markeditem) markeditem->SetMarked(true); - } - else - fLanguageMenu=NULL; - + } else + fLanguageMenu = NULL; + menu->AddSeparatorItem(); - temp = TRANSLATE("About Capital Be"); temp += "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_ABOUT))); + temp = TRANSLATE("About Capital Be"); + temp += "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_ABOUT))); bar->AddItem(menu); - + menu = new BMenu(TRANSLATE("File")); - temp = TRANSLATE("Categories"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_CATEGORY_WINDOW))); - temp = TRANSLATE("Scheduled Transactions"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_SCHEDULED_WINDOW))); + temp = TRANSLATE("Categories"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_CATEGORY_WINDOW))); + temp = TRANSLATE("Scheduled Transactions"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_SCHEDULED_WINDOW))); menu->AddSeparatorItem(); - temp = TRANSLATE("Import from QIF File"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_IMPORT_PANEL))); - temp = TRANSLATE("Export to QIF File"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_EXPORT_PANEL))); - + temp = TRANSLATE("Import from QIF File"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_IMPORT_PANEL))); + temp = TRANSLATE("Export to QIF File"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_EXPORT_PANEL))); + bar->AddItem(menu); - + menu = new BMenu(TRANSLATE("Account")); bar->AddItem(menu); - - temp = TRANSLATE("Reconcile"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_RECONCILE_WINDOW),'R')); + + temp = TRANSLATE("Reconcile"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_RECONCILE_WINDOW), 'R')); menu->AddSeparatorItem(); - temp = TRANSLATE("New"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_NEW_ACCOUNT),'N')); - temp = TRANSLATE("Delete"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_DELETE_ACCOUNT))); - fAccountClosedItem = new BMenuItem(TRANSLATE("Close"),new BMessage(M_CLOSE_ACCOUNT)); + temp = TRANSLATE("New"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_NEW_ACCOUNT), 'N')); + temp = TRANSLATE("Delete"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_DELETE_ACCOUNT))); + fAccountClosedItem = new BMenuItem(TRANSLATE("Close"), new BMessage(M_CLOSE_ACCOUNT)); menu->AddItem(fAccountClosedItem); menu->AddSeparatorItem(); - temp = TRANSLATE("Settings"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_ACCOUNT_SETTINGS))); + temp = TRANSLATE("Settings"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_ACCOUNT_SETTINGS))); menu->AddSeparatorItem(); - menu->AddItem(new BMenuItem(TRANSLATE("Previous"),new BMessage(M_PREVIOUS_ACCOUNT),B_UP_ARROW, - B_COMMAND_KEY | B_SHIFT_KEY)); - menu->AddItem(new BMenuItem(TRANSLATE("Next"),new BMessage(M_NEXT_ACCOUNT),B_DOWN_ARROW, - B_COMMAND_KEY | B_SHIFT_KEY)); + menu->AddItem(new BMenuItem( + TRANSLATE("Previous"), new BMessage(M_PREVIOUS_ACCOUNT), B_UP_ARROW, + B_COMMAND_KEY | B_SHIFT_KEY + )); + menu->AddItem(new BMenuItem( + TRANSLATE("Next"), new BMessage(M_NEXT_ACCOUNT), B_DOWN_ARROW, B_COMMAND_KEY | B_SHIFT_KEY + )); menu = new BMenu(TRANSLATE("Transaction")); bar->AddItem(menu); - temp = TRANSLATE("Edit"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_EDIT_TRANSACTION), - 'E')); - temp = TRANSLATE("Enter a Transfer"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_ENTER_TRANSFER),'T')); + temp = TRANSLATE("Edit"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_EDIT_TRANSACTION), 'E')); + temp = TRANSLATE("Enter a Transfer"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_ENTER_TRANSFER), 'T')); menu->AddSeparatorItem(); - menu->AddItem(new BMenuItem(TRANSLATE("Delete"),new BMessage(M_DELETE_TRANSACTION))); + menu->AddItem(new BMenuItem(TRANSLATE("Delete"), new BMessage(M_DELETE_TRANSACTION))); menu->AddSeparatorItem(); - temp = TRANSLATE("Schedule This Transaction"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(), - new BMessage(M_SCHEDULE_TRANSACTION))); + temp = TRANSLATE("Schedule This Transaction"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SCHEDULE_TRANSACTION))); menu->AddSeparatorItem(); - menu->AddItem(new BMenuItem(TRANSLATE("Previous"),new BMessage(M_PREVIOUS_TRANSACTION), - B_UP_ARROW)); - menu->AddItem(new BMenuItem(TRANSLATE("Next"),new BMessage(M_NEXT_TRANSACTION),B_DOWN_ARROW)); - + menu->AddItem( + new BMenuItem(TRANSLATE("Previous"), new BMessage(M_PREVIOUS_TRANSACTION), B_UP_ARROW) + ); + menu->AddItem(new BMenuItem(TRANSLATE("Next"), new BMessage(M_NEXT_TRANSACTION), B_DOWN_ARROW)); + menu = new BMenu(TRANSLATE("Tools")); bar->AddItem(menu); - temp = TRANSLATE("Budget"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_BUDGET_WINDOW))); - temp = TRANSLATE("Reports"); temp << "…"; - menu->AddItem(new BMenuItem(temp.String(),new BMessage(M_SHOW_REPORTS_WINDOW))); - + temp = TRANSLATE("Budget"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_BUDGET_WINDOW))); + temp = TRANSLATE("Reports"); + temp << "…"; + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_REPORTS_WINDOW))); + // We load the financial data before we create any of the views because the // notifications are not sent and startup time is *significantly* reduced LoadData(); - + r = Bounds(); - r.top = bar->Frame().bottom+1; - fRegisterView = new RegisterView("registerview",B_WILL_DRAW); - - fImportPanel = new BFilePanel(B_OPEN_PANEL,new BMessenger(this),NULL,B_FILE_NODE, - false,new BMessage(M_IMPORT_ACCOUNT)); - temp = "Capital Be: "; temp += TRANSLATE("Import"); + r.top = bar->Frame().bottom + 1; + fRegisterView = new RegisterView("registerview", B_WILL_DRAW); + + fImportPanel = new BFilePanel( + B_OPEN_PANEL, new BMessenger(this), NULL, B_FILE_NODE, false, new BMessage(M_IMPORT_ACCOUNT) + ); + temp = "Capital Be: "; + temp += TRANSLATE("Import"); fImportPanel->Window()->SetTitle(temp.String()); - fExportPanel = new BFilePanel(B_SAVE_PANEL,new BMessenger(this),NULL,B_FILE_NODE, - false,new BMessage(M_EXPORT_ACCOUNT)); - temp = "Capital Be: "; temp += TRANSLATE("Export"); + fExportPanel = new BFilePanel( + B_SAVE_PANEL, new BMessenger(this), NULL, B_FILE_NODE, false, new BMessage(M_EXPORT_ACCOUNT) + ); + temp = "Capital Be: "; + temp += TRANSLATE("Export"); fExportPanel->Window()->SetTitle(temp.String()); gDatabase.AddObserver(this); - + HandleScheduledTransactions(); - - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(bar) - .Add(fRegisterView) - .End(); + + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(bar).Add(fRegisterView).End(); } -MainWindow::~MainWindow(void) -{ +MainWindow::~MainWindow(void) { SavePreferences(PREFERENCES_PATH "/CapitalBeSettings"); delete fImportPanel; } -void MainWindow::OpenAbout(void) -{ - BAboutWindow* abwin = new BAboutWindow("Capital Be","application/x-vnd.wgp-CapitalBe"); +void +MainWindow::OpenAbout(void) { + BAboutWindow *abwin = new BAboutWindow("Capital Be", "application/x-vnd.wgp-CapitalBe"); - const char* authors[] = { + const char *authors[] = { "DarkWyrm", "Jérôme Duval", "Panagiotis Vasilopoulos", @@ -253,10 +261,7 @@ void MainWindow::OpenAbout(void) NULL }; - const char* thanks[] = { - "Tanausú Gómez (Spanish translation)", - NULL - }; + const char *thanks[] = {"Tanausú Gómez (Spanish translation)", NULL}; abwin->AddCopyright(2009, "DarkWyrm"); abwin->AddText("Distributed under the terms of the MIT License"); @@ -266,538 +271,518 @@ void MainWindow::OpenAbout(void) abwin->Show(); } -bool MainWindow::QuitRequested(void) -{ +bool +MainWindow::QuitRequested(void) { #ifndef NOSAVE SaveData(); #endif prefsLock.Lock(); gPreferences.RemoveData("mainframe"); - gPreferences.AddRect("mainframe",Frame()); + gPreferences.AddRect("mainframe", Frame()); prefsLock.Unlock(); - + be_app->PostMessage(B_QUIT_REQUESTED); return true; } -void MainWindow::InitSettings(void) -{ +void +MainWindow::InitSettings(void) { // This loads all the settings from disk and uses sane defaults if a setting // is non-existent or invalid - if(gPreferences.FindString("lastfile",&fLastFile)!=B_OK) + if (gPreferences.FindString("lastfile", &fLastFile) != B_OK) fLastFile = PREFERENCES_PATH "/MyAccountData"; } - -void MainWindow::MessageReceived(BMessage *msg) -{ +void +MainWindow::MessageReceived(BMessage *msg) { Account *acc = gDatabase.CurrentAccount(); - - switch(msg->what) - { - case M_SET_LANGUAGE: - { - int32 language; - if(msg->FindInt32("index",&language)!=B_OK) - break; - - BMenuItem *item = fLanguageMenu->ItemAt(language); - if(!item) - break; - - fLanguage = item->Label(); - WriteLanguageSettings(); - - // This will *rock* under Haiku and any other places which are running - // the daemon - if(be_roster->IsRunning("application/x-vnd.Haiku-ServicesDaemon")) - { - BMessenger msgr("application/x-vnd.Haiku-ServicesDaemon"); - BMessage msg(B_SERVICES_DAEMON_RESTART); - msg.AddString("signature","application/x-vnd.wgp-CapitalBe"); - msgr.SendMessage(&msg); - be_app->PostMessage(B_QUIT_REQUESTED); - } - else - { - ShowAlert(TRANSLATE("Changes will be made on restart"), - TRANSLATE("Capital Be will be use your language choice the next time it is " - "started."),B_IDEA_ALERT); - } - break; - } - case M_REPORT_BUG: - { - BString cmdstring("/boot/beos/apps/BeMail mailto:support@capitalbe.com &"); - system(cmdstring.String()); + + switch (msg->what) { + case M_SET_LANGUAGE: { + int32 language; + if (msg->FindInt32("index", &language) != B_OK) break; - } - case M_SHOW_NEW_ACCOUNT: - { - #ifdef PREVIEW_MODE - if(gDatabase.CountAccounts()>=5) - { - ShowAlert(TRANSLATE("Preview Mode Limit"), - TRANSLATE( - "You can have up to 5 accounts in Capital Be's demo version. " - "We hope that you like Capital Be and will " - "purchase the full version. Have a nice day!"), - B_IDEA_ALERT); - break; - } - #endif - - AccountSettingsWindow *newaccwin = new AccountSettingsWindow(NULL); - BRect r(Frame()); - newaccwin->MoveTo(r.left + ((Bounds().Width()-newaccwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-newaccwin->Bounds().Height())/2) ); - newaccwin->Show(); + + BMenuItem *item = fLanguageMenu->ItemAt(language); + if (!item) break; - } - case M_SHOW_ACCOUNT_SETTINGS: - { - if(!acc) - break; - - AccountSettingsWindow *accwin = new AccountSettingsWindow(acc); - BRect r(Frame()); - accwin->MoveTo(r.left + ((Bounds().Width()-accwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-accwin->Bounds().Height())/2) ); - accwin->Show(); + + fLanguage = item->Label(); + WriteLanguageSettings(); + + // This will *rock* under Haiku and any other places which are running + // the daemon + if (be_roster->IsRunning("application/x-vnd.Haiku-ServicesDaemon")) { + BMessenger msgr("application/x-vnd.Haiku-ServicesDaemon"); + BMessage msg(B_SERVICES_DAEMON_RESTART); + msg.AddString("signature", "application/x-vnd.wgp-CapitalBe"); + msgr.SendMessage(&msg); + be_app->PostMessage(B_QUIT_REQUESTED); + } else { + ShowAlert( + TRANSLATE("Changes will be made on restart"), + TRANSLATE("Capital Be will be use your language choice the next time it is " + "started."), + B_IDEA_ALERT + ); + } + break; + } + case M_REPORT_BUG: { + BString cmdstring("/boot/beos/apps/BeMail mailto:support@capitalbe.com &"); + system(cmdstring.String()); + break; + } + case M_SHOW_NEW_ACCOUNT: { +#ifdef PREVIEW_MODE + if (gDatabase.CountAccounts() >= 5) { + ShowAlert( + TRANSLATE("Preview Mode Limit"), + TRANSLATE("You can have up to 5 accounts in Capital Be's demo version. " + "We hope that you like Capital Be and will " + "purchase the full version. Have a nice day!"), + B_IDEA_ALERT + ); break; } - case M_DELETE_ACCOUNT: - { - if(!acc) - break; - - DAlert *alert = new DAlert(TRANSLATE("Really Delete Account?"), - TRANSLATE("Once deleted, you will not be able to " - "get back any data on this account."), - TRANSLATE("Delete"), - TRANSLATE("Cancel"),NULL,B_WIDTH_AS_USUAL,B_STOP_ALERT); - - if(alert->Go()==0) - { - int32 index = gDatabase.IndexOf(acc); - if(index==0) - { - gDatabase.SetCurrentAccount(1); - } - else - if(index>0) - { - gDatabase.SetCurrentAccount(index-1); - } - gDatabase.RemoveAccount(acc); - } +#endif + + AccountSettingsWindow *newaccwin = new AccountSettingsWindow(NULL); + BRect r(Frame()); + newaccwin->MoveTo( + r.left + ((Bounds().Width() - newaccwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - newaccwin->Bounds().Height()) / 2) + ); + newaccwin->Show(); + break; + } + case M_SHOW_ACCOUNT_SETTINGS: { + if (!acc) break; - } - case M_PREVIOUS_ACCOUNT: - { - if(gDatabase.CountAccounts()<2) - break; - - int32 index = gDatabase.IndexOf(acc); - if(index < 1 || index > gDatabase.CountAccounts()-1) - break; - - // Because there is no way to call BListView::Select without generating - // a selection notification firing, we have to hack a method to manually - // do the selecting which then generates the proper notification instead - // of tweaking the database via SetCurrentAccount. Man, I hate hacks sometimes. :/ - fRegisterView->SelectAccount(index-1); + + AccountSettingsWindow *accwin = new AccountSettingsWindow(acc); + BRect r(Frame()); + accwin->MoveTo( + r.left + ((Bounds().Width() - accwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - accwin->Bounds().Height()) / 2) + ); + accwin->Show(); + break; + } + case M_DELETE_ACCOUNT: { + if (!acc) break; - } - case M_NEXT_ACCOUNT: - { - if(gDatabase.CountAccounts()<2) - break; - + + DAlert *alert = new DAlert( + TRANSLATE("Really Delete Account?"), + TRANSLATE("Once deleted, you will not be able to " + "get back any data on this account."), + TRANSLATE("Delete"), TRANSLATE("Cancel"), NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT + ); + + if (alert->Go() == 0) { int32 index = gDatabase.IndexOf(acc); - if(index < 0 || index >= gDatabase.CountAccounts()-1) - break; - - // Because there is no way to call BListView::Select without generating - // a selection notification firing, we have to hack a method to manually - // do the selecting which then generates the proper notification instead - // of tweaking the database via SetCurrentAccount. Man, I hate hacks sometimes. :/ - fRegisterView->SelectAccount(index+1); - break; - } - case M_SHOW_IMPORT_PANEL: - { - fImportPanel->Show(); - break; - } - case M_IMPORT_ACCOUNT: - { - entry_ref ref; - -// BEntry entry("/boot/develop/projects/Capital Be/source/yoderdata.qif"); -// entry.GetRef(&ref); - - if(msg->FindRef("refs",&ref)!=B_OK) - break; - - if(!gDatabase.ImportFile(ref)) - { - BString errmsg(TRANSLATE("Could not import the data in the file %%FILENAME%%.")); - errmsg.ReplaceFirst("%%FILENAME%%",ref.name); - ShowAlert(errmsg.String(), - TRANSLATE("This happens when the kind of file is not " - "supported, when the file's data is damaged, or when you feed " - "it a recipe for quiche.")); + if (index == 0) { + gDatabase.SetCurrentAccount(1); + } else if (index > 0) { + gDatabase.SetCurrentAccount(index - 1); } - break; + gDatabase.RemoveAccount(acc); } - case M_SHOW_EXPORT_PANEL: - { - fExportPanel->Show(); + break; + } + case M_PREVIOUS_ACCOUNT: { + if (gDatabase.CountAccounts() < 2) break; - } - case M_EXPORT_ACCOUNT: - { - entry_ref dir; - BString name; - if(msg->FindRef("directory",&dir)!=B_OK || - msg->FindString("name",&name)!=B_OK) - break; - - BPath path(&dir); - name.Prepend("/"); - name.Prepend(path.Path()); - - BEntry entry(name.String()); - entry.GetRef(&dir); - - if(!gDatabase.ExportFile(dir)) - { - BString errmsg(TRANSLATE("Could not export your financial data to the file %%FILENAME%%.")); - errmsg.ReplaceFirst("%%FILENAME%%",dir.name); - ShowAlert(errmsg.String(), - TRANSLATE("This really shouldn't happen, so you probably " - "should e-mail support about this.")); - } + + int32 index = gDatabase.IndexOf(acc); + if (index < 1 || index > gDatabase.CountAccounts() - 1) break; - } - case M_CLOSE_ACCOUNT: - { - if(!acc) - break; - - if(acc->IsClosed()) - gDatabase.ReopenAccount(acc); - else - gDatabase.CloseAccount(acc); + + // Because there is no way to call BListView::Select without generating + // a selection notification firing, we have to hack a method to manually + // do the selecting which then generates the proper notification instead + // of tweaking the database via SetCurrentAccount. Man, I hate hacks sometimes. :/ + fRegisterView->SelectAccount(index - 1); + break; + } + case M_NEXT_ACCOUNT: { + if (gDatabase.CountAccounts() < 2) break; - } - case M_SHOW_ABOUT: - { - OpenAbout(); + + int32 index = gDatabase.IndexOf(acc); + if (index < 0 || index >= gDatabase.CountAccounts() - 1) break; - } - case M_PREVIOUS_TRANSACTION: - { - fRegisterView->SelectPreviousTransaction(); + + // Because there is no way to call BListView::Select without generating + // a selection notification firing, we have to hack a method to manually + // do the selecting which then generates the proper notification instead + // of tweaking the database via SetCurrentAccount. Man, I hate hacks sometimes. :/ + fRegisterView->SelectAccount(index + 1); + break; + } + case M_SHOW_IMPORT_PANEL: { + fImportPanel->Show(); + break; + } + case M_IMPORT_ACCOUNT: { + entry_ref ref; + + // BEntry entry("/boot/develop/projects/Capital Be/source/yoderdata.qif"); + // entry.GetRef(&ref); + + if (msg->FindRef("refs", &ref) != B_OK) break; - } - case M_NEXT_TRANSACTION: - { - fRegisterView->SelectNextTransaction(); + + if (!gDatabase.ImportFile(ref)) { + BString errmsg(TRANSLATE("Could not import the data in the file %%FILENAME%%.")); + errmsg.ReplaceFirst("%%FILENAME%%", ref.name); + ShowAlert( + errmsg.String(), + TRANSLATE("This happens when the kind of file is not " + "supported, when the file's data is damaged, or when you feed " + "it a recipe for quiche.") + ); + } + break; + } + case M_SHOW_EXPORT_PANEL: { + fExportPanel->Show(); + break; + } + case M_EXPORT_ACCOUNT: { + entry_ref dir; + BString name; + if (msg->FindRef("directory", &dir) != B_OK || msg->FindString("name", &name) != B_OK) break; - } - case M_FIRST_TRANSACTION: - { - fRegisterView->SelectFirstTransaction(); + + BPath path(&dir); + name.Prepend("/"); + name.Prepend(path.Path()); + + BEntry entry(name.String()); + entry.GetRef(&dir); + + if (!gDatabase.ExportFile(dir)) { + BString errmsg( + TRANSLATE("Could not export your financial data to the file %%FILENAME%%.") + ); + errmsg.ReplaceFirst("%%FILENAME%%", dir.name); + ShowAlert( + errmsg.String(), TRANSLATE("This really shouldn't happen, so you probably " + "should e-mail support about this.") + ); + } + break; + } + case M_CLOSE_ACCOUNT: { + if (!acc) break; - } - case M_LAST_TRANSACTION: - { - fRegisterView->SelectLastTransaction(); + + if (acc->IsClosed()) + gDatabase.ReopenAccount(acc); + else + gDatabase.CloseAccount(acc); + break; + } + case M_SHOW_ABOUT: { + OpenAbout(); + break; + } + case M_PREVIOUS_TRANSACTION: { + fRegisterView->SelectPreviousTransaction(); + break; + } + case M_NEXT_TRANSACTION: { + fRegisterView->SelectNextTransaction(); + break; + } + case M_FIRST_TRANSACTION: { + fRegisterView->SelectFirstTransaction(); + break; + } + case M_LAST_TRANSACTION: { + fRegisterView->SelectLastTransaction(); + break; + } + case M_DELETE_TRANSACTION: { + if (!acc) break; - } - case M_DELETE_TRANSACTION: - { - if(!acc) - break; - - uint32 count = acc->CountTransactions(); - if(!count) - break; - - uint32 item = acc->CurrentTransaction(); - - if(!fRegisterView->SelectPreviousTransaction()) - fRegisterView->SelectNextTransaction(); - gDatabase.RemoveTransaction(item); + + uint32 count = acc->CountTransactions(); + if (!count) break; - } - case M_ENTER_TRANSFER: - { - if(gDatabase.CountAccounts()<2) - { - ShowAlert(TRANSLATE("Not enough accounts for a transfer."), - TRANSLATE("You need to have at least 2 accounts to perform a transfer.")); - break; - } - - TransferWindow *tnwin = new TransferWindow(this); - BRect r(Frame()); - tnwin->MoveTo(r.left + ((Bounds().Width()-tnwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-tnwin->Bounds().Height())/2) ); - tnwin->Show(); + + uint32 item = acc->CurrentTransaction(); + + if (!fRegisterView->SelectPreviousTransaction()) + fRegisterView->SelectNextTransaction(); + gDatabase.RemoveTransaction(item); + break; + } + case M_ENTER_TRANSFER: { + if (gDatabase.CountAccounts() < 2) { + ShowAlert( + TRANSLATE("Not enough accounts for a transfer."), + TRANSLATE("You need to have at least 2 accounts to perform a transfer.") + ); break; } - case M_EDIT_TRANSACTION: - { - if(!acc) - break; - - if(!acc->CurrentTransaction()) - { - if(!acc->CountTransactions()) - break; - } - - TransactionData data; - gDatabase.GetTransaction(acc->CurrentTransaction(),data); - BRect r(Frame()); - r.right = r.left + 400; - r.bottom = r.top + 300; - TransactionEditWindow *transwin = new TransactionEditWindow(r,data); - transwin->MoveTo(r.left + ((Bounds().Width()-transwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-transwin->Bounds().Height())/2) ); - transwin->Show(); + + TransferWindow *tnwin = new TransferWindow(this); + BRect r(Frame()); + tnwin->MoveTo( + r.left + ((Bounds().Width() - tnwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - tnwin->Bounds().Height()) / 2) + ); + tnwin->Show(); + break; + } + case M_EDIT_TRANSACTION: { + if (!acc) break; - } - case M_SCHEDULE_TRANSACTION: - { - if(!acc) - break; - - if(!acc->CurrentTransaction()) - { - if(!acc->CountTransactions()) - break; - } - - TransactionData data; - gDatabase.GetTransaction(acc->CurrentTransaction(),data); - - if(data.Type().TypeCode()== TRANS_NUMERIC) - { - ShowAlert(TRANSLATE("Numbered transactions cannot be scheduled."), - TRANSLATE("You can schedule transfers, deposits, or ATM transactions.")); + + if (!acc->CurrentTransaction()) { + if (!acc->CountTransactions()) break; - } - - BRect r(Frame()); - r.right = r.left + 400; - r.bottom = r.top + 300; - - ScheduleAddWindow *schedwin = new ScheduleAddWindow(r,data); - schedwin->MoveTo(r.left + ((Bounds().Width()-schedwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-schedwin->Bounds().Height())/2) ); - schedwin->Show(); - break; - } - case M_CREATE_TRANSFER: - { - CreateTransfer(msg); - break; } - case M_SHOW_OPTIONS_WINDOW: - { - PrefWindow *pwin = new PrefWindow(Frame()); - pwin->Show(); - break; - } - case M_SHOW_REPORTS_WINDOW: - { - // While it seems kind of silly to show the reports window if - // there is no data, it seems more like a bug to not bother showing it - - ReportWindow *rwin = new ReportWindow(Frame()); - rwin->Show(); + + TransactionData data; + gDatabase.GetTransaction(acc->CurrentTransaction(), data); + BRect r(Frame()); + r.right = r.left + 400; + r.bottom = r.top + 300; + TransactionEditWindow *transwin = new TransactionEditWindow(r, data); + transwin->MoveTo( + r.left + ((Bounds().Width() - transwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - transwin->Bounds().Height()) / 2) + ); + transwin->Show(); + break; + } + case M_SCHEDULE_TRANSACTION: { + if (!acc) break; - } - case M_SHOW_RECONCILE_WINDOW: - { - if(!acc) - { - if(gDatabase.CountAccounts()<1) - ShowAlert(TRANSLATE("Oops!"), - TRANSLATE("You need to have an account created in order to reconcile it.")); - else - ShowAlert(TRANSLATE("Oops!"), - TRANSLATE("You need to select an account in order to reconcile it.")); + + if (!acc->CurrentTransaction()) { + if (!acc->CountTransactions()) break; - } - - BRect r(Frame()); - ReconcileWindow *recwin = new ReconcileWindow(BRect(100,100,600,425), acc); - recwin->MoveTo(r.left + ((Bounds().Width()-recwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-recwin->Bounds().Height())/2) ); - recwin->Show(); - break; - } - case M_SHOW_SCHEDULED_WINDOW: - { - BRect r(Frame()); - ScheduleListWindow *schedwin = new ScheduleListWindow(BRect(100,100,600,425)); - schedwin->MoveTo(r.left + ((Bounds().Width()-schedwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-schedwin->Bounds().Height())/2) ); - schedwin->Show(); - break; - } - case M_SHOW_BUDGET_WINDOW: - { - BudgetWindow *bwin = new BudgetWindow(Frame()); - bwin->Show(); - break; } - case M_SHOW_CATEGORY_WINDOW: - { - BRect r(Frame()); - CategoryWindow *catwin = new CategoryWindow(BRect(100,100,600,425)); - catwin->MoveTo(r.left + ((Bounds().Width()-catwin->Bounds().Width())/2), - r.top + ((Bounds().Height()-catwin->Bounds().Height())/2) ); - catwin->Show(); - break; - } - case M_PURCHASE_FULL_VERSION: - { - BMessage msg(B_NETPOSITIVE_OPEN_URL); - msg.AddString("be:url","http://www.capitalbe.com/"); - be_roster->Launch(B_NETPOSITIVE_APP_SIGNATURE,&msg); + + TransactionData data; + gDatabase.GetTransaction(acc->CurrentTransaction(), data); + + if (data.Type().TypeCode() == TRANS_NUMERIC) { + ShowAlert( + TRANSLATE("Numbered transactions cannot be scheduled."), + TRANSLATE("You can schedule transfers, deposits, or ATM transactions.") + ); break; } - default: - { - BWindow::MessageReceived(msg); + + BRect r(Frame()); + r.right = r.left + 400; + r.bottom = r.top + 300; + + ScheduleAddWindow *schedwin = new ScheduleAddWindow(r, data); + schedwin->MoveTo( + r.left + ((Bounds().Width() - schedwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - schedwin->Bounds().Height()) / 2) + ); + schedwin->Show(); + break; + } + case M_CREATE_TRANSFER: { + CreateTransfer(msg); + break; + } + case M_SHOW_OPTIONS_WINDOW: { + PrefWindow *pwin = new PrefWindow(Frame()); + pwin->Show(); + break; + } + case M_SHOW_REPORTS_WINDOW: { + // While it seems kind of silly to show the reports window if + // there is no data, it seems more like a bug to not bother showing it + + ReportWindow *rwin = new ReportWindow(Frame()); + rwin->Show(); + break; + } + case M_SHOW_RECONCILE_WINDOW: { + if (!acc) { + if (gDatabase.CountAccounts() < 1) + ShowAlert( + TRANSLATE("Oops!"), + TRANSLATE("You need to have an account created in order to reconcile it.") + ); + else + ShowAlert( + TRANSLATE("Oops!"), + TRANSLATE("You need to select an account in order to reconcile it.") + ); break; } + + BRect r(Frame()); + ReconcileWindow *recwin = new ReconcileWindow(BRect(100, 100, 600, 425), acc); + recwin->MoveTo( + r.left + ((Bounds().Width() - recwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - recwin->Bounds().Height()) / 2) + ); + recwin->Show(); + break; + } + case M_SHOW_SCHEDULED_WINDOW: { + BRect r(Frame()); + ScheduleListWindow *schedwin = new ScheduleListWindow(BRect(100, 100, 600, 425)); + schedwin->MoveTo( + r.left + ((Bounds().Width() - schedwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - schedwin->Bounds().Height()) / 2) + ); + schedwin->Show(); + break; + } + case M_SHOW_BUDGET_WINDOW: { + BudgetWindow *bwin = new BudgetWindow(Frame()); + bwin->Show(); + break; + } + case M_SHOW_CATEGORY_WINDOW: { + BRect r(Frame()); + CategoryWindow *catwin = new CategoryWindow(BRect(100, 100, 600, 425)); + catwin->MoveTo( + r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), + r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) + ); + catwin->Show(); + break; + } + case M_PURCHASE_FULL_VERSION: { + BMessage msg(B_NETPOSITIVE_OPEN_URL); + msg.AddString("be:url", "http://www.capitalbe.com/"); + be_roster->Launch(B_NETPOSITIVE_APP_SIGNATURE, &msg); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } -void MainWindow::LoadData(void) -{ - if(gDatabase.OpenFile(fLastFile.String())!=B_OK) - { +void +MainWindow::LoadData(void) { + if (gDatabase.OpenFile(fLastFile.String()) != B_OK) { BEntry entry(fLastFile.String()); - if(!entry.Exists()) - { + if (!entry.Exists()) { // TODO: Show Capital Be introduction -// TODO: Show a Create File dialog + // TODO: Show a Create File dialog gDatabase.CreateFile(fLastFile.String()); PostMessage(M_SHOW_NEW_ACCOUNT); } } } -void MainWindow::SaveData(void) -{ -} +void +MainWindow::SaveData(void) {} -void MainWindow::CreateTransfer(BMessage *msg) -{ - Account *from,*to; - BString amount,memo,datestr; +void +MainWindow::CreateTransfer(BMessage *msg) { + Account *from, *to; + BString amount, memo, datestr; Fixed fixed; time_t date; - - if( (msg->FindPointer("from",(void**)&from)!=B_OK) || - (msg->FindPointer("to",(void**)&to)!=B_OK) || - (msg->FindString("amount",&amount)!=B_OK) || - (gCurrentLocale.StringToCurrency(amount.String(),fixed)!=B_OK) || - (msg->FindString("date",&datestr)!=B_OK) || - (gDefaultLocale.StringToDate(datestr.String(),date)!=B_OK) ) + + if ((msg->FindPointer("from", (void **)&from) != B_OK) || + (msg->FindPointer("to", (void **)&to) != B_OK) || + (msg->FindString("amount", &amount) != B_OK) || + (gCurrentLocale.StringToCurrency(amount.String(), fixed) != B_OK) || + (msg->FindString("date", &datestr) != B_OK) || + (gDefaultLocale.StringToDate(datestr.String(), date) != B_OK)) return; - - if(msg->FindString("memo",&memo)!=B_OK) - memo=""; - + + if (msg->FindString("memo", &memo) != B_OK) + memo = ""; + // Now that we've gathered all the data from the message sent to us by TransferWindow, // we create the transactions needed for each account. BString payee = TRANSLATE("Transfer to %%PAYEE%%"); - payee.ReplaceFirst("%%PAYEE%%",to->Name()); - + payee.ReplaceFirst("%%PAYEE%%", to->Name()); + uint32 transid = gDatabase.NextTransactionID(); TransactionType type("XFER"); - gDatabase.AddTransaction(from->GetID(),transid,date,type,payee.String(), - fixed.InvertAsCopy(),"Transfer",memo.String()); - + gDatabase.AddTransaction( + from->GetID(), transid, date, type, payee.String(), fixed.InvertAsCopy(), "Transfer", + memo.String() + ); + payee = TRANSLATE("Transfer from %%PAYEE%%"); - payee.ReplaceFirst("%%PAYEE%%",to->Name()); + payee.ReplaceFirst("%%PAYEE%%", to->Name()); payee << from->Name(); - gDatabase.AddTransaction(to->GetID(),transid,date,type,payee.String(), - fixed,"Transfer",memo.String()); + gDatabase.AddTransaction( + to->GetID(), transid, date, type, payee.String(), fixed, "Transfer", memo.String() + ); } -void MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) -{ - bool lockwin=false; - if(!IsLocked()) - { +void +MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { + bool lockwin = false; + if (!IsLocked()) { Lock(); - lockwin=true; + lockwin = true; } - - if(value & WATCH_ACCOUNT) - { + + if (value & WATCH_ACCOUNT) { Account *acc; - if(msg->FindPointer("item",(void**)&acc)!=B_OK || !acc) - { - if(lockwin) + if (msg->FindPointer("item", (void **)&acc) != B_OK || !acc) { + if (lockwin) Unlock(); return; } - - if(value & WATCH_SELECT || value & WATCH_CHANGE) - { - if(acc->IsClosed()) - { + + if (value & WATCH_SELECT || value & WATCH_CHANGE) { + if (acc->IsClosed()) { fAccountClosedItem->SetLabel(TRANSLATE("Reopen")); - } - else - { + } else { fAccountClosedItem->SetLabel(TRANSLATE("Close")); } } } - if(lockwin) + if (lockwin) Unlock(); } -void MainWindow::ReadLanguageSettings(void) -{ +void +MainWindow::ReadLanguageSettings(void) { BFile file("/boot/home/config/settings/CapitalBe/CurrentLocale", B_READ_ONLY); - - if(file.InitCheck()!=B_OK) + + if (file.InitCheck() != B_OK) return; - - file.Seek(0,SEEK_END); + + file.Seek(0, SEEK_END); off_t size = file.Position(); - file.Seek(0,SEEK_SET); - + file.Seek(0, SEEK_SET); + char name[size]; - file.Read(name,size); + file.Read(name, size); file.Unset(); - - fLanguage=name; + + fLanguage = name; } -void MainWindow::WriteLanguageSettings(void) -{ - BFile file("/boot/home/config/settings/CapitalBe/CurrentLocale", - B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); - - if(file.InitCheck()!=B_OK) +void +MainWindow::WriteLanguageSettings(void) { + BFile file( + "/boot/home/config/settings/CapitalBe/CurrentLocale", + B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE + ); + + if (file.InitCheck() != B_OK) return; - - file.Seek(0,SEEK_SET); - file.Write(fLanguage.String(),fLanguage.Length()+1); + + file.Seek(0, SEEK_SET); + file.Write(fLanguage.String(), fLanguage.Length() + 1); file.Unset(); } diff --git a/src/MainWindow.h b/src/MainWindow.h index b47007b..9bc85a1 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -1,28 +1,27 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include +#include "Database.h" +#include "Notifier.h" #include -#include -#include +#include #include #include -#include -#include "Database.h" -#include "Notifier.h" +#include +#include +#include class RegisterView; -enum -{ - M_FILE_NEW=1000, +enum { + M_FILE_NEW = 1000, M_FILE_OPEN, M_FILE_BACKUP, - + M_PURCHASE_FULL_VERSION, M_REPORT_BUG, M_SET_LANGUAGE, - + M_SHOW_NEW_ACCOUNT, M_IMPORT_ACCOUNT, M_SHOW_IMPORT_PANEL, @@ -37,27 +36,26 @@ enum M_PREVIOUS_ACCOUNT, M_NEXT_ACCOUNT, M_CLOSE_ACCOUNT, - + M_PREVIOUS_TRANSACTION, M_NEXT_TRANSACTION, M_FIRST_TRANSACTION, M_LAST_TRANSACTION, - + M_SPLIT_TRANSACTION, M_EDIT_TRANSACTION, M_DELETE_TRANSACTION, M_SCHEDULE_TRANSACTION, M_ENTER_TRANSFER, - - M_SHOW_ABOUT='msha', + + M_SHOW_ABOUT = 'msha', M_SHOW_REPORTS_WINDOW, M_SHOW_OPTIONS_WINDOW, M_SHOW_SCHEDULED_WINDOW }; -class MainWindow : public BWindow, public Observer -{ -public: +class MainWindow : public BWindow, public Observer { + public: MainWindow(BRect frame); ~MainWindow(void); @@ -67,21 +65,21 @@ class MainWindow : public BWindow, public Observer void HandleNotify(const uint64 &value, const BMessage *msg); void ReadLanguageSettings(void); void WriteLanguageSettings(void); - -private: + + private: void InitSettings(void); void LoadData(void); void SaveData(void); - + void CreateTransfer(BMessage *msg); - + RegisterView *fRegisterView; BFilePanel *fImportPanel, *fExportPanel; - + BString fLastFile; BMenuItem *fAccountClosedItem; BMenu *fLanguageMenu; - + bool fLoadError; BString fLanguage; }; diff --git a/src/MsgDefs.h b/src/MsgDefs.h index d9fe987..ab7bef0 100644 --- a/src/MsgDefs.h +++ b/src/MsgDefs.h @@ -1,10 +1,6 @@ #ifndef MSGDEFS_H #define MSGDEFS_H -enum -{ - M_PREVIOUS_FIELD = 'mpvf', - M_NEXT_FIELD = 'mnxf' -}; +enum { M_PREVIOUS_FIELD = 'mpvf', M_NEXT_FIELD = 'mnxf' }; #endif diff --git a/src/NavTextBox.cpp b/src/NavTextBox.cpp index b27574c..7517808 100644 --- a/src/NavTextBox.cpp +++ b/src/NavTextBox.cpp @@ -4,43 +4,37 @@ #include "MsgDefs.h" #include "TimeSupport.h" -NavTextBoxFilter::NavTextBoxFilter(NavTextBox *box) - : AutoTextControlFilter(box) -{ -} +NavTextBoxFilter::NavTextBoxFilter(NavTextBox *box) : AutoTextControlFilter(box) {} -filter_result NavTextBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +NavTextBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB && ((NavTextBox*)TextControl())->IsTabFiltering()) - { - if(mod & B_SHIFT_KEY) + if (key == B_TAB && ((NavTextBox *)TextControl())->IsTabFiltering()) { + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - +#endif + return B_DISPATCH_MESSAGE; } -NavTextBox::NavTextBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags), - fFilterTab(true) -{ +NavTextBox::NavTextBox( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) { SetFilter(new NavTextBoxFilter(this)); } -bool NavTextBox::Validate(const bool &alert) -{ +bool +NavTextBox::Validate(const bool &alert) { return true; } diff --git a/src/NavTextBox.h b/src/NavTextBox.h index 9466a42..561fb8a 100644 --- a/src/NavTextBox.h +++ b/src/NavTextBox.h @@ -5,27 +5,27 @@ class NavTextBox; -class NavTextBoxFilter : public AutoTextControlFilter -{ -public: +class NavTextBoxFilter : public AutoTextControlFilter { + public: NavTextBoxFilter(NavTextBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class NavTextBox : public AutoTextControl -{ -public: - NavTextBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class NavTextBox : public AutoTextControl { + public: + NavTextBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); virtual bool Validate(const bool &alert = true); - + void UseTabFiltering(const bool &value) { fFilterTab = value; } + bool IsTabFiltering(void) const { return fFilterTab; } - -private: + + private: friend NavTextBoxFilter; - + bool fFilterTab; }; diff --git a/src/NetWorthReport.cpp b/src/NetWorthReport.cpp index b1d2b76..f66c22a 100644 --- a/src/NetWorthReport.cpp +++ b/src/NetWorthReport.cpp @@ -1,133 +1,121 @@ -#include "ReportWindow.h" #include "Account.h" #include "CBLocale.h" -#include "Database.h" -#include "ReportGrid.h" #include "ColumnListView.h" #include "ColumnTypes.h" +#include "Database.h" +#include "ReportGrid.h" +#include "ReportWindow.h" #include "TimeSupport.h" -void ReportWindow::ComputeNetWorth(void) -{ +void +ReportWindow::ComputeNetWorth(void) { // Total of all accounts // Calculate the number of columns and the starting date for each one - BObjectList timelist(20,true); - - if(fSubtotalMode != SUBTOTAL_NONE) - { - for(time_t t=fStartDate; t timelist(20, true); + + if (fSubtotalMode != SUBTOTAL_NONE) { + for (time_t t = fStartDate; t < fEndDate;) { time_t *item = new time_t(t); timelist.AddItem(item); - - switch(fSubtotalMode) - { - case SUBTOTAL_MONTH: - { - t = IncrementDateByMonth(t); - break; - } - case SUBTOTAL_QUARTER: - { - t = IncrementDateByQuarter(t); - break; - } - case SUBTOTAL_YEAR: - { - t = IncrementDateByYear(t); - break; - } - default: - { - t = fEndDate; - break; - } + + switch (fSubtotalMode) { + case SUBTOTAL_MONTH: { + t = IncrementDateByMonth(t); + break; + } + case SUBTOTAL_QUARTER: { + t = IncrementDateByQuarter(t); + break; + } + case SUBTOTAL_YEAR: { + t = IncrementDateByYear(t); + break; + } + default: { + t = fEndDate; + break; + } } } } timelist.AddItem(new time_t(fEndDate)); - - ReportGrid accountgrid(1, timelist.CountItems()); - + + ReportGrid accountgrid(1, timelist.CountItems()); + BString longestname(TRANSLATE("Total Worth")); int longestnamelength = longestname.CountChars(); - - for(int32 subtotal_index=0; subtotal_index longestnamelength) - { + if (length > longestnamelength) { longestname = rowtitle; longestnamelength = length; } - - + + Fixed accounttotal; - - for(int32 i=0; iCountItems(); i++) - { - AccountItem *item = (AccountItem*)fAccountList->ItemAt(i); - if(!item) + + for (int32 i = 0; i < fAccountList->CountItems(); i++) { + AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + if (!item) continue; - + accounttotal += item->account->BalanceAt(subtotal_start); } // end for each account - - accountgrid.SetValue(0,subtotal_index,accounttotal); + + accountgrid.SetValue(0, subtotal_index, accounttotal); } - - if(fGraphView->IsHidden()) - { + + if (fGraphView->IsHidden()) { // Now that we have all the data, we need to set up the rows and columns for the report grid - - BColumn *col = new BStringColumn(TRANSLATE("Date"),fGridView->StringWidth(longestname.String())+20,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,0); - col = new BStringColumn(TRANSLATE("Total"),75,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,1); - + + BColumn *col = new BStringColumn( + TRANSLATE("Date"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, + B_TRUNCATE_END + ); + fGridView->AddColumn(col, 0); + col = new BStringColumn(TRANSLATE("Total"), 75, 10, 300, B_TRUNCATE_END); + fGridView->AddColumn(col, 1); + fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Total Worth")),0); + titlerow->SetField(new BStringField(TRANSLATE("Total Worth")), 0); fGridView->AddRow(new BRow()); - + // Now that the grid is set up, start adding data to the grid - for(int32 rowindex=0; rowindexAddRow(row); - + BStringField *catname = new BStringField(accountgrid.RowTitle(rowindex)); - row->SetField(catname,0); - + row->SetField(catname, 0); + BString temp; Fixed f; - - accountgrid.ValueAt(0,rowindex,f); - gCurrentLocale.CurrencyToString(f,temp); - + + accountgrid.ValueAt(0, rowindex, f); + gCurrentLocale.CurrencyToString(f, temp); + BStringField *amountfield = new BStringField(temp.String()); - row->SetField(amountfield,1); + row->SetField(amountfield, 1); } } } diff --git a/src/Notifier.cpp b/src/Notifier.cpp index 8223b3c..db58b84 100644 --- a/src/Notifier.cpp +++ b/src/Notifier.cpp @@ -1,34 +1,34 @@ #include "Notifier.h" -#include #include #include +#include -void PrintNotification(const uint64 &value, const BMessage *msg) -{ +void +PrintNotification(const uint64 &value, const BMessage *msg) { BString action; - if(value & WATCH_CREATE) + if (value & WATCH_CREATE) action << "WATCH_CREATE "; - - if(value & WATCH_DELETE) + + if (value & WATCH_DELETE) action << "WATCH_DELETE "; - - if(value & WATCH_CHANGE) + + if (value & WATCH_CHANGE) action << "WATCH_CHANGE "; - - if(value & WATCH_RENAME) + + if (value & WATCH_RENAME) action << "WATCH_RENAME "; - - if(value & WATCH_SELECT) + + if (value & WATCH_SELECT) action << "WATCH_SELECT "; - + BString target; - - if(value & WATCH_ACCOUNT) + + if (value & WATCH_ACCOUNT) target << "WATCH_ACCOUNT "; - - if(value & WATCH_TRANSACTION) + + if (value & WATCH_TRANSACTION) target << "WATCH_TRANSACTION "; - - printf("Notify: %s : %s\n",action.String(),target.String()); + + printf("Notify: %s : %s\n", action.String(), target.String()); msg->PrintToStream(); } diff --git a/src/Notifier.h b/src/Notifier.h index a8b055f..e1920a2 100644 --- a/src/Notifier.h +++ b/src/Notifier.h @@ -4,82 +4,88 @@ #include #include -#define WATCH_CREATE 0x1 -#define WATCH_DELETE 0x2 -#define WATCH_RENAME 0x4 -#define WATCH_CHANGE 0x8 -#define WATCH_SELECT 0x10 -#define WATCH_REDRAW 0x20 -#define WATCH_MASS_EDIT 0x40 - -#define WATCH_ACCOUNT 0x0000000100000000LL -#define WATCH_TRANSACTION 0x0000000200000000LL -#define WATCH_BUDGET 0x0000000400000000LL -#define WATCH_SCHED_TRANSACTION 0x0000000800000000LL -#define WATCH_LOCALE 0x0000001000000000LL - -#define WATCH_EVENTS 0xFFFFFFFF00000000LL -#define WATCH_ACTIONS 0xFFFFFFFF -#define WATCH_ALL 0xFFFFFFFFFFFFFFFFLL - -void PrintNotification(const uint64 &value, const BMessage *msg); - -class Observer -{ -public: - Observer(const uint64 &flags=WATCH_ALL) { AddWatch(flags); fEnabled = true; } +#define WATCH_CREATE 0x1 +#define WATCH_DELETE 0x2 +#define WATCH_RENAME 0x4 +#define WATCH_CHANGE 0x8 +#define WATCH_SELECT 0x10 +#define WATCH_REDRAW 0x20 +#define WATCH_MASS_EDIT 0x40 + +#define WATCH_ACCOUNT 0x0000000100000000LL +#define WATCH_TRANSACTION 0x0000000200000000LL +#define WATCH_BUDGET 0x0000000400000000LL +#define WATCH_SCHED_TRANSACTION 0x0000000800000000LL +#define WATCH_LOCALE 0x0000001000000000LL + +#define WATCH_EVENTS 0xFFFFFFFF00000000LL +#define WATCH_ACTIONS 0xFFFFFFFF +#define WATCH_ALL 0xFFFFFFFFFFFFFFFFLL + +void +PrintNotification(const uint64 &value, const BMessage *msg); + +class Observer { + public: + Observer(const uint64 &flags = WATCH_ALL) { + AddWatch(flags); + fEnabled = true; + } + virtual ~Observer(void) {} - - void AddWatch(const uint64 &flags) { fFlags |= flags; } + + void AddWatch(const uint64 &flags) { fFlags |= flags; } + void RemoveWatch(const uint64 &flags) { fFlags &= ~flags; } - + bool IsWatching(const uint64 &flags) { return fFlags & flags; } - + // Implement this to do whatever you want it to. - virtual void HandleNotify(const uint64 &value, const BMessage *msg) { } - + virtual void HandleNotify(const uint64 &value, const BMessage *msg) {} + virtual void SetObserving(const bool &value) { fEnabled = value; } + bool IsObserving(void) const { return fEnabled; } - -private: + + private: uint64 fFlags; bool fEnabled; }; -class Notifier -{ -public: +class Notifier { + public: Notifier(void) { fEnabled = true; } + virtual ~Notifier(void) {} - + // If these methods are subclassed, please make sure that these versions // are also called. virtual void AddObserver(Observer *obs) { fObserverList.AddItem(obs); } + virtual void RemoveObserver(Observer *obs) { fObserverList.RemoveItem(obs); } + bool HasObserver(Observer *obs) { return fObserverList.HasItem(obs); } - - virtual void Notify(const uint64 &value, const BMessage *msg=NULL) - { - if(!fEnabled) + + virtual void Notify(const uint64 &value, const BMessage *msg = NULL) { + if (!fEnabled) return; - - for(int32 i=0; iIsObserving() && obs->IsWatching(value)) + + if (obs->IsObserving() && obs->IsWatching(value)) obs->HandleNotify(value, msg); } } - + void SetNotify(const bool &value) { fEnabled = value; } + bool IsNotifying(void) const { return fEnabled; } - -private: - + + private: BList fObserverList; bool fEnabled; }; diff --git a/src/NumBox.cpp b/src/NumBox.cpp index ecaa037..fca7b94 100644 --- a/src/NumBox.cpp +++ b/src/NumBox.cpp @@ -4,72 +4,61 @@ #include "MsgDefs.h" #include "TimeSupport.h" -NumBoxFilter::NumBoxFilter(NumBox *box) - : AutoTextControlFilter(box) -{ -} +NumBoxFilter::NumBoxFilter(NumBox *box) : AutoTextControlFilter(box) {} -filter_result NumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +NumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB) - { - if(!((NumBox*)TextControl())->IsTabFiltering()) + if (key == B_TAB) { + if (!((NumBox *)TextControl())->IsTabFiltering()) return B_DISPATCH_MESSAGE; - - if(mod & B_SHIFT_KEY) + + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; +#endif + + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; return B_DISPATCH_MESSAGE; } -NumBox::NumBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags), - fFilterTab(true), - fAllowNegatives(true) -{ +NumBox::NumBox(const char *name, const char *label, const char *text, BMessage *msg, uint32 flags) + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true), fAllowNegatives(true) { SetFilter(new NumBoxFilter(this)); - const char num_disallowed[]=" `~!@#%^&*()_+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" - "ZXCVBNM<>?/qwertyuiopasdfghjklzxcvbnm$¥£"; - int32 i=0; - while(num_disallowed[i]) - { + const char num_disallowed[] = " `~!@#%^&*()_+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" + "ZXCVBNM<>?/qwertyuiopasdfghjklzxcvbnm$¥£"; + int32 i = 0; + while (num_disallowed[i]) { TextView()->DisallowChar(num_disallowed[i]); i++; } } -bool NumBox::Validate(bool alert) -{ - if(strlen(Text())<1) +bool +NumBox::Validate(bool alert) { + if (strlen(Text()) < 1) SetText("0"); return true; } -void NumBox::AllowNegatives(const bool &value) -{ - if(fAllowNegatives != value) - { +void +NumBox::AllowNegatives(const bool &value) { + if (fAllowNegatives != value) { fAllowNegatives = value; - if(fAllowNegatives) + if (fAllowNegatives) TextView()->AllowChar('-'); else TextView()->DisallowChar('-'); diff --git a/src/NumBox.h b/src/NumBox.h index fd625f6..5b812ab 100644 --- a/src/NumBox.h +++ b/src/NumBox.h @@ -5,28 +5,30 @@ class NumBox; -class NumBoxFilter : public AutoTextControlFilter -{ -public: +class NumBoxFilter : public AutoTextControlFilter { + public: NumBoxFilter(NumBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class NumBox : public AutoTextControl -{ -public: - NumBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class NumBox : public AutoTextControl { + public: + NumBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); bool Validate(bool alert = true); - + void UseTabFiltering(const bool &value) { fFilterTab = value; } + bool IsTabFiltering(void) const { return fFilterTab; } - + void AllowNegatives(const bool &value); + bool AllowsNegatives(void) const { return fAllowNegatives; } -private: + + private: friend NumBoxFilter; bool fFilterTab; bool fAllowNegatives; diff --git a/src/ObjectList.h b/src/ObjectList.h index 6fc9f16..5a77505 100644 --- a/src/ObjectList.h +++ b/src/ObjectList.h @@ -68,41 +68,39 @@ All rights reserved. #include -template class BObjectList; +template class BObjectList; -template -struct UnaryPredicate { +template struct UnaryPredicate { virtual int operator()(const T *) const - // virtual could be avoided here if FindBinaryInsertionIndex, - // etc. were member template functions - { return 0; } + // virtual could be avoided here if FindBinaryInsertionIndex, + // etc. were member template functions + { + return 0; + } -private: + private: static int _unary_predicate_glue(const void *item, void *context); -friend class BObjectList; + friend class BObjectList; }; -template +template int -UnaryPredicate::_unary_predicate_glue(const void *item, void *context) -{ +UnaryPredicate::_unary_predicate_glue(const void *item, void *context) { return ((UnaryPredicate *)context)->operator()((const T *)item); } - class _PointerList_ : public BList { -public: + public: _PointerList_(const _PointerList_ &list); _PointerList_(int32 itemsPerBlock = 20, bool owning = false); ~_PointerList_(); - typedef void *(* GenericEachFunction)(void *, void *); - typedef int (* GenericCompareFunction)(const void *, const void *); - typedef int (* GenericCompareFunctionWithState)(const void *, const void *, - void *); - typedef int (* UnaryPredicateGlue)(const void *, void *); + typedef void *(*GenericEachFunction)(void *, void *); + typedef int (*GenericCompareFunction)(const void *, const void *); + typedef int (*GenericCompareFunctionWithState)(const void *, const void *, void *); + typedef int (*UnaryPredicateGlue)(const void *, void *); void *EachElement(GenericEachFunction, void *); void SortItems(GenericCompareFunction); @@ -120,31 +118,28 @@ class _PointerList_ : public BList { bool Owning() const; bool ReplaceItem(int32, void *); -protected: + protected: bool owning; - }; -template -class BObjectList : private _PointerList_ { -public: - +template class BObjectList : private _PointerList_ { + public: // iteration and sorting - typedef T *(* EachFunction)(T *, void *); - typedef const T *(* ConstEachFunction)(const T *, void *); - typedef int (* CompareFunction)(const T *, const T *); - typedef int (* CompareFunctionWithState)(const T *, const T *, void *state); + typedef T *(*EachFunction)(T *, void *); + typedef const T *(*ConstEachFunction)(const T *, void *); + typedef int (*CompareFunction)(const T *, const T *); + typedef int (*CompareFunctionWithState)(const T *, const T *, void *state); BObjectList(int32 itemsPerBlock = 20, bool owning = false); BObjectList(const BObjectList &list); - // clones list; if list is owning, makes copies of all - // the items + // clones list; if list is owning, makes copies of all + // the items virtual ~BObjectList(); BObjectList &operator=(const BObjectList &list); - // clones list; if list is owning, makes copies of all - // the items + // clones list; if list is owning, makes copies of all + // the items // adding and removing // ToDo: @@ -155,9 +150,9 @@ class BObjectList : private _PointerList_ { bool AddList(BObjectList *, int32); bool RemoveItem(T *, bool deleteIfOwning = true); - // if owning, deletes the removed item + // if owning, deletes the removed item T *RemoveItemAt(int32); - // returns the removed item + // returns the removed item void MakeEmpty(); @@ -165,10 +160,10 @@ class BObjectList : private _PointerList_ { T *ItemAt(int32) const; bool ReplaceItem(int32 index, T *); - // if list is owning, deletes the item at first + // if list is owning, deletes the item at first T *SwapWithItem(int32 index, T *newItem); - // same as ReplaceItem, except does not delete old item at , - // returns it instead + // same as ReplaceItem, except does not delete old item at , + // returns it instead T *FirstItem() const; T *LastItem() const; @@ -195,13 +190,13 @@ class BObjectList : private _PointerList_ { T *BinarySearch(const T &, CompareFunction) const; T *BinarySearch(const T &, CompareFunctionWithState, void *state) const; - template - T *BinarySearchByKey(const Key &key, int (*compare)(const Key *, const T *)) - const; + template + T *BinarySearchByKey(const Key &key, int (*compare)(const Key *, const T *)) const; - template - T *BinarySearchByKey(const Key &key, - int (*compare)(const Key *, const T *, void *), void *state) const; + template + T *BinarySearchByKey( + const Key &key, int (*compare)(const Key *, const T *, void *), void *state + ) const; // Binary insertion - list must be sorted with CompareFunction for // these to work @@ -226,22 +221,22 @@ class BObjectList : private _PointerList_ { T *BinaryInsertCopyUnique(const T ©This, CompareFunctionWithState, void *state); int32 FindBinaryInsertionIndex(const UnaryPredicate &, bool *alreadyInList = 0) const; - // returns either the index into which a new item should be inserted - // or index of an existing item that matches the predicate + + // returns either the index into which a new item should be inserted + // or index of an existing item that matches the predicate // deprecated API, will go away - BList *AsBList() - { return this; } - const BList *AsBList() const - { return this; } -private: + BList *AsBList() { return this; } + + const BList *AsBList() const { return this; } + + private: void SetItem(int32, T *); }; -template +template Result -WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1), Param1 p1) -{ +WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1), Param1 p1) { Result result = 0; int32 count = list->CountItems(); @@ -252,10 +247,9 @@ WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1), Param1 return result; } -template +template Result -WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1), Param1 p1) -{ +WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1), Param1 p1) { Result result = 0; int32 count = list->CountItems(); @@ -266,11 +260,11 @@ WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1), Param return result; } -template +template Result -WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1, Param2), - Param1 p1, Param2 p2) -{ +WhileEachListItem( + BObjectList *list, Result (Item::*func)(Param1, Param2), Param1 p1, Param2 p2 +) { Result result = 0; int32 count = list->CountItems(); @@ -281,11 +275,11 @@ WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1, Param2), return result; } -template +template Result -WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1, Param2), - Param1 p1, Param2 p2) -{ +WhileEachListItem( + BObjectList *list, Result (*func)(Item *, Param1, Param2), Param1 p1, Param2 p2 +) { Result result = 0; int32 count = list->CountItems(); @@ -296,11 +290,12 @@ WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1, Param2 return result; } -template +template Result -WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1, Param2, - Param3, Param4), Param1 p1, Param2 p2, Param3 p3, Param4 p4) -{ +WhileEachListItem( + BObjectList *list, Result (*func)(Item *, Param1, Param2, Param3, Param4), Param1 p1, + Param2 p2, Param3 p3, Param4 p4 +) { Result result = 0; int32 count = list->CountItems(); @@ -311,60 +306,55 @@ WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1, Param2 return result; } -template +template void -EachListItemIgnoreResult(BObjectList *list, Result (Item::*func)()) -{ +EachListItemIgnoreResult(BObjectList *list, Result (Item::*func)()) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (list->ItemAt(index)->*func)(); } -template +template void -EachListItem(BObjectList *list, void (*func)(Item *, Param1), Param1 p1) -{ +EachListItem(BObjectList *list, void (*func)(Item *, Param1), Param1 p1) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1); } -template +template void -EachListItem(BObjectList *list, void (Item::*func)(Param1, Param2), - Param1 p1, Param2 p2) -{ +EachListItem(BObjectList *list, void (Item::*func)(Param1, Param2), Param1 p1, Param2 p2) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (list->ItemAt(index)->*func)(p1, p2); } -template +template void -EachListItem(BObjectList *list, void (*func)(Item *,Param1, Param2), - Param1 p1, Param2 p2) -{ +EachListItem(BObjectList *list, void (*func)(Item *, Param1, Param2), Param1 p1, Param2 p2) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2); } -template +template void -EachListItem(BObjectList *list, void (*func)(Item *,Param1, Param2, - Param3), Param1 p1, Param2 p2, Param3 p3) -{ +EachListItem( + BObjectList *list, void (*func)(Item *, Param1, Param2, Param3), Param1 p1, Param2 p2, + Param3 p3 +) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2, p3); } - -template +template void -EachListItem(BObjectList *list, void (*func)(Item *,Param1, Param2, - Param3, Param4), Param1 p1, Param2 p2, Param3 p3, Param4 p4) -{ +EachListItem( + BObjectList *list, void (*func)(Item *, Param1, Param2, Param3, Param4), Param1 p1, + Param2 p2, Param3 p3, Param4 p4 +) { int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2, p3, p4); @@ -373,26 +363,20 @@ EachListItem(BObjectList *list, void (*func)(Item *,Param1, Param2, // inline code inline bool -_PointerList_::Owning() const -{ +_PointerList_::Owning() const { return owning; } -template +template BObjectList::BObjectList(int32 itemsPerBlock, bool owning) - : _PointerList_(itemsPerBlock, owning) -{ -} + : _PointerList_(itemsPerBlock, owning) {} -template -BObjectList::BObjectList(const BObjectList &list) - : _PointerList_(list) -{ +template BObjectList::BObjectList(const BObjectList &list) : _PointerList_(list) { owning = list.owning; if (owning) { // make our own copies in an owning list int32 count = list.CountItems(); - for (int32 index = 0; index < count; index++) { + for (int32 index = 0; index < count; index++) { T *item = list.ItemAt(index); if (item) item = new T(*item); @@ -401,24 +385,21 @@ BObjectList::BObjectList(const BObjectList &list) } } -template -BObjectList::~BObjectList() -{ +template BObjectList::~BObjectList() { if (Owning()) // have to nuke elements first MakeEmpty(); } -template +template BObjectList & -BObjectList::operator=(const BObjectList &list) -{ +BObjectList::operator=(const BObjectList &list) { owning = list.owning; BObjectList &result = (BObjectList &)_PointerList_::operator=(list); if (owning) { // make our own copies in an owning list int32 count = list.CountItems(); - for (int32 index = 0; index < count; index++) { + for (int32 index = 0; index < count; index++) { T *item = list.ItemAt(index); if (item) item = new T(*item); @@ -428,40 +409,34 @@ BObjectList::operator=(const BObjectList &list) return result; } -template +template bool -BObjectList::AddItem(T *item) -{ +BObjectList::AddItem(T *item) { // need to cast to void * to make T work for const pointers return _PointerList_::AddItem((void *)item); } -template +template bool -BObjectList::AddItem(T *item, int32 atIndex) -{ +BObjectList::AddItem(T *item, int32 atIndex) { return _PointerList_::AddItem((void *)item, atIndex); } -template +template bool -BObjectList::AddList(BObjectList *newItems) -{ +BObjectList::AddList(BObjectList *newItems) { return _PointerList_::AddList(newItems); } -template +template bool -BObjectList::AddList(BObjectList *newItems, int32 atIndex) -{ +BObjectList::AddList(BObjectList *newItems, int32 atIndex) { return _PointerList_::AddList(newItems, atIndex); } - -template +template bool -BObjectList::RemoveItem(T *item, bool deleteIfOwning) -{ +BObjectList::RemoveItem(T *item, bool deleteIfOwning) { bool result = _PointerList_::RemoveItem((void *)item); if (result && Owning() && deleteIfOwning) @@ -470,91 +445,79 @@ BObjectList::RemoveItem(T *item, bool deleteIfOwning) return result; } -template +template T * -BObjectList::RemoveItemAt(int32 index) -{ +BObjectList::RemoveItemAt(int32 index) { return (T *)_PointerList_::RemoveItem(index); } -template +template inline T * -BObjectList::ItemAt(int32 index) const -{ +BObjectList::ItemAt(int32 index) const { return (T *)_PointerList_::ItemAt(index); } -template +template bool -BObjectList::ReplaceItem(int32 index, T *item) -{ +BObjectList::ReplaceItem(int32 index, T *item) { if (owning) delete ItemAt(index); return _PointerList_::ReplaceItem(index, (void *)item); } -template +template T * -BObjectList::SwapWithItem(int32 index, T *newItem) -{ +BObjectList::SwapWithItem(int32 index, T *newItem) { T *result = ItemAt(index); _PointerList_::ReplaceItem(index, (void *)newItem); return result; } -template +template void -BObjectList::SetItem(int32 index, T *newItem) -{ +BObjectList::SetItem(int32 index, T *newItem) { _PointerList_::ReplaceItem(index, (void *)newItem); } -template +template int32 -BObjectList::IndexOf(const T *item) const -{ +BObjectList::IndexOf(const T *item) const { return _PointerList_::IndexOf((void *)item); } -template +template T * -BObjectList::FirstItem() const -{ +BObjectList::FirstItem() const { return (T *)_PointerList_::FirstItem(); } -template +template T * -BObjectList::LastItem() const -{ +BObjectList::LastItem() const { return (T *)_PointerList_::LastItem(); } -template +template bool -BObjectList::HasItem(const T *item) const -{ +BObjectList::HasItem(const T *item) const { return _PointerList_::HasItem((void *)item); } -template +template bool -BObjectList::IsEmpty() const -{ +BObjectList::IsEmpty() const { return _PointerList_::IsEmpty(); } -template +template int32 -BObjectList::CountItems() const -{ +BObjectList::CountItems() const { return _PointerList_::CountItems(); } -template +template void -BObjectList::MakeEmpty() -{ +BObjectList::MakeEmpty() { if (owning) { int32 count = CountItems(); for (int32 index = 0; index < count; index++) @@ -563,27 +526,23 @@ BObjectList::MakeEmpty() _PointerList_::MakeEmpty(); } -template +template T * -BObjectList::EachElement(EachFunction func, void *params) -{ +BObjectList::EachElement(EachFunction func, void *params) { return (T *)_PointerList_::EachElement((GenericEachFunction)func, params); } - -template +template const T * -BObjectList::EachElement(ConstEachFunction func, void *params) const -{ - return (const T *) - const_cast *>(this)->_PointerList_::EachElement( - (GenericEachFunction)func, params); +BObjectList::EachElement(ConstEachFunction func, void *params) const { + return (const T *)const_cast *>(this)->_PointerList_::EachElement( + (GenericEachFunction)func, params + ); } -template +template const T * -BObjectList::FindIf(const UnaryPredicate &predicate) const -{ +BObjectList::FindIf(const UnaryPredicate &predicate) const { int32 count = CountItems(); for (int32 index = 0; index < count; index++) if (predicate.operator()(ItemAt(index)) == 0) @@ -591,10 +550,9 @@ BObjectList::FindIf(const UnaryPredicate &predicate) const return 0; } -template +template T * -BObjectList::FindIf(const UnaryPredicate &predicate) -{ +BObjectList::FindIf(const UnaryPredicate &predicate) { int32 count = CountItems(); for (int32 index = 0; index < count; index++) if (predicate.operator()(ItemAt(index)) == 0) @@ -602,80 +560,62 @@ BObjectList::FindIf(const UnaryPredicate &predicate) return 0; } - -template +template void -BObjectList::SortItems(CompareFunction function) -{ +BObjectList::SortItems(CompareFunction function) { _PointerList_::SortItems((GenericCompareFunction)function); } -template +template void -BObjectList::SortItems(CompareFunctionWithState function, void *state) -{ +BObjectList::SortItems(CompareFunctionWithState function, void *state) { _PointerList_::SortItems((GenericCompareFunctionWithState)function, state); } -template +template void -BObjectList::HSortItems(CompareFunction function) -{ +BObjectList::HSortItems(CompareFunction function) { _PointerList_::HSortItems((GenericCompareFunction)function); } -template +template void -BObjectList::HSortItems(CompareFunctionWithState function, void *state) -{ +BObjectList::HSortItems(CompareFunctionWithState function, void *state) { _PointerList_::HSortItems((GenericCompareFunctionWithState)function, state); } -template +template T * -BObjectList::BinarySearch(const T &key, CompareFunction func) const -{ - return (T*)_PointerList_::BinarySearch(&key, - (GenericCompareFunction)func); +BObjectList::BinarySearch(const T &key, CompareFunction func) const { + return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunction)func); } -template +template T * -BObjectList::BinarySearch(const T &key, CompareFunctionWithState func, void *state) const -{ - return (T*)_PointerList_::BinarySearch(&key, - (GenericCompareFunctionWithState)func, state); +BObjectList::BinarySearch(const T &key, CompareFunctionWithState func, void *state) const { + return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)func, state); } - -template -template +template +template T * -BObjectList::BinarySearchByKey(const Key &key, - int (*compare)(const Key *, const T *)) const -{ - return (T*)_PointerList_::BinarySearch(&key, - (GenericCompareFunction)compare); +BObjectList::BinarySearchByKey(const Key &key, int (*compare)(const Key *, const T *)) const { + return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunction)compare); } - -template -template +template +template T * -BObjectList::BinarySearchByKey(const Key &key, - int (*compare)(const Key *, const T *, void *), void *state) const -{ - return (T*)_PointerList_::BinarySearch(&key, - (GenericCompareFunctionWithState)compare, state); +BObjectList::BinarySearchByKey( + const Key &key, int (*compare)(const Key *, const T *, void *), void *state +) const { + return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)compare, state); } - -template +template bool -BObjectList::BinaryInsert(T *item, CompareFunction func) -{ - int32 index = _PointerList_::BinarySearchIndex(item, - (GenericCompareFunction)func); +BObjectList::BinaryInsert(T *item, CompareFunction func) { + int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunction)func); if (index >= 0) { // already in list, add after existing return AddItem(item, index + 1); @@ -684,12 +624,11 @@ BObjectList::BinaryInsert(T *item, CompareFunction func) return AddItem(item, -index - 1); } -template +template bool -BObjectList::BinaryInsert(T *item, CompareFunctionWithState func, void *state) -{ - int32 index = _PointerList_::BinarySearchIndex(item, - (GenericCompareFunctionWithState)func, state); +BObjectList::BinaryInsert(T *item, CompareFunctionWithState func, void *state) { + int32 index = + _PointerList_::BinarySearchIndex(item, (GenericCompareFunctionWithState)func, state); if (index >= 0) { // already in list, add after existing return AddItem(item, index + 1); @@ -698,37 +637,31 @@ BObjectList::BinaryInsert(T *item, CompareFunctionWithState func, void *state return AddItem(item, -index - 1); } -template +template bool -BObjectList::BinaryInsertUnique(T *item, CompareFunction func) -{ - int32 index = _PointerList_::BinarySearchIndex(item, - (GenericCompareFunction)func); +BObjectList::BinaryInsertUnique(T *item, CompareFunction func) { + int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunction)func); if (index >= 0) return false; return AddItem(item, -index - 1); } -template +template bool -BObjectList::BinaryInsertUnique(T *item, CompareFunctionWithState func, void *state) -{ - int32 index = _PointerList_::BinarySearchIndex(item, - (GenericCompareFunctionWithState)func, state); +BObjectList::BinaryInsertUnique(T *item, CompareFunctionWithState func, void *state) { + int32 index = + _PointerList_::BinarySearchIndex(item, (GenericCompareFunctionWithState)func, state); if (index >= 0) return false; return AddItem(item, -index - 1); } - -template +template T * -BObjectList::BinaryInsertCopy(const T ©This, CompareFunction func) -{ - int32 index = _PointerList_::BinarySearchIndex(©This, - (GenericCompareFunction)func); +BObjectList::BinaryInsertCopy(const T ©This, CompareFunction func) { + int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunction)func); if (index >= 0) index++; @@ -740,12 +673,11 @@ BObjectList::BinaryInsertCopy(const T ©This, CompareFunction func) return newItem; } -template +template T * -BObjectList::BinaryInsertCopy(const T ©This, CompareFunctionWithState func, void *state) -{ - int32 index = _PointerList_::BinarySearchIndex(©This, - (GenericCompareFunctionWithState)func, state); +BObjectList::BinaryInsertCopy(const T ©This, CompareFunctionWithState func, void *state) { + int32 index = + _PointerList_::BinarySearchIndex(©This, (GenericCompareFunctionWithState)func, state); if (index >= 0) index++; @@ -757,12 +689,10 @@ BObjectList::BinaryInsertCopy(const T ©This, CompareFunctionWithState fun return newItem; } -template +template T * -BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunction func) -{ - int32 index = _PointerList_::BinarySearchIndex(©This, - (GenericCompareFunction)func); +BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunction func) { + int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunction)func); if (index >= 0) return ItemAt(index); @@ -772,13 +702,13 @@ BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunction func) return newItem; } -template +template T * -BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunctionWithState func, - void *state) -{ - int32 index = _PointerList_::BinarySearchIndex(©This, - (GenericCompareFunctionWithState)func, state); +BObjectList::BinaryInsertCopyUnique( + const T ©This, CompareFunctionWithState func, void *state +) { + int32 index = + _PointerList_::BinarySearchIndex(©This, (GenericCompareFunctionWithState)func, state); if (index >= 0) return ItemAt(index); @@ -788,13 +718,12 @@ BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunctionWithSta return newItem; } -template +template int32 -BObjectList::FindBinaryInsertionIndex(const UnaryPredicate &pred, bool *alreadyInList) - const -{ - int32 index = _PointerList_::BinarySearchIndexByPredicate(&pred, - (UnaryPredicateGlue)&UnaryPredicate::_unary_predicate_glue); +BObjectList::FindBinaryInsertionIndex(const UnaryPredicate &pred, bool *alreadyInList) const { + int32 index = _PointerList_::BinarySearchIndexByPredicate( + &pred, (UnaryPredicateGlue)&UnaryPredicate::_unary_predicate_glue + ); if (alreadyInList) *alreadyInList = index >= 0; @@ -805,17 +734,15 @@ BObjectList::FindBinaryInsertionIndex(const UnaryPredicate &pred, bool *al return index; } -template +template bool -BObjectList::BinaryInsert(T *item, const UnaryPredicate &pred) -{ +BObjectList::BinaryInsert(T *item, const UnaryPredicate &pred) { return AddItem(item, FindBinaryInsertionIndex(pred)); } -template +template bool -BObjectList::BinaryInsertUnique(T *item, const UnaryPredicate &pred) -{ +BObjectList::BinaryInsertUnique(T *item, const UnaryPredicate &pred) { bool alreadyInList; int32 index = FindBinaryInsertionIndex(pred, &alreadyInList); if (alreadyInList) @@ -825,4 +752,4 @@ BObjectList::BinaryInsertUnique(T *item, const UnaryPredicate &pred) return true; } -#endif /* __OBJECT_LIST__ */ +#endif /* __OBJECT_LIST__ */ diff --git a/src/PayeeBox.cpp b/src/PayeeBox.cpp index f6d4dd0..31bcecf 100644 --- a/src/PayeeBox.cpp +++ b/src/PayeeBox.cpp @@ -5,90 +5,79 @@ #include "TimeSupport.h" #include "Translate.h" -PayeeBoxFilter::PayeeBoxFilter(PayeeBox *box) - : AutoTextControlFilter(box) -{ -} +PayeeBoxFilter::PayeeBoxFilter(PayeeBox *box) : AutoTextControlFilter(box) {} -filter_result PayeeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) -{ +filter_result +PayeeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { // Here is where all the *real* work for a date box is done. - if(key==B_TAB) - { - if(mod & B_SHIFT_KEY) + if (key == B_TAB) { + if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #ifdef ENTER_NAVIGATION - if(key==B_ENTER) - { + +#ifdef ENTER_NAVIGATION + if (key == B_ENTER) { SendMessage(new BMessage(M_ENTER_NAVIGATION)); return B_SKIP_MESSAGE; } - #endif - -// if(key == B_ESCAPE && !IsEscapeCancel()) -// return B_SKIP_MESSAGE; +#endif - if(key<32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && - !(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) ) + // if(key == B_ESCAPE && !IsEscapeCancel()) + // return B_SKIP_MESSAGE; + + if (key < 32 || ((mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && !(mod & B_OPTION_KEY) && + !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - + Account *acc = gDatabase.CurrentAccount(); - if(!acc) + if (!acc) return B_DISPATCH_MESSAGE; - + int32 start, end; - TextControl()->TextView()->GetSelection(&start,&end); - if(end == (int32)strlen(TextControl()->Text())) - { - TextControl()->TextView()->Delete(start,end); - + TextControl()->TextView()->GetSelection(&start, &end); + if (end == (int32)strlen(TextControl()->Text())) { + TextControl()->TextView()->Delete(start, end); + BString string; - if(GetCurrentMessage()->FindString("bytes",&string)!=B_OK) - string=""; + if (GetCurrentMessage()->FindString("bytes", &string) != B_OK) + string = ""; string.Prepend(TextControl()->Text()); - + BString autocomplete = acc->AutocompletePayee(string.String()); - - if(autocomplete.CountChars()>0) - { + + if (autocomplete.CountChars() > 0) { BMessage automsg(M_PAYEE_AUTOCOMPLETE); - automsg.AddInt32("start",strlen(TextControl()->Text())+1); - automsg.AddString("string",autocomplete.String()); + automsg.AddInt32("start", strlen(TextControl()->Text()) + 1); + automsg.AddString("string", autocomplete.String()); SendMessage(&automsg); } } - + return B_DISPATCH_MESSAGE; } -PayeeBox::PayeeBox(const char *name, const char *label, - const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name,label,text,msg,flags) -{ +PayeeBox::PayeeBox( + const char *name, const char *label, const char *text, BMessage *msg, uint32 flags +) + : AutoTextControl(name, label, text, msg, flags) { SetFilter(new PayeeBoxFilter(this)); SetCharacterLimit(32); } - - -bool PayeeBox::Validate(const bool &showalert) -{ - if(showalert && (Text()==NULL || strlen(Text())<1) ) - { - ShowAlert(TRANSLATE("Payee is missing."), - TRANSLATE("You need to enter a payee.")); +bool +PayeeBox::Validate(const bool &showalert) { + if (showalert && (Text() == NULL || strlen(Text()) < 1)) { + ShowAlert(TRANSLATE("Payee is missing."), TRANSLATE("You need to enter a payee.")); MakeFocus(true); return false; } - -// BString text = Text(); -// CapitalizeEachWord(text); -// SetText(text.String()); - + + // BString text = Text(); + // CapitalizeEachWord(text); + // SetText(text.String()); + return true; } diff --git a/src/PayeeBox.h b/src/PayeeBox.h index 06fbad2..d8a05e9 100644 --- a/src/PayeeBox.h +++ b/src/PayeeBox.h @@ -3,30 +3,26 @@ #include "AutoTextControl.h" -enum -{ - M_PAYEE_AUTOCOMPLETE='acpy' -}; +enum { M_PAYEE_AUTOCOMPLETE = 'acpy' }; class PayeeBox; -class PayeeBoxFilter : public AutoTextControlFilter -{ -public: +class PayeeBoxFilter : public AutoTextControlFilter { + public: PayeeBoxFilter(PayeeBox *box); filter_result KeyFilter(const int32 &key, const int32 &mod); }; -class PayeeBox : public AutoTextControl -{ -public: - PayeeBox(const char *name, const char *label, - const char *text, BMessage *msg, - uint32 flags = B_WILL_DRAW | B_NAVIGABLE); +class PayeeBox : public AutoTextControl { + public: + PayeeBox( + const char *name, const char *label, const char *text, BMessage *msg, + uint32 flags = B_WILL_DRAW | B_NAVIGABLE + ); + + bool Validate(const bool &showalert = true); - bool Validate(const bool &showalert=true); - -private: + private: friend PayeeBoxFilter; }; diff --git a/src/PrefWindow.cpp b/src/PrefWindow.cpp index ec54e1d..621301a 100644 --- a/src/PrefWindow.cpp +++ b/src/PrefWindow.cpp @@ -6,20 +6,19 @@ #include #include -#include "EscapeCancelFilter.h" #include "Database.h" +#include "EscapeCancelFilter.h" #include "Translate.h" // PrefWindow #define M_EDIT_OPTIONS 'edop' // PrefView -enum -{ - M_DMY_FORMAT='dmyf', +enum { + M_DMY_FORMAT = 'dmyf', M_MDY_FORMAT, M_NEW_DATE_SEPARATOR, - + M_NEW_CURRENCY_SYMBOL, M_NEW_CURRENCY_SEPARATOR, M_NEW_CURRENCY_DECIMAL, @@ -27,33 +26,32 @@ enum }; PrefWindow::PrefWindow(const BRect &frame) - : BWindow(frame,TRANSLATE("Options"),B_FLOATING_WINDOW_LOOK, - B_MODAL_APP_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) -{ + : BWindow( + frame, TRANSLATE("Options"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS + ) { BString temp; - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut('Q',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddCommonFilter(new EscapeCancelFilter()); - + BView *back = new BView(NULL, B_WILL_DRAW); - back->SetViewColor(240,240,240); - - temp = TRANSLATE("Default Account Settings"); temp += ":"; + back->SetViewColor(240, 240, 240); + + temp = TRANSLATE("Default Account Settings"); + temp += ":"; fLabel = new BStringView("windowlabel", temp.String()); fLabel->SetFont(be_bold_font); - - fDatePrefView = new DatePrefView("dateview",&gDefaultLocale); - fCurrencyPrefView = new CurrencyPrefView("dateview",&gDefaultLocale); - - fOK = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_EDIT_OPTIONS)); + fDatePrefView = new DatePrefView("dateview", &gDefaultLocale); + + fCurrencyPrefView = new CurrencyPrefView("dateview", &gDefaultLocale); + + fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_OPTIONS)); fOK->SetLabel(TRANSLATE("OK")); - - fCancel = new BButton("cancelbutton",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); - + + fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + SetDefaultButton(fOK); BLayoutBuilder::Group<>(back, B_VERTICAL, 0.0f) @@ -62,82 +60,72 @@ PrefWindow::PrefWindow(const BRect &frame) .Add(fDatePrefView) .Add(fCurrencyPrefView) .AddGrid(0.0f, 0.0f) - .AddGlue(0, 0) - .Add(fCancel, 1, 0) - .Add(fOK, 2, 0) + .AddGlue(0, 0) + .Add(fCancel, 1, 0) + .Add(fOK, 2, 0) .End() - .End(); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(back) - .End(); + .End(); + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(back).End(); } -void PrefWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_EDIT_OPTIONS: - { - Locale temp = gDefaultLocale; - fDatePrefView->GetSettings(temp); - fCurrencyPrefView->GetSettings(temp); - - if(temp != gDefaultLocale) - { - gDefaultLocale = temp; - gDatabase.SetDefaultLocale(gDefaultLocale); - } - PostMessage(B_QUIT_REQUESTED); - break; - } - default: - { - BWindow::MessageReceived(msg); - break; +void +PrefWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_EDIT_OPTIONS: { + Locale temp = gDefaultLocale; + fDatePrefView->GetSettings(temp); + fCurrencyPrefView->GetSettings(temp); + + if (temp != gDefaultLocale) { + gDefaultLocale = temp; + gDatabase.SetDefaultLocale(gDefaultLocale); } + PostMessage(B_QUIT_REQUESTED); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) - : BView(name,flags) -{ + : BView(name, flags) { BString temp; - SetViewColor(240,240,240); - - if(locale) + SetViewColor(240, 240, 240); + + if (locale) fLocale = *locale; else fLocale = gDefaultLocale; - + BBox *fDateBox = new BBox("DateBox"); fDateBox->SetLabel(TRANSLATE("Date")); - + BString datestr; - fLocale.DateToString(0,datestr); + fLocale.DateToString(0, datestr); temp = ""; temp << TRANSLATE("Date Format") << ": " << datestr; - fDateLabel = new BStringView("datelabel",temp.String()); - + fDateLabel = new BStringView("datelabel", temp.String()); + temp = ""; - temp << TRANSLATE("Month") << ", " << TRANSLATE("Day") << ", " - << TRANSLATE("Year"); - fDateMDY = new BRadioButton("mdybutton",temp.String(), - new BMessage(M_MDY_FORMAT)); - + temp << TRANSLATE("Month") << ", " << TRANSLATE("Day") << ", " << TRANSLATE("Year"); + fDateMDY = new BRadioButton("mdybutton", temp.String(), new BMessage(M_MDY_FORMAT)); + temp = ""; - temp << TRANSLATE("Day") << ", " << TRANSLATE("Month") << ", " - << TRANSLATE("Year"); - fDateDMY = new BRadioButton("dmybutton",temp.String(), - new BMessage(M_DMY_FORMAT)); - if(fLocale.DateFormat()==DATE_MDY) + temp << TRANSLATE("Day") << ", " << TRANSLATE("Month") << ", " << TRANSLATE("Year"); + fDateDMY = new BRadioButton("dmybutton", temp.String(), new BMessage(M_DMY_FORMAT)); + if (fLocale.DateFormat() == DATE_MDY) fDateMDY->SetValue(B_CONTROL_ON); else fDateDMY->SetValue(B_CONTROL_ON); - - temp = TRANSLATE("Separator"); temp += ":"; - fDateSeparatorBox = new AutoTextControl("datesep",temp.String(), - fLocale.DateSeparator(),new BMessage(M_NEW_DATE_SEPARATOR)); + + temp = TRANSLATE("Separator"); + temp += ":"; + fDateSeparatorBox = new AutoTextControl( + "datesep", temp.String(), fLocale.DateSeparator(), new BMessage(M_NEW_DATE_SEPARATOR) + ); fDateSeparatorBox->SetDivider(StringWidth(temp.String()) + 5); fDateSeparatorBox->SetCharacterLimit(2); @@ -148,195 +136,187 @@ DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) .Add(fDateMDY) .Add(fDateDMY) .Add(fDateSeparatorBox) - .End(); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .Add(fDateBox) - .End(); + .End(); + BLayoutBuilder::Group<>(this, B_VERTICAL).Add(fDateBox).End(); } -void DatePrefView::AttachedToWindow(void) -{ +void +DatePrefView::AttachedToWindow(void) { fDateMDY->SetTarget(this); fDateDMY->SetTarget(this); fDateSeparatorBox->SetTarget(this); } -void DatePrefView::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_DMY_FORMAT: - { - fLocale.SetDateFormat(DATE_DMY); - UpdateDateLabel(); - break; - } - case M_MDY_FORMAT: - { - fLocale.SetDateFormat(DATE_MDY); - UpdateDateLabel(); - break; - } - case M_NEW_DATE_SEPARATOR: - { - if(strlen(fDateSeparatorBox->Text())<1) - break; - - fLocale.SetDateSeparator(fDateSeparatorBox->Text()); - UpdateDateLabel(); - break; - } - default: - BView::MessageReceived(msg); +void +DatePrefView::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_DMY_FORMAT: { + fLocale.SetDateFormat(DATE_DMY); + UpdateDateLabel(); + break; + } + case M_MDY_FORMAT: { + fLocale.SetDateFormat(DATE_MDY); + UpdateDateLabel(); + break; + } + case M_NEW_DATE_SEPARATOR: { + if (strlen(fDateSeparatorBox->Text()) < 1) break; + + fLocale.SetDateSeparator(fDateSeparatorBox->Text()); + UpdateDateLabel(); + break; + } + default: + BView::MessageReceived(msg); + break; } } -void DatePrefView::UpdateDateLabel(void) -{ - BString temp,label; - fLocale.DateToString(0,temp); +void +DatePrefView::UpdateDateLabel(void) { + BString temp, label; + fLocale.DateToString(0, temp); label << TRANSLATE("Date Format") << ": " << temp; fDateLabel->SetText(label.String()); } -void DatePrefView::GetSettings(Locale &locale) -{ - if(strlen(fDateSeparatorBox->Text())>0) +void +DatePrefView::GetSettings(Locale &locale) { + if (strlen(fDateSeparatorBox->Text()) > 0) locale.SetDateSeparator(fDateSeparatorBox->Text()); - locale.SetDateFormat( (fDateDMY->Value()==B_CONTROL_ON) ? DATE_DMY : DATE_MDY ); + locale.SetDateFormat((fDateDMY->Value() == B_CONTROL_ON) ? DATE_DMY : DATE_MDY); } - -CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, - const int32 &flags) - : BView(name,flags), - fSampleAmount((long)12345678,true) -{ +CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 &flags) + : BView(name, flags), fSampleAmount((long)12345678, true) { BString temp; - SetViewColor(240,240,240); - - if(locale) + SetViewColor(240, 240, 240); + + if (locale) fLocale = *locale; else fLocale = gDefaultLocale; - + BBox *fCurrencyBox = new BBox("CurrencyBox"); fCurrencyBox->SetLabel(TRANSLATE("Currency")); - + BString curstr; - fLocale.CurrencyToString(fSampleAmount,curstr); + fLocale.CurrencyToString(fSampleAmount, curstr); temp = TRANSLATE("Currency Format"); temp << ": " << curstr; - fCurrencyLabel = new BStringView("datelabel",temp.String()); - - temp = TRANSLATE("Symbol"); temp += ":"; - fCurrencySymbolBox = new AutoTextControl("moneysym",temp.String(), - fLocale.CurrencySymbol(),new BMessage(M_NEW_CURRENCY_SYMBOL)); + fCurrencyLabel = new BStringView("datelabel", temp.String()); + + temp = TRANSLATE("Symbol"); + temp += ":"; + fCurrencySymbolBox = new AutoTextControl( + "moneysym", temp.String(), fLocale.CurrencySymbol(), new BMessage(M_NEW_CURRENCY_SYMBOL) + ); fCurrencySymbolBox->SetDivider(StringWidth(temp.String()) + 5); fCurrencySymbolBox->SetCharacterLimit(2); - fCurrencySymbolPrefix = new BCheckBox("prefixcheck", - TRANSLATE("Appears Before Amount"), - new BMessage(M_TOGGLE_PREFIX)); - fCurrencySymbolPrefix->SetValue( (fLocale.IsCurrencySymbolPrefix()) ? - B_CONTROL_ON : B_CONTROL_OFF ); + fCurrencySymbolPrefix = new BCheckBox( + "prefixcheck", TRANSLATE("Appears Before Amount"), new BMessage(M_TOGGLE_PREFIX) + ); + fCurrencySymbolPrefix->SetValue( + (fLocale.IsCurrencySymbolPrefix()) ? B_CONTROL_ON : B_CONTROL_OFF + ); - temp = TRANSLATE("Separator"); temp += ":"; - fCurrencySeparatorBox = new AutoTextControl("moneysep",temp.String(), - fLocale.CurrencySeparator(),new BMessage(M_NEW_CURRENCY_SEPARATOR)); + temp = TRANSLATE("Separator"); + temp += ":"; + fCurrencySeparatorBox = new AutoTextControl( + "moneysep", temp.String(), fLocale.CurrencySeparator(), + new BMessage(M_NEW_CURRENCY_SEPARATOR) + ); fCurrencySeparatorBox->SetDivider(StringWidth(temp.String()) + 5); fCurrencySeparatorBox->SetCharacterLimit(2); - - temp = TRANSLATE("Decimal"); temp += ":"; - fCurrencyDecimalBox = new AutoTextControl("moneydecimal",temp.String(), - fLocale.CurrencyDecimal(),new BMessage(M_NEW_CURRENCY_DECIMAL)); + + temp = TRANSLATE("Decimal"); + temp += ":"; + fCurrencyDecimalBox = new AutoTextControl( + "moneydecimal", temp.String(), fLocale.CurrencyDecimal(), + new BMessage(M_NEW_CURRENCY_DECIMAL) + ); fCurrencyDecimalBox->SetDivider(StringWidth(temp.String()) + 5); - fCurrencyDecimalBox->SetCharacterLimit(2); + fCurrencyDecimalBox->SetCharacterLimit(2); BFont font; BLayoutBuilder::Group<>(fCurrencyBox, B_VERTICAL, 0.0f) .SetInsets(10, font.Size() * 1.3, 10, 10) .Add(fCurrencyLabel) .AddGrid(1.0f, 1.0f) - .Add(fCurrencySymbolBox, 0, 0) - .Add(fCurrencySymbolPrefix, 1, 0) - .Add(fCurrencySeparatorBox, 0, 1) - .Add(fCurrencyDecimalBox, 1, 1) + .Add(fCurrencySymbolBox, 0, 0) + .Add(fCurrencySymbolPrefix, 1, 0) + .Add(fCurrencySeparatorBox, 0, 1) + .Add(fCurrencyDecimalBox, 1, 1) .End() - .End(); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .Add(fCurrencyBox) - .End(); + .End(); + BLayoutBuilder::Group<>(this, B_VERTICAL).Add(fCurrencyBox).End(); } -void CurrencyPrefView::AttachedToWindow(void) -{ +void +CurrencyPrefView::AttachedToWindow(void) { fCurrencySymbolBox->SetTarget(this); fCurrencyDecimalBox->SetTarget(this); fCurrencySeparatorBox->SetTarget(this); fCurrencySymbolPrefix->SetTarget(this); } -void CurrencyPrefView::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_NEW_CURRENCY_SYMBOL: - { - if(strlen(fCurrencySymbolBox->Text())<1) - break; - - fLocale.SetCurrencySymbol(fCurrencySymbolBox->Text()); - UpdateCurrencyLabel(); - break; - } - case M_NEW_CURRENCY_SEPARATOR: - { - if(strlen(fCurrencySeparatorBox->Text())<1) - break; - - fLocale.SetCurrencySeparator(fCurrencySeparatorBox->Text()); - UpdateCurrencyLabel(); +void +CurrencyPrefView::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_NEW_CURRENCY_SYMBOL: { + if (strlen(fCurrencySymbolBox->Text()) < 1) break; - } - case M_NEW_CURRENCY_DECIMAL: - { - if(strlen(fCurrencyDecimalBox->Text())<1) - break; - - fLocale.SetCurrencyDecimal(fCurrencyDecimalBox->Text()); - UpdateCurrencyLabel(); - break; - } - case M_TOGGLE_PREFIX: - { - fLocale.SetCurrencySymbolPrefix(fCurrencySymbolPrefix->Value()==B_CONTROL_ON); - UpdateCurrencyLabel(); + + fLocale.SetCurrencySymbol(fCurrencySymbolBox->Text()); + UpdateCurrencyLabel(); + break; + } + case M_NEW_CURRENCY_SEPARATOR: { + if (strlen(fCurrencySeparatorBox->Text()) < 1) break; - } - default: - BView::MessageReceived(msg); + + fLocale.SetCurrencySeparator(fCurrencySeparatorBox->Text()); + UpdateCurrencyLabel(); + break; + } + case M_NEW_CURRENCY_DECIMAL: { + if (strlen(fCurrencyDecimalBox->Text()) < 1) break; + + fLocale.SetCurrencyDecimal(fCurrencyDecimalBox->Text()); + UpdateCurrencyLabel(); + break; + } + case M_TOGGLE_PREFIX: { + fLocale.SetCurrencySymbolPrefix(fCurrencySymbolPrefix->Value() == B_CONTROL_ON); + UpdateCurrencyLabel(); + break; + } + default: + BView::MessageReceived(msg); + break; } } -void CurrencyPrefView::UpdateCurrencyLabel(void) -{ - BString temp,label; - fLocale.CurrencyToString(fSampleAmount,temp); +void +CurrencyPrefView::UpdateCurrencyLabel(void) { + BString temp, label; + fLocale.CurrencyToString(fSampleAmount, temp); label << TRANSLATE("Currency Format") << ": " << temp; fCurrencyLabel->SetText(label.String()); } -void CurrencyPrefView::GetSettings(Locale &locale) -{ - if(strlen(fCurrencySeparatorBox->Text())>0) +void +CurrencyPrefView::GetSettings(Locale &locale) { + if (strlen(fCurrencySeparatorBox->Text()) > 0) locale.SetCurrencySeparator(fCurrencySeparatorBox->Text()); - if(strlen(fCurrencyDecimalBox->Text())>0) + if (strlen(fCurrencyDecimalBox->Text()) > 0) locale.SetCurrencyDecimal(fCurrencyDecimalBox->Text()); - if(strlen(fCurrencySymbolBox->Text())>0) + if (strlen(fCurrencySymbolBox->Text()) > 0) locale.SetCurrencySymbol(fCurrencySymbolBox->Text()); - - locale.SetCurrencySymbolPrefix(fCurrencySymbolPrefix->Value()==B_CONTROL_ON); + + locale.SetCurrencySymbolPrefix(fCurrencySymbolPrefix->Value() == B_CONTROL_ON); } diff --git a/src/PrefWindow.h b/src/PrefWindow.h index 2b4aa35..a1e332a 100644 --- a/src/PrefWindow.h +++ b/src/PrefWindow.h @@ -12,67 +12,59 @@ #include #include "AutoTextControl.h" -#include "Fixed.h" #include "CBLocale.h" +#include "Fixed.h" class DatePrefView; class CurrencyPrefView; -class PrefWindow : public BWindow -{ -public: +class PrefWindow : public BWindow { + public: PrefWindow(const BRect &frame); void MessageReceived(BMessage *msg); -private: - DatePrefView *fDatePrefView; - CurrencyPrefView *fCurrencyPrefView; - BButton *fOK, *fCancel; - BStringView *fLabel; + private: + DatePrefView *fDatePrefView; + CurrencyPrefView *fCurrencyPrefView; + BButton *fOK, *fCancel; + BStringView *fLabel; }; -class DatePrefView : public BView -{ -public: - DatePrefView(const char *name, Locale *locale = NULL, - const int32 &flags = B_WILL_DRAW); +class DatePrefView : public BView { + public: + DatePrefView(const char *name, Locale *locale = NULL, const int32 &flags = B_WILL_DRAW); void AttachedToWindow(void); void MessageReceived(BMessage *msg); - + void GetSettings(Locale &locale); - -private: + + private: void UpdateDateLabel(void); - - BStringView *fDateLabel; - BRadioButton *fDateMDY, - *fDateDMY; - AutoTextControl *fDateSeparatorBox; - - Locale fLocale; + + BStringView *fDateLabel; + BRadioButton *fDateMDY, *fDateDMY; + AutoTextControl *fDateSeparatorBox; + + Locale fLocale; }; -class CurrencyPrefView : public BView -{ -public: - CurrencyPrefView(const char *name, Locale *locale = NULL, - const int32 &flags = B_WILL_DRAW); +class CurrencyPrefView : public BView { + public: + CurrencyPrefView(const char *name, Locale *locale = NULL, const int32 &flags = B_WILL_DRAW); void AttachedToWindow(void); void MessageReceived(BMessage *msg); - + void GetSettings(Locale &locale); - -private: + + private: void UpdateCurrencyLabel(void); - - BStringView *fCurrencyLabel; - AutoTextControl *fCurrencySymbolBox, - *fCurrencyDecimalBox, - *fCurrencySeparatorBox; - BCheckBox *fCurrencySymbolPrefix; - - Locale fLocale; - Fixed fSampleAmount; + + BStringView *fCurrencyLabel; + AutoTextControl *fCurrencySymbolBox, *fCurrencyDecimalBox, *fCurrencySeparatorBox; + BCheckBox *fCurrencySymbolPrefix; + + Locale fLocale; + Fixed fSampleAmount; }; #endif diff --git a/src/Preferences.cpp b/src/Preferences.cpp index 757a92f..08fbab3 100644 --- a/src/Preferences.cpp +++ b/src/Preferences.cpp @@ -1,145 +1,135 @@ #include "Preferences.h" +#include +#include +#include +#include #include -#include -#include #include +#include #include -#include -#include -#include -#include +#include BLocker prefsLock; BMessage gPreferences; BString gAppPath; -static rgb_color sSelectionFocusColor={205,205,255,255}; -static rgb_color sSelectionNoFocusColor={205,205,230,255}; -static rgb_color sGridHeaderColor={225,225,255,255}; +static rgb_color sSelectionFocusColor = {205, 205, 255, 255}; +static rgb_color sSelectionNoFocusColor = {205, 205, 230, 255}; +static rgb_color sGridHeaderColor = {225, 225, 255, 255}; -void ConstrainWindowFrameToScreen(BRect *rect) -{ - if(!rect) +void +ConstrainWindowFrameToScreen(BRect *rect) { + if (!rect) return; - + // Even though we have the proper settings, we're going to make sure that // the whole window can be seen on screen. BRect screenframe = BScreen().Frame(); - + // make sure that the top left corner is actually on the screen int32 xoff = 0, yoff = 0; - if(rect->left < 0) - xoff = (int32) (0-rect->left) + 5; - if(rect->top < 0) - yoff = (int32) (0-rect->top) + 15; - rect->OffsetBy(xoff,yoff); - + if (rect->left < 0) + xoff = (int32)(0 - rect->left) + 5; + if (rect->top < 0) + yoff = (int32)(0 - rect->top) + 15; + rect->OffsetBy(xoff, yoff); + // If either dimension is too large for the screen, we move and resize the rect so // that it occupies the screen in that dimension - if(rect->Width() > screenframe.Width()) - { + if (rect->Width() > screenframe.Width()) { rect->left = 5; rect->right = screenframe.right - 5; } - - if(rect->Height() > screenframe.Height()) - { + + if (rect->Height() > screenframe.Height()) { // We set top to 15 to account for the window tab rect->top = 15; rect->bottom = screenframe.bottom - 5; } - - if(rect->right > screenframe.right) + + if (rect->right > screenframe.right) rect->right = screenframe.right - 5; - - if(rect->bottom > screenframe.bottom) + + if (rect->bottom > screenframe.bottom) rect->bottom = screenframe.bottom - 5; } -status_t SavePreferences(const char *path) -{ - if(!path) +status_t +SavePreferences(const char *path) { + if (!path) return B_ERROR; - + prefsLock.Lock(); - - BFile file(path,B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); - - status_t status=file.InitCheck(); - if(status!=B_OK) - { + + BFile file(path, B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); + + status_t status = file.InitCheck(); + if (status != B_OK) { prefsLock.Unlock(); return status; } - - status=gPreferences.Flatten(&file); + + status = gPreferences.Flatten(&file); prefsLock.Unlock(); return status; } -status_t LoadPreferences(const char *path) -{ - if(!path) +status_t +LoadPreferences(const char *path) { + if (!path) return B_ERROR; - + prefsLock.Lock(); - + app_info ai; be_app->GetAppInfo(&ai); - + BEntry entry(&ai.ref); entry_ref ref; BEntry parent; - + entry.GetParent(&parent); parent.GetRef(&ref); BPath pathobj(&ref); gAppPath = pathobj.Path(); gAppPath += "/"; - - BFile file(path,B_READ_ONLY); + + BFile file(path, B_READ_ONLY); BMessage msg; - - status_t status=file.InitCheck(); - if(status!=B_OK) - { + + status_t status = file.InitCheck(); + if (status != B_OK) { prefsLock.Unlock(); return status; } - - status=msg.Unflatten(&file); - if(status==B_OK) - gPreferences=msg; - + + status = msg.Unflatten(&file); + if (status == B_OK) + gPreferences = msg; + prefsLock.Unlock(); return status; - } -rgb_color GetColor(const CapitalBeColor &color) -{ - rgb_color returncolor={0,0,0,0}; - - switch(color) - { - case BC_SELECTION_NOFOCUS: - { - returncolor = sSelectionNoFocusColor; - break; - } - case BC_SELECTION_FOCUS: - { - returncolor = sSelectionFocusColor; - break; - } - case BC_GRID_HEADER: - { - returncolor = sGridHeaderColor; - } - default: - break; +rgb_color +GetColor(const CapitalBeColor &color) { + rgb_color returncolor = {0, 0, 0, 0}; + + switch (color) { + case BC_SELECTION_NOFOCUS: { + returncolor = sSelectionNoFocusColor; + break; + } + case BC_SELECTION_FOCUS: { + returncolor = sSelectionFocusColor; + break; + } + case BC_GRID_HEADER: { + returncolor = sGridHeaderColor; + } + default: + break; } return returncolor; } - diff --git a/src/Preferences.h b/src/Preferences.h index 6ca0f03..899f560 100644 --- a/src/Preferences.h +++ b/src/Preferences.h @@ -1,12 +1,12 @@ #ifndef PREFERENCES_H_ #define PREFERENCES_H_ +#include "Fixed.h" +#include +#include #include #include -#include #include -#include -#include "Fixed.h" extern BLocker prefsLock; extern BMessage gPreferences; @@ -14,18 +14,17 @@ extern BString gAppPath; #define PREFERENCES_PATH "/boot/home/config/settings/CapitalBe" -status_t SavePreferences(const char *path); -status_t LoadPreferences(const char *path); +status_t +SavePreferences(const char *path); +status_t +LoadPreferences(const char *path); -void ConstrainWindowFrameToScreen(BRect *rect); +void +ConstrainWindowFrameToScreen(BRect *rect); -typedef enum -{ - BC_SELECTION_FOCUS=0, - BC_SELECTION_NOFOCUS, - BC_GRID_HEADER -} CapitalBeColor; +typedef enum { BC_SELECTION_FOCUS = 0, BC_SELECTION_NOFOCUS, BC_GRID_HEADER } CapitalBeColor; -rgb_color GetColor(const CapitalBeColor &color); +rgb_color +GetColor(const CapitalBeColor &color); #endif diff --git a/src/QuickTrackerItem.cpp b/src/QuickTrackerItem.cpp index db967b7..9a2d80a 100644 --- a/src/QuickTrackerItem.cpp +++ b/src/QuickTrackerItem.cpp @@ -1,133 +1,117 @@ #include "QuickTrackerItem.h" -#include -#include "Fixed.h" +#include "Account.h" #include "CBLocale.h" #include "Database.h" -#include "Account.h" +#include "Fixed.h" #include "Translate.h" +#include // Calculates the user's net worth by adding up the balances of all accounts QTNetWorthItem::QTNetWorthItem(const char *name, uint32 flags) - : QuickTrackerItem(name,flags), - fIgnore(false) -{ - for(int32 i=0; iAddObserver(this); } } -QTNetWorthItem::~QTNetWorthItem(void) -{ - for(int32 i=0; iRemoveObserver(this); } } -void QTNetWorthItem::AttachedToWindow(void) -{ +void +QTNetWorthItem::AttachedToWindow(void) { QuickTrackerItem::AttachedToWindow(); Calculate(); } -void QTNetWorthItem::SetObserving(const bool &value) -{ - if(IsObserving()!=value) - { +void +QTNetWorthItem::SetObserving(const bool &value) { + if (IsObserving() != value) { Observer::SetObserving(value); Calculate(); } } -void QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) -{ -/* - TODO: Make QTNetWorthItem ignore mass edits - if(value & WATCH_MASS_EDIT) - { - // Something which will massively change the database will happen. We will - // receive two of them, so we will start ignoring when we receive the first - // one and stop the second time. We do this because each call to Calculate - // resultes in a hit on the database for each account - fIgnore = !fIgnore; - } - - if(fIgnore) - return; -*/ - if(value & WATCH_ACCOUNT) - { +void +QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) { + /* + TODO: Make QTNetWorthItem ignore mass edits + if(value & WATCH_MASS_EDIT) + { + // Something which will massively change the database will happen. We will + // receive two of them, so we will start ignoring when we receive the first + // one and stop the second time. We do this because each call to Calculate + // resultes in a hit on the database for each account + fIgnore = !fIgnore; + } + + if(fIgnore) + return; + */ + if (value & WATCH_ACCOUNT) { Account *acc = NULL; - if(msg->FindPointer("item",(void**)&acc)!=B_OK) + if (msg->FindPointer("item", (void **)&acc) != B_OK) return; - - if(value & WATCH_CREATE) - { + + if (value & WATCH_CREATE) { acc->AddObserver(this); - } - else - if(value & WATCH_DELETE) - { + } else if (value & WATCH_DELETE) { acc->RemoveObserver(this); - if(gDatabase.CountAccounts()==1) - { - if(Window()) + if (gDatabase.CountAccounts() == 1) { + if (Window()) Window()->Lock(); - - BString label,temp; + + BString label, temp; temp << TRANSLATE("Account Total") << ": "; - if(gCurrentLocale.CurrencyToString(Fixed(),label)==B_OK) + if (gCurrentLocale.CurrencyToString(Fixed(), label) == B_OK) temp << label; SetText(temp.String()); - - if(Window()) + + if (Window()) Window()->Unlock(); return; } } } - if(!(value & WATCH_SELECT)) + if (!(value & WATCH_SELECT)) Calculate(); } -void QTNetWorthItem::Calculate(void) -{ - BString label,temp; +void +QTNetWorthItem::Calculate(void) { + BString label, temp; Fixed balance; - + temp << TRANSLATE("Account Total") << ": "; - - if(gDatabase.CountAccounts() == 0) - { - if(Window()) + + if (gDatabase.CountAccounts() == 0) { + if (Window()) Window()->Lock(); - - if(gCurrentLocale.CurrencyToString(balance,label)==B_OK) + + if (gCurrentLocale.CurrencyToString(balance, label) == B_OK) temp << " \n" << label; - + SetText(temp.String()); - - if(Window()) + + if (Window()) Window()->Unlock(); return; } - - for(int32 i=0; iIsClosed()) + if (!account->IsClosed()) balance += account->Balance(); } - - if(gDefaultLocale.CurrencyToString(balance,label)==B_OK) - { + + if (gDefaultLocale.CurrencyToString(balance, label) == B_OK) { temp << " \n" << label; - - if(Window()) - { + + if (Window()) { Window()->Lock(); SetText(label.String()); Invalidate(); @@ -137,108 +121,93 @@ void QTNetWorthItem::Calculate(void) } // Calculates the budget variance for one category -QTBudgetCategoryItem::QTBudgetCategoryItem(const char *category, - const char *name, uint32 flags) - : QuickTrackerItem(name,flags), - fIgnore(false) -{ - for(int32 i=0; iAddObserver(this); } - - gDatabase.GetBudgetEntry(category,fEntry); + + gDatabase.GetBudgetEntry(category, fEntry); } -QTBudgetCategoryItem::~QTBudgetCategoryItem(void) -{ - for(int32 i=0; iRemoveObserver(this); } } -void QTBudgetCategoryItem::AttachedToWindow(void) -{ +void +QTBudgetCategoryItem::AttachedToWindow(void) { QuickTrackerItem::AttachedToWindow(); Calculate(); } -void QTBudgetCategoryItem::SetObserving(const bool &value) -{ - if(IsObserving()!=value) - { +void +QTBudgetCategoryItem::SetObserving(const bool &value) { + if (IsObserving() != value) { Observer::SetObserving(value); Calculate(); } } -void QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) -{ -/* - TODO: Make QTBudgetCategoryItem ignore mass edits - if(value & WATCH_MASS_EDIT) - { - // Something which will massively change the database will happen. We will - // receive two of them, so we will start ignoring when we receive the first - // one and stop the second time. We do this because each call to Calculate - // resultes in a hit on the database for each account - fIgnore = !fIgnore; - } - - if(fIgnore) - return; -*/ - if(value & WATCH_ACCOUNT) - { +void +QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) { + /* + TODO: Make QTBudgetCategoryItem ignore mass edits + if(value & WATCH_MASS_EDIT) + { + // Something which will massively change the database will happen. We will + // receive two of them, so we will start ignoring when we receive the first + // one and stop the second time. We do this because each call to Calculate + // resultes in a hit on the database for each account + fIgnore = !fIgnore; + } + + if(fIgnore) + return; + */ + if (value & WATCH_ACCOUNT) { Account *acc = NULL; - if(msg->FindPointer("item",(void**)&acc)!=B_OK) + if (msg->FindPointer("item", (void **)&acc) != B_OK) return; - - if(value & WATCH_CREATE) - { + + if (value & WATCH_CREATE) { acc->AddObserver(this); - } - else - if(value & WATCH_DELETE) - { + } else if (value & WATCH_DELETE) { acc->RemoveObserver(this); - if(gDatabase.CountAccounts()==1) - { - if(Window()) + if (gDatabase.CountAccounts() == 1) { + if (Window()) Window()->Lock(); - - BString label,temp; + + BString label, temp; temp << TRANSLATE("Account Total") << ": "; - if(gCurrentLocale.CurrencyToString(Fixed(),label)==B_OK) + if (gCurrentLocale.CurrencyToString(Fixed(), label) == B_OK) temp << label; SetText(temp.String()); - - if(Window()) + + if (Window()) Window()->Unlock(); return; } } } - if(!(value & WATCH_SELECT)) + if (!(value & WATCH_SELECT)) Calculate(); } -void QTBudgetCategoryItem::Calculate(void) -{ - BString label,temp; +void +QTBudgetCategoryItem::Calculate(void) { + BString label, temp; Fixed variance; - + temp << TRANSLATE("Budget") << ": " << fEntry.name; - - if(gDefaultLocale.CurrencyToString(variance,label)==B_OK) - { + + if (gDefaultLocale.CurrencyToString(variance, label) == B_OK) { temp << " \n" << label; - - if(Window()) - { + + if (Window()) { Window()->Lock(); SetText(label.String()); Invalidate(); @@ -247,31 +216,25 @@ void QTBudgetCategoryItem::Calculate(void) } } -QuickTrackerItem::QuickTrackerItem(const char *name, uint32 flags) - : BTextView(name,flags) -{ +QuickTrackerItem::QuickTrackerItem(const char *name, uint32 flags) : BTextView(name, flags) { MakeEditable(false); MakeSelectable(false); gDatabase.AddObserver(this); } +QuickTrackerItem::~QuickTrackerItem(void) { gDatabase.RemoveObserver(this); } -QuickTrackerItem::~QuickTrackerItem(void) -{ - gDatabase.RemoveObserver(this); -} - -void QuickTrackerItem::AttachedToWindow(void) -{ +void +QuickTrackerItem::AttachedToWindow(void) { SetViewColor(Parent()->ViewColor()); } -void QuickTrackerItem::HandleNotify(const uint64 &value, const BMessage *msg) -{ +void +QuickTrackerItem::HandleNotify(const uint64 &value, const BMessage *msg) { // Does nothing by default - hook function for child classes } -void QuickTrackerItem::Configure(void) -{ +void +QuickTrackerItem::Configure(void) { // Does nothing by default - hook function for child classes } diff --git a/src/QuickTrackerItem.h b/src/QuickTrackerItem.h index e936b88..c09f108 100644 --- a/src/QuickTrackerItem.h +++ b/src/QuickTrackerItem.h @@ -1,47 +1,43 @@ #ifndef QTITEM_H #define QTITEM_H -#include -#include "Notifier.h" #include "Budget.h" +#include "Notifier.h" +#include -class QuickTrackerItem : public BTextView, public Observer -{ -public: - QuickTrackerItem(const char *name,uint32 flags = B_WILL_DRAW); +class QuickTrackerItem : public BTextView, public Observer { + public: + QuickTrackerItem(const char *name, uint32 flags = B_WILL_DRAW); virtual ~QuickTrackerItem(void); - + virtual void HandleNotify(const uint64 &value, const BMessage *msg); virtual void Configure(void); virtual void AttachedToWindow(void); }; -class QTNetWorthItem : public QuickTrackerItem -{ -public: +class QTNetWorthItem : public QuickTrackerItem { + public: QTNetWorthItem(const char *name, uint32 flags = B_WILL_DRAW); ~QTNetWorthItem(void); - + void HandleNotify(const uint64 &value, const BMessage *msg); void AttachedToWindow(void); void SetObserving(const bool &value); - -protected: + + protected: void Calculate(void); bool fIgnore; }; -class QTBudgetCategoryItem : public QuickTrackerItem -{ -public: - QTBudgetCategoryItem(const char *category, const char *name, - uint32 flags = B_WILL_DRAW); +class QTBudgetCategoryItem : public QuickTrackerItem { + public: + QTBudgetCategoryItem(const char *category, const char *name, uint32 flags = B_WILL_DRAW); ~QTBudgetCategoryItem(void); void HandleNotify(const uint64 &value, const BMessage *msg); void AttachedToWindow(void); void SetObserving(const bool &value); - -protected: + + protected: void Calculate(void); bool fIgnore; BudgetEntry fEntry; diff --git a/src/ReconcileItem.cpp b/src/ReconcileItem.cpp index c03e472..dd03a59 100644 --- a/src/ReconcileItem.cpp +++ b/src/ReconcileItem.cpp @@ -1,91 +1,81 @@ -#include -#include -#include -#include -#include -#include "CBLocale.h" +#include "ReconcileItem.h" #include "Account.h" -#include "Preferences.h" +#include "CBLocale.h" +#include "Category.h" #include "Database.h" #include "MainWindow.h" -#include "Category.h" -#include "ReconcileItem.h" -#include "TransactionLayout.h" +#include "Preferences.h" #include "TransactionData.h" +#include "TransactionLayout.h" +#include +#include +#include +#include +#include - -ReconcileItem::ReconcileItem(const TransactionData &trans) - : BStringItem(""), - fTransaction(trans) -{ +ReconcileItem::ReconcileItem(const TransactionData &trans) : BStringItem(""), fTransaction(trans) { fValue = fTransaction.Status(); } -ReconcileItem::~ReconcileItem(void) -{ -} +ReconcileItem::~ReconcileItem(void) {} -void ReconcileItem::DrawItem(BView *owner, BRect frame, bool complete) -{ - if(IsSelected()) - { +void +ReconcileItem::DrawItem(BView *owner, BRect frame, bool complete) { + if (IsSelected()) { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); - } - else - { + } else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); } owner->FillRect(frame); - if(IsSelected()) - { + if (IsSelected()) { owner->SetHighColor(100, 100, 100); owner->StrokeRect(frame); } - - if(IsReconciled()) + + if (IsReconciled()) owner->SetFont(be_bold_font); else owner->SetFont(be_plain_font); - - owner->SetHighColor(0,0,0); - + + owner->SetHighColor(0, 0, 0); + // Draw amount first BString string; - - if(fTransaction.Amount().IsNegative()) - gCurrentLocale.CurrencyToString(fTransaction.Amount().InvertAsCopy(),string); + + if (fTransaction.Amount().IsNegative()) + gCurrentLocale.CurrencyToString(fTransaction.Amount().InvertAsCopy(), string); else - gCurrentLocale.CurrencyToString(fTransaction.Amount(),string); - + gCurrentLocale.CurrencyToString(fTransaction.Amount(), string); + float width = owner->StringWidth(string.String()); - owner->DrawString(string.String(),BPoint(frame.right - width, frame.bottom)); - - + owner->DrawString(string.String(), BPoint(frame.right - width, frame.bottom)); + + // Draw Payee next BRect r(frame); r.right -= width + 5; BRegion region(r); owner->ConstrainClippingRegion(®ion); - owner->DrawString(fTransaction.Payee(),BPoint(frame.left+1,frame.bottom-2)); + owner->DrawString(fTransaction.Payee(), BPoint(frame.left + 1, frame.bottom - 2)); owner->ConstrainClippingRegion(NULL); } -void ReconcileItem::SetReconciled(bool value) -{ - fTransaction.SetStatus( value ? TRANS_RECONCILED : TRANS_OPEN ); +void +ReconcileItem::SetReconciled(bool value) { + fTransaction.SetStatus(value ? TRANS_RECONCILED : TRANS_OPEN); } -bool ReconcileItem::IsReconciled(void) const -{ - return (fTransaction.Status()==TRANS_RECONCILED); +bool +ReconcileItem::IsReconciled(void) const { + return (fTransaction.Status() == TRANS_RECONCILED); } -void ReconcileItem::SyncToTransaction(void) -{ - if(fTransaction.Status()==TRANS_RECONCILED) - gDatabase.SetTransactionStatus(fTransaction.GetID(),TRANS_RECONCILED); +void +ReconcileItem::SyncToTransaction(void) { + if (fTransaction.Status() == TRANS_RECONCILED) + gDatabase.SetTransactionStatus(fTransaction.GetID(), TRANS_RECONCILED); else - gDatabase.SetTransactionStatus(fTransaction.GetID(),TRANS_OPEN); + gDatabase.SetTransactionStatus(fTransaction.GetID(), TRANS_OPEN); } diff --git a/src/ReconcileItem.h b/src/ReconcileItem.h index 7bf9d9d..da817ed 100644 --- a/src/ReconcileItem.h +++ b/src/ReconcileItem.h @@ -5,19 +5,22 @@ class TransactionData; -class ReconcileItem : public BStringItem -{ -public: +class ReconcileItem : public BStringItem { + public: ReconcileItem(const TransactionData &trans); ~ReconcileItem(void); void DrawItem(BView *owner, BRect frame, bool complete = false); + TransactionData *GetTransaction(void) { return &fTransaction; } + void SetReconciled(bool value); bool IsReconciled(void) const; - + void SyncToTransaction(void); + void RevertTransaction(void) { fTransaction.SetStatus(TRANS_OPEN); } -private: + + private: TransactionData fTransaction; uint8 fValue; }; diff --git a/src/ReconcileWindow.cpp b/src/ReconcileWindow.cpp index 317defe..6750dbc 100644 --- a/src/ReconcileWindow.cpp +++ b/src/ReconcileWindow.cpp @@ -1,24 +1,23 @@ #include -#include -#include #include +#include +#include +#include "CBLocale.h" #include "CurrencyBox.h" #include "DAlert.h" #include "Database.h" #include "DateBox.h" -#include "CBLocale.h" #include "MsgDefs.h" -#include "ReconcileWindow.h" -#include "ReconcileItem.h" #include "Preferences.h" +#include "ReconcileItem.h" +#include "ReconcileWindow.h" #include "TimeSupport.h" #include "Transaction.h" #include "Translate.h" -enum -{ - M_TOGGLE_DEPOSIT='tgdp', +enum { + M_TOGGLE_DEPOSIT = 'tgdp', M_TOGGLE_CHECK, M_TOGGLE_CHARGE, M_SET_BALANCES, @@ -41,593 +40,534 @@ class ReconcileFilter : public BMessageFilter */ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) - : BWindow(frame,"",B_DOCUMENT_WINDOW_LOOK,B_NORMAL_WINDOW_FEEL,B_NOT_MINIMIZABLE | - B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) -{ + : BWindow( + frame, "", B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, + B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS + ) { BString temp; fCurrentDate = GetCurrentDate(); -// AddCommonFilter(new ReconcileFilter(this)); + // AddCommonFilter(new ReconcileFilter(this)); - if(account) - { + if (account) { temp = TRANSLATE("Reconcile"); temp << ": " << account->Name(); SetTitle(temp.String()); gDatabase.AddObserver(this); } fAccount = account; - - - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut('Q',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - - BView *back = new BView("backview",B_WILL_DRAW); - back->SetViewColor(240,240,240); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(back) - .End(); - - temp = TRANSLATE("Date"); temp += ":"; + + + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + + BView *back = new BView("backview", B_WILL_DRAW); + back->SetViewColor(240, 240, 240); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); + + temp = TRANSLATE("Date"); + temp += ":"; float width = back->StringWidth(temp.String()); - + BString datestr; - gDefaultLocale.DateToString(GetCurrentDate(),datestr); - fDate = new DateBox("dateentry",temp.String(),datestr.String(),NULL); + gDefaultLocale.DateToString(GetCurrentDate(), datestr); + fDate = new DateBox("dateentry", temp.String(), datestr.String(), NULL); fDate->GetFilter()->SetMessenger(new BMessenger(this)); - - - temp = TRANSLATE("Starting Balance"); temp += ": "; - fOpening = new CurrencyBox("starting",temp.String(),NULL,new BMessage(M_SET_BALANCES)); + + + temp = TRANSLATE("Starting Balance"); + temp += ": "; + fOpening = new CurrencyBox("starting", temp.String(), NULL, new BMessage(M_SET_BALANCES)); fOpening->GetFilter()->SetMessenger(new BMessenger(this)); - - temp = TRANSLATE("Ending Balance"); temp += ":"; - fClosing = new CurrencyBox("closing",temp.String(),NULL, - new BMessage(M_SET_BALANCES)); + + temp = TRANSLATE("Ending Balance"); + temp += ":"; + fClosing = new CurrencyBox("closing", temp.String(), NULL, new BMessage(M_SET_BALANCES)); fClosing->GetFilter()->SetMessenger(new BMessenger(this)); - - temp = TRANSLATE("Bank Charges"); temp += ":"; - fCharges = new CurrencyBox("charges",temp.String(),NULL,NULL); + + temp = TRANSLATE("Bank Charges"); + temp += ":"; + fCharges = new CurrencyBox("charges", temp.String(), NULL, NULL); fCharges->GetFilter()->SetMessenger(new BMessenger(this)); - - temp = TRANSLATE("Interest Earned"); temp += ":"; - fInterest = new CurrencyBox("interest",temp.String(),NULL,NULL); + + temp = TRANSLATE("Interest Earned"); + temp += ":"; + fInterest = new CurrencyBox("interest", temp.String(), NULL, NULL); fInterest->GetFilter()->SetMessenger(new BMessenger(this)); - - fDepositList = new BListView("depositlist",B_SINGLE_SELECTION_LIST); + + fDepositList = new BListView("depositlist", B_SINGLE_SELECTION_LIST); fDepositList->SetFlags(fDepositList->Flags() | B_FULL_UPDATE_ON_RESIZE); fDepositList->SetInvocationMessage(new BMessage(M_TOGGLE_DEPOSIT)); - fDepScroll = new BScrollView("fDepScroll",fDepositList,0,false,true); + fDepScroll = new BScrollView("fDepScroll", fDepositList, 0, false, true); fDepScroll->SetViewColor(back->ViewColor()); - - fCheckList = new BListView("checklist",B_SINGLE_SELECTION_LIST); + + fCheckList = new BListView("checklist", B_SINGLE_SELECTION_LIST); fCheckList->SetFlags(fDepositList->Flags() | B_FULL_UPDATE_ON_RESIZE); fCheckList->SetInvocationMessage(new BMessage(M_TOGGLE_CHECK)); - fCheckScroll = new BScrollView("fCheckScroll",fCheckList,0,false,true); + fCheckScroll = new BScrollView("fCheckScroll", fCheckList, 0, false, true); fCheckScroll->SetViewColor(back->ViewColor()); - - fChargeList = new BListView("chargelist",B_SINGLE_SELECTION_LIST); + + fChargeList = new BListView("chargelist", B_SINGLE_SELECTION_LIST); fChargeList->SetFlags(fDepositList->Flags() | B_FULL_UPDATE_ON_RESIZE); fChargeList->SetInvocationMessage(new BMessage(M_TOGGLE_CHARGE)); - fChargeScroll = new BScrollView("fChargeScroll",fChargeList,0,false,true); + fChargeScroll = new BScrollView("fChargeScroll", fChargeList, 0, false, true); fChargeScroll->SetViewColor(back->ViewColor()); - + BString label; - - gCurrentLocale.CurrencyToString(fDepositTotal,label); + + gCurrentLocale.CurrencyToString(fDepositTotal, label); temp = TRANSLATE("Total Deposits"); temp << ": " << label; - - fDepLabel = new BStringView("deplabel",temp.String()); + + fDepLabel = new BStringView("deplabel", temp.String()); fDepLabel->SetAlignment(B_ALIGN_RIGHT); - - gCurrentLocale.CurrencyToString(fCheckTotal,label); + + gCurrentLocale.CurrencyToString(fCheckTotal, label); temp = TRANSLATE("Total Checks"); temp << ": " << label; - - fCheckLabel = new BStringView("checklabel",temp.String()); + + fCheckLabel = new BStringView("checklabel", temp.String()); fCheckLabel->SetAlignment(B_ALIGN_RIGHT); - - gCurrentLocale.CurrencyToString(fChargeTotal,label); + + gCurrentLocale.CurrencyToString(fChargeTotal, label); temp = TRANSLATE("Total Charges"); temp << ": " << label; - fChargeLabel = new BStringView("chargelabel",temp.String()); + fChargeLabel = new BStringView("chargelabel", temp.String()); fChargeLabel->SetAlignment(B_ALIGN_RIGHT); - - fReconcile = new BButton("reconcile",TRANSLATE("Reconcile"), - new BMessage(M_RECONCILE)); - - fCancel = new BButton("cancel",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); - - fReset = new BButton("reset",TRANSLATE("Reset"),new BMessage(M_RESET)); - - fAutoReconcile = new BButton("autoreconcile",TRANSLATE("Quick Balance"), - new BMessage(M_AUTORECONCILE)); - + + fReconcile = new BButton("reconcile", TRANSLATE("Reconcile"), new BMessage(M_RECONCILE)); + + fCancel = new BButton("cancel", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + + fReset = new BButton("reset", TRANSLATE("Reset"), new BMessage(M_RESET)); + + fAutoReconcile = + new BButton("autoreconcile", TRANSLATE("Quick Balance"), new BMessage(M_AUTORECONCILE)); + prefsLock.Lock(); BString rechelp = gAppPath; prefsLock.Unlock(); rechelp << "helpfiles/" << gCurrentLanguage->Name() << "/Reconcile Window Help"; - fHelpButton = new HelpButton("rechelp",rechelp.String()); - - temp = TRANSLATE("Unreconciled Total"); temp += ":"; - fTotalLabel = new BStringView("totallabel",temp.String()); - - account->DoForEachTransaction(AddReconcileItems,this); - + fHelpButton = new HelpButton("rechelp", rechelp.String()); + + temp = TRANSLATE("Unreconciled Total"); + temp += ":"; + fTotalLabel = new BStringView("totallabel", temp.String()); + + account->DoForEachTransaction(AddReconcileItems, this); + fDate->MakeFocus(true); - + BLayoutBuilder::Group<>(back, B_VERTICAL, 0) .SetInsets(10) .AddGrid(1.0f, 1.0f) - .Add(fDate, 0, 0) - .Add(fOpening, 1, 0, 2) - .Add(fClosing, 3, 0, 2) + .Add(fDate, 0, 0) + .Add(fOpening, 1, 0, 2) + .Add(fClosing, 3, 0, 2) .End() .AddGrid() - .Add(fCharges, 0, 0) - .Add(fInterest, 1, 0) + .Add(fCharges, 0, 0) + .Add(fInterest, 1, 0) .End() .AddGroup(B_HORIZONTAL) - .AddGroup(B_VERTICAL, 0) - .Add(fDepScroll) - .Add(fDepLabel) - .End() - .AddGroup(B_VERTICAL, 0) - .Add(fCheckScroll) - .Add(fCheckLabel) - .End() - .AddGroup(B_VERTICAL, 0) - .Add(fChargeScroll) - .Add(fChargeLabel) - .End() + .AddGroup(B_VERTICAL, 0) + .Add(fDepScroll) + .Add(fDepLabel) + .End() + .AddGroup(B_VERTICAL, 0) + .Add(fCheckScroll) + .Add(fCheckLabel) + .End() + .AddGroup(B_VERTICAL, 0) + .Add(fChargeScroll) + .Add(fChargeLabel) + .End() .End() .AddGrid(1.0f, 1.0f) - .Add(fTotalLabel, 0, 0) - .Add(fAutoReconcile, 0, 1) - .Add(fHelpButton, 1, 1) - .AddGlue(2, 1, 2) - .Add(fReset, 4, 1) - .AddGlue(5, 1) - .Add(fCancel, 6, 1) - .Add(fReconcile, 7, 1) + .Add(fTotalLabel, 0, 0) + .Add(fAutoReconcile, 0, 1) + .Add(fHelpButton, 1, 1) + .AddGlue(2, 1, 2) + .Add(fReset, 4, 1) + .AddGlue(5, 1) + .Add(fCancel, 6, 1) + .Add(fReconcile, 7, 1) .End() - .End(); + .End(); } -ReconcileWindow::~ReconcileWindow(void) -{ +ReconcileWindow::~ReconcileWindow(void) { prefsLock.Lock(); gPreferences.RemoveData("reconcileframe"); - gPreferences.AddRect("reconcileframe",Frame()); + gPreferences.AddRect("reconcileframe", Frame()); prefsLock.Unlock(); } -void ReconcileWindow::FrameResized(float w, float h) -{ - // We implement our own resizing routines because all the controls need to be resized in a proportional - // manner of the window being resized, such as the 3 listviews each taking up just a little less than 1/3 - // of the window's width -/* - fDate->ResizeTo(w * fDateMultiplier, fDate->Frame().Height()); - fOpening->ResizeTo(w * fOpeningMultiplier, fOpening->Frame().Height()); - fOpening->MoveTo(fDate->Frame().right + 10,fOpening->Frame().top); - fClosing->MoveTo(fOpening->Frame().right + 10,fClosing->Frame().top); - fClosing->ResizeTo(w - 10 - fClosing->Frame().left, fClosing->Frame().Height()); - - - fCharges->ResizeTo((w/2)-15,fCharges->Frame().Height()); - fInterest->MoveTo(fCharges->Frame().right + 10,fInterest->Frame().top); - fInterest->ResizeTo(w - 10 - fInterest->Frame().left,fInterest->Frame().Height()); - - float listwidth = (Bounds().Width() - 40)/3; - float height = fDepScroll->Frame().Height(); - - fDepScroll->ResizeTo(listwidth, height); - fCheckScroll->ResizeTo(listwidth, height); - fChargeScroll->ResizeTo(listwidth, height); - - float top = fCheckList->Parent()->Frame().top; - fCheckScroll->MoveTo(fDepScroll->Frame().right + 10,top); - fChargeScroll->MoveTo(fCheckScroll->Frame().right + 10,top); - - fDepLabel->MoveTo(fDepScroll->Frame().left, fDepScroll->Frame().bottom+5); - fCheckLabel->MoveTo(fCheckScroll->Frame().left, fCheckScroll->Frame().bottom+5); - fChargeLabel->MoveTo(fChargeScroll->Frame().left, fChargeScroll->Frame().bottom+5); - - fDepLabel->ResizeTo(fDepScroll->Frame().Width(),fDepLabel->Frame().Height()); - fCheckLabel->ResizeTo(fCheckScroll->Frame().Width(),fCheckLabel->Frame().Height()); - fChargeLabel->ResizeTo(fChargeScroll->Frame().Width(),fChargeLabel->Frame().Height()); -*/ +void +ReconcileWindow::FrameResized(float w, float h) { + // We implement our own resizing routines because all the controls need to be resized in a + // proportional manner of the window being resized, such as the 3 listviews each taking up just + // a little less than 1/3 of the window's width + /* + fDate->ResizeTo(w * fDateMultiplier, fDate->Frame().Height()); + fOpening->ResizeTo(w * fOpeningMultiplier, fOpening->Frame().Height()); + fOpening->MoveTo(fDate->Frame().right + 10,fOpening->Frame().top); + fClosing->MoveTo(fOpening->Frame().right + 10,fClosing->Frame().top); + fClosing->ResizeTo(w - 10 - fClosing->Frame().left, fClosing->Frame().Height()); + + + fCharges->ResizeTo((w/2)-15,fCharges->Frame().Height()); + fInterest->MoveTo(fCharges->Frame().right + 10,fInterest->Frame().top); + fInterest->ResizeTo(w - 10 - fInterest->Frame().left,fInterest->Frame().Height()); + + float listwidth = (Bounds().Width() - 40)/3; + float height = fDepScroll->Frame().Height(); + + fDepScroll->ResizeTo(listwidth, height); + fCheckScroll->ResizeTo(listwidth, height); + fChargeScroll->ResizeTo(listwidth, height); + + float top = fCheckList->Parent()->Frame().top; + fCheckScroll->MoveTo(fDepScroll->Frame().right + 10,top); + fChargeScroll->MoveTo(fCheckScroll->Frame().right + 10,top); + + fDepLabel->MoveTo(fDepScroll->Frame().left, fDepScroll->Frame().bottom+5); + fCheckLabel->MoveTo(fCheckScroll->Frame().left, fCheckScroll->Frame().bottom+5); + fChargeLabel->MoveTo(fChargeScroll->Frame().left, fChargeScroll->Frame().bottom+5); + + fDepLabel->ResizeTo(fDepScroll->Frame().Width(),fDepLabel->Frame().Height()); + fCheckLabel->ResizeTo(fCheckScroll->Frame().Width(),fCheckLabel->Frame().Height()); + fChargeLabel->ResizeTo(fChargeScroll->Frame().Width(),fChargeLabel->Frame().Height()); + */ } -void ReconcileWindow::MessageReceived(BMessage *msg) -{ +void +ReconcileWindow::MessageReceived(BMessage *msg) { int32 index; ReconcileItem *selection; - BString label,temp; - - switch(msg->what) - { - case M_PREVIOUS_FIELD: - { - if(fDate->TextView()->IsFocus()) - fReconcile->MakeFocus(true); - else - if(fOpening->TextView()->IsFocus()) - fDate->MakeFocus(true); - else - if(fClosing->TextView()->IsFocus()) - fOpening->MakeFocus(true); - else - if(fCharges->TextView()->IsFocus()) - fClosing->MakeFocus(true); - else - if(fInterest->TextView()->IsFocus()) - fCharges->MakeFocus(true); - break; + BString label, temp; + + switch (msg->what) { + case M_PREVIOUS_FIELD: { + if (fDate->TextView()->IsFocus()) + fReconcile->MakeFocus(true); + else if (fOpening->TextView()->IsFocus()) + fDate->MakeFocus(true); + else if (fClosing->TextView()->IsFocus()) + fOpening->MakeFocus(true); + else if (fCharges->TextView()->IsFocus()) + fClosing->MakeFocus(true); + else if (fInterest->TextView()->IsFocus()) + fCharges->MakeFocus(true); + break; + } + case M_NEXT_FIELD: { + if (fDate->TextView()->IsFocus()) + fOpening->MakeFocus(true); + else if (fOpening->TextView()->IsFocus()) + fClosing->MakeFocus(true); + else if (fClosing->TextView()->IsFocus()) + fCharges->MakeFocus(true); + else if (fCharges->TextView()->IsFocus()) + fInterest->MakeFocus(true); + else if (fInterest->TextView()->IsFocus()) + fDepositList->MakeFocus(true); + + break; + } + case M_RECONCILE: { + ApplyChargesAndInterest(); + + int32 i; + ReconcileItem *item; + for (i = 0; i < fDepositList->CountItems(); i++) { + item = (ReconcileItem *)fDepositList->ItemAt(i); + if (item->IsReconciled()) + item->SyncToTransaction(); } - case M_NEXT_FIELD: - { - if(fDate->TextView()->IsFocus()) - fOpening->MakeFocus(true); - else - if(fOpening->TextView()->IsFocus()) - fClosing->MakeFocus(true); - else - if(fClosing->TextView()->IsFocus()) - fCharges->MakeFocus(true); - else - if(fCharges->TextView()->IsFocus()) - fInterest->MakeFocus(true); - else - if(fInterest->TextView()->IsFocus()) - fDepositList->MakeFocus(true); - - break; + + for (i = 0; i < fCheckList->CountItems(); i++) { + item = (ReconcileItem *)fCheckList->ItemAt(i); + if (item->IsReconciled()) + item->SyncToTransaction(); } - case M_RECONCILE: - { - ApplyChargesAndInterest(); - - int32 i; - ReconcileItem *item; - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fDepositList->ItemAt(i); - if(item->IsReconciled()) - item->SyncToTransaction(); - } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fCheckList->ItemAt(i); - if(item->IsReconciled()) - item->SyncToTransaction(); - } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fChargeList->ItemAt(i); - if(item->IsReconciled()) - item->SyncToTransaction(); - } - - BMessage notify; - fAccount->Notify(WATCH_REDRAW | WATCH_ACCOUNT,¬ify); - PostMessage(B_QUIT_REQUESTED); - break; + + for (i = 0; i < fChargeList->CountItems(); i++) { + item = (ReconcileItem *)fChargeList->ItemAt(i); + if (item->IsReconciled()) + item->SyncToTransaction(); } - case M_RESET: - { - int32 i; - ReconcileItem *item; - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fDepositList->ItemAt(i); - if(item->IsReconciled()) - { - item->RevertTransaction(); - fDepositList->InvalidateItem(i); - } - } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fCheckList->ItemAt(i); - if(item->IsReconciled()) - { - item->RevertTransaction(); - fCheckList->InvalidateItem(i); - } + + BMessage notify; + fAccount->Notify(WATCH_REDRAW | WATCH_ACCOUNT, ¬ify); + PostMessage(B_QUIT_REQUESTED); + break; + } + case M_RESET: { + int32 i; + ReconcileItem *item; + for (i = 0; i < fDepositList->CountItems(); i++) { + item = (ReconcileItem *)fDepositList->ItemAt(i); + if (item->IsReconciled()) { + item->RevertTransaction(); + fDepositList->InvalidateItem(i); } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fChargeList->ItemAt(i); - if(item->IsReconciled()) - { - item->RevertTransaction(); - fChargeList->InvalidateItem(i); - } + } + + for (i = 0; i < fCheckList->CountItems(); i++) { + item = (ReconcileItem *)fCheckList->ItemAt(i); + if (item->IsReconciled()) { + item->RevertTransaction(); + fCheckList->InvalidateItem(i); } - break; } - case M_TOGGLE_DEPOSIT: - { - index = fDepositList->CurrentSelection(); - selection = (ReconcileItem*)fDepositList->ItemAt(index); - if(selection) - { - if(selection->IsReconciled()) - { - selection->SetReconciled(false); - fDepositTotal -= selection->GetTransaction()->Amount(); - fTotal -= selection->GetTransaction()->Amount(); - } - else - { - selection->SetReconciled(true); - fDepositTotal += selection->GetTransaction()->Amount(); - fTotal += selection->GetTransaction()->Amount(); - } - fDepositList->InvalidateItem(index); - - fAccount->GetLocale().CurrencyToString(fDepositTotal,label); - temp << TRANSLATE("Total Deposits") << ": " << label; - fDepLabel->SetText(label.String()); - - fAccount->GetLocale().CurrencyToString(fTotal + fDifference,label); - temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; - fTotalLabel->SetText(label.String()); - - if( (fTotal+fDifference) == 0) - fReconcile->SetEnabled(true); - else - fReconcile->SetEnabled(false); + + for (i = 0; i < fChargeList->CountItems(); i++) { + item = (ReconcileItem *)fChargeList->ItemAt(i); + if (item->IsReconciled()) { + item->RevertTransaction(); + fChargeList->InvalidateItem(i); } - break; } - case M_TOGGLE_CHECK: - { - index = fCheckList->CurrentSelection(); - selection = (ReconcileItem*)fCheckList->ItemAt(index); - if(selection) - { - if(selection->IsReconciled()) - { - selection->SetReconciled(false); - fCheckTotal += selection->GetTransaction()->Amount(); - fTotal -= selection->GetTransaction()->Amount(); - } - else - { - selection->SetReconciled(true); - fCheckTotal -= selection->GetTransaction()->Amount(); - fTotal += selection->GetTransaction()->Amount(); - } - fCheckList->InvalidateItem(index); - - fAccount->GetLocale().CurrencyToString(fCheckTotal,label); - temp << TRANSLATE("TotaChecks") << ": " << label; - fCheckLabel->SetText(label.String()); - - fAccount->GetLocale().CurrencyToString(fTotal + fDifference,label); - temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; - fTotalLabel->SetText(label.String()); - - if( (fTotal+fDifference) == 0) - fReconcile->SetEnabled(true); - else - fReconcile->SetEnabled(false); + break; + } + case M_TOGGLE_DEPOSIT: { + index = fDepositList->CurrentSelection(); + selection = (ReconcileItem *)fDepositList->ItemAt(index); + if (selection) { + if (selection->IsReconciled()) { + selection->SetReconciled(false); + fDepositTotal -= selection->GetTransaction()->Amount(); + fTotal -= selection->GetTransaction()->Amount(); + } else { + selection->SetReconciled(true); + fDepositTotal += selection->GetTransaction()->Amount(); + fTotal += selection->GetTransaction()->Amount(); } - break; + fDepositList->InvalidateItem(index); + + fAccount->GetLocale().CurrencyToString(fDepositTotal, label); + temp << TRANSLATE("Total Deposits") << ": " << label; + fDepLabel->SetText(label.String()); + + fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); + temp = ""; + temp << TRANSLATE("Unreconciled Total") << ": " << label; + fTotalLabel->SetText(label.String()); + + if ((fTotal + fDifference) == 0) + fReconcile->SetEnabled(true); + else + fReconcile->SetEnabled(false); } - case M_TOGGLE_CHARGE: - { - index = fChargeList->CurrentSelection(); - selection = (ReconcileItem*)fChargeList->ItemAt(index); - if(selection) - { - if(selection->IsReconciled()) - { - selection->SetReconciled(false); - fChargeTotal += selection->GetTransaction()->Amount(); - fTotal -= selection->GetTransaction()->Amount(); - } - else - { - selection->SetReconciled(true); - fChargeTotal -= selection->GetTransaction()->Amount(); - fTotal += selection->GetTransaction()->Amount(); - } - fChargeList->InvalidateItem(index); - - fAccount->GetLocale().CurrencyToString(fChargeTotal,label); - temp << TRANSLATE("Total Charges") << ": " << label; - fChargeLabel->SetText(label.String()); - - fAccount->GetLocale().CurrencyToString(fTotal + fDifference,label); - temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; - fTotalLabel->SetText(label.String()); - - if( (fTotal+fDifference) == 0) - fReconcile->SetEnabled(true); - else - fReconcile->SetEnabled(false); + break; + } + case M_TOGGLE_CHECK: { + index = fCheckList->CurrentSelection(); + selection = (ReconcileItem *)fCheckList->ItemAt(index); + if (selection) { + if (selection->IsReconciled()) { + selection->SetReconciled(false); + fCheckTotal += selection->GetTransaction()->Amount(); + fTotal -= selection->GetTransaction()->Amount(); + } else { + selection->SetReconciled(true); + fCheckTotal -= selection->GetTransaction()->Amount(); + fTotal += selection->GetTransaction()->Amount(); } - break; + fCheckList->InvalidateItem(index); + + fAccount->GetLocale().CurrencyToString(fCheckTotal, label); + temp << TRANSLATE("TotaChecks") << ": " << label; + fCheckLabel->SetText(label.String()); + + fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); + temp = ""; + temp << TRANSLATE("Unreconciled Total") << ": " << label; + fTotalLabel->SetText(label.String()); + + if ((fTotal + fDifference) == 0) + fReconcile->SetEnabled(true); + else + fReconcile->SetEnabled(false); } - case M_SET_BALANCES: - { - Fixed fixed,fixed2; - if(gCurrentLocale.StringToCurrency(fOpening->Text(),fixed)!=B_OK || - gCurrentLocale.StringToCurrency(fClosing->Text(),fixed2)!=B_OK ) - break; - - fDifference = fixed - fixed2; - - gCurrentLocale.CurrencyToString(fTotal + fDifference,label); - label.Prepend(" "); - label.Prepend("Unreconciled Total:"); + break; + } + case M_TOGGLE_CHARGE: { + index = fChargeList->CurrentSelection(); + selection = (ReconcileItem *)fChargeList->ItemAt(index); + if (selection) { + if (selection->IsReconciled()) { + selection->SetReconciled(false); + fChargeTotal += selection->GetTransaction()->Amount(); + fTotal -= selection->GetTransaction()->Amount(); + } else { + selection->SetReconciled(true); + fChargeTotal -= selection->GetTransaction()->Amount(); + fTotal += selection->GetTransaction()->Amount(); + } + fChargeList->InvalidateItem(index); + + fAccount->GetLocale().CurrencyToString(fChargeTotal, label); + temp << TRANSLATE("Total Charges") << ": " << label; + fChargeLabel->SetText(label.String()); + + fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); + temp = ""; + temp << TRANSLATE("Unreconciled Total") << ": " << label; fTotalLabel->SetText(label.String()); - - if( (fTotal+fDifference) == 0) + + if ((fTotal + fDifference) == 0) fReconcile->SetEnabled(true); else fReconcile->SetEnabled(false); - break; } - case M_AUTORECONCILE: - { - AutoReconcile(); - BMessage notify; - fAccount->Notify(WATCH_REDRAW | WATCH_ACCOUNT,¬ify); - + break; + } + case M_SET_BALANCES: { + Fixed fixed, fixed2; + if (gCurrentLocale.StringToCurrency(fOpening->Text(), fixed) != B_OK || + gCurrentLocale.StringToCurrency(fClosing->Text(), fixed2) != B_OK) break; - } - default: - BWindow::MessageReceived(msg); + + fDifference = fixed - fixed2; + + gCurrentLocale.CurrencyToString(fTotal + fDifference, label); + label.Prepend(" "); + label.Prepend("Unreconciled Total:"); + fTotalLabel->SetText(label.String()); + + if ((fTotal + fDifference) == 0) + fReconcile->SetEnabled(true); + else + fReconcile->SetEnabled(false); + break; + } + case M_AUTORECONCILE: { + AutoReconcile(); + BMessage notify; + fAccount->Notify(WATCH_REDRAW | WATCH_ACCOUNT, ¬ify); + + break; + } + default: + BWindow::MessageReceived(msg); } } -void ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) -{ - bool unlock=false; - if(!IsLocked()) - { +void +ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { + bool unlock = false; + if (!IsLocked()) { unlock = true; Lock(); } - + // This should prevent a rather spectacular slowdown if the user decides to import some accounts // while reconciling. Bizarre and unthinkable, but people is people. :P - if(value & WATCH_MASS_EDIT) - { - if(IsWatching(WATCH_TRANSACTION)) - { + if (value & WATCH_MASS_EDIT) { + if (IsWatching(WATCH_TRANSACTION)) { RemoveWatch(WATCH_ALL); AddWatch(WATCH_MASS_EDIT); - } - else - { + } else { AddWatch(WATCH_ALL); } - - if(unlock) + + if (unlock) Unlock(); return; } - + Account *acc = NULL; - if( (value & WATCH_ACCOUNT) && (value & WATCH_DELETE) ) - { - if( (msg->FindPointer("item",(void**)&acc)==B_OK) && (acc == fAccount) ) + if ((value & WATCH_ACCOUNT) && (value & WATCH_DELETE)) { + if ((msg->FindPointer("item", (void **)&acc) == B_OK) && (acc == fAccount)) PostMessage(B_QUIT_REQUESTED); - } - else - if( (value & WATCH_TRANSACTION) ) - { - if(value & WATCH_DELETE) - { + } else if ((value & WATCH_TRANSACTION)) { + if (value & WATCH_DELETE) { uint32 id; - if( msg->FindInt32("id",(int32*)&id)==B_OK) - { + if (msg->FindInt32("id", (int32 *)&id) == B_OK) { ReconcileItem *deleteditem; BListView *itemlist; - + deleteditem = FindItemForID(fDepositList, id); - if(deleteditem) + if (deleteditem) itemlist = fDepositList; - else - { + else { deleteditem = FindItemForID(fCheckList, id); - if(deleteditem) + if (deleteditem) itemlist = fCheckList; - else - { + else { deleteditem = FindItemForID(fChargeList, id); - if(deleteditem) + if (deleteditem) itemlist = fChargeList; - else - { + else { ShowBug("No list for ID in ReconcileWindow::HandleNotify"); - if(unlock) + if (unlock) Unlock(); return; } } } - + itemlist->RemoveItem(deleteditem); delete deleteditem; } - } - else - if(value & WATCH_CREATE) - { + } else if (value & WATCH_CREATE) { uint32 accountid; - if(msg->FindInt32("accountid",(int32*)&accountid)!=B_OK || accountid != fAccount->GetID()) - { - if(unlock) + if (msg->FindInt32("accountid", (int32 *)&accountid) != B_OK || + accountid != fAccount->GetID()) { + if (unlock) Unlock(); return; } - + TransactionData *data; - if(msg->FindPointer("item",(void**)&data)==B_OK) - { + if (msg->FindPointer("item", (void **)&data) == B_OK) { ReconcileItem *newitem = new ReconcileItem(*data); - - if(data->Type().TypeCode()==TRANS_DEP) - InsertTransactionItem(fDepositList,newitem); - else - if(data->Type().TypeCode()==TRANS_NUMERIC) - InsertTransactionItem(fCheckList,newitem); + + if (data->Type().TypeCode() == TRANS_DEP) + InsertTransactionItem(fDepositList, newitem); + else if (data->Type().TypeCode() == TRANS_NUMERIC) + InsertTransactionItem(fCheckList, newitem); else - InsertTransactionItem(fChargeList,newitem); + InsertTransactionItem(fChargeList, newitem); } } - } - if(unlock) + if (unlock) Unlock(); } -bool ReconcileWindow::QuitRequested(void) -{ +bool +ReconcileWindow::QuitRequested(void) { gDatabase.RemoveObserver(this); return true; } -void ReconcileWindow::ApplyChargesAndInterest(void) -{ +void +ReconcileWindow::ApplyChargesAndInterest(void) { Fixed charge; - if(strlen(fCharges->Text())>0 && gCurrentLocale.StringToCurrency(fCharges->Text(), charge)==B_OK) - { - TransactionData chargetrans(fAccount, fDate->Text(),"ATM",TRANSLATE("Bank Charge"), - fCharges->Text(),TRANSLATE("Bank Charge"),NULL, - TRANS_RECONCILED); + if (strlen(fCharges->Text()) > 0 && + gCurrentLocale.StringToCurrency(fCharges->Text(), charge) == B_OK) { + TransactionData chargetrans( + fAccount, fDate->Text(), "ATM", TRANSLATE("Bank Charge"), fCharges->Text(), + TRANSLATE("Bank Charge"), NULL, TRANS_RECONCILED + ); gDatabase.AddTransaction(chargetrans); } - + Fixed interest; - if(strlen(fInterest->Text())>0 && gCurrentLocale.StringToCurrency(fInterest->Text(), interest)==B_OK) - { - TransactionData interesttrans(fAccount,fDate->Text(),TRANSLATE("DEP"), - TRANSLATE("Account Interest"), - fInterest->Text(),TRANSLATE("Account Interest"),NULL, - TRANS_RECONCILED); + if (strlen(fInterest->Text()) > 0 && + gCurrentLocale.StringToCurrency(fInterest->Text(), interest) == B_OK) { + TransactionData interesttrans( + fAccount, fDate->Text(), TRANSLATE("DEP"), TRANSLATE("Account Interest"), + fInterest->Text(), TRANSLATE("Account Interest"), NULL, TRANS_RECONCILED + ); gDatabase.AddTransaction(interesttrans); } } -bool ReconcileWindow::AutoReconcile(void) -{ +bool +ReconcileWindow::AutoReconcile(void) { // We are going to attempt to automatically reconcile the account. We will do // this by adding up the values of all transactions unreconciled before the // statement date. If they balance, we can notify the user that we were successful @@ -636,129 +576,120 @@ bool ReconcileWindow::AutoReconcile(void) time_t statdate; int32 i; ReconcileItem *item; - - if(gDefaultLocale.StringToDate(fDate->Text(),statdate)!=B_OK) - { + + if (gDefaultLocale.StringToDate(fDate->Text(), statdate) != B_OK) { // Do we have an empty date box? - if(strlen(fDate->Text())<1) - { - ShowAlert(TRANSLATE("Date is missing."), - TRANSLATE("You need to enter the date for the statement to Quick Balance.")); + if (strlen(fDate->Text()) < 1) { + ShowAlert( + TRANSLATE("Date is missing."), + TRANSLATE("You need to enter the date for the statement to Quick Balance.") + ); return false; } } - - Fixed dep,chrg,chk,bankchrg,interest; + + Fixed dep, chrg, chk, bankchrg, interest; BList list; - - if(strlen(fCharges->Text())>0) - { - if(gCurrentLocale.StringToCurrency(fCharges->Text(),bankchrg)==B_OK) + + if (strlen(fCharges->Text()) > 0) { + if (gCurrentLocale.StringToCurrency(fCharges->Text(), bankchrg) == B_OK) bankchrg.Invert(); - else - { - ShowAlert(TRANSLATE("Capital Be didn't understand the amount for Bank Charges."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.")); + else { + ShowAlert( + TRANSLATE("Capital Be didn't understand the amount for Bank Charges."), + TRANSLATE("There may be a typo or the wrong kind of currency symbol " + "for this account.") + ); return false; } } - - if(strlen(fInterest->Text())>0) - { - if(gCurrentLocale.StringToCurrency(fInterest->Text(),interest)!=B_OK) - { - ShowAlert(TRANSLATE("Capital Be didn't understand the amount for Interest Earned."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.")); + + if (strlen(fInterest->Text()) > 0) { + if (gCurrentLocale.StringToCurrency(fInterest->Text(), interest) != B_OK) { + ShowAlert( + TRANSLATE("Capital Be didn't understand the amount for Interest Earned."), + TRANSLATE("There may be a typo or the wrong kind of currency symbol " + "for this account.") + ); return false; } } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fDepositList->ItemAt(i); - if(item->GetTransaction()->Date()>=statdate) + + for (i = 0; i < fDepositList->CountItems(); i++) { + item = (ReconcileItem *)fDepositList->ItemAt(i); + if (item->GetTransaction()->Date() >= statdate) break; - - if(!item->IsReconciled()) - { + + if (!item->IsReconciled()) { dep += item->GetTransaction()->Amount(); list.AddItem(item); } } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fCheckList->ItemAt(i); - if(item->GetTransaction()->Date()>=statdate) + + for (i = 0; i < fCheckList->CountItems(); i++) { + item = (ReconcileItem *)fCheckList->ItemAt(i); + if (item->GetTransaction()->Date() >= statdate) break; - - if(!item->IsReconciled()) - { + + if (!item->IsReconciled()) { chk += item->GetTransaction()->Amount(); list.AddItem(item); } } - - for(i=0; iCountItems(); i++) - { - item = (ReconcileItem*)fChargeList->ItemAt(i); - if(item->GetTransaction()->Date()>=statdate) + + for (i = 0; i < fChargeList->CountItems(); i++) { + item = (ReconcileItem *)fChargeList->ItemAt(i); + if (item->GetTransaction()->Date() >= statdate) break; - - if(!item->IsReconciled()) - { + + if (!item->IsReconciled()) { chrg += item->GetTransaction()->Amount(); list.AddItem(item); } } - - if( dep + chk + chrg + bankchrg + interest + fDifference == 0) - { - for(i=0; iSetReconciled(true); } ApplyChargesAndInterest(); - ShowAlert(TRANSLATE("Success!"),TRANSLATE("Quick Balance successful!"),B_IDEA_ALERT); + ShowAlert(TRANSLATE("Success!"), TRANSLATE("Quick Balance successful!"), B_IDEA_ALERT); PostMessage(B_QUIT_REQUESTED); return true; } - - ShowAlert(TRANSLATE("Couldn't Quick Balance."), + + ShowAlert( + TRANSLATE("Couldn't Quick Balance."), TRANSLATE("Quick Balance failed. This doesn't mean " - "that you did something wrong - it's just that Quick Balance works on " - "simpler cases in balancing an account than this one. Sorry.")); + "that you did something wrong - it's just that Quick Balance works on " + "simpler cases in balancing an account than this one. Sorry.") + ); return false; } -ReconcileItem *ReconcileWindow::FindItemForID(BListView *target, const uint32 &id) -{ - for(int32 i=0; iCountItems(); i++) - { - ReconcileItem *temp = (ReconcileItem*)target->ItemAt(i); - if(temp->GetTransaction()->GetID() == id) +ReconcileItem * +ReconcileWindow::FindItemForID(BListView *target, const uint32 &id) { + for (int32 i = 0; i < target->CountItems(); i++) { + ReconcileItem *temp = (ReconcileItem *)target->ItemAt(i); + if (temp->GetTransaction()->GetID() == id) return temp; } return NULL; } -void ReconcileWindow::InsertTransactionItem(BListView *target, ReconcileItem *item) -{ +void +ReconcileWindow::InsertTransactionItem(BListView *target, ReconcileItem *item) { TransactionData *itemdata = item->GetTransaction(); - - for(int32 i=0; iCountItems(); i++) - { - ReconcileItem *temp = (ReconcileItem*)target->ItemAt(i); + + for (int32 i = 0; i < target->CountItems(); i++) { + ReconcileItem *temp = (ReconcileItem *)target->ItemAt(i); TransactionData *tempdata = temp->GetTransaction(); - - if(itemdata->Date() < tempdata->Date() || - (itemdata->Date() == tempdata->Date() && - strcmp(itemdata->Payee(),tempdata->Payee())<1) ) - { - target->AddItem(item,i); + + if (itemdata->Date() < tempdata->Date() || + (itemdata->Date() == tempdata->Date() && + strcmp(itemdata->Payee(), tempdata->Payee()) < 1)) { + target->AddItem(item, i); return; } } @@ -766,41 +697,37 @@ void ReconcileWindow::InsertTransactionItem(BListView *target, ReconcileItem *it target->AddItem(item); } -void AddReconcileItems(const TransactionData &data, void *ptr) -{ - if(data.Status()==TRANS_RECONCILED) +void +AddReconcileItems(const TransactionData &data, void *ptr) { + if (data.Status() == TRANS_RECONCILED) return; - + ReconcileWindow *win = (ReconcileWindow *)ptr; - - switch(data.Type().TypeCode()) - { - case TRANS_NUMERIC: - { - win->fCheckList->AddItem(new ReconcileItem(data)); - break; - } - - case TRANS_DEP: - { - win->fDepositList->AddItem(new ReconcileItem(data)); - break; - } - - case TRANS_ATM: - case TRANS_XFER: - default: - { - win->fChargeList->AddItem(new ReconcileItem(data)); - break; - } + + switch (data.Type().TypeCode()) { + case TRANS_NUMERIC: { + win->fCheckList->AddItem(new ReconcileItem(data)); + break; + } + + case TRANS_DEP: { + win->fDepositList->AddItem(new ReconcileItem(data)); + break; + } + + case TRANS_ATM: + case TRANS_XFER: + default: { + win->fChargeList->AddItem(new ReconcileItem(data)); + break; + } } } /* ReconcileFilter::ReconcileFilter(ReconcileWindow *win) : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE,B_KEY_DOWN), - fWindow(win) + fWindow(win) { } @@ -817,15 +744,15 @@ filter_result ReconcileFilter::Filter(BMessage *msg, BHandler **target) (mod & B_OPTION_KEY) ) return B_DISPATCH_MESSAGE; } - + BView *v=dynamic_cast(*target); if(!v || strcmp("_input_",v->Name())!=0) return B_DISPATCH_MESSAGE; - + BTextControl *text = dynamic_cast(v->Parent()); if(!text) return B_DISPATCH_MESSAGE; - + if(text==fWindow->fDate) { int32 rawchar; @@ -835,20 +762,20 @@ filter_result ReconcileFilter::Filter(BMessage *msg, BHandler **target) // fWindow->PostMessage(M_NEXT_FIELD); // return B_SKIP_MESSAGE; // } - + // Weed out navigation keys if(rawchar<32 && rawchar!=B_PAGE_UP && rawchar!=B_PAGE_DOWN) return B_DISPATCH_MESSAGE; - + int32 start, end; text->TextView()->GetSelection(&start,&end); - + BString string; if(rawchar=='+') { if(strlen(text->Text())>0) fWindow->fCurrentDate = IncrementDateByDay(fWindow->fCurrentDate); - + gDefaultLocale.DateToString(fWindow->fCurrentDate,string); text->SetText(string.String()); text->TextView()->SelectAll(); @@ -895,7 +822,7 @@ filter_result ReconcileFilter::Filter(BMessage *msg, BHandler **target) return B_SKIP_MESSAGE; } } - + return B_DISPATCH_MESSAGE; } */ diff --git a/src/ReconcileWindow.h b/src/ReconcileWindow.h index 60a9c4a..e69ff7d 100644 --- a/src/ReconcileWindow.h +++ b/src/ReconcileWindow.h @@ -1,35 +1,35 @@ #ifndef RECONCILEWINDOW_H #define RECONCILEWINDOW_H -#include -#include -#include +#include "Account.h" +#include "HelpButton.h" +#include "Notifier.h" +#include #include +#include #include -#include -#include #include -#include "Account.h" -#include "Notifier.h" -#include "HelpButton.h" +#include +#include +#include class DateBox; class CurrencyBox; class ReconcileItem; -void AddReconcileItems(const TransactionData &data, void *recwin); +void +AddReconcileItems(const TransactionData &data, void *recwin); -class ReconcileWindow : public BWindow, public Observer -{ -public: +class ReconcileWindow : public BWindow, public Observer { + public: ReconcileWindow(const BRect frame, Account *account); ~ReconcileWindow(void); void MessageReceived(BMessage *msg); void FrameResized(float w, float h); void HandleNotify(const uint64 &value, const BMessage *msg); bool QuitRequested(void); - -private: + + private: friend class ReconcileFilter; friend void AddReconcileItems(const TransactionData &data, void *ptr); @@ -37,22 +37,22 @@ class ReconcileWindow : public BWindow, public Observer ReconcileItem *FindItemForID(BListView *target, const uint32 &id); void InsertTransactionItem(BListView *target, ReconcileItem *item); bool AutoReconcile(void); - + Account *fAccount; - + BListView *fDepositList, *fCheckList, *fChargeList; CurrencyBox *fOpening, *fClosing, *fCharges, *fInterest; DateBox *fDate; BButton *fReset, *fReconcile, *fCancel, *fAutoReconcile; - + // fTotal is the sum of all of the deposits, checks, and charges // The way to tell if we are done is if fDifference + fTotal == 0 Fixed fDepositTotal, fCheckTotal, fChargeTotal, fDifference, fTotal; BStringView *fDepLabel, *fCheckLabel, *fChargeLabel, *fTotalLabel; BScrollView *fDepScroll, *fCheckScroll, *fChargeScroll; - + HelpButton *fHelpButton; - + float fDateMultiplier, fOpeningMultiplier, fClosingMultiplier; time_t fCurrentDate; }; diff --git a/src/RegisterView.cpp b/src/RegisterView.cpp index 9c46615..01e7ea7 100644 --- a/src/RegisterView.cpp +++ b/src/RegisterView.cpp @@ -12,210 +12,175 @@ #include "QuickTrackerItem.h" #include "Translate.h" -enum -{ - M_SELECT_ACCOUNT='slac', - M_SELECT_CURRENT -}; - -RegisterView::RegisterView(const char *name, int32 flags) - : BView(name, flags| B_FRAME_EVENTS) -{ - SetViewColor(240,240,240); - - BStringView *accountlabel = new BStringView("accountlabel", - TRANSLATE("Accounts")); - -// fAccountView = new DragListView(r,"accountview"); +enum { M_SELECT_ACCOUNT = 'slac', M_SELECT_CURRENT }; + +RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { + SetViewColor(240, 240, 240); + + BStringView *accountlabel = new BStringView("accountlabel", TRANSLATE("Accounts")); + + // fAccountView = new DragListView(r,"accountview"); fAccountView = new BListView("accountview", B_SINGLE_SELECTION_LIST); fAccountView->SetSelectionMessage(new BMessage(M_SELECT_ACCOUNT)); fAccountView->SetInvocationMessage(new BMessage(M_SHOW_ACCOUNT_SETTINGS)); - fAccountScroller = new BScrollView("accountscroll",fAccountView,0,true,true); + fAccountScroller = new BScrollView("accountscroll", fAccountView, 0, true, true); fAccountScroller->SetViewColor(ViewColor()); - + fCheckView = new CheckView("checkview", B_WILL_DRAW); gDatabase.AddObserver(fCheckView); - - for(int32 i=0; iAddItem(new AccountListItem(acc)); acc->AddObserver(this); } - + fTransactionView = new TransactionView(); gDatabase.AddObserver(fTransactionView); gDatabase.AddObserver(this); - + fTrackBox = new BBox("qtbox"); fTrackBox->SetLabel(TRANSLATE("QuickTracker")); - - QTNetWorthItem *item; + + QTNetWorthItem *item; item = new QTNetWorthItem("networth"); - + BFont font; BLayoutBuilder::Group<>(fTrackBox, B_VERTICAL, 0) .SetInsets(10, font.Size() * 1.3, 10, 10) .Add(item) .AddGlue(1024 * 1024 * 2014) - .End(); + .End(); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .SetInsets(10) .Add(accountlabel) .AddGroup(B_HORIZONTAL) - .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING, 1) - .Add(fAccountScroller) - .Add(fTrackBox) - .End() - .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING, 3) - .Add(fTransactionView) - .Add(fCheckView) - .End() + .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING, 1) + .Add(fAccountScroller) + .Add(fTrackBox) .End() - .End(); + .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING, 3) + .Add(fTransactionView) + .Add(fCheckView) + .End() + .End() + .End(); } -RegisterView::~RegisterView(void) -{ -} +RegisterView::~RegisterView(void) {} -void RegisterView::AttachedToWindow(void) -{ +void +RegisterView::AttachedToWindow(void) { fAccountView->SetTarget(this); - + // If the selection done is before being attached to the window, the message is // never received. bool selected = false; - for(int32 i=0; iIsClosed()) - { + if (acc && !acc->IsClosed()) { fAccountView->Select(i); selected = true; } } - if(!selected) + if (!selected) fAccountView->Select(0); fCheckView->MakeFocus(true); } -void RegisterView::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_SELECT_ACCOUNT: - { - if(fAccountView->CurrentSelection()<0) - break; - gDatabase.SetCurrentAccount(fAccountView->CurrentSelection()); - break; - } - case M_SHOW_ACCOUNT_SETTINGS: - { - if(Window()) - Window()->PostMessage(M_SHOW_ACCOUNT_SETTINGS); - break; - } - default: - { - BView::MessageReceived(msg); +void +RegisterView::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_SELECT_ACCOUNT: { + if (fAccountView->CurrentSelection() < 0) break; - } + gDatabase.SetCurrentAccount(fAccountView->CurrentSelection()); + break; + } + case M_SHOW_ACCOUNT_SETTINGS: { + if (Window()) + Window()->PostMessage(M_SHOW_ACCOUNT_SETTINGS); + break; + } + default: { + BView::MessageReceived(msg); + break; + } } } -void RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) -{ - bool lockwin=false; - if(!Window()->IsLocked()) - { +void +RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { + bool lockwin = false; + if (!Window()->IsLocked()) { Window()->Lock(); - lockwin=true; + lockwin = true; } - - if(value & WATCH_ACCOUNT) - { + + if (value & WATCH_ACCOUNT) { Account *acc; - if(msg->FindPointer("item",(void**)&acc)!=B_OK) - { - if(lockwin) + if (msg->FindPointer("item", (void **)&acc) != B_OK) { + if (lockwin) Window()->Unlock(); return; } - - if(value & WATCH_CREATE) - { + + if (value & WATCH_CREATE) { fAccountView->AddItem(new AccountListItem(acc)); - if(fAccountView->CountItems()==1) + if (fAccountView->CountItems() == 1) fAccountView->Select(0); acc->AddObserver(this); - } - else - if(value & WATCH_DELETE) - { - AccountListItem *item = (AccountListItem*)fAccountView->RemoveItem(gDatabase.IndexOf(acc)); + } else if (value & WATCH_DELETE) { + AccountListItem *item = + (AccountListItem *)fAccountView->RemoveItem(gDatabase.IndexOf(acc)); delete item; fAccountView->Select(0); - } - else - if(value & WATCH_CHANGE) - { - for(int32 i=0; iCountItems(); i++) - { - AccountListItem *listitem = (AccountListItem*)fAccountView->ItemAt(i); - if(listitem && listitem->GetAccount()==acc) - { + } else if (value & WATCH_CHANGE) { + for (int32 i = 0; i < fAccountView->CountItems(); i++) { + AccountListItem *listitem = (AccountListItem *)fAccountView->ItemAt(i); + if (listitem && listitem->GetAccount() == acc) { fAccountView->InvalidateItem(i); break; } } } - + // Adjust the horizontal scroll bar every time there is a change - + float maxwidth = 0; - for(int32 i=0; iStringWidth(acc->Name()) + B_V_SCROLL_BAR_WIDTH + 10; maxwidth = (namewidth > maxwidth) ? namewidth : maxwidth; } - + float range = maxwidth - fAccountScroller->Bounds().Width(); - if(range < 0) + if (range < 0) range = 0; - + BScrollBar *bar = fAccountScroller->ScrollBar(B_HORIZONTAL); - bar->SetRange(0,range); + bar->SetRange(0, range); - } - else - if(value & WATCH_TRANSACTION) - { - if(value & WATCH_CREATE || value & WATCH_DELETE || value & WATCH_CHANGE) + } else if (value & WATCH_TRANSACTION) { + if (value & WATCH_CREATE || value & WATCH_DELETE || value & WATCH_CHANGE) fAccountView->Invalidate(); - } - else - if(value & WATCH_LOCALE) - { - for(int32 i=0; iCountItems(); i++) - { - AccountListItem *listitem = (AccountListItem*)fAccountView->ItemAt(i); - if(listitem) + } else if (value & WATCH_LOCALE) { + for (int32 i = 0; i < fAccountView->CountItems(); i++) { + AccountListItem *listitem = (AccountListItem *)fAccountView->ItemAt(i); + if (listitem) fAccountView->InvalidateItem(i); } } - if(lockwin) + if (lockwin) Window()->Unlock(); } -void RegisterView::SelectAccount(const int32 &index) -{ - if(index < 0 || index > fAccountView->CountItems()-1) +void +RegisterView::SelectAccount(const int32 &index) { + if (index < 0 || index > fAccountView->CountItems() - 1) return; - + fAccountView->Select(index); } diff --git a/src/RegisterView.h b/src/RegisterView.h index 9d896a4..baec343 100644 --- a/src/RegisterView.h +++ b/src/RegisterView.h @@ -1,32 +1,34 @@ #ifndef REGSITERVIEW_H #define REGSITERVIEW_H -#include -#include -#include #include "Notifier.h" #include "TransactionView.h" +#include +#include +#include class CheckView; #define M_SHOW_ACCOUNT_SETTINGS 'acst' -class RegisterView : public BView, public Observer -{ -public: +class RegisterView : public BView, public Observer { + public: RegisterView(const char *name, int32 flags); ~RegisterView(void); void MessageReceived(BMessage *msg); void AttachedToWindow(void); void HandleNotify(const uint64 &value, const BMessage *msg); void SelectAccount(const int32 &index); - + bool SelectNextTransaction(void) { return fTransactionView->SelectNext(); } + bool SelectPreviousTransaction(void) { return fTransactionView->SelectPrevious(); } + bool SelectFirstTransaction(void) { return fTransactionView->SelectFirst(); } + bool SelectLastTransaction(void) { return fTransactionView->SelectLast(); } - -private: + + private: CheckView *fCheckView; BListView *fAccountView; BScrollView *fAccountScroller; diff --git a/src/ReportGrid.cpp b/src/ReportGrid.cpp index 8345995..9c32b25 100644 --- a/src/ReportGrid.cpp +++ b/src/ReportGrid.cpp @@ -1,128 +1,119 @@ #include "ReportGrid.h" #include -ReportGrid::ReportGrid(const uint32 &width, const uint32 &height) - : fList(20,true), - fWidth(width) -{ - for(uint32 i=0; iTitle() : NULL; } -void ReportGrid::SetRowTitle(const int32 &index, const char *title) -{ - ReportGrid::GridRecord *record = (ReportGrid::GridRecord*) fList.ItemAt(index); - - if(record) +void +ReportGrid::SetRowTitle(const int32 &index, const char *title) { + ReportGrid::GridRecord *record = (ReportGrid::GridRecord *)fList.ItemAt(index); + + if (record) record->SetTitle(title); } - -int32 ReportGrid::FindTitle(const char *title) -{ - if(!title || fList.CountItems()==0) +int32 +ReportGrid::FindTitle(const char *title) { + if (!title || fList.CountItems() == 0) return -1; - - for(int32 i=0; iTitle(),title)==0) + if (strcmp(record->Title(), title) == 0) return i; } return -1; } -status_t ReportGrid::ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed) -{ - if(y >= (uint32)fList.CountItems() || x >= fWidth) +status_t +ReportGrid::ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed) { + if (y >= (uint32)fList.CountItems() || x >= fWidth) return B_ERROR; - + ReportGrid::GridRecord *record = fList.ItemAt(y); - - if(!record) + + if (!record) return B_ERROR; - - return record->ValueAt(x,fixed); + + return record->ValueAt(x, fixed); } -status_t ReportGrid::SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed) -{ - if(y >= (uint32)fList.CountItems() || x >= fWidth) +status_t +ReportGrid::SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed) { + if (y >= (uint32)fList.CountItems() || x >= fWidth) return B_ERROR; - - ReportGrid::GridRecord *record = (ReportGrid::GridRecord*) fList.ItemAt(y); - - if(!record) + + ReportGrid::GridRecord *record = (ReportGrid::GridRecord *)fList.ItemAt(y); + + if (!record) return B_ERROR; - - return record->SetValue(x,fixed); + + return record->SetValue(x, fixed); } -int ReportGrid::CompareGridrecord(const ReportGrid::GridRecord *item1, const ReportGrid::GridRecord *item2) -{ -// ReportGrid::GridRecord *listitem1 = *((ReportGrid::GridRecord**)item1); -// ReportGrid::GridRecord *listitem2 = *((ReportGrid::GridRecord**)item2); - -// return strcmp(listitem1->Title(),listitem2->Title()); - return strcmp(item1->Title(),item2->Title()); +int +ReportGrid::CompareGridrecord( + const ReportGrid::GridRecord *item1, const ReportGrid::GridRecord *item2 +) { + // ReportGrid::GridRecord *listitem1 = *((ReportGrid::GridRecord**)item1); + // ReportGrid::GridRecord *listitem2 = *((ReportGrid::GridRecord**)item2); + + // return strcmp(listitem1->Title(),listitem2->Title()); + return strcmp(item1->Title(), item2->Title()); } -void ReportGrid::AddItem(const int32 &index) -{ - if(index < 0) +void +ReportGrid::AddItem(const int32 &index) { + if (index < 0) fList.AddItem(new ReportGrid::GridRecord(fWidth)); else - fList.AddItem(new ReportGrid::GridRecord(fWidth),index); + fList.AddItem(new ReportGrid::GridRecord(fWidth), index); } -void ReportGrid::RemoveItem(const int32 &index) -{ +void +ReportGrid::RemoveItem(const int32 &index) { ReportGrid::GridRecord *item = fList.RemoveItemAt(index); - if(item) + if (item) delete item; } -void ReportGrid::MakeEmpty(void) -{ +void +ReportGrid::MakeEmpty(void) { fList.MakeEmpty(); } -void ReportGrid::Sort(void) -{ +void +ReportGrid::Sort(void) { fList.SortItems(CompareGridrecord); } -void ReportGrid::PrintToStream(void) -{ - if(CountItems()==0) - { +void +ReportGrid::PrintToStream(void) { + if (CountItems() == 0) { printf("Grid is empty\n"); - } - else - for(int32 i=0; iTitle()); - for(uint32 j=0; jValueAt(j,f); - printf("%.2f ",f.AsFloat()); + } else + for (int32 i = 0; i < CountItems(); i++) { + ReportGrid::GridRecord *item = fList.ItemAt(i); + + printf("Row %ld: %s ", i, item->Title()); + for (uint32 j = 0; j < fWidth; j++) { + Fixed f; + item->ValueAt(j, f); + printf("%.2f ", f.AsFloat()); + } + printf("\n"); } - printf("\n"); - } printf("\n"); } @@ -130,41 +121,36 @@ void ReportGrid::PrintToStream(void) ReportGrid::GridRecord::GridRecord(const uint32 &size, const char *title) - : fList(size), - fTitle(title) -{ - for(uint32 i=0; i -#include #include "Fixed.h" #include "ObjectList.h" +#include +#include -class ReportGrid -{ -public: +class ReportGrid { + public: ReportGrid(const uint32 &width, const uint32 &height); ~ReportGrid(void); - + const char *RowTitle(const int32 &index); void SetRowTitle(const int32 &index, const char *title); int32 FindTitle(const char *title); - + status_t ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed); status_t SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed); - + void AddItem(const int32 &index = -1); void RemoveItem(const int32 &index); - + int32 CountItems(void) const { return fList.CountItems(); } + void MakeEmpty(void); - + void Sort(void); - + void PrintToStream(void); - + uint32 Width(void) const { return fWidth; } + uint32 Height(void) const { return (uint32)fList.CountItems(); } - -private: - - class GridRecord - { - public: - GridRecord(const uint32 &size, const char *title = NULL); - ~GridRecord(void); - - const char *Title(void) const { return fTitle.String(); } - void SetTitle(const char *title) { fTitle = title; } - - status_t ValueAt(const uint32 &index, Fixed &fixed); - status_t SetValue(const uint32 &index, const Fixed &fixed); - private: - BObjectList fList; - BString fTitle; + + private: + class GridRecord { + public: + GridRecord(const uint32 &size, const char *title = NULL); + ~GridRecord(void); + + const char *Title(void) const { return fTitle.String(); } + + void SetTitle(const char *title) { fTitle = title; } + + status_t ValueAt(const uint32 &index, Fixed &fixed); + status_t SetValue(const uint32 &index, const Fixed &fixed); + + private: + BObjectList fList; + BString fTitle; }; static int CompareGridrecord(const GridRecord *item1, const GridRecord *item2); diff --git a/src/ReportWindow.cpp b/src/ReportWindow.cpp index ab00784..c19dce2 100644 --- a/src/ReportWindow.cpp +++ b/src/ReportWindow.cpp @@ -1,27 +1,27 @@ #include "ReportWindow.h" -#include -#include -#include -#include -#include -#include -#include "ReportGrid.h" +#include "ColumnTypes.h" +#include "Database.h" #include "DateBox.h" -#include "StickyDrawButton.h" +#include "HelpButton.h" #include "Layout.h" -#include "TimeSupport.h" +#include "MsgDefs.h" #include "ObjectList.h" -#include "Database.h" -#include "ColumnTypes.h" -#include "HelpButton.h" #include "Preferences.h" -#include "MsgDefs.h" +#include "ReportGrid.h" +#include "StickyDrawButton.h" +#include "TimeSupport.h" +#include +#include +#include +#include +#include +#include -int compare_stringitem(const void *item1, const void *item2); +int +compare_stringitem(const void *item1, const void *item2); -enum -{ - M_REPORT_CASH_FLOW='csfl', +enum { + M_REPORT_CASH_FLOW = 'csfl', M_REPORT_NET_WORTH, M_REPORT_TRANSACTIONS, M_REPORT_BUDGET, @@ -39,27 +39,21 @@ enum M_TOGGLE_GRAPH }; - ReportWindow::ReportWindow(BRect frame) - : BWindow(frame,TRANSLATE("Reports"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), - fSubtotalMode(SUBTOTAL_NONE), - fReportMode(REPORT_CASH_FLOW), - fStartDate(GetCurrentYear()), - fEndDate(GetCurrentDate()), - fTitleFont(be_bold_font), - fHeaderFont(be_plain_font) -{ + : BWindow( + frame, TRANSLATE("Reports"), B_DOCUMENT_WINDOW, + B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ), + fSubtotalMode(SUBTOTAL_NONE), fReportMode(REPORT_CASH_FLOW), fStartDate(GetCurrentYear()), + fEndDate(GetCurrentDate()), fTitleFont(be_bold_font), fHeaderFont(be_plain_font) { BString temp; fHeaderFont.SetFace(B_ITALIC_FACE); BView *view = new BView("back", B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f) - .SetInsets(0) - .Add(view) - .End(); - view->SetViewColor(240,240,240); - + BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f).SetInsets(0).Add(view).End(); + view->SetViewColor(240, 240, 240); + BGroupLayout *reportsLayout = new BGroupLayout(B_VERTICAL, 0); BGroupLayout *accountsLayout = new BGroupLayout(B_VERTICAL, 0); BGroupLayout *subtotalLayout = new BGroupLayout(B_VERTICAL, 0); @@ -69,64 +63,68 @@ ReportWindow::ReportWindow(BRect frame) BLayoutBuilder::Group<>(view, B_HORIZONTAL) .SetInsets(10) .AddGroup(B_VERTICAL, 1.0f) - .Add(reportsLayout, 1) - .Add(accountsLayout, 5) - .Add(subtotalLayout, 1) - .Add(categoriesLayout, 5) + .Add(reportsLayout, 1) + .Add(accountsLayout, 5) + .Add(subtotalLayout, 1) + .Add(categoriesLayout, 5) .End() .Add(layout_) - .End(); + .End(); BMenu *reportmenu = new BMenu(TRANSLATE("Reports")); reportmenu->SetLabelFromMarked(true); -// TODO: Re-enable the Budget report -// reportmenu->AddItem(new BMenuItem(TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET))); + // TODO: Re-enable the Budget report + // reportmenu->AddItem(new BMenuItem(TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET))); temp << TRANSLATE("Income") << " / " << TRANSLATE("Spending"); reportmenu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_CASH_FLOW))); reportmenu->AddItem(new BMenuItem(TRANSLATE("Total Worth"), new BMessage(M_REPORT_NET_WORTH))); - reportmenu->AddItem(new BMenuItem(TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS))); + reportmenu->AddItem( + new BMenuItem(TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS)) + ); reportmenu->SetRadioMode(true); reportmenu->ItemAt(0L)->SetMarked(true); fReportMode = REPORT_BUDGET; - BRect r(10,10,reportmenu->StringWidth(temp.String())+45,60); + BRect r(10, 10, reportmenu->StringWidth(temp.String()) + 45, 60); - temp = TRANSLATE("Reports"); temp += ": "; - BStringView *sv = new BStringView("reportsv",temp.String()); + temp = TRANSLATE("Reports"); + temp += ": "; + BStringView *sv = new BStringView("reportsv", temp.String()); reportsLayout->AddView(sv); - fReportField = new BMenuField("reportfield","",reportmenu); + fReportField = new BMenuField("reportfield", "", reportmenu); reportsLayout->AddView(fReportField); - temp = TRANSLATE("Accounts"); temp += ": "; - sv = new BStringView("accountsv",temp.String()); + temp = TRANSLATE("Accounts"); + temp += ": "; + sv = new BStringView("accountsv", temp.String()); accountsLayout->AddView(sv); - fAccountList = new BListView("reportaccountlist",B_MULTIPLE_SELECTION_LIST); - BScrollView *scrollview = new BScrollView("accountscroller",fAccountList,0, - false,true); + fAccountList = new BListView("reportaccountlist", B_MULTIPLE_SELECTION_LIST); + BScrollView *scrollview = new BScrollView("accountscroller", fAccountList, 0, false, true); accountsLayout->AddView(scrollview); -// This is disabled because otherwise the report is rendered once for each -// account added when the report window is shown initially -// fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT)); + // This is disabled because otherwise the report is rendered once for each + // account added when the report window is shown initially + // fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT)); - temp = TRANSLATE("Subtotal"); temp += ":"; - sv = new BStringView("subtotalsv",temp.String()); + temp = TRANSLATE("Subtotal"); + temp += ":"; + sv = new BStringView("subtotalsv", temp.String()); subtotalLayout->AddView(sv); BMenu *subtotalmenu = new BMenu(TRANSLATE("Subtotal")); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("None"),new BMessage(M_SUBTOTAL_NONE))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Month"),new BMessage(M_SUBTOTAL_MONTH))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Quarter"),new BMessage(M_SUBTOTAL_QUARTER))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Year"),new BMessage(M_SUBTOTAL_YEAR))); + subtotalmenu->AddItem(new BMenuItem(TRANSLATE("None"), new BMessage(M_SUBTOTAL_NONE))); + subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Month"), new BMessage(M_SUBTOTAL_MONTH))); + subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Quarter"), new BMessage(M_SUBTOTAL_QUARTER))); + subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Year"), new BMessage(M_SUBTOTAL_YEAR))); subtotalmenu->SetLabelFromMarked(true); subtotalmenu->SetRadioMode(true); subtotalmenu->ItemAt(0)->SetMarked(true); - fSubtotalField = new BMenuField("subtotalfield","",subtotalmenu); + fSubtotalField = new BMenuField("subtotalfield", "", subtotalmenu); subtotalLayout->AddView(fSubtotalField); prefsLock.Lock(); @@ -135,86 +133,93 @@ ReportWindow::ReportWindow(BRect frame) reporthelp << "helpfiles/" << gCurrentLanguage->Name() << "/Report Window Help"; HelpButton *help = new HelpButton("reporthelp", reporthelp.String()); - temp = TRANSLATE("Categories"); temp += ": "; - sv = new BStringView("catsv",temp.String()); + temp = TRANSLATE("Categories"); + temp += ": "; + sv = new BStringView("catsv", temp.String()); categoriesLayout->AddView(sv); - fCategoryList = new BListView("reportcattlist",B_MULTIPLE_SELECTION_LIST, - B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE | B_NAVIGABLE); - fCategoryScroller = new BScrollView("catscroller",fCategoryList,0,false,true); + fCategoryList = new BListView( + "reportcattlist", B_MULTIPLE_SELECTION_LIST, + B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE | B_NAVIGABLE + ); + fCategoryScroller = new BScrollView("catscroller", fCategoryList, 0, false, true); categoriesLayout->AddView(fCategoryScroller); fCategoryList->SetSelectionMessage(new BMessage(M_CATEGORIES_CHANGED)); fCategoryList->SetInvocationMessage(new BMessage(M_CATEGORIES_CHANGED)); BString datestring; - gDefaultLocale.DateToString(GetCurrentYear(),datestring); + gDefaultLocale.DateToString(GetCurrentYear(), datestring); - temp = TRANSLATE("Starting Date"); temp += ": "; + temp = TRANSLATE("Starting Date"); + temp += ": "; - fStartDateBox = new DateBox("startdate",temp.String(),datestring.String(), - new BMessage(M_START_DATE_CHANGED)); + fStartDateBox = new DateBox( + "startdate", temp.String(), datestring.String(), new BMessage(M_START_DATE_CHANGED) + ); fStartDateBox->SetDate(GetCurrentYear()); -// fStartDateBox->SetEscapeCancel(true); + // fStartDateBox->SetEscapeCancel(true); layout_->AddView(fStartDateBox); fStartDateBox->GetFilter()->SetMessenger(new BMessenger(this)); - gDefaultLocale.DateToString(GetCurrentDate(),datestring); - temp = TRANSLATE("Ending Date"); temp += ": "; + gDefaultLocale.DateToString(GetCurrentDate(), datestring); + temp = TRANSLATE("Ending Date"); + temp += ": "; - fEndDateBox = new DateBox("enddate",temp.String(),datestring.String(), - new BMessage(M_END_DATE_CHANGED)); + fEndDateBox = new DateBox( + "enddate", temp.String(), datestring.String(), new BMessage(M_END_DATE_CHANGED) + ); fEndDateBox->SetDate(GetCurrentDate()); layout_->AddView(fEndDateBox); fEndDateBox->GetFilter()->SetMessenger(new BMessenger(this)); BBitmap *up, *down; - BRect brect(0,0,16,16); - up = BTranslationUtils::GetBitmap('PNG ',"BarGraphUp.png"); - if(!up) - up = new BBitmap(brect,B_RGB32); - down = BTranslationUtils::GetBitmap('PNG ',"BarGraphDown.png"); - if(!down) - down = new BBitmap(brect,B_RGB32); - - brect.OffsetTo(Bounds().right - 10 - brect.Width(),10 + - ((fEndDateBox->Frame().Height() - 16)/2) ); - fGraphButton = new StickyDrawButton(brect,"graphbutton",up,down, - new BMessage(M_TOGGLE_GRAPH), - B_FOLLOW_TOP | B_FOLLOW_RIGHT,B_WILL_DRAW); -// view->AddChild(fGraphButton); - -// TODO: This needs to be unhidden when graph support is finally added + BRect brect(0, 0, 16, 16); + up = BTranslationUtils::GetBitmap('PNG ', "BarGraphUp.png"); + if (!up) + up = new BBitmap(brect, B_RGB32); + down = BTranslationUtils::GetBitmap('PNG ', "BarGraphDown.png"); + if (!down) + down = new BBitmap(brect, B_RGB32); + + brect.OffsetTo( + Bounds().right - 10 - brect.Width(), 10 + ((fEndDateBox->Frame().Height() - 16) / 2) + ); + fGraphButton = new StickyDrawButton( + brect, "graphbutton", up, down, new BMessage(M_TOGGLE_GRAPH), B_FOLLOW_TOP | B_FOLLOW_RIGHT, + B_WILL_DRAW + ); + // view->AddChild(fGraphButton); + + // TODO: This needs to be unhidden when graph support is finally added fGraphButton->Hide(); - fGridView = new BColumnListView("gridview",B_WILL_DRAW, B_FANCY_BORDER); + fGridView = new BColumnListView("gridview", B_WILL_DRAW, B_FANCY_BORDER); layout_->AddView(fGridView); - layout_->AddItem(BGridLayoutBuilder(0.0f, 0.0f) - .Add(BSpaceLayoutItem::CreateGlue(), 0, 0) - .Add(help, 1, 0) + layout_->AddItem( + BGridLayoutBuilder(0.0f, 0.0f).Add(BSpaceLayoutItem::CreateGlue(), 0, 0).Add(help, 1, 0) ); - + // Configuring to make it look good and not like a grid fGridView->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); fGridView->SetSortingEnabled(false); fGridView->SetEditMode(false); - rgb_color white = { 255,255,255,255 }; - fGridView->SetColor(B_COLOR_BACKGROUND,white); - fGridView->SetColor(B_COLOR_ROW_DIVIDER,fGridView->Color(B_COLOR_BACKGROUND)); - fGridView->SetColor(B_COLOR_SELECTION,fGridView->Color(B_COLOR_BACKGROUND)); - fGridView->SetColor(B_COLOR_NON_FOCUS_SELECTION,fGridView->Color(B_COLOR_BACKGROUND)); - fGridView->SetColor(B_COLOR_SEPARATOR_BORDER,fGridView->Color(B_COLOR_BACKGROUND)); - fGridView->SetColor(B_COLOR_SEPARATOR_LINE,fGridView->Color(B_COLOR_BACKGROUND)); + rgb_color white = {255, 255, 255, 255}; + fGridView->SetColor(B_COLOR_BACKGROUND, white); + fGridView->SetColor(B_COLOR_ROW_DIVIDER, fGridView->Color(B_COLOR_BACKGROUND)); + fGridView->SetColor(B_COLOR_SELECTION, fGridView->Color(B_COLOR_BACKGROUND)); + fGridView->SetColor(B_COLOR_NON_FOCUS_SELECTION, fGridView->Color(B_COLOR_BACKGROUND)); + fGridView->SetColor(B_COLOR_SEPARATOR_BORDER, fGridView->Color(B_COLOR_BACKGROUND)); + fGridView->SetColor(B_COLOR_SEPARATOR_LINE, fGridView->Color(B_COLOR_BACKGROUND)); - fGraphView = new BView(r,"As Graph",B_FOLLOW_ALL,B_WILL_DRAW); -// view->AddChild(fGraphView); + fGraphView = new BView(r, "As Graph", B_FOLLOW_ALL, B_WILL_DRAW); + // view->AddChild(fGraphView); fGraphView->Hide(); gDatabase.AddObserver(this); - for(int32 i=0; iSortItems(compare_stringitem); fCategoryList->SortItems(compare_stringitem); - for(int32 i=0; iCountItems(); i++) - { - BStringItem *item = (BStringItem*)fAccountList->ItemAt(i); - if(!item) + for (int32 i = 0; i < fAccountList->CountItems(); i++) { + BStringItem *item = (BStringItem *)fAccountList->ItemAt(i); + if (!item) continue; Account *itemaccount = gDatabase.AccountByName(item->Text()); - if(itemaccount && (!itemaccount->IsClosed())) - fAccountList->Select(i,true); + if (itemaccount && (!itemaccount->IsClosed())) + fAccountList->Select(i, true); } -// fAccountList->Select(0,fAccountList->CountItems()-1,true); - fCategoryList->Select(0,fCategoryList->CountItems()-1,true); + // fAccountList->Select(0,fAccountList->CountItems()-1,true); + fCategoryList->Select(0, fCategoryList->CountItems() - 1, true); // Set up the scrollbars CalcCategoryString(); @@ -244,228 +248,185 @@ ReportWindow::ReportWindow(BRect frame) fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT)); } -void ReportWindow::HandleNotify(const uint64 &value, const BMessage *msg) -{ +void +ReportWindow::HandleNotify(const uint64 &value, const BMessage *msg) { Lock(); - if(value & WATCH_ACCOUNT) - { + if (value & WATCH_ACCOUNT) { Account *acc; - if(msg->FindPointer("item",(void**)&acc)!=B_OK) - { + if (msg->FindPointer("item", (void **)&acc) != B_OK) { Unlock(); return; } - if(value & WATCH_CREATE) - { + if (value & WATCH_CREATE) { AddAccount(acc); + } else if (value & WATCH_DELETE) { + } else if (value & WATCH_RENAME) { + } else if (value & WATCH_CHANGE) { } - else - if(value & WATCH_DELETE) - { - } - else - if(value & WATCH_RENAME) - { - } - else - if(value & WATCH_CHANGE) - { - } - } - else - if(value & WATCH_TRANSACTION) - { + } else if (value & WATCH_TRANSACTION) { } RenderReport(); Unlock(); } -void ReportWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_PREVIOUS_FIELD: - { - if(fStartDateBox->ChildAt(0)->IsFocus()) - fCategoryList->MakeFocus(); - else - if(fEndDateBox->ChildAt(0)->IsFocus()) - fStartDateBox->MakeFocus(); - break; - } - case M_NEXT_FIELD: - { - if(fStartDateBox->ChildAt(0)->IsFocus()) - fEndDateBox->MakeFocus(); - else - if(fEndDateBox->ChildAt(0)->IsFocus()) - fGridView->MakeFocus(); - break; - } - case M_REPORT_CASH_FLOW: - { - fReportMode = REPORT_CASH_FLOW; - RenderReport(); - break; - } - case M_REPORT_NET_WORTH: - { - fReportMode = REPORT_NET_WORTH; - RenderReport(); - break; - } - case M_REPORT_TRANSACTIONS: - { - fReportMode = REPORT_TRANSACTIONS; - RenderReport(); - break; - } - case M_REPORT_BUDGET: - { - fReportMode = REPORT_BUDGET; - RenderReport(); - break; - } +void +ReportWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_PREVIOUS_FIELD: { + if (fStartDateBox->ChildAt(0)->IsFocus()) + fCategoryList->MakeFocus(); + else if (fEndDateBox->ChildAt(0)->IsFocus()) + fStartDateBox->MakeFocus(); + break; + } + case M_NEXT_FIELD: { + if (fStartDateBox->ChildAt(0)->IsFocus()) + fEndDateBox->MakeFocus(); + else if (fEndDateBox->ChildAt(0)->IsFocus()) + fGridView->MakeFocus(); + break; + } + case M_REPORT_CASH_FLOW: { + fReportMode = REPORT_CASH_FLOW; + RenderReport(); + break; + } + case M_REPORT_NET_WORTH: { + fReportMode = REPORT_NET_WORTH; + RenderReport(); + break; + } + case M_REPORT_TRANSACTIONS: { + fReportMode = REPORT_TRANSACTIONS; + RenderReport(); + break; + } + case M_REPORT_BUDGET: { + fReportMode = REPORT_BUDGET; + RenderReport(); + break; + } + case M_SUBTOTAL_NONE: { + fSubtotalMode = SUBTOTAL_NONE; + RenderReport(); + break; + } + case M_SUBTOTAL_MONTH: { + fSubtotalMode = SUBTOTAL_MONTH; + RenderReport(); + break; + } + case M_SUBTOTAL_QUARTER: { + fSubtotalMode = SUBTOTAL_QUARTER; + RenderReport(); + break; + } + case M_SUBTOTAL_YEAR: { + fSubtotalMode = SUBTOTAL_YEAR; + RenderReport(); + break; + } - case M_SUBTOTAL_NONE: - { - fSubtotalMode = SUBTOTAL_NONE; - RenderReport(); - break; - } - case M_SUBTOTAL_MONTH: - { - fSubtotalMode = SUBTOTAL_MONTH; - RenderReport(); - break; - } - case M_SUBTOTAL_QUARTER: - { - fSubtotalMode = SUBTOTAL_QUARTER; - RenderReport(); - break; - } - case M_SUBTOTAL_YEAR: - { - fSubtotalMode = SUBTOTAL_YEAR; + case M_START_DATE_CHANGED: { + time_t temp; + if (gDefaultLocale.StringToDate(fStartDateBox->Text(), temp) == B_OK) { + fStartDate = temp; + if (fStartDate > fEndDate) + fStartDate = fEndDate; RenderReport(); + } else { + ShowAlert( + TRANSLATE("Capital Be didn't understand the date you entered."), + TRANSLATE("Capital Be understands lots of different ways of entering dates. " + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") + ); + fStartDateBox->MakeFocus(true); break; } - case M_START_DATE_CHANGED: - { - time_t temp; - if(gDefaultLocale.StringToDate(fStartDateBox->Text(),temp)==B_OK) - { - fStartDate = temp; - if(fStartDate > fEndDate) - fStartDate = fEndDate; - RenderReport(); - } - else - { - ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE( - "Capital Be understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.")); - fStartDateBox->MakeFocus(true); - break; - } + BString formatted; + gDefaultLocale.DateToString(fStartDate, formatted); + fStartDateBox->SetText(formatted.String()); - BString formatted; - gDefaultLocale.DateToString(fStartDate,formatted); - fStartDateBox->SetText(formatted.String()); - - break; - } - case M_END_DATE_CHANGED: - { - time_t temp; - if(gDefaultLocale.StringToDate(fEndDateBox->Text(),temp)==B_OK) - { - fEndDate = temp; - if(fStartDate > fEndDate) - fStartDate = fEndDate; - RenderReport(); - } - else - { - ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE( - "Capital Be understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.")); - fEndDateBox->MakeFocus(true); - break; - } - - BString formatted; - gDefaultLocale.DateToString(fEndDate,formatted); - fEndDateBox->SetText(formatted.String()); - break; - } - case M_CATEGORIES_CHANGED: - { - CalcCategoryString(); - RenderReport(); - break; - } - case M_TOGGLE_ACCOUNT: - { + break; + } + case M_END_DATE_CHANGED: { + time_t temp; + if (gDefaultLocale.StringToDate(fEndDateBox->Text(), temp) == B_OK) { + fEndDate = temp; + if (fStartDate > fEndDate) + fStartDate = fEndDate; RenderReport(); + } else { + ShowAlert( + TRANSLATE("Capital Be didn't understand the date you entered."), + TRANSLATE("Capital Be understands lots of different ways of entering dates. " + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") + ); + fEndDateBox->MakeFocus(true); break; } - case M_TOGGLE_GRAPH: - { - if(fGridView->IsHidden()) - { - fGridView->Show(); - fGraphView->Hide(); - } - else - { - fGridView->Hide(); - fGraphView->Show(); - } - break; + + BString formatted; + gDefaultLocale.DateToString(fEndDate, formatted); + fEndDateBox->SetText(formatted.String()); + break; + } + case M_CATEGORIES_CHANGED: { + CalcCategoryString(); + RenderReport(); + break; + } + case M_TOGGLE_ACCOUNT: { + RenderReport(); + break; + } + case M_TOGGLE_GRAPH: { + if (fGridView->IsHidden()) { + fGridView->Show(); + fGraphView->Hide(); + } else { + fGridView->Hide(); + fGraphView->Show(); } - default: - BWindow::MessageReceived(msg); + break; + } + default: + BWindow::MessageReceived(msg); } } -void ReportWindow::FrameResized(float w, float h) -{ +void +ReportWindow::FrameResized(float w, float h) { BScrollBar *bar = fCategoryScroller->ScrollBar(B_VERTICAL); - if(fCategoryList->CountItems()) - { + if (fCategoryList->CountItems()) { float itemheight = fCategoryList->ItemAt(0)->Height(); - float itemrange = (fCategoryList->CountItems()+1) * itemheight; - if(itemrange < fCategoryScroller->Frame().Height()) - bar->SetRange(0,0); + float itemrange = (fCategoryList->CountItems() + 1) * itemheight; + if (itemrange < fCategoryScroller->Frame().Height()) + bar->SetRange(0, 0); else - bar->SetRange(0,itemrange - fCategoryScroller->Frame().Height()); + bar->SetRange(0, itemrange - fCategoryScroller->Frame().Height()); float big, small; bar->GetSteps(&small, &big); big = (int32)(fCategoryScroller->Frame().Height() * .9); - bar->SetSteps(small,big); - } - else - bar->SetRange(0,0); + bar->SetSteps(small, big); + } else + bar->SetRange(0, 0); FixGridScrollbar(); } -void ReportWindow::AddAccount(Account *acc) -{ - if(!acc) +void +ReportWindow::AddAccount(Account *acc) { + if (!acc) return; acc->AddObserver(this); @@ -475,34 +436,29 @@ void ReportWindow::AddAccount(Account *acc) BString command = "select category from account_"; command << acc->GetID() << ";"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"ReportWindow::AddAccount"); + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "ReportWindow::AddAccount"); - while(!query.eof()) - { + while (!query.eof()) { BString catstr = DeescapeIllegalCharacters(query.getStringField(0)); - if(catstr.CountChars()<1) - { + if (catstr.CountChars() < 1) { query.nextRow(); continue; } // Make sure that the category is not already in the list. BStringItem *existing = NULL; - for(int32 k=0; kCountItems(); k++) - { - BStringItem *item = (BStringItem*)fCategoryList->ItemAt(k); - if(!item) + for (int32 k = 0; k < fCategoryList->CountItems(); k++) { + BStringItem *item = (BStringItem *)fCategoryList->ItemAt(k); + if (!item) continue; - if(catstr.ICompare(item->Text())==0) - { + if (catstr.ICompare(item->Text()) == 0) { existing = item; break; } } - if(existing) - { + if (existing) { query.nextRow(); continue; } @@ -513,24 +469,25 @@ void ReportWindow::AddAccount(Account *acc) } } -void ReportWindow::FixGridScrollbar(void) -{ +void +ReportWindow::FixGridScrollbar(void) { BScrollBar *bar = fGridView->ScrollBar(B_VERTICAL); if (!bar) return; BRow *row = fGridView->RowAt(0); - if(!row) + if (!row) return; - float itemrange = (fGridView->CountRows()+3) * row->Height();; - if(itemrange < fGridView->Frame().Height() - B_H_SCROLL_BAR_HEIGHT) - bar->SetRange(0,0); + float itemrange = (fGridView->CountRows() + 3) * row->Height(); + ; + if (itemrange < fGridView->Frame().Height() - B_H_SCROLL_BAR_HEIGHT) + bar->SetRange(0, 0); else - bar->SetRange(0,itemrange - fGridView->Frame().Height()); + bar->SetRange(0, itemrange - fGridView->Frame().Height()); float big, small; bar->GetSteps(&small, &big); big = (int32)(fGridView->Frame().Height() * .9); - bar->SetSteps(small,big); + bar->SetSteps(small, big); } /* @@ -551,16 +508,14 @@ void ReportWindow::CalcAccountString(void) } } */ -void ReportWindow::CalcCategoryString(void) -{ +void +ReportWindow::CalcCategoryString(void) { // Compile list of selected categories fCategoryString = ""; - for(int32 i=0; iCountItems(); i++) - { - BStringItem *catitem = (BStringItem*)fCategoryList->ItemAt(i); - if(catitem && catitem->IsSelected()) - { - if(fCategoryString.CountChars()>0) + for (int32 i = 0; i < fCategoryList->CountItems(); i++) { + BStringItem *catitem = (BStringItem *)fCategoryList->ItemAt(i); + if (catitem && catitem->IsSelected()) { + if (fCategoryString.CountChars() > 0) fCategoryString << ",'" << EscapeIllegalCharacters(catitem->Text()) << "'"; else fCategoryString << "'" << EscapeIllegalCharacters(catitem->Text()) << "'"; @@ -568,57 +523,50 @@ void ReportWindow::CalcCategoryString(void) } } -void ReportWindow::RenderReport(void) -{ +void +ReportWindow::RenderReport(void) { fGridView->Clear(); BColumn *column = fGridView->ColumnAt(0); - while(column) - { + while (column) { fGridView->RemoveColumn(column); delete column; column = fGridView->ColumnAt(0); } - if(fAccountList->CountItems()<1 || fAccountList->CurrentSelection()<0) + if (fAccountList->CountItems() < 1 || fAccountList->CurrentSelection() < 0) return; - switch(fReportMode) - { - case REPORT_CASH_FLOW: - { - ComputeCashFlow(); - break; - } - case REPORT_NET_WORTH: - { - ComputeNetWorth(); - break; - } - case REPORT_TRANSACTIONS: - { - ComputeTransactions(); - break; - } - case REPORT_BUDGET: - { - ComputeBudget(); - break; - } - default: - break; + switch (fReportMode) { + case REPORT_CASH_FLOW: { + ComputeCashFlow(); + break; + } + case REPORT_NET_WORTH: { + ComputeNetWorth(); + break; + } + case REPORT_TRANSACTIONS: { + ComputeTransactions(); + break; + } + case REPORT_BUDGET: { + ComputeBudget(); + break; + } + default: + break; } FixGridScrollbar(); } -bool ReportWindow::QuitRequested(void) -{ +bool +ReportWindow::QuitRequested(void) { // We need to remove this window's observer object from each account's notifier, or else // we will crash the app after closing the window and selecting an account - for (int32 i = 0; i < gDatabase.CountAccounts(); i++) - { + for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { Account *acc = gDatabase.AccountAt(i); - if(!acc) + if (!acc) continue; acc->RemoveObserver(this); @@ -627,27 +575,22 @@ bool ReportWindow::QuitRequested(void) return true; } +int +compare_stringitem(const void *item1, const void *item2) { + BListItem *listitem1 = *((BListItem **)item1); + BListItem *listitem2 = *((BListItem **)item2); -int compare_stringitem(const void *item1, const void *item2) -{ - BListItem *listitem1 = *((BListItem**)item1); - BListItem *listitem2 = *((BListItem**)item2); - - BStringItem *stritem1=(BStringItem *)listitem1; - BStringItem *stritem2=(BStringItem *)listitem2; + BStringItem *stritem1 = (BStringItem *)listitem1; + BStringItem *stritem2 = (BStringItem *)listitem2; int len1 = (stritem1 && stritem1->Text()) ? strlen(stritem1->Text()) : 0; - int len2 = (stritem2&& stritem2->Text()) ? strlen(stritem2->Text()) : 0; + int len2 = (stritem2 && stritem2->Text()) ? strlen(stritem2->Text()) : 0; - if(len1 < 1) - { + if (len1 < 1) { return (len2 < 1) ? 0 : 1; - } - else - if(len2 < 1) - { + } else if (len2 < 1) { return (len1 < 1) ? 0 : -1; } - return strcmp(stritem1->Text(),stritem2->Text()); + return strcmp(stritem1->Text(), stritem2->Text()); } diff --git a/src/ReportWindow.h b/src/ReportWindow.h index 064d9ae..af10e2d 100644 --- a/src/ReportWindow.h +++ b/src/ReportWindow.h @@ -1,66 +1,52 @@ #ifndef REPORTWINDOW_H #define REPORTWINDOW_H +#include "Account.h" +#include "DStringList.h" +#include "Notifier.h" +#include "Translate.h" +#include #include -#include -#include +#include +#include #include +#include #include -#include -#include -#include #include +#include +#include #include -#include "DStringList.h" -#include "Notifier.h" -#include "Account.h" -#include -#include "Translate.h" class StickyDrawButton; class DateBox; // This is ordered from smallest interval to largest for a reason. :^) -// Note that if this is changed, you need to also change the BUDGET_ enum in +// Note that if this is changed, you need to also change the BUDGET_ enum in // Budget.h. The BudgetReport code depends on them having the same values -enum -{ - SUBTOTAL_WEEK=0, - SUBTOTAL_MONTH, - SUBTOTAL_QUARTER, - SUBTOTAL_YEAR, - SUBTOTAL_NONE -}; +enum { SUBTOTAL_WEEK = 0, SUBTOTAL_MONTH, SUBTOTAL_QUARTER, SUBTOTAL_YEAR, SUBTOTAL_NONE }; -enum -{ - REPORT_CASH_FLOW=0, - REPORT_NET_WORTH, - REPORT_TRANSACTIONS, - REPORT_BUDGET -}; +enum { REPORT_CASH_FLOW = 0, REPORT_NET_WORTH, REPORT_TRANSACTIONS, REPORT_BUDGET }; -class ReportWindow : public BWindow, public Observer -{ -public: +class ReportWindow : public BWindow, public Observer { + public: ReportWindow(BRect frame); void MessageReceived(BMessage *msg); void FrameResized(float w, float h); void HandleNotify(const uint64 &value, const BMessage *msg); bool QuitRequested(void); - -private: + + private: void AddAccount(Account *acc); void FixGridScrollbar(void); void RenderReport(void); - + void ComputeCashFlow(void); void ComputeNetWorth(void); void ComputeTransactions(void); void ComputeBudget(void); - + void CalcCategoryString(void); - + BMenuField *fReportField; BMenuField *fSubtotalField; BListView *fAccountList; @@ -70,28 +56,25 @@ class ReportWindow : public BWindow, public Observer BScrollView *fCategoryScroller; DateBox *fStartDateBox, *fEndDateBox; StickyDrawButton *fGraphButton; - + uint8 fSubtotalMode; uint8 fReportMode; time_t fStartDate, fEndDate; - - BFont fTitleFont,fHeaderFont; - BString fAccountString,fCategoryString; + + BFont fTitleFont, fHeaderFont; + BString fAccountString, fCategoryString; }; -class AccountItem : public BStringItem -{ -public: - AccountItem(Account *acc) : BStringItem("") - { - if(acc) +class AccountItem : public BStringItem { + public: + AccountItem(Account *acc) : BStringItem("") { + if (acc) SetText(acc->Name()); account = acc; } - + Account *account; }; - #endif diff --git a/src/ScheduleAddWindow.cpp b/src/ScheduleAddWindow.cpp index 2c960fe..35962d9 100644 --- a/src/ScheduleAddWindow.cpp +++ b/src/ScheduleAddWindow.cpp @@ -1,25 +1,24 @@ #include "ScheduleAddWindow.h" #include +#include #include -#include -#include #include #include #include -#include +#include +#include #include #include "CBLocale.h" -#include "Layout.h" -#include "NumBox.h" #include "Database.h" #include "DateBox.h" +#include "Layout.h" +#include "NumBox.h" #include "ScheduledTransData.h" #include "Translate.h" -enum -{ - M_SCHEDULED_MONTHLY='schm', +enum { + M_SCHEDULED_MONTHLY = 'schm', M_SCHEDULED_WEEKLY, M_SCHEDULED_QUARTERLY, M_SCHEDULED_ANNUALLY, @@ -31,217 +30,199 @@ enum }; ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData &data) - : BWindow(frame,TRANSLATE("Schedule Transaction"),B_TITLED_WINDOW_LOOK, - B_MODAL_APP_WINDOW_FEEL,B_NOT_ZOOMABLE | B_NOT_RESIZABLE | - B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fTransData(data) -{ - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - - BView *back = new BView("backview",B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(back) - .End(); - back->SetViewColor(240,240,240); - + : BWindow( + frame, TRANSLATE("Schedule Transaction"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS + ), + fTransData(data) { + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + + BView *back = new BView("backview", B_WILL_DRAW); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); + back->SetViewColor(240, 240, 240); + BString label; label << TRANSLATE("Type") << ": " << data.Type().Type(); BStringView *typelabel = new BStringView("typelabel", label.String()); - + label = TRANSLATE("Payee"); label << ": " << data.Payee(); - BStringView *payeelabel = new BStringView("payeelabel",label.String()); - + BStringView *payeelabel = new BStringView("payeelabel", label.String()); + BString temp; - gCurrentLocale.CurrencyToString(data.Amount().AbsoluteValue(),temp); + gCurrentLocale.CurrencyToString(data.Amount().AbsoluteValue(), temp); label = TRANSLATE("Amount"); label << ": " << temp; - - BStringView *amountlabel = new BStringView("amountlabel",label.String()); - - label = TRANSLATE("Category"); label+=": "; - if(data.CountCategories()>1) + + BStringView *amountlabel = new BStringView("amountlabel", label.String()); + + label = TRANSLATE("Category"); + label += ": "; + if (data.CountCategories() > 1) label << TRANSLATE("Split"); else label << data.NameAt(0); - - BStringView *categorylabel = new BStringView("categorylabel",label.String()); - + + BStringView *categorylabel = new BStringView("categorylabel", label.String()); + label = TRANSLATE("Memo"); label << ": " << data.Memo(); - BStringView *memolabel = new BStringView("memolabel",label.String()); + BStringView *memolabel = new BStringView("memolabel", label.String()); + + // Since layout-api, we need other way to make divider + // BBox *divider = new BBox(r); + // AddChild(divider); -// Since layout-api, we need other way to make divider -// BBox *divider = new BBox(r); -// AddChild(divider); - fIntervalMenu = new BMenu(TRANSLATE("Frequency")); - fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Monthly"), - new BMessage(M_SCHEDULED_MONTHLY))); - fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Quarterly"), - new BMessage(M_SCHEDULED_QUARTERLY))); - fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Annually"), - new BMessage(M_SCHEDULED_ANNUALLY))); + fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Monthly"), new BMessage(M_SCHEDULED_MONTHLY))); + fIntervalMenu->AddItem( + new BMenuItem(TRANSLATE("Quarterly"), new BMessage(M_SCHEDULED_QUARTERLY)) + ); + fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Annually"), new BMessage(M_SCHEDULED_ANNUALLY)) + ); fIntervalMenu->ItemAt(0)->SetMarked(true); fIntervalMenu->SetLabelFromMarked(true); - - temp = TRANSLATE("Frequency"); temp += ": "; - BMenuField *intervalfield = new BMenuField("intervalfield", - temp.String(),fIntervalMenu); - - temp = TRANSLATE("Starting Date"); temp += ": "; - fStartDate = new DateBox("startdate",temp.String(),"", - new BMessage(M_DATE_CHANGED)); + + temp = TRANSLATE("Frequency"); + temp += ": "; + BMenuField *intervalfield = new BMenuField("intervalfield", temp.String(), fIntervalMenu); + + temp = TRANSLATE("Starting Date"); + temp += ": "; + fStartDate = new DateBox("startdate", temp.String(), "", new BMessage(M_DATE_CHANGED)); fStartDate->UseTabFiltering(false); - gDefaultLocale.DateToString(data.Date(),temp); + gDefaultLocale.DateToString(data.Date(), temp); fStartDate->SetText(temp.String()); - - fRepeatAlways = new BRadioButton("inftimes",TRANSLATE("Indefinitely"), - new BMessage(M_REPEAT_ALWAYS)); - - fRepeatLimited = new BRadioButton("limitedtimes","",new BMessage(M_REPEAT_LIMITED)); - - fRepeatCount = new NumBox("repeatcount",NULL,"999", - new BMessage(M_COUNT_CHANGED)); + + fRepeatAlways = + new BRadioButton("inftimes", TRANSLATE("Indefinitely"), new BMessage(M_REPEAT_ALWAYS)); + + fRepeatLimited = new BRadioButton("limitedtimes", "", new BMessage(M_REPEAT_LIMITED)); + + fRepeatCount = new NumBox("repeatcount", NULL, "999", new BMessage(M_COUNT_CHANGED)); fRepeatCount->UseTabFiltering(false); fRepeatCount->SetEnabled(false); - - BStringView *timeslabel = new BStringView("timeslabel",TRANSLATE("times")); - + + BStringView *timeslabel = new BStringView("timeslabel", TRANSLATE("times")); + fRepeatAlways->SetValue(B_CONTROL_ON); - + intervalfield->MakeFocus(true); - - BButton *okbutton = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_SCHEDULE_TRANSACTION)); + + BButton *okbutton = + new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_SCHEDULE_TRANSACTION)); okbutton->MakeDefault(true); okbutton->SetLabel(TRANSLATE("OK")); - - BButton *cancelbutton = new BButton("cancelbutton", - TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); + + BButton *cancelbutton = + new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); cancelbutton->MakeDefault(true); - + BLayoutBuilder::Group<>(back, B_VERTICAL) .SetInsets(10) .AddGrid(8.0f, 1.0f) - .Add(typelabel, 0, 0) - .Add(payeelabel, 1, 0) - .Add(amountlabel, 2, 0) - .Add(categorylabel, 0, 1) - .Add(memolabel, 1, 1) + .Add(typelabel, 0, 0) + .Add(payeelabel, 1, 0) + .Add(amountlabel, 2, 0) + .Add(categorylabel, 0, 1) + .Add(memolabel, 1, 1) .End() .AddGrid(1.0f, 1.0f) - .Add(intervalfield, 0, 0) - .Add(fRepeatAlways, 1, 0) - .Add(fStartDate, 0, 1) - .AddGrid(1.0f, 1.0f, 1, 1) - .Add(fRepeatLimited, 0, 0) - .Add(fRepeatCount, 1, 0) - .End() + .Add(intervalfield, 0, 0) + .Add(fRepeatAlways, 1, 0) + .Add(fStartDate, 0, 1) + .AddGrid(1.0f, 1.0f, 1, 1) + .Add(fRepeatLimited, 0, 0) + .Add(fRepeatCount, 1, 0) + .End() .End() .AddGrid(1.0f, 1.0f) - .AddGlue(0, 0) - .Add(cancelbutton, 1, 0) - .Add(okbutton, 2, 0) + .AddGlue(0, 0) + .Add(cancelbutton, 1, 0) + .Add(okbutton, 2, 0) .End() - .End(); + .End(); } -void ScheduleAddWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_REPEAT_ALWAYS: - { - fRepeatCount->SetEnabled(false); +void +ScheduleAddWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_REPEAT_ALWAYS: { + fRepeatCount->SetEnabled(false); + break; + } + case M_REPEAT_LIMITED: { + fRepeatCount->SetEnabled(true); + break; + } + case M_COUNT_CHANGED: { + if (fRepeatLimited->Value() == B_CONTROL_ON) { + if (strlen(fRepeatCount->Text()) < 1) + fRepeatCount->SetText("1"); + + if (atoi(fRepeatCount->Text()) < 1) + fRepeatCount->SetText("1"); + } + break; + } + case M_SCHEDULE_TRANSACTION: { + ScheduledTransData stdata(fTransData); + + BMenuItem *intervalitem = fIntervalMenu->FindMarked(); + if (!intervalitem) { + ShowBug("NULL menu item in ScheduleAddWindow"); break; } - case M_REPEAT_LIMITED: - { - fRepeatCount->SetEnabled(true); + + switch (fIntervalMenu->IndexOf(intervalitem)) { + case 0: { + stdata.SetInterval(SCHEDULED_MONTHLY); break; } - case M_COUNT_CHANGED: - { - if(fRepeatLimited->Value() == B_CONTROL_ON) - { - if(strlen(fRepeatCount->Text())<1) - fRepeatCount->SetText("1"); - - if(atoi(fRepeatCount->Text()) < 1) - fRepeatCount->SetText("1"); - } + case 1: { + stdata.SetInterval(SCHEDULED_QUARTERLY); break; } - case M_SCHEDULE_TRANSACTION: - { - ScheduledTransData stdata(fTransData); - - BMenuItem *intervalitem = fIntervalMenu->FindMarked(); - if(!intervalitem) - { - ShowBug("NULL menu item in ScheduleAddWindow"); - break; - } - - switch(fIntervalMenu->IndexOf(intervalitem)) - { - case 0: - { - stdata.SetInterval(SCHEDULED_MONTHLY); - break; - } - case 1: - { - stdata.SetInterval(SCHEDULED_QUARTERLY); - break; - } - case 2: - { - stdata.SetInterval(SCHEDULED_ANNUALLY); - break; - } - default: - { - ShowBug("Bad Interval index in ScheduleAddWindow"); - break; - } - } - - if(fRepeatCount->IsEnabled()) - stdata.SetCount(atoi(fRepeatCount->Text())); - - time_t tempdate; - BString datestr = fStartDate->Text(); - if(datestr.CountChars()<3 || - gDefaultLocale.StringToDate(datestr.String(),tempdate)!=B_OK) - { - ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE( - "Capital Be understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.")); - break; - } - - stdata.SetDate(tempdate); - - gDatabase.AddScheduledTransaction(stdata); - - if(fTransData.Type().TypeCode()==TRANS_XFER) - { - // Get the counterpart and add it to the scheduled list - gDatabase.GetTransferCounterpart(stdata.GetID(),stdata); - gDatabase.AddScheduledTransaction(stdata); - } - - PostMessage(B_QUIT_REQUESTED); + case 2: { + stdata.SetInterval(SCHEDULED_ANNUALLY); + break; + } + default: { + ShowBug("Bad Interval index in ScheduleAddWindow"); break; } - default: - BWindow::MessageReceived(msg); + } + + if (fRepeatCount->IsEnabled()) + stdata.SetCount(atoi(fRepeatCount->Text())); + + time_t tempdate; + BString datestr = fStartDate->Text(); + if (datestr.CountChars() < 3 || + gDefaultLocale.StringToDate(datestr.String(), tempdate) != B_OK) { + ShowAlert( + TRANSLATE("Capital Be didn't understand the date you entered."), + TRANSLATE("Capital Be understands lots of different ways of entering dates. " + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") + ); + break; + } + + stdata.SetDate(tempdate); + + gDatabase.AddScheduledTransaction(stdata); + + if (fTransData.Type().TypeCode() == TRANS_XFER) { + // Get the counterpart and add it to the scheduled list + gDatabase.GetTransferCounterpart(stdata.GetID(), stdata); + gDatabase.AddScheduledTransaction(stdata); + } + + PostMessage(B_QUIT_REQUESTED); + break; + } + default: + BWindow::MessageReceived(msg); } } - diff --git a/src/ScheduleAddWindow.h b/src/ScheduleAddWindow.h index bc26462..5d604ea 100644 --- a/src/ScheduleAddWindow.h +++ b/src/ScheduleAddWindow.h @@ -1,27 +1,25 @@ #ifndef SCHEDULE_ADD_WINDOW_H #define SCHEDULE_ADD_WINDOW_H -#include -#include +#include #include #include -#include +#include +#include #include "TransactionData.h" class DateBox; class NumBox; -class ScheduleAddWindow : public BWindow -{ -public: +class ScheduleAddWindow : public BWindow { + public: ScheduleAddWindow(const BRect &frame, const TransactionData &data); void MessageReceived(BMessage *msg); -private: - DateBox *fStartDate; - BRadioButton *fRepeatAlways, - *fRepeatLimited; + private: + DateBox *fStartDate; + BRadioButton *fRepeatAlways, *fRepeatLimited; BMenu *fIntervalMenu; NumBox *fRepeatCount; diff --git a/src/ScheduleListWindow.cpp b/src/ScheduleListWindow.cpp index 50e967c..9d7fa1e 100644 --- a/src/ScheduleListWindow.cpp +++ b/src/ScheduleListWindow.cpp @@ -3,8 +3,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -24,262 +24,263 @@ #include "TransactionLayout.h" #include "Translate.h" -enum -{ - M_REMOVE_ITEM='rmit' -}; +enum { M_REMOVE_ITEM = 'rmit' }; -class ScheduleListView : public BView -{ -public: +class ScheduleListView : public BView { + public: ScheduleListView(const char *name, const int32 &flags); void AttachedToWindow(void); void MessageReceived(BMessage *msg); -private: + private: // This is a float so we can get the maximum string width for payees. float RefreshScheduleList(void); - - BColumnListView *fListView; - - BButton *fRemoveButton; - BList fTransList; - HelpButton *fHelpButton; - - float fBestWidth; + + BColumnListView *fListView; + + BButton *fRemoveButton; + BList fTransList; + HelpButton *fHelpButton; + + float fBestWidth; }; -ScheduleListView::ScheduleListView(const char *name, const int32 &flags) - : BView(name, flags) -{ +ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView(name, flags) { BString temp; - SetViewColor(240,240,240); + SetViewColor(240, 240, 240); // the buttons - temp = TRANSLATE("Remove"); temp += "…"; - fRemoveButton = new BButton("removebutton",temp.String(), new BMessage(M_REMOVE_ITEM)); - + temp = TRANSLATE("Remove"); + temp += "…"; + fRemoveButton = new BButton("removebutton", temp.String(), new BMessage(M_REMOVE_ITEM)); + // the transaction list fListView = new BColumnListView("listview", B_FANCY_BORDER); - + fListView->SetSortingEnabled(false); fListView->SetEditMode(false); - - rgb_color white = {255,255,255,255}; - fListView->SetColor(B_COLOR_BACKGROUND,white); - fListView->SetColor(B_COLOR_SELECTION,GetColor(BC_SELECTION_FOCUS)); - - fListView->AddColumn(new BStringColumn(TRANSLATE("Payee"),100,25,300,B_ALIGN_LEFT),0); - + + rgb_color white = {255, 255, 255, 255}; + fListView->SetColor(B_COLOR_BACKGROUND, white); + fListView->SetColor(B_COLOR_SELECTION, GetColor(BC_SELECTION_FOCUS)); + + fListView->AddColumn(new BStringColumn(TRANSLATE("Payee"), 100, 25, 300, B_ALIGN_LEFT), 0); + float amountwidth = StringWidth("$000,000.00"); float amountlabelwidth = StringWidth(TRANSLATE("Amount")); - fListView->AddColumn(new BStringColumn(TRANSLATE("Amount"),MAX(amountwidth,amountlabelwidth),25,300,B_ALIGN_LEFT),1); - fListView->AddColumn(new BStringColumn(TRANSLATE("Payments"),StringWidth(TRANSLATE("Payments"))+20,25,300,B_ALIGN_LEFT),2); - fListView->AddColumn(new BStringColumn(TRANSLATE("Frequency"),StringWidth(TRANSLATE("Frequency"))+20,25,300,B_ALIGN_LEFT),3); - fListView->AddColumn(new BStringColumn(TRANSLATE("Next Payment"),StringWidth(TRANSLATE("Next Payment"))+20,25,300,B_ALIGN_LEFT),4); - + fListView->AddColumn( + new BStringColumn( + TRANSLATE("Amount"), MAX(amountwidth, amountlabelwidth), 25, 300, B_ALIGN_LEFT + ), + 1 + ); + fListView->AddColumn( + new BStringColumn( + TRANSLATE("Payments"), StringWidth(TRANSLATE("Payments")) + 20, 25, 300, B_ALIGN_LEFT + ), + 2 + ); + fListView->AddColumn( + new BStringColumn( + TRANSLATE("Frequency"), StringWidth(TRANSLATE("Frequency")) + 20, 25, 300, B_ALIGN_LEFT + ), + 3 + ); + fListView->AddColumn( + new BStringColumn( + TRANSLATE("Next Payment"), StringWidth(TRANSLATE("Next Payment")) + 20, 25, 300, + B_ALIGN_LEFT + ), + 4 + ); + float maxwidth = RefreshScheduleList(); - fBestWidth = (fRemoveButton->Frame().Width()*2) + 45; + fBestWidth = (fRemoveButton->Frame().Width() * 2) + 45; fBestWidth = MAX(fBestWidth, maxwidth + 35); fBestWidth += TDateWidth() + TAmountWidth() + TLeftPadding() + TLeftPadding(); fBestWidth += StringWidth("XFER") + 5; - + prefsLock.Lock(); BString schedhelp = gAppPath; prefsLock.Unlock(); schedhelp << "helpfiles/" << gCurrentLanguage->Name() << "/Scheduled Transaction Window Help"; - fHelpButton = new HelpButton("schedhelp",schedhelp.String()); + fHelpButton = new HelpButton("schedhelp", schedhelp.String()); BLayoutBuilder::Group<>(this, B_VERTICAL) .SetInsets(15, 15) .AddGrid(1.0f, 1.0f) - .Add(fListView, 0, 0, 3) - .AddGrid(1.0f, 1.0f, 0, 1, 3) - .AddGlue(0, 0) - .Add(fHelpButton, 1, 0) - .Add(fRemoveButton, 2, 0) - .End() + .Add(fListView, 0, 0, 3) + .AddGrid(1.0f, 1.0f, 0, 1, 3) + .AddGlue(0, 0) + .Add(fHelpButton, 1, 0) + .Add(fRemoveButton, 2, 0) + .End() .End() - .End(); + .End(); } -void ScheduleListView::AttachedToWindow(void) -{ +void +ScheduleListView::AttachedToWindow(void) { fListView->SetTarget(this); fRemoveButton->SetTarget(this); - - Window()->ResizeTo(fBestWidth,Window()->Frame().Height()); + + Window()->ResizeTo(fBestWidth, Window()->Frame().Height()); fListView->MakeFocus(true); } -void ScheduleListView::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_REMOVE_ITEM: - { - int32 selection = fListView->IndexOf(fListView->CurrentSelection()); - if(selection < 0) - break; - - ScheduledTransData *data = (ScheduledTransData*)fTransList.ItemAt(selection); - gDatabase.RemoveScheduledTransaction(data->GetID()); - - fTransList.RemoveItem(data); - delete data; - - // TODO: Do we need to delete this row ourselves? - fListView->RemoveRow(fListView->CurrentSelection()); +void +ScheduleListView::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_REMOVE_ITEM: { + int32 selection = fListView->IndexOf(fListView->CurrentSelection()); + if (selection < 0) break; - } - default: - { - BView::MessageReceived(msg); - break; - } + + ScheduledTransData *data = (ScheduledTransData *)fTransList.ItemAt(selection); + gDatabase.RemoveScheduledTransaction(data->GetID()); + + fTransList.RemoveItem(data); + delete data; + + // TODO: Do we need to delete this row ourselves? + fListView->RemoveRow(fListView->CurrentSelection()); + break; + } + default: { + BView::MessageReceived(msg); + break; + } } } -float ScheduleListView::RefreshScheduleList(void) -{ - for(int32 i=0; iClear(); - - CppSQLite3Query query = gDatabase.DBQuery("select count(*) from scheduledlist", - "ScheduleListView::RefreshScheduleList: count transactions"); - - if(query.eof()) + + CppSQLite3Query query = gDatabase.DBQuery( + "select count(*) from scheduledlist", + "ScheduleListView::RefreshScheduleList: count transactions" + ); + + if (query.eof()) return 0; - + int transcount = query.getIntField(0); query.finalize(); - - if(transcount<1) + + if (transcount < 1) return 0; - + uint32 idlist[transcount]; - - query = gDatabase.DBQuery("select transid from scheduledlist order by transid", - "ScheduleListView::RefreshScheduleList: get transids"); - uint32 count=0; + + query = gDatabase.DBQuery( + "select transid from scheduledlist order by transid", + "ScheduleListView::RefreshScheduleList: get transids" + ); + uint32 count = 0; idlist[count] = query.getInt64Field(0); query.nextRow(); - - while(!query.eof()) - { + + while (!query.eof()) { uint32 value = query.getInt64Field(0); - if(value!=idlist[count]) - { + if (value != idlist[count]) { count++; - idlist[count]=value; + idlist[count] = value; } query.nextRow(); } query.finalize(); - - + + // Now that we have obtained the transaction IDs of all the scheduled transactions, // we need to actually get them from the database and add them to the list. - float maxwidth=0; - - for(uint32 i=0; i<=count; i++) - { + float maxwidth = 0; + + for (uint32 i = 0; i <= count; i++) { ScheduledTransData *sdata = new ScheduledTransData(); - if(!gDatabase.GetScheduledTransaction(idlist[i],*sdata)) - { + if (!gDatabase.GetScheduledTransaction(idlist[i], *sdata)) { delete sdata; continue; } - + float width = StringWidth(sdata->Payee()); - maxwidth = MAX(maxwidth,width); - + maxwidth = MAX(maxwidth, width); + fTransList.AddItem(sdata); } - - for(int32 i=0; iAddRow(row); - - ScheduledTransData *sdata = (ScheduledTransData*)fTransList.ItemAt(i); - - row->SetField(new BStringField(sdata->Payee()),0); - + + ScheduledTransData *sdata = (ScheduledTransData *)fTransList.ItemAt(i); + + row->SetField(new BStringField(sdata->Payee()), 0); + BString string; Locale locale = sdata->GetAccount()->GetLocale(); - locale.CurrencyToString(sdata->Amount().AbsoluteValue(),string); - - row->SetField(new BStringField(sdata->Payee()),0); - row->SetField(new BStringField(string.String()),1); - - if(sdata->GetCount() > 0) - { + locale.CurrencyToString(sdata->Amount().AbsoluteValue(), string); + + row->SetField(new BStringField(sdata->Payee()), 0); + row->SetField(new BStringField(string.String()), 1); + + if (sdata->GetCount() > 0) { string = ""; string << sdata->GetCount(); - } - else + } else string = TRANSLATE("Unlimited"); - - row->SetField(new BStringField(string.String()),2); - - switch(sdata->GetInterval()) - { - case SCHEDULED_MONTHLY: - { - string = TRANSLATE("Monthly"); - break; - } - case SCHEDULED_WEEKLY: - { - string = TRANSLATE("Weekly"); - break; - } - case SCHEDULED_QUARTERLY: - { - string = TRANSLATE("Quarterly"); - break; - } - case SCHEDULED_ANNUALLY: - { - string = TRANSLATE("Annually"); - break; - } - default: - { - string = TRANSLATE("Unknown"); - break; - } + + row->SetField(new BStringField(string.String()), 2); + + switch (sdata->GetInterval()) { + case SCHEDULED_MONTHLY: { + string = TRANSLATE("Monthly"); + break; + } + case SCHEDULED_WEEKLY: { + string = TRANSLATE("Weekly"); + break; + } + case SCHEDULED_QUARTERLY: { + string = TRANSLATE("Quarterly"); + break; + } + case SCHEDULED_ANNUALLY: { + string = TRANSLATE("Annually"); + break; } - + default: { + string = TRANSLATE("Unknown"); + break; + } + } + // frequency - row->SetField(new BStringField(string.String()),3); - + row->SetField(new BStringField(string.String()), 3); + // next pay date - gDefaultLocale.DateToString(sdata->GetNextDueDate(),string); - row->SetField(new BStringField(string.String()),4); + gDefaultLocale.DateToString(sdata->GetNextDueDate(), string); + row->SetField(new BStringField(string.String()), 4); } - + return maxwidth; } ScheduleListWindow::ScheduleListWindow(const BRect &frame) - : BWindow(frame,TRANSLATE("Scheduled Transactions"),B_DOCUMENT_WINDOW_LOOK,B_NORMAL_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) -{ + : BWindow( + frame, TRANSLATE("Scheduled Transactions"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, + B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ) { AddCommonFilter(new EscapeCancelFilter); - - ScheduleListView *view = new ScheduleListView("schedview",B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL) - .SetInsets(0) - .Add(view) - .End(); -// AddShortcut('A',B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW),view); -// AddShortcut('R',B_COMMAND_KEY, new BMessage(M_REMOVE_CATEGORY),view); + ScheduleListView *view = new ScheduleListView("schedview", B_WILL_DRAW); + BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); + + // AddShortcut('A',B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW),view); + // AddShortcut('R',B_COMMAND_KEY, new BMessage(M_REMOVE_CATEGORY),view); } diff --git a/src/ScheduleListWindow.h b/src/ScheduleListWindow.h index 89db361..410da89 100644 --- a/src/ScheduleListWindow.h +++ b/src/ScheduleListWindow.h @@ -3,9 +3,8 @@ #include -class ScheduleListWindow : public BWindow -{ -public: +class ScheduleListWindow : public BWindow { + public: ScheduleListWindow(const BRect &frame); }; diff --git a/src/ScheduledExecutor.cpp b/src/ScheduledExecutor.cpp index 9289669..4c9a2de 100644 --- a/src/ScheduledExecutor.cpp +++ b/src/ScheduledExecutor.cpp @@ -1,70 +1,69 @@ -#include "ScheduledTransData.h" #include "Database.h" +#include "ScheduledTransData.h" #include "TimeSupport.h" -void HandleScheduledTransactions(void) -{ +void +HandleScheduledTransactions(void) { // This function does one thing: enter any transactions which are // scheduled for entry - - CppSQLite3Query query = gDatabase.DBQuery("select count(*) from scheduledlist", - "ScheduleListView::RefreshScheduleList: count transactions"); - - if(query.eof()) + + CppSQLite3Query query = gDatabase.DBQuery( + "select count(*) from scheduledlist", + "ScheduleListView::RefreshScheduleList: count transactions" + ); + + if (query.eof()) return; - + int transcount = query.getIntField(0); query.finalize(); - - if(transcount<1) + + if (transcount < 1) return; - + uint32 idlist[transcount]; - - query = gDatabase.DBQuery("select transid from scheduledlist order by transid", - "ScheduleListView::RefreshScheduleList: get transids"); - uint32 count=0; + + query = gDatabase.DBQuery( + "select transid from scheduledlist order by transid", + "ScheduleListView::RefreshScheduleList: get transids" + ); + uint32 count = 0; idlist[count] = query.getInt64Field(0); query.nextRow(); - - while(!query.eof()) - { + + while (!query.eof()) { uint32 value = query.getInt64Field(0); - if(value!=idlist[count]) - { + if (value != idlist[count]) { count++; - idlist[count]=value; + idlist[count] = value; } query.nextRow(); } query.finalize(); - - + + // Now that we have obtained the transaction IDs of all the scheduled transactions, // we need to actually get them from the database and add them to the list. time_t current = GetCurrentDate(); - for(uint32 i=0; i<=count; i++) - { + for (uint32 i = 0; i <= count; i++) { ScheduledTransData sdata; - if(!gDatabase.GetScheduledTransaction(idlist[i],sdata)) + if (!gDatabase.GetScheduledTransaction(idlist[i], sdata)) continue; - + time_t saved_date = sdata.Date(); bool updated = false; - while(sdata.GetNextDueDate() -#include -#include -#include -#include -#include "CBLocale.h" +#include "ScheduledTransItem.h" #include "Account.h" -#include "Preferences.h" +#include "CBLocale.h" +#include "Category.h" #include "Database.h" #include "MainWindow.h" -#include "Category.h" -#include "ScheduledTransItem.h" -#include "TransactionLayout.h" +#include "Preferences.h" #include "TransactionData.h" +#include "TransactionLayout.h" #include "Translate.h" +#include +#include +#include +#include +#include ScheduledTransItem::ScheduledTransItem(const ScheduledTransData &data) - :BListItem(), - fAccount(data.GetAccount()), - fType(data.Type().Type()), - fPayee(data.Payee()), - fAmount(""), - fCategory(""), - fMemo(data.Memo()), - fDate(""), - fID(data.GetID()) -{ + : BListItem(), fAccount(data.GetAccount()), fType(data.Type().Type()), fPayee(data.Payee()), + fAmount(""), fCategory(""), fMemo(data.Memo()), fDate(""), fID(data.GetID()) { Locale locale = data.GetAccount()->GetLocale(); - locale.CurrencyToString(data.Amount().AbsoluteValue(),fAmount); - gDefaultLocale.DateToString(data.Date(),fDate); - - if(data.CountCategories()>1) - fCategory=TRANSLATE("Split"); + locale.CurrencyToString(data.Amount().AbsoluteValue(), fAmount); + gDefaultLocale.DateToString(data.Date(), fDate); + + if (data.CountCategories() > 1) + fCategory = TRANSLATE("Split"); else - fCategory=data.NameAt(0); + fCategory = data.NameAt(0); } -void ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) -{ +void +ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) { BString string; Locale locale = fAccount->GetLocale(); - + BRect r(frame); r.right--; - + rgb_color linecolor; - - if(IsSelected()) - { - linecolor.red=120; - linecolor.green=120; - linecolor.blue=120; + + if (IsSelected()) { + linecolor.red = 120; + linecolor.green = 120; + linecolor.blue = 120; owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); owner->FillRect(frame); owner->SetHighColor(linecolor); owner->StrokeRect(frame); - owner->SetHighColor(255,255,255); - } - else - { - linecolor.red=200; - linecolor.green=200; - linecolor.blue=200; - + owner->SetHighColor(255, 255, 255); + } else { + linecolor.red = 200; + linecolor.green = 200; + linecolor.blue = 200; + owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); owner->FillRect(frame); -// owner->SetHighColor(222, 222, 222); + // owner->SetHighColor(222, 222, 222); owner->SetHighColor(linecolor); - owner->StrokeLine(r.LeftBottom(),r.RightBottom()); + owner->StrokeLine(r.LeftBottom(), r.RightBottom()); } owner->SetHighColor(0, 0, 0); @@ -82,85 +71,85 @@ void ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) cliprect.right = xpos + TDateWidth(); cliprect.top = ypos - TRowHeight(); cliprect.bottom = ypos; - + clip = cliprect; owner->ConstrainClippingRegion(&clip); owner->DrawString(fDate.String(), BPoint(xpos, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + xpos += TDateWidth(); owner->SetHighColor(linecolor); - - //Line Between Date & Type + + // Line Between Date & Type owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - - owner->StrokeLine(BPoint(0,ypos),BPoint(r.right,ypos)); + + owner->StrokeLine(BPoint(0, ypos), BPoint(r.right, ypos)); owner->SetHighColor(0, 0, 0); - + // Type - owner->SetHighColor(0,0,0); + owner->SetHighColor(0, 0, 0); owner->DrawString(fType.String(), BPoint(xpos + 5, ypos - 3)); // Line between Type and Payee xpos += TNumWidth(); owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Calculate the rectangle for the payee, but this field depends on the // width of the view, so we can't yet easily calculate the right coordinate // of the rectangle just yet BRect payee_rect(xpos, ypos, xpos, ypos - TRowHeight()); - - + + // Balance xpos = r.right - TAmountWidth(); cliprect.right = r.right; cliprect.left = xpos; clip = cliprect; owner->SetHighColor(0, 0, 0); - -/* Fixed balance = fAccount->BalanceAt(fDate); - if(balance.AsFixed()<0) - owner->SetHighColor(150, 0, 0); - locale.CurrencyToString(balance,string); - owner->DrawString(string.String(), BPoint(xpos + 5, ypos - 3)); -*/ + + /* Fixed balance = fAccount->BalanceAt(fDate); + if(balance.AsFixed()<0) + owner->SetHighColor(150, 0, 0); + locale.CurrencyToString(balance,string); + owner->DrawString(string.String(), BPoint(xpos + 5, ypos - 3)); + */ // Line between Balance and Amount owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Amount xpos -= TAmountWidth(); cliprect.right = cliprect.left; cliprect.left = xpos; clip = cliprect; - owner->SetHighColor(0,0,0); - + owner->SetHighColor(0, 0, 0); + owner->ConstrainClippingRegion(&clip); owner->DrawString(fAmount.String(), BPoint(xpos + 5, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + // Line between Amount and Payee owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Payee payee_rect.right = xpos; payee_rect.top = ypos - TRowHeight(); payee_rect.bottom = ypos; xpos = payee_rect.left; - + owner->SetHighColor(0, 0, 0); clip = payee_rect; owner->ConstrainClippingRegion(&clip); owner->DrawString(fPayee.String(), BPoint(xpos + 5, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(r.left, ypos), BPoint(r.right, ypos)); - + // Category - owner->SetHighColor(0,0,0); + owner->SetHighColor(0, 0, 0); ypos += TRowHeight(); xpos = TLeftPadding(); cliprect.left = TLeftPadding(); @@ -171,51 +160,47 @@ void ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) owner->ConstrainClippingRegion(&clip); owner->DrawString(fCategory.String(), BPoint(xpos, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + xpos = r.right / 2; cliprect.left = xpos; cliprect.right = r.right; - + // Line between Category and Memo owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Memo clip = cliprect; owner->ConstrainClippingRegion(&clip); - if(fMemo.CountChars()>0) - { - owner->SetHighColor(0,0,0); + if (fMemo.CountChars() > 0) { + owner->SetHighColor(0, 0, 0); owner->DrawString(fMemo.String(), BPoint(xpos + 5, ypos - 3)); - } - else - { + } else { owner->SetHighColor(linecolor); owner->DrawString("No Memo", BPoint(xpos + 5, ypos - 3)); } owner->ConstrainClippingRegion(NULL); } -void ScheduledTransItem::Update(BView *owner, const BFont *finfo) -{ +void +ScheduledTransItem::Update(BView *owner, const BFont *finfo) { BListItem::Update(owner, finfo); SetHeight(TRowHeight() * 2); } -void ScheduledTransItem::SetData(const TransactionData &trans) -{ +void +ScheduledTransItem::SetData(const TransactionData &trans) { fAccount = trans.GetAccount(); Locale locale = fAccount->GetLocale(); - - gDefaultLocale.DateToString(trans.Date(),fDate); + + gDefaultLocale.DateToString(trans.Date(), fDate); fType = trans.Type().Type(); fPayee = trans.Payee(); - locale.CurrencyToString(trans.Amount().AbsoluteValue(),fAmount); - if(trans.CountCategories()>1) - fCategory=TRANSLATE("Split"); + locale.CurrencyToString(trans.Amount().AbsoluteValue(), fAmount); + if (trans.CountCategories() > 1) + fCategory = TRANSLATE("Split"); else - fCategory=trans.NameAt(0); + fCategory = trans.NameAt(0); fMemo = trans.Memo(); fID = trans.GetID(); } - diff --git a/src/ScheduledTransItem.h b/src/ScheduledTransItem.h index 03b710c..c16db67 100644 --- a/src/ScheduledTransItem.h +++ b/src/ScheduledTransItem.h @@ -1,27 +1,30 @@ #ifndef SCHEDULEDTRANS_ITEM_H #define SCHEDULEDTRANS_ITEM_H +#include "ScheduledTransData.h" #include #include -#include "ScheduledTransData.h" class Account; -//void InitTransactionItemLayout(BView *owner); +// void InitTransactionItemLayout(BView *owner); -class ScheduledTransItem : public BListItem -{ -public: +class ScheduledTransItem : public BListItem { + public: ScheduledTransItem(const ScheduledTransData &data); - + void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView* owner, const BFont* finfo); + void Update(BView *owner, const BFont *finfo); + uint32 GetID(void) const { return fID; } - const char * GetDate(void) const { return fDate.String(); } + + const char *GetDate(void) const { return fDate.String(); } + const char *GetPayee(void) const { return fPayee.String(); } + void SetData(const TransactionData &trans); - -private: + + private: Account *fAccount; BString fType; BString fPayee; diff --git a/src/SplitItem.cpp b/src/SplitItem.cpp index b894f38..56e531b 100644 --- a/src/SplitItem.cpp +++ b/src/SplitItem.cpp @@ -1,56 +1,48 @@ #include "SplitItem.h" #include "Database.h" -SplitItem::SplitItem(void) - : BStringItem(""), - fName(""), - fAmount(0L), - fMemo("") -{ -} +SplitItem::SplitItem(void) : BStringItem(""), fName(""), fAmount(0L), fMemo("") {} -SplitItem::~SplitItem(void) -{ -} +SplitItem::~SplitItem(void) {} -void SplitItem::SetCategory(const char *value) -{ - fName=value; +void +SplitItem::SetCategory(const char *value) { + fName = value; UpdateLabel(); } -const char *SplitItem::GetCategory(void) const -{ +const char * +SplitItem::GetCategory(void) const { return fName.String(); } -void SplitItem::SetAmount(const Fixed &fixed) -{ - fAmount=fixed; +void +SplitItem::SetAmount(const Fixed &fixed) { + fAmount = fixed; UpdateLabel(); } -Fixed SplitItem::GetAmount(void) const -{ +Fixed +SplitItem::GetAmount(void) const { return fAmount; } -void SplitItem::SetMemo(const char *value) -{ - fMemo=value; +void +SplitItem::SetMemo(const char *value) { + fMemo = value; UpdateLabel(); } -const char *SplitItem::GetMemo(void) const -{ +const char * +SplitItem::GetMemo(void) const { return fMemo.String(); } -void SplitItem::UpdateLabel(void) -{ +void +SplitItem::UpdateLabel(void) { BString text = fName; BString amount; - gCurrentLocale.CurrencyToString(fAmount.AbsoluteValue(),amount); + gCurrentLocale.CurrencyToString(fAmount.AbsoluteValue(), amount); text << " " << amount << " " << fMemo; SetText(text.String()); } diff --git a/src/SplitItem.h b/src/SplitItem.h index 609026e..13f46aa 100644 --- a/src/SplitItem.h +++ b/src/SplitItem.h @@ -1,27 +1,26 @@ #ifndef SPLIT_ITEM_H #define SPLIT_ITEM_H +#include "Fixed.h" #include #include -#include "Fixed.h" -class SplitItem : public BStringItem -{ -public: +class SplitItem : public BStringItem { + public: SplitItem(void); ~SplitItem(void); -// void DrawItem(BView *owner, BRect frame, bool complete = false); - + // void DrawItem(BView *owner, BRect frame, bool complete = false); + void SetCategory(const char *value); const char *GetCategory(void) const; - + void SetAmount(const Fixed &fixed); Fixed GetAmount(void) const; - + void SetMemo(const char *value); const char *GetMemo(void) const; - -private: + + private: void UpdateLabel(void); BString fName; Fixed fAmount; diff --git a/src/SplitView.cpp b/src/SplitView.cpp index 282242b..daf175b 100644 --- a/src/SplitView.cpp +++ b/src/SplitView.cpp @@ -1,11 +1,11 @@ #include "SplitView.h" +#include "DAlert.h" +#include #include -#include #include #include +#include #include -#include "DAlert.h" -#include #include "Account.h" #include "CategoryBox.h" @@ -17,7 +17,6 @@ #include "HelpButton.h" #include "Layout.h" #include "MainWindow.h" -#include "MainWindow.h" #include "MsgDefs.h" #include "NavTextBox.h" #include "PayeeBox.h" @@ -26,164 +25,163 @@ #include "SplitViewFilter.h" #include "Translate.h" - SplitView::SplitView(const char *name, const TransactionData &trans, const int32 &flags) - : BView(name,flags | B_FRAME_EVENTS), - Observer(WATCH_SELECT | WATCH_TRANSACTION | WATCH_ACCOUNT) -{ + : BView(name, flags | B_FRAME_EVENTS), + Observer(WATCH_SELECT | WATCH_TRANSACTION | WATCH_ACCOUNT) { fTransaction = trans; - + fStartExpanded = false; fCheckNum = fTransaction.GetAccount()->LastCheckNumber(); - - fDateLabel = new BStringView("datelabel",TRANSLATE("Date")); - - fDate = new DateBox("dateentry","", "text",new BMessage(M_DATE_CHANGED)); -// fDate->SetEscapeCancel(true); + + fDateLabel = new BStringView("datelabel", TRANSLATE("Date")); + + fDate = new DateBox("dateentry", "", "text", new BMessage(M_DATE_CHANGED)); + // fDate->SetEscapeCancel(true); fDate->SetDate(trans.Date()); - + BString tempstr; - gDefaultLocale.DateToString(fTransaction.Date(),tempstr); + gDefaultLocale.DateToString(fTransaction.Date(), tempstr); fDate->SetText(tempstr.String()); - - fType = new CheckNumBox("typeentry","",NULL,new BMessage(M_TYPE_CHANGED)); - + + fType = new CheckNumBox("typeentry", "", NULL, new BMessage(M_TYPE_CHANGED)); + fType->SetText(fTransaction.Type().Type()); - - fTypeLabel=new BStringView("typelabel",TRANSLATE("Type")); - - fPayee = new PayeeBox("payeeentry","",fTransaction.Payee(),new BMessage(M_PAYEE_CHANGED)); - - fPayeeLabel = new BStringView("payeelabel",TRANSLATE("Payee")); - - fAmount = new CurrencyBox("amountentry","",NULL,new BMessage(M_AMOUNT_CHANGED)); - - gCurrentLocale.CurrencyToString( (fTransaction.Amount() < 0) ? fTransaction.Amount().InvertAsCopy() : - fTransaction.Amount(),tempstr); + + fTypeLabel = new BStringView("typelabel", TRANSLATE("Type")); + + fPayee = new PayeeBox("payeeentry", "", fTransaction.Payee(), new BMessage(M_PAYEE_CHANGED)); + + fPayeeLabel = new BStringView("payeelabel", TRANSLATE("Payee")); + + fAmount = new CurrencyBox("amountentry", "", NULL, new BMessage(M_AMOUNT_CHANGED)); + + gCurrentLocale.CurrencyToString( + (fTransaction.Amount() < 0) ? fTransaction.Amount().InvertAsCopy() : fTransaction.Amount(), + tempstr + ); fAmount->SetText(tempstr.String()); - - fAmountLabel = new BStringView("amountlabel",TRANSLATE("Amount")); - - fCategoryLabel = new BStringView("categorylabel",TRANSLATE("Category")); - - fCategory = new CategoryBox("categoryentry","",fTransaction.NameAt(0), - new BMessage(M_CATEGORY_CHANGED)); - - fMemoLabel = new BStringView("memolabel",TRANSLATE("Memo")); - - fMemo = new NavTextBox("memoentry","",fTransaction.Memo(),new BMessage(M_MEMO_CHANGED)); - - fSplit = new BButton("expander",TRANSLATE("Show Split"),new BMessage(M_EXPANDER_CHANGED), B_WILL_DRAW); - + + fAmountLabel = new BStringView("amountlabel", TRANSLATE("Amount")); + + fCategoryLabel = new BStringView("categorylabel", TRANSLATE("Category")); + + fCategory = new CategoryBox( + "categoryentry", "", fTransaction.NameAt(0), new BMessage(M_CATEGORY_CHANGED) + ); + + fMemoLabel = new BStringView("memolabel", TRANSLATE("Memo")); + + fMemo = new NavTextBox("memoentry", "", fTransaction.Memo(), new BMessage(M_MEMO_CHANGED)); + + fSplit = new BButton( + "expander", TRANSLATE("Show Split"), new BMessage(M_EXPANDER_CHANGED), B_WILL_DRAW + ); + prefsLock.Lock(); BString splithelp = gAppPath; prefsLock.Unlock(); splithelp << "helpfiles/" << gCurrentLanguage->Name() << "/Transaction Editor Window Help"; - fHelpButton = new HelpButton("splithelp",splithelp.String()); - + fHelpButton = new HelpButton("splithelp", splithelp.String()); + fSplitContainer = new BView("splitcontainer", B_WILL_DRAW); - fSplitContainer->SetViewColor(240,240,240); - - fAddSplit = new BButton("addsplit",TRANSLATE("Add Item"), new BMessage(M_ADD_SPLIT)); - - fRemoveSplit = new BButton("removesplit",TRANSLATE("Remove Item"), new BMessage(M_REMOVE_SPLIT)); - - fSplitCategory = new BTextControl("splitcategory",NULL,NULL,NULL, B_WILL_DRAW); - - - fSplitAmount = new BTextControl("splitamount",NULL,NULL,NULL, B_WILL_DRAW); - - fSplitMemo = new BTextControl("splitmemo",NULL,NULL,NULL, B_WILL_DRAW); - + fSplitContainer->SetViewColor(240, 240, 240); + + fAddSplit = new BButton("addsplit", TRANSLATE("Add Item"), new BMessage(M_ADD_SPLIT)); + + fRemoveSplit = + new BButton("removesplit", TRANSLATE("Remove Item"), new BMessage(M_REMOVE_SPLIT)); + + fSplitCategory = new BTextControl("splitcategory", NULL, NULL, NULL, B_WILL_DRAW); + + + fSplitAmount = new BTextControl("splitamount", NULL, NULL, NULL, B_WILL_DRAW); + + fSplitMemo = new BTextControl("splitmemo", NULL, NULL, NULL, B_WILL_DRAW); + fSplitItems = new BListView("splititems"); fSplitItems->SetSelectionMessage(new BMessage(M_SELECT_SPLIT)); - fSplitScroller = new BScrollView("split scroller",fSplitItems,0,false,true); - + fSplitScroller = new BScrollView("split scroller", fSplitItems, 0, false, true); + BString totallabel(TRANSLATE("Total")); totallabel << ": " << fTransaction.Amount().AbsoluteValue().AsFloat(); - fSplitTotal = new BStringView("splittotal",totallabel.String()); + fSplitTotal = new BStringView("splittotal", totallabel.String()); fSplitContainer->Hide(); - - fEnter = new BButton("enterbutton",TRANSLATE("Enter"), - new BMessage(M_ENTER_TRANSACTION)); - #ifndef ENTER_NAVIGATION + fEnter = new BButton("enterbutton", TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); + +#ifndef ENTER_NAVIGATION fEnter->MakeDefault(true); - #endif - +#endif + fKeyFilter = new SplitViewFilter(this); - + fCurrentDate = fTransaction.Date(); - + Locale locale = fTransaction.GetAccount()->GetLocale(); - + int32 count = fTransaction.CountCategories(); - for(int32 i=0; iSetCategory(fTransaction.NameAt(i)); item->SetAmount(fTransaction.AmountAt(i)); item->SetMemo(fTransaction.MemoAt(i)); - + fSplitItems->AddItem(item); } - - - if(fTransaction.CountCategories()>1 || strcmp(fTransaction.NameAt(0),TRANSLATE("Split"))==0) - { + + + if (fTransaction.CountCategories() > 1 || + strcmp(fTransaction.NameAt(0), TRANSLATE("Split")) == 0) { fCategory->SetText(TRANSLATE("Split Transaction")); fStartExpanded = true; } - + BLayoutBuilder::Group<>(fSplitContainer, B_VERTICAL, 0) .SetInsets(0) .AddGrid(1.0f, 0.0f) - .Add(fAddSplit, 0, 0) - .Add(fRemoveSplit, 1, 0) - .AddGlue(2, 0) - .Add(fSplitTotal, 3, 0) - .AddGlue(4, 0) + .Add(fAddSplit, 0, 0) + .Add(fRemoveSplit, 1, 0) + .AddGlue(2, 0) + .Add(fSplitTotal, 3, 0) + .AddGlue(4, 0) .End() .AddGrid(1.0f, 0.0f) - .Add(fSplitCategory, 0, 0) - .Add(fSplitAmount, 1, 0) - .Add(fSplitMemo, 3, 0) + .Add(fSplitCategory, 0, 0) + .Add(fSplitAmount, 1, 0) + .Add(fSplitMemo, 3, 0) .End() .Add(fSplitScroller) - .End(); + .End(); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .SetInsets(10) .AddGrid(1.0f, 0.0f) - .Add(fDateLabel, 0, 0) - .Add(fDate, 0, 1, 2) - .Add(fTypeLabel, 2, 0) - .Add(fType, 2, 1) - .Add(fPayeeLabel, 3, 0) - .Add(fPayee, 3, 1, 2) - .Add(fAmountLabel, 5, 0) - .Add(fAmount, 5, 1, 2) - .Add(fCategoryLabel, 0, 2) - .Add(fCategory, 0, 3, 3) - .Add(fMemoLabel, 3, 2) - .Add(fMemo, 3, 3, 4) - .Add(fSplit, 0, 5) - .Add(fHelpButton, 1, 5) - .Add(fEnter, 6, 5) + .Add(fDateLabel, 0, 0) + .Add(fDate, 0, 1, 2) + .Add(fTypeLabel, 2, 0) + .Add(fType, 2, 1) + .Add(fPayeeLabel, 3, 0) + .Add(fPayee, 3, 1, 2) + .Add(fAmountLabel, 5, 0) + .Add(fAmount, 5, 1, 2) + .Add(fCategoryLabel, 0, 2) + .Add(fCategory, 0, 3, 3) + .Add(fMemoLabel, 3, 2) + .Add(fMemo, 3, 3, 4) + .Add(fSplit, 0, 5) + .Add(fHelpButton, 1, 5) + .Add(fEnter, 6, 5) .End() .AddGroup(B_VERTICAL, 0.0f) - .Add(fSplitContainer) + .Add(fSplitContainer) .End() - .End(); + .End(); } -SplitView::~SplitView(void) -{ - delete fMessenger; -} +SplitView::~SplitView(void) { delete fMessenger; } -void SplitView::AttachedToWindow(void) -{ - SetViewColor(240,240,240); +void +SplitView::AttachedToWindow(void) { + SetViewColor(240, 240, 240); Window()->AddCommonFilter(fKeyFilter); fMessenger = new BMessenger(this); fDate->GetFilter()->SetMessenger(new BMessenger(this)); @@ -192,422 +190,347 @@ void SplitView::AttachedToWindow(void) fAmount->GetFilter()->SetMessenger(new BMessenger(this)); fCategory->GetFilter()->SetMessenger(new BMessenger(this)); fMemo->GetFilter()->SetMessenger(new BMessenger(this)); - + fEnter->SetTarget(this); fDate->MakeFocus(true); fSplit->SetTarget(this); fAddSplit->SetTarget(this); fRemoveSplit->SetTarget(this); fSplitItems->SetTarget(this); - - if(fStartExpanded) - { - // fSplit->Invoke(); + + if (fStartExpanded) { + // fSplit->Invoke(); ToggleSplit(); fSplitCategory->MakeFocus(true); } - - if(fSplitItems->CountItems()>0) + + if (fSplitItems->CountItems() > 0) fSplitItems->Select(0L); } -void SplitView::DetachedFromWindow(void) -{ +void +SplitView::DetachedFromWindow(void) { Window()->RemoveCommonFilter(fKeyFilter); } -void SplitView::MessageReceived(BMessage *msg) -{ +void +SplitView::MessageReceived(BMessage *msg) { int32 start; BString string; - switch(msg->what) - { - case M_EXPANDER_CHANGED: - { - ToggleSplit(); - break; + switch (msg->what) { + case M_EXPANDER_CHANGED: { + ToggleSplit(); + break; + } + case M_TYPE_AUTOCOMPLETE: { + + msg->FindInt32("start", &start); + msg->FindString("string", &string); + fType->SetText(string.String()); + fType->TextView()->Select(start, string.CountChars()); + break; + } + case M_PAYEE_AUTOCOMPLETE: { + msg->FindInt32("start", &start); + msg->FindString("string", &string); + fPayee->SetText(string.String()); + fPayee->TextView()->Select(start, string.CountChars()); + break; + } + case M_CATEGORY_AUTOCOMPLETE: { + msg->FindInt32("start", &start); + msg->FindString("string", &string); + if (fSplitContainer->IsHidden()) { + fCategory->SetText(string.String()); + fCategory->TextView()->Select(start, string.CountChars()); + } else { + fSplitCategory->SetText(string.String()); + fSplitCategory->TextView()->Select(start, string.CountChars()); } - case M_TYPE_AUTOCOMPLETE: - { - - msg->FindInt32("start",&start); - msg->FindString("string",&string); - fType->SetText(string.String()); - fType->TextView()->Select(start,string.CountChars()); + break; + } + case M_ENTER_TRANSACTION: { + // The text filter sends this message whenever the user hits Enter + // from the Memo field. The SplitView instance should do whatever is + // needed to post the transaction into the register + if (!fDate->Validate()) break; - } - case M_PAYEE_AUTOCOMPLETE: - { - msg->FindInt32("start",&start); - msg->FindString("string",&string); - fPayee->SetText(string.String()); - fPayee->TextView()->Select(start,string.CountChars()); + + if (!fType->Validate()) break; - } - case M_CATEGORY_AUTOCOMPLETE: - { - msg->FindInt32("start",&start); - msg->FindString("string",&string); - if(fSplitContainer->IsHidden()) - { - fCategory->SetText(string.String()); - fCategory->TextView()->Select(start,string.CountChars()); - } - else - { - fSplitCategory->SetText(string.String()); - fSplitCategory->TextView()->Select(start,string.CountChars()); - } + + if (!fPayee->Validate()) break; - } - case M_ENTER_TRANSACTION: - { - // The text filter sends this message whenever the user hits Enter - // from the Memo field. The SplitView instance should do whatever is - // needed to post the transaction into the register - if(!fDate->Validate()) - break; - - if(!fType->Validate()) - break; - - if(!fPayee->Validate()) - break; - - if(!fAmount->Validate()) - break; - - if(!fCategory->Validate()) - break; - - if(!ValidateSplitItems()) - break; - - Account *account = fTransaction.GetAccount(); - if(!account) - ShowBug("NULL transaction account in SplitView::M_ENTER_TRANSACTION"); - - Category *cat = MakeCategory(); - fTransaction.Set(account,fDate->Text(),fType->Text(),fPayee->Text(), - fAmount->Text(),NULL, fMemo->Text(),fTransaction.Status()); - fTransaction.SetCategory(*cat); - delete cat; - - try { - gDatabase.RemoveTransaction(fTransaction.GetID()); - - // This adds the transaction data without generating a new transaction id - gDatabase.AddTransaction(fTransaction,false); - } - catch(CppSQLite3Exception &e) - { - debugger(e.errorMessage()); - } - Window()->PostMessage(B_QUIT_REQUESTED); + + if (!fAmount->Validate()) break; - } - case M_PREVIOUS_FIELD: - { - if(fDate->ChildAt(0)->IsFocus()) - { - if(fDate->Validate()) - fEnter->MakeFocus(true); - } - else - if(fType->ChildAt(0)->IsFocus()) - fDate->MakeFocus(true); - else - if(fPayee->ChildAt(0)->IsFocus()) - { - if(fPayee->Validate()) - fType->MakeFocus(true); - } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - if(fAmount->Validate()) - fPayee->MakeFocus(true); - } - else - if(fCategory->ChildAt(0)->IsFocus()) - { - if(fCategory->Validate()) - fAmount->MakeFocus(true); - } - else - if(fMemo->ChildAt(0)->IsFocus()) - { - if(fSplitContainer->IsHidden()) - fCategory->MakeFocus(true); - else - fAmount->MakeFocus(true); - } - else - if(fSplit->IsFocus()) - fMemo->MakeFocus(true); - else - if(fAddSplit->IsFocus()) - fSplit->MakeFocus(true); - else - if(fRemoveSplit->IsFocus()) - fAddSplit->MakeFocus(true); - else - if(fSplitCategory->ChildAt(0)->IsFocus()) - fRemoveSplit->MakeFocus(true); - else - if(fSplitAmount->ChildAt(0)->IsFocus()) - { - if(ValidateSplitAmountField()) - fSplitCategory->MakeFocus(true); - } - else - if(fSplitMemo->ChildAt(0)->IsFocus()) - fSplitAmount->MakeFocus(true); - else - if(fSplitScroller->IsFocus()) - fSplitMemo->MakeFocus(); - else - if(fEnter->IsFocus()) - { - if(fSplitContainer->IsHidden()) - fSplit->MakeFocus(true); - else - fSplitItems->MakeFocus(true); - } - else - { - // We should *never* be here - ShowBug("M_PREVIOUS_FIELD received for unrecognized view"); - } + + if (!fCategory->Validate()) break; + + if (!ValidateSplitItems()) + break; + + Account *account = fTransaction.GetAccount(); + if (!account) + ShowBug("NULL transaction account in SplitView::M_ENTER_TRANSACTION"); + + Category *cat = MakeCategory(); + fTransaction.Set( + account, fDate->Text(), fType->Text(), fPayee->Text(), fAmount->Text(), NULL, + fMemo->Text(), fTransaction.Status() + ); + fTransaction.SetCategory(*cat); + delete cat; + + try { + gDatabase.RemoveTransaction(fTransaction.GetID()); + + // This adds the transaction data without generating a new transaction id + gDatabase.AddTransaction(fTransaction, false); + } catch (CppSQLite3Exception &e) { + debugger(e.errorMessage()); } - case M_NEXT_FIELD: - { - // This message is received from the text filter in order to - // use the Enter key to change from one entry field to another - if(fDate->ChildAt(0)->IsFocus()) - { - if(fDate->Validate()) - fType->MakeFocus(true); - } - else - if(fType->ChildAt(0)->IsFocus()) + Window()->PostMessage(B_QUIT_REQUESTED); + break; + } + case M_PREVIOUS_FIELD: { + if (fDate->ChildAt(0)->IsFocus()) { + if (fDate->Validate()) + fEnter->MakeFocus(true); + } else if (fType->ChildAt(0)->IsFocus()) + fDate->MakeFocus(true); + else if (fPayee->ChildAt(0)->IsFocus()) { + if (fPayee->Validate()) + fType->MakeFocus(true); + } else if (fAmount->ChildAt(0)->IsFocus()) { + if (fAmount->Validate()) fPayee->MakeFocus(true); + } else if (fCategory->ChildAt(0)->IsFocus()) { + if (fCategory->Validate()) + fAmount->MakeFocus(true); + } else if (fMemo->ChildAt(0)->IsFocus()) { + if (fSplitContainer->IsHidden()) + fCategory->MakeFocus(true); else - if(fPayee->ChildAt(0)->IsFocus()) - { - if(fPayee->Validate()) - fAmount->MakeFocus(true); - } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - if(fAmount->Validate()) - { - if(fSplitContainer->IsHidden()) - fCategory->MakeFocus(true); - else - fMemo->MakeFocus(true); - } - } - else - if(fCategory->ChildAt(0)->IsFocus()) - { - if(fCategory->Validate()) - fMemo->MakeFocus(true); - } - else - if(fMemo->ChildAt(0)->IsFocus()) + fAmount->MakeFocus(true); + } else if (fSplit->IsFocus()) + fMemo->MakeFocus(true); + else if (fAddSplit->IsFocus()) + fSplit->MakeFocus(true); + else if (fRemoveSplit->IsFocus()) + fAddSplit->MakeFocus(true); + else if (fSplitCategory->ChildAt(0)->IsFocus()) + fRemoveSplit->MakeFocus(true); + else if (fSplitAmount->ChildAt(0)->IsFocus()) { + if (ValidateSplitAmountField()) + fSplitCategory->MakeFocus(true); + } else if (fSplitMemo->ChildAt(0)->IsFocus()) + fSplitAmount->MakeFocus(true); + else if (fSplitScroller->IsFocus()) + fSplitMemo->MakeFocus(); + else if (fEnter->IsFocus()) { + if (fSplitContainer->IsHidden()) fSplit->MakeFocus(true); else - if(fSplit->IsFocus()) - { - if(fSplitContainer->IsHidden()) - fEnter->MakeFocus(true); + fSplitItems->MakeFocus(true); + } else { + // We should *never* be here + ShowBug("M_PREVIOUS_FIELD received for unrecognized view"); + } + break; + } + case M_NEXT_FIELD: { + // This message is received from the text filter in order to + // use the Enter key to change from one entry field to another + if (fDate->ChildAt(0)->IsFocus()) { + if (fDate->Validate()) + fType->MakeFocus(true); + } else if (fType->ChildAt(0)->IsFocus()) + fPayee->MakeFocus(true); + else if (fPayee->ChildAt(0)->IsFocus()) { + if (fPayee->Validate()) + fAmount->MakeFocus(true); + } else if (fAmount->ChildAt(0)->IsFocus()) { + if (fAmount->Validate()) { + if (fSplitContainer->IsHidden()) + fCategory->MakeFocus(true); else - fAddSplit->MakeFocus(true); - } - else - if(fAddSplit->IsFocus()) - fRemoveSplit->MakeFocus(true); - else - if(fRemoveSplit->IsFocus()) - fSplitCategory->MakeFocus(true); - else - if(fSplitCategory->ChildAt(0)->IsFocus()) - fSplitAmount->MakeFocus(true); - else - if(fSplitAmount->ChildAt(0)->IsFocus()) - { - if(ValidateSplitAmountField()) - fSplitMemo->MakeFocus(true); + fMemo->MakeFocus(true); } - else - if(fSplitMemo->ChildAt(0)->IsFocus()) - fSplitItems->MakeFocus(true); - else - if(fSplitItems->IsFocus()) + } else if (fCategory->ChildAt(0)->IsFocus()) { + if (fCategory->Validate()) + fMemo->MakeFocus(true); + } else if (fMemo->ChildAt(0)->IsFocus()) + fSplit->MakeFocus(true); + else if (fSplit->IsFocus()) { + if (fSplitContainer->IsHidden()) fEnter->MakeFocus(true); else - if(fEnter->IsFocus()) - fDate->MakeFocus(true); - else - { - // We should *never* be here - ShowBug("M_NEXT_FIELD received for unrecognized view"); - } - break; - } - case M_ADD_SPLIT: - { - if(fSplitContainer->IsHidden()) - ToggleSplit(); - - SplitItem *item = new SplitItem(); - item->SetCategory(TRANSLATE("Uncategorized")); - item->SetAmount(fTransaction.Amount().AbsoluteValue() - CalculateTotal().AbsoluteValue()); - fSplitItems->AddItem(item); - fSplitItems->Select(fSplitItems->IndexOf(item)); + fAddSplit->MakeFocus(true); + } else if (fAddSplit->IsFocus()) + fRemoveSplit->MakeFocus(true); + else if (fRemoveSplit->IsFocus()) fSplitCategory->MakeFocus(true); - fSplitCategory->TextView()->SelectAll(); - break; + else if (fSplitCategory->ChildAt(0)->IsFocus()) + fSplitAmount->MakeFocus(true); + else if (fSplitAmount->ChildAt(0)->IsFocus()) { + if (ValidateSplitAmountField()) + fSplitMemo->MakeFocus(true); + } else if (fSplitMemo->ChildAt(0)->IsFocus()) + fSplitItems->MakeFocus(true); + else if (fSplitItems->IsFocus()) + fEnter->MakeFocus(true); + else if (fEnter->IsFocus()) + fDate->MakeFocus(true); + else { + // We should *never* be here + ShowBug("M_NEXT_FIELD received for unrecognized view"); } - case M_REMOVE_SPLIT: - { - if(fSplitContainer->IsHidden()) - break; - - int32 selection = fSplitItems->CurrentSelection(); - if(selection<0) - break; - - int32 newselection; - if(fSplitItems->CountItems()==1) - newselection = -1; - else - newselection = (selection == 0) ? 0 : selection - 1; - - SplitItem *item = (SplitItem*)fSplitItems->ItemAt(selection); - fSplitItems->RemoveItem(item); - fSplitItems->Select(newselection); - fSplitCategory->TextView()->SelectAll(); + break; + } + case M_ADD_SPLIT: { + if (fSplitContainer->IsHidden()) + ToggleSplit(); + + SplitItem *item = new SplitItem(); + item->SetCategory(TRANSLATE("Uncategorized")); + item->SetAmount(fTransaction.Amount().AbsoluteValue() - CalculateTotal().AbsoluteValue()); + fSplitItems->AddItem(item); + fSplitItems->Select(fSplitItems->IndexOf(item)); + fSplitCategory->MakeFocus(true); + fSplitCategory->TextView()->SelectAll(); + break; + } + case M_REMOVE_SPLIT: { + if (fSplitContainer->IsHidden()) break; - } - case M_SELECT_SPLIT: - { - int32 selection = fSplitItems->CurrentSelection(); - if(selection<0) - break; - - SplitItem *item = (SplitItem*)fSplitItems->ItemAt(selection); - fSplitCategory->SetText(item->GetCategory()); - - BString amount; - gCurrentLocale.CurrencyToString(item->GetAmount().AbsoluteValue(),amount); - fSplitAmount->SetText(amount.String()); - - fSplitMemo->SetText(item->GetMemo()); - fSplitCategory->TextView()->SelectAll(); + + int32 selection = fSplitItems->CurrentSelection(); + if (selection < 0) break; - } - case M_EDIT_KEY: - { - // we receive this message when the user uses an editing key, such as - // backspace or delete. The reason we do this is to allow the textbox - // filter to let the editing key pass through and still save the changes - // to disk - int32 command; - if(msg->FindInt32("command",&command)==B_OK) - fMessenger->SendMessage(command); + + int32 newselection; + if (fSplitItems->CountItems() == 1) + newselection = -1; + else + newselection = (selection == 0) ? 0 : selection - 1; + + SplitItem *item = (SplitItem *)fSplitItems->ItemAt(selection); + fSplitItems->RemoveItem(item); + fSplitItems->Select(newselection); + fSplitCategory->TextView()->SelectAll(); + break; + } + case M_SELECT_SPLIT: { + int32 selection = fSplitItems->CurrentSelection(); + if (selection < 0) break; - } - // These shouldn't even be necessary, but I guess for performance - // reasons, BTextControls don't send update messages with every keystroke, - // which, unfortunately, is what we want. - case M_SPLIT_CATEGORY_CHANGED: - { - int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem*)fSplitItems->ItemAt(selection); - if(!splititem) - break; - - splititem->SetCategory(fSplitCategory->Text()); - fSplitItems->InvalidateItem(selection); - - if(strlen(fSplitCategory->Text())<1) - fTransaction.SetNameAt(selection,TRANSLATE("Uncategorized")); - else - fTransaction.SetNameAt(selection,fSplitCategory->Text()); + + SplitItem *item = (SplitItem *)fSplitItems->ItemAt(selection); + fSplitCategory->SetText(item->GetCategory()); + + BString amount; + gCurrentLocale.CurrencyToString(item->GetAmount().AbsoluteValue(), amount); + fSplitAmount->SetText(amount.String()); + + fSplitMemo->SetText(item->GetMemo()); + fSplitCategory->TextView()->SelectAll(); + break; + } + case M_EDIT_KEY: { + // we receive this message when the user uses an editing key, such as + // backspace or delete. The reason we do this is to allow the textbox + // filter to let the editing key pass through and still save the changes + // to disk + int32 command; + if (msg->FindInt32("command", &command) == B_OK) + fMessenger->SendMessage(command); + break; + } + // These shouldn't even be necessary, but I guess for performance + // reasons, BTextControls don't send update messages with every keystroke, + // which, unfortunately, is what we want. + case M_SPLIT_CATEGORY_CHANGED: { + int32 selection = fSplitItems->CurrentSelection(); + SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + if (!splititem) break; - } - case M_SPLIT_AMOUNT_CHANGED: - { - int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem*)fSplitItems->ItemAt(selection); - if(!splititem) - break; - - Fixed fixed; - if(gCurrentLocale.StringToCurrency(fSplitAmount->Text(),fixed)!=B_OK) - break; - - splititem->SetAmount(fixed); - fSplitItems->InvalidateItem(selection); - - fTransaction.SetAmountAt(selection,fixed); - - BString label("Total:"); - label << CalculateTotal().AbsoluteValue().AsFloat(); - fSplitTotal->SetText(label.String()); + + splititem->SetCategory(fSplitCategory->Text()); + fSplitItems->InvalidateItem(selection); + + if (strlen(fSplitCategory->Text()) < 1) + fTransaction.SetNameAt(selection, TRANSLATE("Uncategorized")); + else + fTransaction.SetNameAt(selection, fSplitCategory->Text()); + break; + } + case M_SPLIT_AMOUNT_CHANGED: { + int32 selection = fSplitItems->CurrentSelection(); + SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + if (!splititem) break; - } - case M_SPLIT_MEMO_CHANGED: - { - int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem*)fSplitItems->ItemAt(selection); - if(!splititem) - break; - - splititem->SetMemo(fSplitMemo->Text()); - fSplitItems->InvalidateItem(selection); - - fTransaction.SetMemoAt(selection,fSplitMemo->Text()); + + Fixed fixed; + if (gCurrentLocale.StringToCurrency(fSplitAmount->Text(), fixed) != B_OK) break; - } - case M_NEXT_SPLIT: - { - if(fSplitContainer->IsHidden()) - break; - - int32 selection = fSplitItems->CurrentSelection(); - if(selection == fSplitItems->CountItems()-1 || selection<0) - break; - - fSplitItems->Select(selection+1); + + splititem->SetAmount(fixed); + fSplitItems->InvalidateItem(selection); + + fTransaction.SetAmountAt(selection, fixed); + + BString label("Total:"); + label << CalculateTotal().AbsoluteValue().AsFloat(); + fSplitTotal->SetText(label.String()); + break; + } + case M_SPLIT_MEMO_CHANGED: { + int32 selection = fSplitItems->CurrentSelection(); + SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + if (!splititem) break; - } - case M_PREVIOUS_SPLIT: - { - if(fSplitContainer->IsHidden()) - break; - - int32 selection = fSplitItems->CurrentSelection(); - if(selection < 1) - break; - - fSplitItems->Select(selection-1); + + splititem->SetMemo(fSplitMemo->Text()); + fSplitItems->InvalidateItem(selection); + + fTransaction.SetMemoAt(selection, fSplitMemo->Text()); + break; + } + case M_NEXT_SPLIT: { + if (fSplitContainer->IsHidden()) break; - } - default: - { - BView::MessageReceived(msg); - } + + int32 selection = fSplitItems->CurrentSelection(); + if (selection == fSplitItems->CountItems() - 1 || selection < 0) + break; + + fSplitItems->Select(selection + 1); + break; + } + case M_PREVIOUS_SPLIT: { + if (fSplitContainer->IsHidden()) + break; + + int32 selection = fSplitItems->CurrentSelection(); + if (selection < 1) + break; + + fSplitItems->Select(selection - 1); + break; + } + default: { + BView::MessageReceived(msg); + } } } -void SplitView::SetFields(const char *date,const char *type, const char *payee, - const char *amount,const char *category,const char *memo) -{ +void +SplitView::SetFields( + const char *date, const char *type, const char *payee, const char *amount, const char *category, + const char *memo +) { fDate->SetText(date); fType->SetText(type); fPayee->SetText(payee); @@ -616,24 +539,21 @@ void SplitView::SetFields(const char *date,const char *type, const char *payee, fMemo->SetText(memo); } -void SplitView::HandleNotify(const uint64 &value, const BMessage *msg) -{ - if(value & WATCH_SELECT) - { - if(value & WATCH_ACCOUNT) +void +SplitView::HandleNotify(const uint64 &value, const BMessage *msg) { + if (value & WATCH_SELECT) { + if (value & WATCH_ACCOUNT) MakeEmpty(); - else - if(value & WATCH_TRANSACTION) - { + else if (value & WATCH_TRANSACTION) { TransactionData *trans; - if(msg->FindPointer("item",(void**)&trans)==B_OK) + if (msg->FindPointer("item", (void **)&trans) == B_OK) fCurrentDate = trans->Date(); } } } -void SplitView::MakeEmpty(void) -{ +void +SplitView::MakeEmpty(void) { fDate->SetText(""); fType->SetText(""); fPayee->SetText(""); @@ -642,176 +562,162 @@ void SplitView::MakeEmpty(void) fMemo->SetText(""); } -void SplitView::MakeFocus(bool value) -{ +void +SplitView::MakeFocus(bool value) { fDate->MakeFocus(value); } -void SplitView::FrameResized(float width, float height) -{ -} +void +SplitView::FrameResized(float width, float height) {} -bool SplitView::ValidateSplitAmountField(void) -{ - if(strlen(fSplitAmount->Text())<1) +bool +SplitView::ValidateSplitAmountField(void) { + if (strlen(fSplitAmount->Text()) < 1) fSplitAmount->SetText("0"); Fixed amount; - if(gCurrentLocale.StringToCurrency(fSplitAmount->Text(),amount)!=B_OK) - { - ShowAlert(TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.")); + if (gCurrentLocale.StringToCurrency(fSplitAmount->Text(), amount) != B_OK) { + ShowAlert( + TRANSLATE("Capital Be didn't understand the amount."), + TRANSLATE("There may be a typo or the wrong kind of currency symbol " + "for this account.") + ); fSplitAmount->MakeFocus(true); return false; - } - else - { + } else { BString string; - gCurrentLocale.CurrencyToString(amount,string); + gCurrentLocale.CurrencyToString(amount, string); fSplitAmount->SetText(string.String()); } - + return true; } -bool SplitView::ValidateSplitItems(void) -{ +bool +SplitView::ValidateSplitItems(void) { Fixed total; - for(int32 i=0; iCountItems(); i++) - { - SplitItem *item = (SplitItem*)fSplitItems->ItemAt(i); + for (int32 i = 0; i < fSplitItems->CountItems(); i++) { + SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); total += item->GetAmount().AbsoluteValue(); } - + Fixed amount; - if(gCurrentLocale.StringToCurrency(fAmount->Text(),amount)!=B_OK) - { + if (gCurrentLocale.StringToCurrency(fAmount->Text(), amount) != B_OK) { fAmount->MakeFocus(true); - ShowAlert(TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.")); + ShowAlert( + TRANSLATE("Capital Be didn't understand the amount."), + TRANSLATE("There may be a typo or the wrong kind of currency symbol " + "for this account.") + ); return false; } - - if(total!=amount.AbsoluteValue()) - { - + + if (total != amount.AbsoluteValue()) { + BString errormsg, totalstr; - gCurrentLocale.CurrencyToString(total,totalstr); - + gCurrentLocale.CurrencyToString(total, totalstr); + errormsg = TRANSLATE("When the split items are added together, they need to add up " - "to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%%"); - errormsg.ReplaceFirst("%%ENTERED_AMOUNT%%",fAmount->Text()); - errormsg.ReplaceFirst("%%TOTAL_AMOUNT%%",totalstr.String()); - - ShowAlert(TRANSLATE("The split total must match the amount box."),errormsg.String()); + "to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%%"); + errormsg.ReplaceFirst("%%ENTERED_AMOUNT%%", fAmount->Text()); + errormsg.ReplaceFirst("%%TOTAL_AMOUNT%%", totalstr.String()); + + ShowAlert(TRANSLATE("The split total must match the amount box."), errormsg.String()); fSplitAmount->MakeFocus(true); return false; } return true; } -bool SplitView::ValidateAllFields(void) -{ +bool +SplitView::ValidateAllFields(void) { BString date; - if(strlen(fDate->Text())<1) - { - gDefaultLocale.DateToString(fCurrentDate,date); + if (strlen(fDate->Text()) < 1) { + gDefaultLocale.DateToString(fCurrentDate, date); fDate->SetText(date.String()); - } - else - if(!fDate->Validate()) + } else if (!fDate->Validate()) return false; - - if(!fPayee->Validate()) + + if (!fPayee->Validate()) return false; - - if(!fCategory->Validate()) + + if (!fCategory->Validate()) return false; - - if(!fAmount->Validate()) + + if (!fAmount->Validate()) return false; - - if(!(ValidateSplitItems())) + + if (!(ValidateSplitItems())) return false; - + return true; } -void SplitView::ToggleSplit(void) -{ - if(fSplitContainer->IsHidden()) - { +void +SplitView::ToggleSplit(void) { + if (fSplitContainer->IsHidden()) { fSplit->SetLabel(TRANSLATE("Hide Split")); - + fSplitContainer->Show(); fCategory->SetEnabled(false); - if(fCategory->ChildAt(0)->IsFocus()) + if (fCategory->ChildAt(0)->IsFocus()) fMemo->MakeFocus(); - + // These calls are needed because of some stupid resize-related bugs in Zeta. :/ Invalidate(); fEnter->Invalidate(); - } - else - { + } else { fSplit->SetLabel(TRANSLATE("Show Split")); - + fSplitContainer->Hide(); fCategory->SetEnabled(true); } } -Category *SplitView::MakeCategory(void) -{ +Category * +SplitView::MakeCategory(void) { // This makes a category object from the existing data Category *cat = new Category(); Locale locale = fTransaction.GetAccount()->GetLocale(); - if(fSplitContainer->IsHidden() && fSplitItems->CountItems()<=1) - { - if(strlen(fCategory->Text())>0 && strlen(fAmount->Text())>0) - { + if (fSplitContainer->IsHidden() && fSplitItems->CountItems() <= 1) { + if (strlen(fCategory->Text()) > 0 && strlen(fAmount->Text()) > 0) { Fixed amt; - if(locale.StringToCurrency(fAmount->Text(),amt)==B_OK) - { + if (locale.StringToCurrency(fAmount->Text(), amt) == B_OK) { BString typestr(fType->Text()); - if(typestr.CountChars()<1 || (typestr.ICompare("dep")!=0 && amt.IsPositive())) + if (typestr.CountChars() < 1 || (typestr.ICompare("dep") != 0 && amt.IsPositive())) amt.Invert(); - - cat->AddItem(fCategory->Text(),amt); + + cat->AddItem(fCategory->Text(), amt); } } return cat; } - - for(int32 i=0; iCountItems(); i++) - { - SplitItem *item = (SplitItem*)fSplitItems->ItemAt(i); - if(!item || strlen(item->GetCategory())<1 || item->GetAmount().IsZero()) + + for (int32 i = 0; i < fSplitItems->CountItems(); i++) { + SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); + if (!item || strlen(item->GetCategory()) < 1 || item->GetAmount().IsZero()) continue; - + Fixed fixed = item->GetAmount(); - + BString typestr(fType->Text()); - if(typestr.CountChars()<1 || (typestr.ICompare("dep")!=0 && fixed.IsPositive())) + if (typestr.CountChars() < 1 || (typestr.ICompare("dep") != 0 && fixed.IsPositive())) fixed.Invert(); - - cat->AddItem(item->GetCategory(),fixed); + + cat->AddItem(item->GetCategory(), fixed); } - + return cat; } -Fixed SplitView::CalculateTotal(void) -{ +Fixed +SplitView::CalculateTotal(void) { Fixed total; - - for(int32 i=0; iCountItems(); i++) - { - SplitItem *item = (SplitItem*)fSplitItems->ItemAt(i); + + for (int32 i = 0; i < fSplitItems->CountItems(); i++) { + SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); total += item->GetAmount().AbsoluteValue(); } - + return total; } diff --git a/src/SplitView.h b/src/SplitView.h index 6da38fb..2536d9b 100644 --- a/src/SplitView.h +++ b/src/SplitView.h @@ -1,23 +1,22 @@ #ifndef SPLITVIEW_H #define SPLITVIEW_H -#include +#include "Fixed.h" +#include "Notifier.h" +#include "TransactionData.h" #include -#include +#include +#include #include #include #include -#include #include -#include "Fixed.h" -#include "Notifier.h" -#include "TransactionData.h" +#include -enum -{ - M_ADD_SPLIT='mads', +enum { + M_ADD_SPLIT = 'mads', M_REMOVE_SPLIT, - M_ENTER_TRANSACTION='metr', + M_ENTER_TRANSACTION = 'metr', M_EXPANDER_CHANGED, M_SELECT_SPLIT, M_SPLIT_CATEGORY_CHANGED, @@ -38,48 +37,50 @@ class CategoryBox; class NavTextBox; class HelpButton; -class SplitView : public BView, public Observer -{ -public: +class SplitView : public BView, public Observer { + public: SplitView(const char *name, const TransactionData &trans, const int32 &flags); ~SplitView(void); void AttachedToWindow(void); void DetachedFromWindow(void); void MessageReceived(BMessage *msg); - void SetFields(const char *date,const char *type, const char *payee, - const char *amount,const char *category,const char *memo); - + void SetFields( + const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo + ); + void HandleNotify(const uint64 &value, const BMessage *msg); void MakeEmpty(void); - void MakeFocus(bool value=true); + void MakeFocus(bool value = true); void FrameResized(float width, float height); + bool IsSplitHidden(void) const { return fSplitContainer->IsHidden(); } + void ToggleSplit(void); - -private: + + private: friend SplitViewFilter; bool ValidateAllFields(void); -// bool ValidateDateField(void); -// bool ValidateAmountField(void); + // bool ValidateDateField(void); + // bool ValidateAmountField(void); bool ValidateSplitAmountField(void); -// bool ValidateCategoryField(void); + // bool ValidateCategoryField(void); bool ValidateSplitItems(void); Fixed CalculateTotal(void); Category *MakeCategory(void); - -// BTextControl *fType,*fPayee,*fAmount,*fCategory,*fMemo; + + // BTextControl *fType,*fPayee,*fAmount,*fCategory,*fMemo; DateBox *fDate; CheckNumBox *fType; PayeeBox *fPayee; CurrencyBox *fAmount; CategoryBox *fCategory; NavTextBox *fMemo; - BStringView *fDateLabel,*fTypeLabel,*fPayeeLabel,*fAmountLabel, - *fCategoryLabel,*fMemoLabel; + BStringView *fDateLabel, *fTypeLabel, *fPayeeLabel, *fAmountLabel, *fCategoryLabel, *fMemoLabel; SplitViewFilter *fKeyFilter; BMessenger *fMessenger; BButton *fEnter, *fTransfer, *fSplit; - + BView *fSplitContainer; BTextControl *fSplitCategory, *fSplitAmount, *fSplitMemo; BListView *fSplitItems; @@ -88,7 +89,7 @@ class SplitView : public BView, public Observer BStringView *fSplitTotal; BCheckBox *fReconciled; HelpButton *fHelpButton; - + time_t fCurrentDate; bool fStartExpanded; TransactionData fTransaction; diff --git a/src/SplitViewFilter.cpp b/src/SplitViewFilter.cpp index 0253d15..bc36b96 100644 --- a/src/SplitViewFilter.cpp +++ b/src/SplitViewFilter.cpp @@ -1,228 +1,187 @@ #include "SplitViewFilter.h" -#include -#include #include "Account.h" -#include "Database.h" -#include "TimeSupport.h" #include "AutoTextControl.h" #include "CategoryBox.h" +#include "Database.h" #include "MsgDefs.h" +#include "TimeSupport.h" #include "Translate.h" +#include +#include SplitViewFilter::SplitViewFilter(SplitView *checkview) - : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE,B_KEY_DOWN), - fView(checkview) -{ -} + : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fView(checkview) {} -SplitViewFilter::~SplitViewFilter(void) -{ -} +SplitViewFilter::~SplitViewFilter(void) {} -filter_result SplitViewFilter::Filter(BMessage *msg, BHandler **target) -{ +filter_result +SplitViewFilter::Filter(BMessage *msg, BHandler **target) { int32 mod; - if(msg->FindInt32("modifiers",&mod)==B_OK) - { - if( (mod & B_COMMAND_KEY) || (mod & B_COMMAND_KEY) || - (mod & B_OPTION_KEY) ) + if (msg->FindInt32("modifiers", &mod) == B_OK) { + if ((mod & B_COMMAND_KEY) || (mod & B_COMMAND_KEY) || (mod & B_OPTION_KEY)) return B_DISPATCH_MESSAGE; } - - BView *v=dynamic_cast(*target); - if(!v) + + BView *v = dynamic_cast(*target); + if (!v) return B_DISPATCH_MESSAGE; - - BTextControl *text = dynamic_cast(v->Parent()); - BButton *button = dynamic_cast(v); - if(!text && !button) + + BTextControl *text = dynamic_cast(v->Parent()); + BButton *button = dynamic_cast(v); + if (!text && !button) return B_DISPATCH_MESSAGE; - + int32 rawchar; - msg->FindInt32("raw_char",&rawchar); - - if(rawchar==B_TAB) - { - if(mod & B_SHIFT_KEY) + msg->FindInt32("raw_char", &rawchar); + + if (rawchar == B_TAB) { + if (mod & B_SHIFT_KEY) fView->fMessenger->SendMessage(new BMessage(M_PREVIOUS_FIELD)); else fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - -// Enter Key Navigation Behavior: -// -// If the transaction is not split, Enter jumps between fields until it hits the -// memo field. From the memo field, it is as if the Enter button was clicked. -// -// If the transaction is split, it jumps from the memo field to the split -// category field. The regular category box is disabled while the split list is -// shown. When Enter is pressed from the split memo field, it is also as if -// the Enter button was pushed - if(rawchar==B_ENTER) - { - if(button) - { - if(button==fView->fEnter) - { + + // Enter Key Navigation Behavior: + // + // If the transaction is not split, Enter jumps between fields until it hits the + // memo field. From the memo field, it is as if the Enter button was clicked. + // + // If the transaction is split, it jumps from the memo field to the split + // category field. The regular category box is disabled while the split list is + // shown. When Enter is pressed from the split memo field, it is also as if + // the Enter button was pushed + if (rawchar == B_ENTER) { + if (button) { + if (button == fView->fEnter) { fView->fMessenger->SendMessage(new BMessage(M_ENTER_TRANSACTION)); return B_DISPATCH_MESSAGE; } - - #ifdef ENTER_NAVIGATION - - else - if(button==fView->fSplit) - { + +#ifdef ENTER_NAVIGATION + + else if (button == fView->fSplit) { fView->ToggleSplit(); fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; - } - else - { + } else { fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } - - #endif + +#endif } - - if(!fView->fSplitContainer->IsHidden()) - { + + if (!fView->fSplitContainer->IsHidden()) { // Enter transaction if the last split item amount box -// if(text==fView->fSplitCategory || text==fView->fSplitAmount) -// { -// fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); -// } -// else -// { -// if(text==fView->fSplitMemo) -// fView->fMessenger->SendMessage(new BMessage(M_ENTER_TRANSACTION)); -// } - - if(text==fView->fSplitMemo) + // if(text==fView->fSplitCategory || text==fView->fSplitAmount) + // { + // fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); + // } + // else + // { + // if(text==fView->fSplitMemo) + // fView->fMessenger->SendMessage(new BMessage(M_ENTER_TRANSACTION)); + // } + + if (text == fView->fSplitMemo) fView->fMessenger->SendMessage(new BMessage(M_ENTER_TRANSACTION)); - - #ifdef ENTER_NAVIGATION - + +#ifdef ENTER_NAVIGATION + else fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); - - #endif + +#endif } return B_DISPATCH_MESSAGE; } - + // Weed out navigation keys -// if(text!=fView->fSplitCategory && text!=fView->fSplitAmount && text!=fView->fSplitMemo) -// if(rawchar<32 || (button && rawchar==B_SPACE)) - switch(rawchar) - { - case B_UP_ARROW: - case B_DOWN_ARROW: - case B_LEFT_ARROW: - case B_RIGHT_ARROW: - case B_HOME: - case B_END: - { + // if(text!=fView->fSplitCategory && text!=fView->fSplitAmount && text!=fView->fSplitMemo) + // if(rawchar<32 || (button && rawchar==B_SPACE)) + switch (rawchar) { + case B_UP_ARROW: + case B_DOWN_ARROW: + case B_LEFT_ARROW: + case B_RIGHT_ARROW: + case B_HOME: + case B_END: { + return B_DISPATCH_MESSAGE; + } + case B_SPACE: { + if (button) return B_DISPATCH_MESSAGE; - } - case B_SPACE: - { - if(button) - return B_DISPATCH_MESSAGE; - } - default: - break; } - + default: + break; + } + int32 start, end; - text->TextView()->GetSelection(&start,&end); - + text->TextView()->GetSelection(&start, &end); + Account *acc = gDatabase.CurrentAccount(); - - if(text==fView->fSplitCategory || text==fView->fSplitAmount || text==fView->fSplitMemo) - { - switch(rawchar) - { - case B_UP_ARROW: - case B_DOWN_ARROW: - case B_LEFT_ARROW: - case B_RIGHT_ARROW: - { - break; + + if (text == fView->fSplitCategory || text == fView->fSplitAmount || text == fView->fSplitMemo) { + switch (rawchar) { + case B_UP_ARROW: + case B_DOWN_ARROW: + case B_LEFT_ARROW: + case B_RIGHT_ARROW: { + break; + } + case B_DELETE: + case B_BACKSPACE: { + // handle this case because of UTF-8 handling needed + + BMessage editmsg(M_EDIT_KEY); + + if (text == fView->fSplitCategory) { + editmsg.AddInt32("command", M_SPLIT_CATEGORY_CHANGED); + } else if (text == fView->fSplitAmount) { + editmsg.AddInt32("command", M_SPLIT_AMOUNT_CHANGED); + } else if (text == fView->fSplitMemo) { + editmsg.AddInt32("command", M_SPLIT_MEMO_CHANGED); } - case B_DELETE: - case B_BACKSPACE: - { - // handle this case because of UTF-8 handling needed - - BMessage editmsg(M_EDIT_KEY); - - if(text==fView->fSplitCategory) - { - editmsg.AddInt32("command",M_SPLIT_CATEGORY_CHANGED); - } - else - if(text==fView->fSplitAmount) - { - editmsg.AddInt32("command",M_SPLIT_AMOUNT_CHANGED); - } - else - if(text==fView->fSplitMemo) - { - editmsg.AddInt32("command",M_SPLIT_MEMO_CHANGED); - } - - fView->fMessenger->SendMessage(&editmsg); - break; + + fView->fMessenger->SendMessage(&editmsg); + break; + } + default: { + if (text == fView->fSplitAmount) { + BString amount_disallowed("`~!@#$%^&*()_-+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" + "ZXCVBNM<>?qwertyuiopasdfghjklzxcvbnm"); + if (amount_disallowed.FindFirst(rawchar) != B_ERROR) + return B_SKIP_MESSAGE; } - default: - { - if(text==fView->fSplitAmount) - { - BString amount_disallowed("`~!@#$%^&*()_-+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" - "ZXCVBNM<>?qwertyuiopasdfghjklzxcvbnm"); - if(amount_disallowed.FindFirst(rawchar)!=B_ERROR) - return B_SKIP_MESSAGE; - } - - BMessage keymsg(M_EDIT_KEY); - if(text==fView->fSplitCategory) - { - keymsg.AddInt32("command",M_SPLIT_CATEGORY_CHANGED); - } - else - if(text==fView->fSplitAmount) - { - keymsg.AddInt32("command",M_SPLIT_AMOUNT_CHANGED); - } - else - if(text==fView->fSplitMemo) - { - keymsg.AddInt32("command",M_SPLIT_MEMO_CHANGED); - } - - fView->fMessenger->SendMessage(&keymsg); - break; + + BMessage keymsg(M_EDIT_KEY); + if (text == fView->fSplitCategory) { + keymsg.AddInt32("command", M_SPLIT_CATEGORY_CHANGED); + } else if (text == fView->fSplitAmount) { + keymsg.AddInt32("command", M_SPLIT_AMOUNT_CHANGED); + } else if (text == fView->fSplitMemo) { + keymsg.AddInt32("command", M_SPLIT_MEMO_CHANGED); } + + fView->fMessenger->SendMessage(&keymsg); + break; + } } - if(end == (int32)strlen(text->Text())) - { - text->TextView()->Delete(start,end); - + if (end == (int32)strlen(text->Text())) { + text->TextView()->Delete(start, end); + BString string; - if(msg->FindString("bytes",&string)!=B_OK) - string=""; + if (msg->FindString("bytes", &string) != B_OK) + string = ""; string.Prepend(text->Text()); - + BString autocomplete = acc->AutocompleteCategory(string.String()); - - if(autocomplete.CountChars()>0 && autocomplete!=TRANSLATE("Split")) - { + + if (autocomplete.CountChars() > 0 && autocomplete != TRANSLATE("Split")) { BMessage automsg(M_CATEGORY_AUTOCOMPLETE); - automsg.AddInt32("start",strlen(text->Text())+1); - automsg.AddString("string",autocomplete.String()); + automsg.AddInt32("start", strlen(text->Text()) + 1); + automsg.AddString("string", autocomplete.String()); fView->fMessenger->SendMessage(&automsg); } } diff --git a/src/SplitViewFilter.h b/src/SplitViewFilter.h index cd37c62..3b76803 100644 --- a/src/SplitViewFilter.h +++ b/src/SplitViewFilter.h @@ -1,18 +1,17 @@ #ifndef SPLITVIEWFILTER_H #define SPLITVIEWFILTER_H +#include "SplitView.h" #include #include -#include "SplitView.h" -class SplitViewFilter : public BMessageFilter -{ -public: +class SplitViewFilter : public BMessageFilter { + public: SplitViewFilter(SplitView *checkview); ~SplitViewFilter(void); virtual filter_result Filter(BMessage *msg, BHandler **target); -private: + private: SplitView *fView; BString fPayeeText; }; diff --git a/src/StickyDrawButton.cpp b/src/StickyDrawButton.cpp index 5c5fb61..80e006b 100644 --- a/src/StickyDrawButton.cpp +++ b/src/StickyDrawButton.cpp @@ -1,19 +1,13 @@ #include "StickyDrawButton.h" -StickyDrawButton::StickyDrawButton(BRect frame, const char *name, BBitmap *up, - BBitmap *down, BMessage *msg, - const int32 &resize, const int32 &flags) - : BButton(frame, name, "", msg, resize, flags), - fUp(up), - fDown(down), - fDisabledUp(NULL), - fDisabledDown(NULL), - fButtonState(B_CONTROL_OFF) -{ -} +StickyDrawButton::StickyDrawButton( + BRect frame, const char *name, BBitmap *up, BBitmap *down, BMessage *msg, const int32 &resize, + const int32 &flags +) + : BButton(frame, name, "", msg, resize, flags), fUp(up), fDown(down), fDisabledUp(NULL), + fDisabledDown(NULL), fButtonState(B_CONTROL_OFF) {} -StickyDrawButton::~StickyDrawButton(void) -{ +StickyDrawButton::~StickyDrawButton(void) { delete fUp; delete fDown; delete fDisabledUp; @@ -21,53 +15,46 @@ StickyDrawButton::~StickyDrawButton(void) } void -StickyDrawButton::ResizeToPreferred(void) -{ - if(fUp) - ResizeTo(fUp->Bounds().Width(),fUp->Bounds().Height()); - else - if(fDown) - ResizeTo(fDown->Bounds().Width(),fDown->Bounds().Height()); - else - if(fDisabledUp) - ResizeTo(fDisabledUp->Bounds().Width(),fDisabledUp->Bounds().Height()); - else - if(fDisabledDown) - ResizeTo(fDisabledDown->Bounds().Width(),fDisabledDown->Bounds().Height()); +StickyDrawButton::ResizeToPreferred(void) { + if (fUp) + ResizeTo(fUp->Bounds().Width(), fUp->Bounds().Height()); + else if (fDown) + ResizeTo(fDown->Bounds().Width(), fDown->Bounds().Height()); + else if (fDisabledUp) + ResizeTo(fDisabledUp->Bounds().Width(), fDisabledUp->Bounds().Height()); + else if (fDisabledDown) + ResizeTo(fDisabledDown->Bounds().Width(), fDisabledDown->Bounds().Height()); } void -StickyDrawButton::SetBitmaps(BBitmap *up, BBitmap *down) -{ +StickyDrawButton::SetBitmaps(BBitmap *up, BBitmap *down) { delete fUp; delete fDown; - + fUp = up; fDown = down; } -void StickyDrawButton::SetDisabled(BBitmap *disabledup, BBitmap *disableddown) -{ +void +StickyDrawButton::SetDisabled(BBitmap *disabledup, BBitmap *disableddown) { delete fDisabledUp; delete fDisabledDown; - + fDisabledUp = disabledup; fDisabledDown = disableddown; } -void StickyDrawButton::MouseUp(BPoint pt) -{ +void +StickyDrawButton::MouseUp(BPoint pt) { BButton::MouseUp(pt); fButtonState = (fButtonState == B_CONTROL_ON) ? B_CONTROL_OFF : B_CONTROL_ON; Invalidate(); } void -StickyDrawButton::SetState(int32 value) -{ - if(fButtonState!=value) - { - if(value==B_CONTROL_ON) +StickyDrawButton::SetState(int32 value) { + if (fButtonState != value) { + if (value == B_CONTROL_ON) fButtonState = B_CONTROL_OFF; else fButtonState = B_CONTROL_ON; @@ -75,45 +62,35 @@ StickyDrawButton::SetState(int32 value) } } -void StickyDrawButton::Draw(BRect update) -{ +void +StickyDrawButton::Draw(BRect update) { // if down - if(fButtonState == B_CONTROL_ON) - { - if(!IsEnabled()) - { - if(fDisabledDown) - DrawBitmap(fDisabledDown, BPoint(0,0)); + if (fButtonState == B_CONTROL_ON) { + if (!IsEnabled()) { + if (fDisabledDown) + DrawBitmap(fDisabledDown, BPoint(0, 0)); else StrokeRect(Bounds()); return; - } - else - { - if(fDown) - DrawBitmap(fDown, BPoint(0,0)); + } else { + if (fDown) + DrawBitmap(fDown, BPoint(0, 0)); else StrokeRect(Bounds()); return; } - } - else - { - if(!IsEnabled()) - { - if(fDisabledUp) - DrawBitmap(fDisabledUp, BPoint(0,0)); + } else { + if (!IsEnabled()) { + if (fDisabledUp) + DrawBitmap(fDisabledUp, BPoint(0, 0)); else StrokeRect(Bounds()); return; - } - else - { - if(fUp) - DrawBitmap(fUp, BPoint(0,0)); + } else { + if (fUp) + DrawBitmap(fUp, BPoint(0, 0)); else StrokeRect(Bounds()); } } } - diff --git a/src/StickyDrawButton.h b/src/StickyDrawButton.h index 0d32695..5f9c3d4 100644 --- a/src/StickyDrawButton.h +++ b/src/StickyDrawButton.h @@ -1,40 +1,37 @@ #ifndef _STICKY_DRAWBUTTON_H #define _STICKY_DRAWBUTTON_H -#include -#include #include #include +#include +#include + +class StickyDrawButton : public BButton { + public: + StickyDrawButton( + BRect frame, const char *name, BBitmap *up, BBitmap *down, BMessage *msg, + const int32 &resize, const int32 &flags + ); + ~StickyDrawButton(void); + + void Draw(BRect update); + + void SetBitmaps(BBitmap *up, BBitmap *down); + void ResizeToPreferred(void); + void SetDisabled(BBitmap *disabledup, BBitmap *disableddown); + void MouseUp(BPoint pt); + + // void MessageReceived(BMessage *msg); + + int32 GetState(void) { return fButtonState ? 1 : 0; }; + + void SetState(int32 value); + private: + BBitmap *fUp, *fDown, *fDisabledUp, *fDisabledDown; -class StickyDrawButton : public BButton -{ -public: - StickyDrawButton(BRect frame, const char *name, BBitmap *up, - BBitmap *down, BMessage *msg, - const int32 &resize, const int32 &flags); - ~StickyDrawButton(void); - - void Draw(BRect update); - - void SetBitmaps(BBitmap *up, BBitmap *down); - void ResizeToPreferred(void); - void SetDisabled(BBitmap *disabledup, BBitmap *disableddown); - void MouseUp(BPoint pt); -// void MessageReceived(BMessage *msg); - - int32 GetState(void) { return fButtonState ? 1 : 0; }; - void SetState(int32 value); - -private: - - BBitmap *fUp, - *fDown, - *fDisabledUp, - *fDisabledDown; - - // true if in state two - int32 fButtonState; + // true if in state two + int32 fButtonState; }; #endif diff --git a/src/TextFile.cpp b/src/TextFile.cpp index b5bf6e0..ce13867 100644 --- a/src/TextFile.cpp +++ b/src/TextFile.cpp @@ -4,90 +4,77 @@ Released under the MIT license. */ #include "TextFile.h" -#include #include +#include #include -TextFile::TextFile(const char *path, const uint32 &openmode) - : BFile(path,openmode) -{ +TextFile::TextFile(const char *path, const uint32 &openmode) : BFile(path, openmode) { InitObject(); } - -TextFile::TextFile(const entry_ref &ref, const uint32 &openmode) - : BFile(&ref,openmode) -{ +TextFile::TextFile(const entry_ref &ref, const uint32 &openmode) : BFile(&ref, openmode) { InitObject(); } - -TextFile::~TextFile(void) -{ - delete [] fBuffer; - delete [] fReadBuffer; +TextFile::~TextFile(void) { + delete[] fBuffer; + delete[] fReadBuffer; } - void -TextFile::InitObject(void) -{ +TextFile::InitObject(void) { fReadBuffer = new char[4096]; fReadBufferSize = 4096; - + if (InitCheck() == B_OK) { GetSize(&fBufferSize); - fBuffer = new char[fBufferSize+1]; - - Read(fBuffer,fBufferSize); - Seek(0,SEEK_SET); - - fBuffer[fBufferSize]=0; + fBuffer = new char[fBufferSize + 1]; + + Read(fBuffer, fBufferSize); + Seek(0, SEEK_SET); + + fBuffer[fBufferSize] = 0; } else { fBuffer = NULL; fBufferSize = 0; } } - const char * -TextFile::ReadLine(void) -{ +TextFile::ReadLine(void) { off_t pos = Position(); - + char *c = fBuffer; c += sizeof(char) * pos; - - char *eol = strchr(c,'\n'); - + + char *eol = strchr(c, '\n'); + if (!eol) { // This means that there are no more linefeeds before the the // end of the file - eol = strchr(c,'\0'); + eol = strchr(c, '\0'); if (!eol) return NULL; } - - int32 length = eol-c; - + + int32 length = eol - c; + if (length > fReadBufferSize) { fReadBufferSize = length; delete fReadBuffer; fReadBuffer = new char[fReadBufferSize]; } - - strncpy(fReadBuffer,c,length); + + strncpy(fReadBuffer, c, length); fReadBuffer[length] = 0; - + Seek(length + 1, SEEK_CUR); - + // do we need to add a \0? return fReadBuffer; } - bool -TextFile::IsEOF(void) -{ +TextFile::IsEOF(void) { return (Position() > fBufferSize); } diff --git a/src/TextFile.h b/src/TextFile.h index 081f8ce..7c31b43 100644 --- a/src/TextFile.h +++ b/src/TextFile.h @@ -8,22 +8,21 @@ #include -class TextFile : public BFile -{ -public: - TextFile(const char *path, const uint32 &openmode); - TextFile(const entry_ref &ref, const uint32 &openmode); - ~TextFile(void); - const char * ReadLine(void); - bool IsEOF(void); - -private: - void InitObject(void); - - char *fBuffer; - off_t fBufferSize; - char *fReadBuffer; - int32 fReadBufferSize; +class TextFile : public BFile { + public: + TextFile(const char *path, const uint32 &openmode); + TextFile(const entry_ref &ref, const uint32 &openmode); + ~TextFile(void); + const char *ReadLine(void); + bool IsEOF(void); + + private: + void InitObject(void); + + char *fBuffer; + off_t fBufferSize; + char *fReadBuffer; + int32 fReadBufferSize; }; #endif diff --git a/src/TimeSupport.cpp b/src/TimeSupport.cpp index 5ee4d8a..784a5e1 100644 --- a/src/TimeSupport.cpp +++ b/src/TimeSupport.cpp @@ -1,109 +1,107 @@ #include "TimeSupport.h" #include -time_t IncrementDateByDay(const time_t &t) -{ +time_t +IncrementDateByDay(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_mday++; return mktime(×truct); } -time_t DecrementDateByDay(const time_t &t) -{ +time_t +DecrementDateByDay(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_mday--; return mktime(×truct); } -time_t IncrementDateByMonth(const time_t &t) -{ +time_t +IncrementDateByMonth(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_mon++; return mktime(×truct); } -time_t DecrementDateByMonth(const time_t &t) -{ +time_t +DecrementDateByMonth(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_mon--; return mktime(×truct); } -time_t IncrementDateByQuarter(const time_t &t) -{ +time_t +IncrementDateByQuarter(const time_t &t) { struct tm timestruct = *localtime(&t); int quarter = (timestruct.tm_mon + 1) / 3; - if( (timestruct.tm_mon + 1) % 3 > 0) + if ((timestruct.tm_mon + 1) % 3 > 0) quarter++; - - if(quarter == 4) - { + + if (quarter == 4) { quarter = 1; timestruct.tm_year++; - } - else + } else quarter++; - + // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we // also have to factor in that this number is indexed from 0, not 1. timestruct.tm_mon = (quarter * 3) - 3; return mktime(×truct); } -time_t IncrementDateByYear(const time_t &t) -{ +time_t +IncrementDateByYear(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_year++; return mktime(×truct); } -time_t DecrementDateByYear(const time_t &t) -{ +time_t +DecrementDateByYear(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_year--; return mktime(×truct); } -time_t GetCurrentDate(void) -{ +time_t +GetCurrentDate(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; return mktime(×truct); } // Returns the value for the first day of the month. -time_t GetCurrentMonth(void) -{ +time_t +GetCurrentMonth(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; return mktime(×truct); } // Returns the value for the first day of the quarter -time_t GetCurrentQuarter(void) -{ +time_t +GetCurrentQuarter(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; - + // Calculate the current quarter int quarter = (timestruct.tm_mon + 1) / 3; - if( (timestruct.tm_mon + 1) % 3 > 0) + if ((timestruct.tm_mon + 1) % 3 > 0) quarter++; - + // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we // also have to factor in that this number is indexed from 0, not 1. timestruct.tm_mon = (quarter * 3) - 3; @@ -111,13 +109,13 @@ time_t GetCurrentQuarter(void) } // Returns the value for the first day of the year -time_t GetCurrentYear(void) -{ +time_t +GetCurrentYear(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; timestruct.tm_mon = 0; @@ -125,56 +123,54 @@ time_t GetCurrentYear(void) return mktime(×truct); } -time_t GetLastMonth(void) -{ +time_t +GetLastMonth(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; timestruct.tm_mon--; - + return mktime(×truct); } -time_t GetLastQuarter(void) -{ +time_t +GetLastQuarter(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; - + // Calculate the current quarter int quarter = (timestruct.tm_mon + 1) / 3; - if( (timestruct.tm_mon + 1) % 3 > 0) + if ((timestruct.tm_mon + 1) % 3 > 0) quarter++; - - if(quarter == 1) - { + + if (quarter == 1) { quarter = 4; timestruct.tm_year--; - } - else + } else quarter--; - + // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we // also have to factor in that this number is indexed from 0, not 1. timestruct.tm_mon = (quarter * 3) - 3; return mktime(×truct); } -time_t GetLastYear(void) -{ +time_t +GetLastYear(void) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; timestruct.tm_mon = 0; @@ -183,135 +179,129 @@ time_t GetLastYear(void) return mktime(×truct); } -BString GetShortMonthName(const uint8 &number) -{ +BString +GetShortMonthName(const uint8 &number) { time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); timestruct.tm_mon = number; - + char string[32]; - strftime(string,32,"%b",×truct); + strftime(string, 32, "%b", ×truct); return BString(string); } -int DayOfWeek(int day, int month, int year) -{ +int +DayOfWeek(int day, int month, int year) { // adjust months so February is the last one month -= 2; - if(month < 1) - { + if (month < 1) { month += 12; --year; } - + // split by century int cent = year / 100; year %= 100; return (((26 * month - 2) / 10 + day + year + year / 4 + cent / 4 - 2 * cent) % 7); -} +} -int DaysInMonth(int month, int year) -{ - if(month > 11 || month < 0 || year < 0) - { +int +DaysInMonth(int month, int year) { + if (month > 11 || month < 0 || year < 0) { debugger("Bad value in DaysInMonth"); return 0; } - - if(year < 200) + + if (year < 200) year += 1900; - - switch(month) + + switch (month) { + case 0: // January + case 2: // March + case 4: // May + case 6: // July + case 7: // August + case 9: // October + case 11: // December { - case 0: // January - case 2: // March - case 4: // May - case 6: // July - case 7: // August - case 9: // October - case 11: // December - { - return 31; - } - case 1: - { - return (IsLeapYear(year) ? 29 : 28); - } - default: - break; + return 31; + } + case 1: { + return (IsLeapYear(year) ? 29 : 28); + } + default: + break; } - + return 30; } -bool IsLeapYear(int year) -{ - if(year < 0) - { +bool +IsLeapYear(int year) { + if (year < 0) { debugger("Bad value in IsLeapYear"); return false; } - - if(year < 200) + + if (year < 200) year += 1900; - + return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) == 1; } -int DayOfYear(int day, int month, int year) -{ - if(month > 11 || month < 0 || year < 0 || day < 0 || day > 31) - { +int +DayOfYear(int day, int month, int year) { + if (month > 11 || month < 0 || year < 0 || day < 0 || day > 31) { debugger("Bad value in DayOfYear"); return 0; } - - if(year < 200) + + if (year < 200) year += 1900; - - int daysinmonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - + + int daysinmonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int days = 0; - for(int i=0; i 0) + if ((timestruct.tm_mon + 1) % 3 > 0) quarter++; return quarter; } -int GetQuarterMonthForDate(const time_t &t) -{ +int +GetQuarterMonthForDate(const time_t &t) { struct tm timestruct = *localtime(&t); timestruct.tm_sec = 0; - timestruct.tm_min = 0; + timestruct.tm_min = 0; timestruct.tm_hour = 0; timestruct.tm_mday = 1; - + // Calculate the current quarter int quarter = (timestruct.tm_mon + 1) / 3; - if( (timestruct.tm_mon + 1) % 3 > 0) + if ((timestruct.tm_mon + 1) % 3 > 0) quarter++; - + // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we // also have to factor in that this number is indexed from 0, not 1. return (quarter * 3) - 2; diff --git a/src/TimeSupport.h b/src/TimeSupport.h index 2e6b2f7..aef8681 100644 --- a/src/TimeSupport.h +++ b/src/TimeSupport.h @@ -1,40 +1,61 @@ #ifndef TIMESUPPORT_H #define TIMESUPPORT_H -#include #include +#include -#define SECONDS_PER_DAY 86400 -#define SECONDS_PER_WEEK 604800 -#define SECONDS_PER_YEAR 31557600 - -time_t IncrementDateByDay(const time_t &t); -time_t DecrementDateByDay(const time_t &t); - -time_t IncrementDateByMonth(const time_t &t); -time_t DecrementDateByMonth(const time_t &t); -time_t IncrementDateByQuarter(const time_t &t); -time_t IncrementDateByYear(const time_t &t); -time_t DecrementDateByYear(const time_t &t); - - -time_t GetCurrentDate(void); -time_t GetCurrentMonth(void); -time_t GetCurrentQuarter(void); -time_t GetCurrentYear(void); - -time_t GetLastMonth(void); -time_t GetLastQuarter(void); -time_t GetLastYear(void); - -BString GetShortMonthName(const uint8 &number); - -int GetQuarterForDate(const time_t &t); -int GetQuarterMonthForDate(const time_t &t); - -bool IsLeapYear(int year); -int DaysInMonth(int month, int year); -int DayOfWeek(int day, int month, int year); -int DayOfYear(int day, int month, int year); +#define SECONDS_PER_DAY 86400 +#define SECONDS_PER_WEEK 604800 +#define SECONDS_PER_YEAR 31557600 + +time_t +IncrementDateByDay(const time_t &t); +time_t +DecrementDateByDay(const time_t &t); + +time_t +IncrementDateByMonth(const time_t &t); +time_t +DecrementDateByMonth(const time_t &t); +time_t +IncrementDateByQuarter(const time_t &t); +time_t +IncrementDateByYear(const time_t &t); +time_t +DecrementDateByYear(const time_t &t); + + +time_t +GetCurrentDate(void); +time_t +GetCurrentMonth(void); +time_t +GetCurrentQuarter(void); +time_t +GetCurrentYear(void); + +time_t +GetLastMonth(void); +time_t +GetLastQuarter(void); +time_t +GetLastYear(void); + +BString +GetShortMonthName(const uint8 &number); + +int +GetQuarterForDate(const time_t &t); +int +GetQuarterMonthForDate(const time_t &t); + +bool +IsLeapYear(int year); +int +DaysInMonth(int month, int year); +int +DayOfWeek(int day, int month, int year); +int +DayOfYear(int day, int month, int year); #endif diff --git a/src/Transaction.cpp b/src/Transaction.cpp index a6c23b9..2235b4f 100644 --- a/src/Transaction.cpp +++ b/src/Transaction.cpp @@ -1,50 +1,42 @@ -#include -#include -#include -#include #include "Transaction.h" +#include "Account.h" #include "CBLocale.h" #include "Database.h" -#include "Account.h" +#include +#include +#include -//#define DEBUG_TRANS +// #define DEBUG_TRANS #ifdef DEBUG_TRANS #define STRACE(x) printf x #else #define STRACE(x) /* nothing */ #endif -Transaction::Transaction(void) - : fID(0) -{ -} +Transaction::Transaction(void) : fID(0) {} -void TransactionType::SetType(const char *data) -{ - if(!data) - { +void +TransactionType::SetType(const char *data) { + if (!data) { fTypeCode = TRANS_INIT; - fTypeData =""; + fTypeData = ""; return; } - + long number = atol(data); - if(number!=0) - { + if (number != 0) { fTypeCode = TRANS_NUMERIC; fTypeData = ""; fTypeData << number; return; } - + fTypeData = data; - if(fTypeData.ICompare("ATM")==0) + if (fTypeData.ICompare("ATM") == 0) fTypeCode = TRANS_ATM; - else - if(fTypeData.ICompare("DEP")==0) + else if (fTypeData.ICompare("DEP") == 0) fTypeCode = TRANS_DEP; - else - if(fTypeData.ICompare("XFER")==0) + else if (fTypeData.ICompare("XFER") == 0) fTypeCode = TRANS_XFER; else fTypeCode = TRANS_OTHER; diff --git a/src/Transaction.h b/src/Transaction.h index f5fe575..d95290d 100644 --- a/src/Transaction.h +++ b/src/Transaction.h @@ -1,57 +1,50 @@ #ifndef TRANSACTION_H #define TRANSACTION_H -#include #include "Category.h" #include "Fixed.h" +#include class Account; -#define TRANS_OPEN 0 -#define TRANS_CLEARED 1 -#define TRANS_RECONCILED 2 - -enum -{ - TRANS_NUMERIC=0, - TRANS_ATM, - TRANS_XFER, - TRANS_DEP, - TRANS_OTHER, - TRANS_INIT -}; +#define TRANS_OPEN 0 +#define TRANS_CLEARED 1 +#define TRANS_RECONCILED 2 -typedef enum -{ - SCHEDULED_MONTHLY=0, +enum { TRANS_NUMERIC = 0, TRANS_ATM, TRANS_XFER, TRANS_DEP, TRANS_OTHER, TRANS_INIT }; + +typedef enum { + SCHEDULED_MONTHLY = 0, SCHEDULED_WEEKLY, SCHEDULED_QUARTERLY, SCHEDULED_ANNUALLY, SCHEDULED_UNKNOWN } TransactionInterval; -class TransactionType -{ -public: +class TransactionType { + public: TransactionType(const char *data) { SetType(data); } + void SetType(const char *data); + const char *Type(void) const { return fTypeData.String(); } + uint8 TypeCode(void) const { return fTypeCode; } -private: + private: uint8 fTypeCode; BString fTypeData; }; -class Transaction -{ -public: +class Transaction { + public: Transaction(void); - + void SetID(const time_t &id) { fID = id; }; + time_t GetID(void) const { return fID; } - -private: + + private: bigtime_t fID; }; diff --git a/src/TransactionData.cpp b/src/TransactionData.cpp index 58d869a..b1c846c 100644 --- a/src/TransactionData.cpp +++ b/src/TransactionData.cpp @@ -1,13 +1,12 @@ -#include -#include -#include -#include #include "TransactionData.h" +#include "Account.h" #include "CBLocale.h" #include "Database.h" -#include "Account.h" +#include +#include +#include -//#define DEBUG_TRANS +// #define DEBUG_TRANS #ifdef DEBUG_TRANS #define STRACE(x) printf x #else @@ -15,179 +14,159 @@ #endif TransactionData::TransactionData(void) - : fDate(0), - fType(""), - fStatus(TRANS_OPEN), - fID(0), - fTimeStamp(0) -{ -} + : fDate(0), fType(""), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) {} -TransactionData::TransactionData(Account *account, const char *date, const char *type, - const char *payee, const char *amount, const char *category, - const char *memo, uint8 status) - : fDate(0), - fType(type), - fAccount(NULL), - fStatus(TRANS_OPEN), - fID(0), - fTimeStamp(0) -{ +TransactionData::TransactionData( + Account *account, const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo, uint8 status +) + : fDate(0), fType(type), fAccount(NULL), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) { fCategory.MakeEmpty(); - Set(account,date,type,payee,amount,category,memo,status); + Set(account, date, type, payee, amount, category, memo, status); } TransactionData::TransactionData(const TransactionData &trans) - : fDate(0), - fType(""), - fStatus(TRANS_OPEN), - fTimeStamp(0) -{ + : fDate(0), fType(""), fStatus(TRANS_OPEN), fTimeStamp(0) { fCategory.MakeEmpty(); *this = trans; } +TransactionData::~TransactionData() {} -TransactionData::~TransactionData() -{ -} - -TransactionData &TransactionData::operator=(const TransactionData &from) -{ +TransactionData & +TransactionData::operator=(const TransactionData &from) { fDate = from.fDate; fType = from.fType; - + fAccount = from.fAccount; fPayee = from.fPayee; fAmount = from.fAmount; fCategory = from.fCategory; - + fMemo = from.fMemo; fStatus = from.fStatus; fID = from.fID; fTimeStamp = from.fTimeStamp; - + return *this; } -status_t TransactionData::Set(Account *account, const char *date, const char *type, - const char *payee,const char *amount, const char *category, const char *memo, - uint8 status) -{ - STRACE(("TransactionData(%s,%s,%s,%s,%s,%s,%s\n",date,type,payee,amount, - category,memo,status ? "reconciled" : "not reconciled")); - +status_t +TransactionData::Set( + Account *account, const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo, uint8 status +) { + STRACE( + ("TransactionData(%s,%s,%s,%s,%s,%s,%s\n", date, type, payee, amount, category, memo, + status ? "reconciled" : "not reconciled") + ); + fAccount = account; - + fType.SetType(type); - gDefaultLocale.StringToDate(date,fDate); - + gDefaultLocale.StringToDate(date, fDate); + fPayee = payee; - if(gCurrentLocale.StringToCurrency(amount,fAmount)!=B_OK) + if (gCurrentLocale.StringToCurrency(amount, fAmount) != B_OK) fAmount = 0; - - if(fType.TypeCode() == TRANS_DEP) - { - if(fAmount.IsNegative()) + + if (fType.TypeCode() == TRANS_DEP) { + if (fAmount.IsNegative()) fAmount.Invert(); - } - else - { - if(fAmount.IsPositive()) + } else { + if (fAmount.IsPositive()) fAmount.Invert(); } - + SetCategory(category); fMemo = memo; fStatus = status; - + return B_OK; } -uint8 TransactionData::Month() -{ - tm* t = localtime(&fDate); - return(t->tm_mon); +uint8 +TransactionData::Month() { + tm *t = localtime(&fDate); + return (t->tm_mon); } -uint8 TransactionData::Year() -{ - tm* t = localtime(&fDate); - return(t->tm_year); +uint8 +TransactionData::Year() { + tm *t = localtime(&fDate); + return (t->tm_year); } -void TransactionData::PrintToStream(void) -{ - BString str,temp; - gDefaultLocale.DateToString(fDate,str); - +void +TransactionData::PrintToStream(void) { + BString str, temp; + gDefaultLocale.DateToString(fDate, str); + str.Prepend(""); - + str << " " << fType.Type() << " " << fPayee << " " << (float)(fAmount.AsFloat()) << " "; printf(str.String()); - + fCategory.PrintToStream(); - + str = ""; str << " " << fMemo << " "; - if(fStatus == TRANS_CLEARED) + if (fStatus == TRANS_CLEARED) str << "cleared"; - else - if(fStatus == TRANS_RECONCILED) + else if (fStatus == TRANS_RECONCILED) str << "reconciled"; else str << "cpen"; - - str << " " << "\n"; + + str << " " + << "\n"; printf(str.String()); } -void TransactionData::SetType(const TransactionType &type) -{ - fType=type; +void +TransactionData::SetType(const TransactionType &type) { + fType = type; } -void TransactionData::SetType(const char *type) -{ +void +TransactionData::SetType(const char *type) { fType.SetType(type); } -void TransactionData::SetCategory(const char *cat) -{ - if(!cat) - { +void +TransactionData::SetCategory(const char *cat) { + if (!cat) { fCategory.MakeEmpty(); return; } - - if(fCategory.CountItems()>0) + + if (fCategory.CountItems() > 0) fCategory.MakeEmpty(); - - fCategory.AddItem(cat,fAmount); + + fCategory.AddItem(cat, fAmount); } -void TransactionData::SetCategory(const Category &cat) -{ +void +TransactionData::SetCategory(const Category &cat) { fCategory = cat; } -void TransactionData::AddCategory(const char *name, const Fixed &amount, const bool &recalculate) -{ - if(!name) +void +TransactionData::AddCategory(const char *name, const Fixed &amount, const bool &recalculate) { + if (!name) return; - - fCategory.AddItem(name,amount); - if(recalculate) - { + + fCategory.AddItem(name, amount); + if (recalculate) { Fixed total; - for(int32 i=0; i #include "Category.h" #include "Fixed.h" #include "TextFile.h" +#include #include "Transaction.h" -class TransactionData -{ -public: +class TransactionData { + public: TransactionData(void); - TransactionData(Account *account, const char *date, const char *type, - const char *payee, const char *amount, const char *category, - const char *memo, uint8 status=TRANS_OPEN); + TransactionData( + Account *account, const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo, uint8 status = TRANS_OPEN + ); TransactionData(const TransactionData &trans); virtual ~TransactionData(void); TransactionData &operator=(const TransactionData &from); - status_t Set(Account *account, const char *date, const char *type, - const char *payee, const char *amount, const char *category, - const char *memo, uint8 status=TRANS_OPEN); - + status_t + Set(Account *account, const char *date, const char *type, const char *payee, const char *amount, + const char *category, const char *memo, uint8 status = TRANS_OPEN); + uint8 Month(void); uint8 Year(void); - + time_t Date(void) const { return fDate; } - void SetDate(const time_t &t) { fDate=t; }; - + + void SetDate(const time_t &t) { fDate = t; }; + TransactionType Type(void) const { return fType; } + void SetType(const TransactionType &type); void SetType(const char *type); - + const char *Payee(void) const { return fPayee.String(); } + void SetPayee(const char *payee) { fPayee = payee; }; - + Fixed Amount(void) const { return fAmount; } - void SetAmount(const Fixed &fixed) { fAmount=fixed; } - + + void SetAmount(const Fixed &fixed) { fAmount = fixed; } + void PrintToStream(void); - + void SetCategory(const char *cat); void SetCategory(const Category &cat); - void AddCategory(const char *name, const Fixed &amount=0, const bool &recalculate=true); + void AddCategory(const char *name, const Fixed &amount = 0, const bool &recalculate = true); + void RemoveCategory(const int32 &index) { fCategory.RemoveItem(index); } - void SetNameAt(const int32 &index, const char *name) { fCategory.SetNameAt(index,name); } + + void SetNameAt(const int32 &index, const char *name) { fCategory.SetNameAt(index, name); } + const char *NameAt(const int32 &index) const { return fCategory.NameAt(index); } - void SetAmountAt(const int32 &index, const Fixed &amount) { fCategory.SetAmountAt(index,amount); } + + void SetAmountAt(const int32 &index, const Fixed &amount) { + fCategory.SetAmountAt(index, amount); + } + Fixed AmountAt(const int32 &index) const { return fCategory.AmountAt(index); } - void SetMemoAt(const int32 &index, const char *memo) { fCategory.SetMemoAt(index,memo); } + + void SetMemoAt(const int32 &index, const char *memo) { fCategory.SetMemoAt(index, memo); } + const char *MemoAt(const int32 &index) const { return fCategory.MemoAt(index); } + int32 CountCategories(void) const { return fCategory.CountItems(); } + Category GetCategory(void) { return fCategory; } - + const char *Memo(void) const { return fMemo.String(); } - void SetMemo(const char *memo) { fMemo=memo; } - + + void SetMemo(const char *memo) { fMemo = memo; } + Account *GetAccount(void) const { return fAccount; } + void SetAccount(Account *acc) { fAccount = acc; } - + uint32 GetID(void) const { return fID; } + void SetID(const uint32 value) { fID = value; } - + // Cleared, Reconciled, etc. uint8 Status(void) const { return fStatus; } - void SetStatus(uint8 value) { fStatus=value; } - + + void SetStatus(uint8 value) { fStatus = value; } + void SetTimeStamp(const bigtime_t &time) { fTimeStamp = time; } + bigtime_t GetTimeStamp(void) const { return fTimeStamp; } - + virtual void MakeEmpty(void); - + // If everything which needs to be in a transaction is there and valid, it // returns true virtual bool IsValid(void) const; - -private: + + private: time_t fDate; TransactionType fType; - + Account *fAccount; BString fPayee; Fixed fAmount; diff --git a/src/TransactionEditWindow.cpp b/src/TransactionEditWindow.cpp index 110cc41..cd1aaa3 100644 --- a/src/TransactionEditWindow.cpp +++ b/src/TransactionEditWindow.cpp @@ -1,48 +1,41 @@ -#include #include "TransactionEditWindow.h" #include "Translate.h" +#include #define M_TOGGLE_SPLIT 'tspl' -TransactionEditWindow::TransactionEditWindow(const BRect &frame, - const TransactionData &trans) - : BWindow(frame, TRANSLATE("Edit Transaction"),B_DOCUMENT_WINDOW_LOOK, - B_FLOATING_APP_WINDOW_FEEL,B_AUTO_UPDATE_SIZE_LIMITS) -{ - fSplitView = new SplitView("splitview",trans,B_WILL_DRAW); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(fSplitView) - .End(); - - AddShortcut('S',B_COMMAND_KEY,new BMessage(M_TOGGLE_SPLIT)); - AddShortcut('A',B_COMMAND_KEY,new BMessage(M_ADD_SPLIT)); - AddShortcut('R',B_COMMAND_KEY,new BMessage(M_REMOVE_SPLIT)); - AddShortcut('Q',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut(B_UP_ARROW,B_COMMAND_KEY,new BMessage(M_PREVIOUS_SPLIT)); - AddShortcut(B_DOWN_ARROW,B_COMMAND_KEY,new BMessage(M_NEXT_SPLIT)); +TransactionEditWindow::TransactionEditWindow(const BRect &frame, const TransactionData &trans) + : BWindow( + frame, TRANSLATE("Edit Transaction"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, + B_AUTO_UPDATE_SIZE_LIMITS + ) { + fSplitView = new SplitView("splitview", trans, B_WILL_DRAW); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(fSplitView).End(); + + AddShortcut('S', B_COMMAND_KEY, new BMessage(M_TOGGLE_SPLIT)); + AddShortcut('A', B_COMMAND_KEY, new BMessage(M_ADD_SPLIT)); + AddShortcut('R', B_COMMAND_KEY, new BMessage(M_REMOVE_SPLIT)); + AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(M_PREVIOUS_SPLIT)); + AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY, new BMessage(M_NEXT_SPLIT)); } -void TransactionEditWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_TOGGLE_SPLIT: - { - fSplitView->ToggleSplit(); - break; - } - case M_ADD_SPLIT: - case M_REMOVE_SPLIT: - case M_NEXT_SPLIT: - case M_PREVIOUS_SPLIT: - { - fSplitView->MessageReceived(msg); - break; - } - default: - BWindow::MessageReceived(msg); +void +TransactionEditWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_TOGGLE_SPLIT: { + fSplitView->ToggleSplit(); + break; + } + case M_ADD_SPLIT: + case M_REMOVE_SPLIT: + case M_NEXT_SPLIT: + case M_PREVIOUS_SPLIT: { + fSplitView->MessageReceived(msg); + break; + } + default: + BWindow::MessageReceived(msg); } } - diff --git a/src/TransactionEditWindow.h b/src/TransactionEditWindow.h index 37bf6ce..20babb2 100644 --- a/src/TransactionEditWindow.h +++ b/src/TransactionEditWindow.h @@ -1,19 +1,18 @@ #ifndef TRANSEDITWIN_H #define TRANSEDITWIN_H -#include -#include #include "SplitView.h" +#include +#include class TransactionData; -class TransactionEditWindow : public BWindow -{ -public: +class TransactionEditWindow : public BWindow { + public: TransactionEditWindow(const BRect &frame, const TransactionData &trans); void MessageReceived(BMessage *msg); -private: + private: SplitView *fSplitView; }; diff --git a/src/TransactionItem.cpp b/src/TransactionItem.cpp index 316c510..546dcba 100644 --- a/src/TransactionItem.cpp +++ b/src/TransactionItem.cpp @@ -1,84 +1,68 @@ -#include -#include -#include -#include -#include -#include "CBLocale.h" +#include "TransactionItem.h" #include "Account.h" -#include "Preferences.h" +#include "CBLocale.h" +#include "Category.h" #include "Database.h" #include "MainWindow.h" -#include "Category.h" -#include "TransactionItem.h" -#include "TransactionLayout.h" +#include "Preferences.h" #include "TransactionData.h" +#include "TransactionLayout.h" #include "Translate.h" - +#include +#include +#include +#include +#include TransactionItem::TransactionItem(const TransactionData &trans) - :BListItem(), - fDate(trans.Date()), - fAccount(trans.GetAccount()), - fType(trans.Type().Type()), - fPayee(trans.Payee()), - fAmount(trans.Amount()), - fCategory(""), - fMemo(trans.Memo()), - fStatus(trans.Status()), - fID(trans.GetID()), - fTimeStamp(trans.GetTimeStamp()) -{ - if(trans.CountCategories()>1) - fCategory=TRANSLATE("Split"); + : BListItem(), fDate(trans.Date()), fAccount(trans.GetAccount()), fType(trans.Type().Type()), + fPayee(trans.Payee()), fAmount(trans.Amount()), fCategory(""), fMemo(trans.Memo()), + fStatus(trans.Status()), fID(trans.GetID()), fTimeStamp(trans.GetTimeStamp()) { + if (trans.CountCategories() > 1) + fCategory = TRANSLATE("Split"); else - fCategory=trans.NameAt(0); + fCategory = trans.NameAt(0); } -void TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) -{ +void +TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { BString string; Locale locale = fAccount->GetLocale(); - + BRect r(frame); r.right--; - + rgb_color linecolor; - - if(IsSelected()) - { - linecolor.red=120; - linecolor.green=120; - linecolor.blue=120; + + if (IsSelected()) { + linecolor.red = 120; + linecolor.green = 120; + linecolor.blue = 120; owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); owner->FillRect(frame); owner->SetHighColor(linecolor); owner->StrokeRect(frame); - owner->SetHighColor(255,255,255); - } - else - { - linecolor.red=200; - linecolor.green=200; - linecolor.blue=200; - - if(fStatus==TRANS_RECONCILED) - { - owner->SetHighColor(232,232,232); - owner->SetLowColor(232,232,232); + owner->SetHighColor(255, 255, 255); + } else { + linecolor.red = 200; + linecolor.green = 200; + linecolor.blue = 200; + + if (fStatus == TRANS_RECONCILED) { + owner->SetHighColor(232, 232, 232); + owner->SetLowColor(232, 232, 232); owner->FillRect(frame); owner->SetHighColor(linecolor); - owner->StrokeLine(r.LeftBottom(),r.RightBottom()); - owner->SetHighColor(255,255,255); - } - else - { + owner->StrokeLine(r.LeftBottom(), r.RightBottom()); + owner->SetHighColor(255, 255, 255); + } else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); owner->FillRect(frame); -// owner->SetHighColor(222, 222, 222); + // owner->SetHighColor(222, 222, 222); owner->SetHighColor(linecolor); - owner->StrokeLine(r.LeftBottom(),r.RightBottom()); + owner->StrokeLine(r.LeftBottom(), r.RightBottom()); } } owner->SetHighColor(0, 0, 0); @@ -93,87 +77,87 @@ void TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) cliprect.right = xpos + TDateWidth(); cliprect.top = ypos - TRowHeight(); cliprect.bottom = ypos; - + clip = cliprect; owner->ConstrainClippingRegion(&clip); - locale.DateToString(fDate,string); + locale.DateToString(fDate, string); owner->DrawString(string.String(), BPoint(xpos, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + xpos += TDateWidth(); owner->SetHighColor(linecolor); - - //Line Between Date & Type + + // Line Between Date & Type owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - - owner->StrokeLine(BPoint(0,ypos),BPoint(r.right,ypos)); + + owner->StrokeLine(BPoint(0, ypos), BPoint(r.right, ypos)); owner->SetHighColor(0, 0, 0); - + // Type - owner->SetHighColor(0,0,0); + owner->SetHighColor(0, 0, 0); owner->DrawString(fType.String(), BPoint(xpos + 5, ypos - 3)); // Line between Type and Payee xpos += TNumWidth(); owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Calculate the rectangle for the payee, but this field depends on the // width of the view, so we can't yet easily calculate the right coordinate // of the rectangle just yet BRect payee_rect(xpos, ypos, xpos, ypos - TRowHeight()); - - + + // Balance xpos = r.right - TAmountWidth(); cliprect.right = r.right; cliprect.left = xpos; clip = cliprect; owner->SetHighColor(0, 0, 0); - - Fixed balance = fAccount->BalanceAtTransaction(fDate,fPayee.String()); - if(balance.AsFixed()<0) + + Fixed balance = fAccount->BalanceAtTransaction(fDate, fPayee.String()); + if (balance.AsFixed() < 0) owner->SetHighColor(150, 0, 0); - locale.CurrencyToString(balance,string); + locale.CurrencyToString(balance, string); owner->DrawString(string.String(), BPoint(xpos + 5, ypos - 3)); - + // Line between Balance and Amount owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Amount xpos -= TAmountWidth(); cliprect.right = cliprect.left; cliprect.left = xpos; clip = cliprect; - owner->SetHighColor(0,0,0); - fAccount->GetLocale().CurrencyToString(fAmount.AbsoluteValue(),string); + owner->SetHighColor(0, 0, 0); + fAccount->GetLocale().CurrencyToString(fAmount.AbsoluteValue(), string); owner->ConstrainClippingRegion(&clip); owner->DrawString(string.String(), BPoint(xpos + 5, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + // Line between Amount and Payee owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Payee payee_rect.right = xpos; payee_rect.top = ypos - TRowHeight(); payee_rect.bottom = ypos; xpos = payee_rect.left; - + owner->SetHighColor(0, 0, 0); clip = payee_rect; owner->ConstrainClippingRegion(&clip); owner->DrawString(fPayee.String(), BPoint(xpos + 5, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(r.left, ypos), BPoint(r.right, ypos)); - + // Category - owner->SetHighColor(0,0,0); + owner->SetHighColor(0, 0, 0); ypos += TRowHeight(); xpos = TLeftPadding(); cliprect.left = TLeftPadding(); @@ -184,50 +168,46 @@ void TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) owner->ConstrainClippingRegion(&clip); owner->DrawString(fCategory.String(), BPoint(xpos, ypos - 3)); owner->ConstrainClippingRegion(NULL); - + xpos = r.right / 2; cliprect.left = xpos; cliprect.right = r.right; - + // Line between Category and Memo owner->SetHighColor(linecolor); owner->StrokeLine(BPoint(xpos, ypos - TRowHeight()), BPoint(xpos, ypos)); - + // Memo clip = cliprect; owner->ConstrainClippingRegion(&clip); - if(fMemo.CountChars()>0) - { - owner->SetHighColor(0,0,0); + if (fMemo.CountChars() > 0) { + owner->SetHighColor(0, 0, 0); owner->DrawString(fMemo.String(), BPoint(xpos + 5, ypos - 3)); - } - else - { + } else { owner->SetHighColor(linecolor); owner->DrawString(TRANSLATE("No Memo"), BPoint(xpos + 5, ypos - 3)); } owner->ConstrainClippingRegion(NULL); } -void TransactionItem::Update(BView *owner, const BFont *finfo) -{ +void +TransactionItem::Update(BView *owner, const BFont *finfo) { BListItem::Update(owner, finfo); SetHeight(TRowHeight() * 2); } -void TransactionItem::SetData(const TransactionData &trans) -{ +void +TransactionItem::SetData(const TransactionData &trans) { fDate = trans.Date(); fAccount = trans.GetAccount(); fType = trans.Type().Type(); fPayee = trans.Payee(); fAmount = trans.Amount(); - if(trans.CountCategories()>1) - fCategory=TRANSLATE("Split"); + if (trans.CountCategories() > 1) + fCategory = TRANSLATE("Split"); else - fCategory=trans.NameAt(0); + fCategory = trans.NameAt(0); fMemo = trans.Memo(); fStatus = trans.Status(); fID = trans.GetID(); } - diff --git a/src/TransactionItem.h b/src/TransactionItem.h index 3e8fa32..a3a59ed 100644 --- a/src/TransactionItem.h +++ b/src/TransactionItem.h @@ -5,24 +5,29 @@ class TransactionData; -void InitTransactionItemLayout(BView *owner); +void +InitTransactionItemLayout(BView *owner); -class TransactionItem : public BListItem -{ -public: +class TransactionItem : public BListItem { + public: TransactionItem(const TransactionData &trans); void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView* owner, const BFont* finfo); + void Update(BView *owner, const BFont *finfo); + uint32 GetID(void) const { return fID; } + time_t GetDate(void) const { return fDate; } + const char *GetPayee(void) const { return fPayee.String(); } + void SetData(const TransactionData &trans); -private: + + private: time_t fDate; Account *fAccount; BString fType; BString fPayee; - Fixed fAmount; + Fixed fAmount; BString fCategory; BString fMemo; uint8 fStatus; diff --git a/src/TransactionLayout.cpp b/src/TransactionLayout.cpp index 52ec8fb..fae5d03 100644 --- a/src/TransactionLayout.cpp +++ b/src/TransactionLayout.cpp @@ -1,26 +1,45 @@ #include "TransactionLayout.h" -static uint8 sLeftPadding=5; -static uint8 sRowHeight=0; -static uint8 sNumWidth=0; -static uint8 sDateWidth=0; -static uint8 sAmountWidth=0; - -void InitTransactionItemLayout(BView *owner) -{ +static uint8 sLeftPadding = 5; +static uint8 sRowHeight = 0; +static uint8 sNumWidth = 0; +static uint8 sDateWidth = 0; +static uint8 sAmountWidth = 0; + +void +InitTransactionItemLayout(BView *owner) { font_height fh; owner->GetFontHeight(&fh); float fontheight = fh.ascent + fh.descent + fh.leading; sRowHeight = (uint8)fontheight + 2; - + sNumWidth = (uint8)owner->StringWidth("000000"); sDateWidth = (uint8)owner->StringWidth("0000000000"); sAmountWidth = (uint8)owner->StringWidth("00,000,000.00"); } -uint8 TLeftPadding(void) { return sLeftPadding; } -uint8 TRowHeight(void) { return sRowHeight; } -uint8 TNumWidth(void) { return sNumWidth; } -uint8 TDateWidth(void) { return sDateWidth; } -uint8 TAmountWidth(void) { return sAmountWidth; } +uint8 +TLeftPadding(void) { + return sLeftPadding; +} + +uint8 +TRowHeight(void) { + return sRowHeight; +} + +uint8 +TNumWidth(void) { + return sNumWidth; +} + +uint8 +TDateWidth(void) { + return sDateWidth; +} + +uint8 +TAmountWidth(void) { + return sAmountWidth; +} diff --git a/src/TransactionLayout.h b/src/TransactionLayout.h index 52cba53..c536276 100644 --- a/src/TransactionLayout.h +++ b/src/TransactionLayout.h @@ -3,12 +3,18 @@ #include -uint8 TLeftPadding(void); -uint8 TRowHeight(void); -uint8 TNumWidth(void); -uint8 TDateWidth(void); -uint8 TAmountWidth(void); +uint8 +TLeftPadding(void); +uint8 +TRowHeight(void); +uint8 +TNumWidth(void); +uint8 +TDateWidth(void); +uint8 +TAmountWidth(void); -void InitTransactionItemLayout(BView *owner); +void +InitTransactionItemLayout(BView *owner); #endif diff --git a/src/TransactionReport.cpp b/src/TransactionReport.cpp index acadce5..e68b2d1 100644 --- a/src/TransactionReport.cpp +++ b/src/TransactionReport.cpp @@ -1,199 +1,195 @@ -#include "ReportWindow.h" #include "Account.h" #include "CBLocale.h" -#include "Database.h" -#include "ReportGrid.h" #include "ColumnListView.h" #include "ColumnTypes.h" +#include "Database.h" +#include "ReportGrid.h" +#include "ReportWindow.h" #include "TimeSupport.h" #include "Transaction.h" #include -void ReportWindow::ComputeTransactions(void) -{ +void +ReportWindow::ComputeTransactions(void) { // Total of all accounts // Calculate the number of columns and the starting date for each one - BObjectList timelist(20,true); - - if(fSubtotalMode == SUBTOTAL_NONE) - { + BObjectList timelist(20, true); + + if (fSubtotalMode == SUBTOTAL_NONE) { timelist.AddItem(new time_t(fStartDate)); timelist.AddItem(new time_t(fEndDate)); - } - else - { - for(time_t t=fStartDate; tStringWidth(TRANSLATE("Transactions"))+20,10,300,B_TRUNCATE_END,B_ALIGN_RIGHT); - fGridView->AddColumn(col,0); - col = new BStringColumn(TRANSLATE("Date"),fGridView->StringWidth("00-00-0000")+15,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,1); - col = new BStringColumn(TRANSLATE("Type"),fGridView->StringWidth(TRANSLATE("Type"))+20,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,2); - col = new BStringColumn(TRANSLATE("Payee"),75,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,3); - + // int longestnamelength = 12; + + BColumn *col = new BStringColumn( + "", fGridView->StringWidth(TRANSLATE("Transactions")) + 20, 10, 300, B_TRUNCATE_END, + B_ALIGN_RIGHT + ); + fGridView->AddColumn(col, 0); + col = new BStringColumn( + TRANSLATE("Date"), fGridView->StringWidth("00-00-0000") + 15, 10, 300, B_TRUNCATE_END + ); + fGridView->AddColumn(col, 1); + col = new BStringColumn( + TRANSLATE("Type"), fGridView->StringWidth(TRANSLATE("Type")) + 20, 10, 300, B_TRUNCATE_END + ); + fGridView->AddColumn(col, 2); + col = new BStringColumn(TRANSLATE("Payee"), 75, 10, 300, B_TRUNCATE_END); + fGridView->AddColumn(col, 3); + // The string we use for calculating width here should work well enough for general purposes - col = new BStringColumn(TRANSLATE("Amount"),fGridView->StringWidth("$00,000.00")+15,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,4); - col = new BStringColumn(TRANSLATE("Category"),fGridView->StringWidth("0000000000")+20,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,5); - col = new BStringColumn(TRANSLATE("Memo"),75,10,300,B_TRUNCATE_END); - fGridView->AddColumn(col,6); - + col = new BStringColumn( + TRANSLATE("Amount"), fGridView->StringWidth("$00,000.00") + 15, 10, 300, B_TRUNCATE_END + ); + fGridView->AddColumn(col, 4); + col = new BStringColumn( + TRANSLATE("Category"), fGridView->StringWidth("0000000000") + 20, 10, 300, B_TRUNCATE_END + ); + fGridView->AddColumn(col, 5); + col = new BStringColumn(TRANSLATE("Memo"), 75, 10, 300, B_TRUNCATE_END); + fGridView->AddColumn(col, 6); + fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Transactions")),0); + titlerow->SetField(new BStringField(TRANSLATE("Transactions")), 0); fGridView->AddRow(new BRow()); - - - int32 payeechars=strlen(TRANSLATE("Payee")), - memochars=strlen(TRANSLATE("Memo")), - categorychars=strlen(TRANSLATE("Category")); - float maxpayee=fGridView->StringWidth(TRANSLATE("Payee")), - maxmemo=fGridView->StringWidth(TRANSLATE("Memo")), - maxcategory=fGridView->StringWidth(TRANSLATE("Category")); - - int32 count = timelist.CountItems()-1; - for(int32 subtotal_index=0; subtotal_indexStringWidth(TRANSLATE("Payee")), + maxmemo = fGridView->StringWidth(TRANSLATE("Memo")), + maxcategory = fGridView->StringWidth(TRANSLATE("Category")); + + int32 count = timelist.CountItems() - 1; + for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { + time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + BRow *row = new BRow(); fGridView->AddRow(row); - + BString datestring, tempstr; - gDefaultLocale.DateToString(subtotal_start,datestring); - row->SetField(new BStringField(datestring.String()),0); - row->SetField(new BStringField("-"),1); + gDefaultLocale.DateToString(subtotal_start, datestring); + row->SetField(new BStringField(datestring.String()), 0); + row->SetField(new BStringField("-"), 1); row = new BRow(); fGridView->AddRow(row); - gDefaultLocale.DateToString(subtotal_end,datestring); - row->SetField(new BStringField(datestring.String()),0); - + gDefaultLocale.DateToString(subtotal_end, datestring); + row->SetField(new BStringField(datestring.String()), 0); + fGridView->AddRow(new BRow()); - + BString command; - - int32 accountcount=0; - for(int32 i=0; iCountItems(); i++) - { - AccountItem *item = (AccountItem*)fAccountList->ItemAt(i); - if(!item || !item->IsSelected()) + + int32 accountcount = 0; + for (int32 i = 0; i < fAccountList->CountItems(); i++) { + AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + if (!item || !item->IsSelected()) continue; - - if(accountcount>0) + + if (accountcount > 0) command << " union all "; - - command << "select date,type,payee,amount,category,memo,transid from account_" << item->account->GetID() - << " where category in (" << fCategoryString << ") and date >= " - << subtotal_start << " and date < " << subtotal_end; - + + command << "select date,type,payee,amount,category,memo,transid from account_" + << item->account->GetID() << " where category in (" << fCategoryString + << ") and date >= " << subtotal_start << " and date < " << subtotal_end; + accountcount++; } command << " order by date,transid;"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"ReportWindow::ComputeTransactions()"); - - if(query.eof()) - { - row = new BRow(); - fGridView->AddRow(row); - row->SetField(new BStringField(TRANSLATE("No Transactions")),0); - fGridView->ColumnAt(0)->SetWidth(fGridView->StringWidth(TRANSLATE("No Transactions"))+15); - } - else - while(!query.eof()) - { + CppSQLite3Query query = + gDatabase.DBQuery(command.String(), "ReportWindow::ComputeTransactions()"); + + if (query.eof()) { row = new BRow(); fGridView->AddRow(row); - - row->SetField(new BStringField(""),0); - - // date - gDefaultLocale.DateToString(query.getInt64Field(0),tempstr); - row->SetField(new BStringField(tempstr.String()),1); - - // type - row->SetField(new BStringField(DeescapeIllegalCharacters(query.getStringField(1)).String()),2); - - // payee - tempstr = DeescapeIllegalCharacters(query.getStringField(2)); - if(tempstr.CountChars() > payeechars) - { - payeechars = tempstr.CountChars(); - maxpayee = fGridView->StringWidth(tempstr.String()); - } - row->SetField(new BStringField(tempstr.String()),3); - - // amount - Fixed f(query.getInt64Field(3),true); - gCurrentLocale.CurrencyToString(f.AbsoluteValue(),tempstr); - row->SetField(new BStringField(tempstr.String()),4); - - // category - tempstr = DeescapeIllegalCharacters(query.getStringField(4)); - if(tempstr.CountChars() > categorychars) - { - categorychars = tempstr.CountChars(); - maxcategory = fGridView->StringWidth(tempstr.String()); - } - row->SetField(new BStringField(tempstr.String()),5); - - // memo - if(!query.fieldIsNull(5)) - { - tempstr = DeescapeIllegalCharacters(query.getStringField(5)); - if(tempstr.CountChars() > memochars) - { - memochars = tempstr.CountChars(); - maxmemo = fGridView->StringWidth(tempstr.String()); + row->SetField(new BStringField(TRANSLATE("No Transactions")), 0); + fGridView->ColumnAt(0)->SetWidth( + fGridView->StringWidth(TRANSLATE("No Transactions")) + 15 + ); + } else + while (!query.eof()) { + row = new BRow(); + fGridView->AddRow(row); + + row->SetField(new BStringField(""), 0); + + // date + gDefaultLocale.DateToString(query.getInt64Field(0), tempstr); + row->SetField(new BStringField(tempstr.String()), 1); + + // type + row->SetField( + new BStringField(DeescapeIllegalCharacters(query.getStringField(1)).String()), 2 + ); + + // payee + tempstr = DeescapeIllegalCharacters(query.getStringField(2)); + if (tempstr.CountChars() > payeechars) { + payeechars = tempstr.CountChars(); + maxpayee = fGridView->StringWidth(tempstr.String()); + } + row->SetField(new BStringField(tempstr.String()), 3); + + // amount + Fixed f(query.getInt64Field(3), true); + gCurrentLocale.CurrencyToString(f.AbsoluteValue(), tempstr); + row->SetField(new BStringField(tempstr.String()), 4); + + // category + tempstr = DeescapeIllegalCharacters(query.getStringField(4)); + if (tempstr.CountChars() > categorychars) { + categorychars = tempstr.CountChars(); + maxcategory = fGridView->StringWidth(tempstr.String()); } - row->SetField(new BStringField(tempstr.String()),6); + row->SetField(new BStringField(tempstr.String()), 5); + + // memo + if (!query.fieldIsNull(5)) { + tempstr = DeescapeIllegalCharacters(query.getStringField(5)); + if (tempstr.CountChars() > memochars) { + memochars = tempstr.CountChars(); + maxmemo = fGridView->StringWidth(tempstr.String()); + } + row->SetField(new BStringField(tempstr.String()), 6); + } + + query.nextRow(); } - - query.nextRow(); - } query.finalize(); - + fGridView->AddRow(new BRow()); } - fGridView->ColumnAt(3)->SetWidth(maxpayee+15); - fGridView->ColumnAt(5)->SetWidth(maxcategory+15); - fGridView->ColumnAt(6)->SetWidth(maxmemo+15); + fGridView->ColumnAt(3)->SetWidth(maxpayee + 15); + fGridView->ColumnAt(5)->SetWidth(maxcategory + 15); + fGridView->ColumnAt(6)->SetWidth(maxmemo + 15); } - diff --git a/src/TransactionView.cpp b/src/TransactionView.cpp index 5115648..489412d 100644 --- a/src/TransactionView.cpp +++ b/src/TransactionView.cpp @@ -1,181 +1,171 @@ -#include +#include "TransactionView.h" +#include "Database.h" +#include "MainWindow.h" +#include "TransactionItem.h" +#include "TransactionLayout.h" #include #include #include #include #include #include +#include #include -#include "Database.h" -#include "MainWindow.h" -#include "TransactionItem.h" -#include "TransactionLayout.h" -#include "TransactionView.h" -TransactionView::TransactionView() - : BView("transactionview", B_WILL_DRAW | B_SUBPIXEL_PRECISE | - B_FRAME_EVENTS), - fCurrent(NULL) -{ +TransactionView::TransactionView() + : BView("transactionview", B_WILL_DRAW | B_SUBPIXEL_PRECISE | B_FRAME_EVENTS), fCurrent(NULL) { InitTransactionItemLayout(this); - fListView = new BListView("RegisterList", B_SINGLE_SELECTION_LIST, - B_WILL_DRAW|B_NAVIGABLE|B_FULL_UPDATE_ON_RESIZE); + fListView = new BListView( + "RegisterList", B_SINGLE_SELECTION_LIST, B_WILL_DRAW | B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE + ); fListView->SetSelectionMessage(new BMessage(M_TRANSACTION_SELECTED)); fListView->SetInvocationMessage(new BMessage(M_TRANSACTION_INVOKED)); - fScrollView = new BScrollView("scrollregister", fListView, 0, false, true); - - fItemList = new BObjectList(20,true); - - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(fScrollView) - .End(); + fScrollView = new BScrollView("scrollregister", fListView, 0, false, true); + + fItemList = new BObjectList(20, true); + + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(fScrollView).End(); } -TransactionView::~TransactionView(void) -{ +TransactionView::~TransactionView(void) { fListView->MakeEmpty(); delete fItemList; } -void TransactionView::AttachedToWindow(void) -{ +void +TransactionView::AttachedToWindow(void) { SetViewColor(Parent()->ViewColor()); fListView->SetTarget(this); // So the scrollbar initially starts with the proper steps BScrollBar *bar = fScrollView->ScrollBar(B_VERTICAL); - + float big, small; bar->GetSteps(&small, &big); big = (int32)(fScrollView->Frame().Height() * .9); - bar->SetSteps(small,big); + bar->SetSteps(small, big); - for(int32 i=0; iAddObserver(this); } } -void TransactionView::SetAccount(Account *acc) -{ +void +TransactionView::SetAccount(Account *acc) { // We accept NULL pointers because sometimes we're given them - + // According to the BeBook, calling BListView::MakeEmpty() doesn't free // the BListItems, so we have to do this manually. :( fListView->MakeEmpty(); fItemList->MakeEmpty(); - if(!acc) + if (!acc) return; - + BList itemlist; BString command("select * from account_"); command << acc->GetID() << " order by date,payee"; - CppSQLite3Query query = gDatabase.DBQuery(command.String(),"TransactionView::SetAcount"); - + CppSQLite3Query query = gDatabase.DBQuery(command.String(), "TransactionView::SetAcount"); + Locale locale = acc->GetLocale(); - - uint32 currentid=0,newid=0; - if(!query.eof()) - { + + uint32 currentid = 0, newid = 0; + if (!query.eof()) { TransactionData data; - - currentid=query.getIntField(1); - newid=query.getIntField(1); + + currentid = query.getIntField(1); + newid = query.getIntField(1); data.SetID(currentid); data.SetDate(atol(query.getStringField(2))); data.SetType(DeescapeIllegalCharacters(query.getStringField(3)).String()); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(4)).String()); data.SetAccount(acc); - + Fixed f; f.SetPremultiplied(atol(query.getStringField(5))); - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(),f,true); - - if(!query.fieldIsNull(7)) - data.SetMemoAt(data.CountCategories()-1, - DeescapeIllegalCharacters(query.getStringField(7)).String()); + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(), f, true); + + if (!query.fieldIsNull(7)) + data.SetMemoAt( + data.CountCategories() - 1, + DeescapeIllegalCharacters(query.getStringField(7)).String() + ); BString status = query.getStringField(8); - if(status.ICompare("Reconciled")==0) + if (status.ICompare("Reconciled") == 0) data.SetStatus(TRANS_RECONCILED); - else - if(status.ICompare("Cleared")==0) + else if (status.ICompare("Cleared") == 0) data.SetStatus(TRANS_CLEARED); else data.SetStatus(TRANS_OPEN); query.nextRow(); - - while(!query.eof()) - { - newid=query.getIntField(1); - - if(currentid!=newid) - { - if(data.CountCategories() == 1) + + while (!query.eof()) { + newid = query.getIntField(1); + + if (currentid != newid) { + if (data.CountCategories() == 1) data.SetMemo(data.MemoAt(0)); - + itemlist.AddItem(new TransactionItem(data)); data.MakeEmpty(); - - currentid=newid; - newid=query.getIntField(1); + + currentid = newid; + newid = query.getIntField(1); data.SetID(currentid); data.SetDate(atol(query.getStringField(2))); data.SetType(DeescapeIllegalCharacters(query.getStringField(3)).String()); data.SetPayee(DeescapeIllegalCharacters(query.getStringField(4)).String()); data.SetAccount(acc); } - + f.SetPremultiplied(atol(query.getStringField(5))); - data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(),f,true); - - if(!query.fieldIsNull(7)) - data.SetMemoAt(data.CountCategories()-1, - DeescapeIllegalCharacters(query.getStringField(7)).String()); - + data.AddCategory(DeescapeIllegalCharacters(query.getStringField(6)).String(), f, true); + + if (!query.fieldIsNull(7)) + data.SetMemoAt( + data.CountCategories() - 1, + DeescapeIllegalCharacters(query.getStringField(7)).String() + ); + status = query.getStringField(8); - if(status.ICompare("Reconciled")==0) + if (status.ICompare("Reconciled") == 0) data.SetStatus(TRANS_RECONCILED); - else - if(status.ICompare("Cleared")==0) + else if (status.ICompare("Cleared") == 0) data.SetStatus(TRANS_CLEARED); else data.SetStatus(TRANS_OPEN); query.nextRow(); } - + itemlist.AddItem(new TransactionItem(data)); fListView->AddList(&itemlist); } - - if(fListView->CurrentSelection()<0) - { - fListView->Select(fListView->CountItems()-1); + + if (fListView->CurrentSelection() < 0) { + fListView->Select(fListView->CountItems() - 1); fListView->ScrollToSelection(); } } -TransactionItem *TransactionView::AddTransaction(const TransactionData &trans, - const int32 &index) -{ - int32 itemindex=0; - if(index<0) - itemindex = FindIndexForDate(trans.Date(),trans.Payee()); +TransactionItem * +TransactionView::AddTransaction(const TransactionData &trans, const int32 &index) { + int32 itemindex = 0; + if (index < 0) + itemindex = FindIndexForDate(trans.Date(), trans.Payee()); else itemindex = index; - TransactionItem* transitem = new TransactionItem(trans); - fListView->AddItem(transitem,itemindex); - fItemList->AddItem(transitem,itemindex); - return (TransactionItem*)transitem; + TransactionItem *transitem = new TransactionItem(trans); + fListView->AddItem(transitem, itemindex); + fItemList->AddItem(transitem, itemindex); + return (TransactionItem *)transitem; } -void TransactionView::DeleteTransaction(const int32 &index) -{ - // This is totally bizarre. If we remove the first TransactionItem from the +void +TransactionView::DeleteTransaction(const int32 &index) { + // This is totally bizarre. If we remove the first TransactionItem from the // actual fListView, it removes *all* of the items. Does commenting out the line // create a memory leak? BDB doesn't report any leaks FWIW. That won't work as // a fix, though, because whenever a transaction is deleted anywhere else, it @@ -185,8 +175,8 @@ void TransactionView::DeleteTransaction(const int32 &index) fItemList->RemoveItemAt(index); } -void TransactionView::Draw(BRect updateRect) -{ +void +TransactionView::Draw(BRect updateRect) { BRect frame = Frame(); frame.OffsetTo(0, 0); frame.bottom = frame.top + 46; @@ -194,123 +184,98 @@ void TransactionView::Draw(BRect updateRect) StrokeRect(frame); } -void TransactionView::EditTransaction(void) -{ +void +TransactionView::EditTransaction(void) { int32 cs = fListView->CurrentSelection(); fListView->InvalidateItem(cs); } -void TransactionView::MessageReceived(BMessage* message) -{ - switch(message->what) - { - case M_TRANSACTION_SELECTED: - { - Account *acc=gDatabase.CurrentAccount(); - if(acc) - { - TransactionItem *titem = (TransactionItem*) - fListView->ItemAt(fListView->CurrentSelection()); - if(titem) - acc->SetCurrentTransaction(titem->GetID()); - } - break; - } - case M_TRANSACTION_INVOKED: - { - Window()->PostMessage(M_EDIT_TRANSACTION); - break; - } - default: - { - BView::MessageReceived(message); - break; +void +TransactionView::MessageReceived(BMessage *message) { + switch (message->what) { + case M_TRANSACTION_SELECTED: { + Account *acc = gDatabase.CurrentAccount(); + if (acc) { + TransactionItem *titem = + (TransactionItem *)fListView->ItemAt(fListView->CurrentSelection()); + if (titem) + acc->SetCurrentTransaction(titem->GetID()); } + break; + } + case M_TRANSACTION_INVOKED: { + Window()->PostMessage(M_EDIT_TRANSACTION); + break; + } + default: { + BView::MessageReceived(message); + break; + } } } -void TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) -{ - bool lockwin=false; - if(!Window()->IsLocked()) - { - lockwin=true; +void +TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { + bool lockwin = false; + if (!Window()->IsLocked()) { + lockwin = true; Window()->Lock(); } - - if(value & WATCH_MASS_EDIT) - { - if(IsWatching(WATCH_TRANSACTION)) - { + + if (value & WATCH_MASS_EDIT) { + if (IsWatching(WATCH_TRANSACTION)) { RemoveWatch(WATCH_ALL); AddWatch(WATCH_MASS_EDIT); - } - else - { + } else { AddWatch(WATCH_ALL); - + // need to reset all transactions for the current account SetAccount(gDatabase.CurrentAccount()); } } - - if(value & WATCH_TRANSACTION) - { - uint32 accountid=0; - if(msg->FindInt32("accountid",(int32*)&accountid)!=B_OK) - { - if(lockwin) + + if (value & WATCH_TRANSACTION) { + uint32 accountid = 0; + if (msg->FindInt32("accountid", (int32 *)&accountid) != B_OK) { + if (lockwin) Window()->Unlock(); return; } - - if(accountid==gDatabase.CurrentAccount()->GetID()) - { - if(value & WATCH_CREATE) - { - TransactionData *trans=NULL; - if(msg->FindPointer("item",(void**)&trans)!=B_OK) - { - if(lockwin) + + if (accountid == gDatabase.CurrentAccount()->GetID()) { + if (value & WATCH_CREATE) { + TransactionData *trans = NULL; + if (msg->FindPointer("item", (void **)&trans) != B_OK) { + if (lockwin) Window()->Unlock(); return; } - + TransactionItem *item = AddTransaction(*trans); fListView->Select(fListView->IndexOf(item)); fListView->ScrollToSelection(); - } - else - if(value & WATCH_DELETE) - { - uint32 id=0; - if(msg->FindInt32("id",(int32*)&id)!=B_OK) - { - if(lockwin) + } else if (value & WATCH_DELETE) { + uint32 id = 0; + if (msg->FindInt32("id", (int32 *)&id) != B_OK) { + if (lockwin) Window()->Unlock(); return; } - + int32 index = FindItemForID(id); - if(index<0) - { - if(lockwin) + if (index < 0) { + if (lockwin) Window()->Unlock(); return; } - + DeleteTransaction(index); - } - else - if(value & WATCH_CHANGE) - { + } else if (value & WATCH_CHANGE) { TransactionData *data; - if(msg->FindPointer("item",(void**)&data)==B_OK) - { + if (msg->FindPointer("item", (void **)&data) == B_OK) { int32 index = FindItemForID(data->GetID()); - TransactionItem *item = (TransactionItem*)fListView->ItemAt(index); - if(item) - { + TransactionItem *item = (TransactionItem *)fListView->ItemAt(index); + if (item) { item->SetData(*data); fListView->InvalidateItem(index); } @@ -323,132 +288,113 @@ void TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) fListView->ScrollToSelection(); } */ } - } - else - if(value & WATCH_ACCOUNT) - { - if(value & WATCH_REDRAW) - { + } else if (value & WATCH_ACCOUNT) { + if (value & WATCH_REDRAW) { fListView->Invalidate(); } - + Account *acc; - if(msg->FindPointer("item",(void**)&acc)!=B_OK) - { - if(lockwin) + if (msg->FindPointer("item", (void **)&acc) != B_OK) { + if (lockwin) Window()->Unlock(); return; } - - if(value & WATCH_SELECT) - { + + if (value & WATCH_SELECT) { SetAccount(gDatabase.CurrentAccount()); - } - else - if(value & WATCH_CREATE) - { + } else if (value & WATCH_CREATE) { acc->AddObserver(this); - } - else - if( value & (WATCH_CHANGE | WATCH_LOCALE) ) - { - if(acc==gDatabase.CurrentAccount()) + } else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { + if (acc == gDatabase.CurrentAccount()) fListView->Invalidate(); } - } - else - if( value & (WATCH_CHANGE | WATCH_LOCALE) ) - { + } else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { // this case handles updates to the default locale // when the default locale is updated Locale *locale; - if(msg->FindPointer("locale",(void**)&locale)==B_OK) - { - if(locale == &gDefaultLocale) + if (msg->FindPointer("locale", (void **)&locale) == B_OK) { + if (locale == &gDefaultLocale) fListView->Invalidate(); } } - - if(lockwin) + + if (lockwin) Window()->Unlock(); } -void TransactionView::FrameResized(float width, float height) -{ +void +TransactionView::FrameResized(float width, float height) { BScrollBar *bar = fScrollView->ScrollBar(B_VERTICAL); - + float big, small; bar->GetSteps(&small, &big); big = (int32)(fScrollView->Frame().Height() * .9); - bar->SetSteps(small,big); - + bar->SetSteps(small, big); } -bool TransactionView::SelectNext(void) -{ +bool +TransactionView::SelectNext(void) { int32 index = fListView->CurrentSelection(); - if(index<0 || index >= fListView->CountItems()-1) + if (index < 0 || index >= fListView->CountItems() - 1) return false; - fListView->Select(index+1); + fListView->Select(index + 1); fListView->ScrollToSelection(); return true; } -bool TransactionView::SelectPrevious(void) -{ +bool +TransactionView::SelectPrevious(void) { int32 index = fListView->CurrentSelection(); - if(index<=0) + if (index <= 0) return false; - fListView->Select(index-1); + fListView->Select(index - 1); fListView->ScrollToSelection(); return true; } -bool TransactionView::SelectFirst(void) -{ - if(fListView->CountItems()<=0) +bool +TransactionView::SelectFirst(void) { + if (fListView->CountItems() <= 0) return false; fListView->Select(0L); fListView->ScrollToSelection(); return true; } -bool TransactionView::SelectLast(void) -{ - if(fListView->CountItems()<=0) +bool +TransactionView::SelectLast(void) { + if (fListView->CountItems() <= 0) return false; - fListView->Select(fListView->CountItems()-1); + fListView->Select(fListView->CountItems() - 1); fListView->ScrollToSelection(); return true; } -int32 TransactionView::FindItemForID(const uint32 &id) -{ - for(int32 i=0; iCountItems(); i++) - { - TransactionItem *item = (TransactionItem*) fListView->ItemAt(i); - if(item->GetID()==id) +int32 +TransactionView::FindItemForID(const uint32 &id) { + for (int32 i = 0; i < fListView->CountItems(); i++) { + TransactionItem *item = (TransactionItem *)fListView->ItemAt(i); + if (item->GetID() == id) return i; } return -1; } -int32 TransactionView::FindIndexForDate(const time_t &time, const char *payee) -{ - // We need to find the appropriate index based on the date of +int32 +TransactionView::FindIndexForDate(const time_t &time, const char *payee) { + // We need to find the appropriate index based on the date of // the transaction and insert it there int32 count = fListView->CountItems(); - - if(count < 0) + + if (count < 0) return 0; - - int32 i=0; - while(iItemAt(i); - - if(time < item->GetDate() || - (time == item->GetDate() && strcmp(payee,item->GetPayee())<1) ) + + int32 i = 0; + while (i < count) { + TransactionItem *item = (TransactionItem *)fListView->ItemAt(i); + + if (time < item->GetDate() || + (time == item->GetDate() && strcmp(payee, item->GetPayee()) < 1)) return i; i++; diff --git a/src/TransactionView.h b/src/TransactionView.h index 0aca315..ea0665d 100644 --- a/src/TransactionView.h +++ b/src/TransactionView.h @@ -1,53 +1,51 @@ #ifndef TRANSACTIONVIEW_H #define TRANSACTIONVIEW_H -#include +#include "Account.h" +#include "Notifier.h" +#include "TransactionData.h" #include #include -#include #include -#include "Account.h" -#include "TransactionData.h" -#include "Notifier.h" +#include +#include #define M_TRANSACTION_SELECTED 'trsl' #define M_TRANSACTION_INVOKED 'trin' class TransactionItem; -class TransactionView : public BView, public Observer -{ -public: +class TransactionView : public BView, public Observer { + public: TransactionView(void); ~TransactionView(void); - + void AttachedToWindow(void); - + void SetAccount(Account *acc); - TransactionItem *AddTransaction(const TransactionData &trans, - const int32 &index=-1); + TransactionItem *AddTransaction(const TransactionData &trans, const int32 &index = -1); void DeleteTransaction(const int32 &index); void EditTransaction(); - + void Draw(BRect updateRect); - void MessageReceived(BMessage* message); - + void MessageReceived(BMessage *message); + void HandleNotify(const uint64 &value, const BMessage *msg); void FrameResized(float width, float height); - + bool SelectNext(void); bool SelectPrevious(void); bool SelectFirst(void); bool SelectLast(void); - -private: + + private: int32 FindItemForID(const uint32 &id); int32 FindIndexForDate(const time_t &time, const char *payee); - + BListView *fListView; BObjectList *fItemList; Transaction *fCurrent; - BStringView *fCategoryLabel,*fMemoLabel; + BStringView *fCategoryLabel, *fMemoLabel; BScrollView *fScrollView; }; diff --git a/src/TransferWindow.cpp b/src/TransferWindow.cpp index ba4b204..c45a1d9 100644 --- a/src/TransferWindow.cpp +++ b/src/TransferWindow.cpp @@ -1,15 +1,15 @@ #include "TransferWindow.h" -#include #include "DAlert.h" #include -#include +#include #include +#include +#include "CBLocale.h" #include "CurrencyBox.h" #include "Database.h" #include "DateBox.h" #include "Fixed.h" -#include "CBLocale.h" #include "MsgDefs.h" #include "TimeSupport.h" @@ -21,270 +21,243 @@ #define M_AMOUNT_CHANGED 'amch' TransferWindow::TransferWindow(BHandler *target) - : BWindow(BRect(100,100,500,350),TRANSLATE("Add Account Transfer"),B_TITLED_WINDOW_LOOK, - B_MODAL_APP_WINDOW_FEEL,B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | - B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fMessenger(target), - fMessage(M_CREATE_TRANSFER) -{ - InitObject(NULL,NULL,Fixed(0)); + : BWindow( + BRect(100, 100, 500, 350), TRANSLATE("Add Account Transfer"), B_TITLED_WINDOW_LOOK, + B_MODAL_APP_WINDOW_FEEL, + B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS + ), + fMessenger(target), fMessage(M_CREATE_TRANSFER) { + InitObject(NULL, NULL, Fixed(0)); } -TransferWindow::TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount) - : BWindow(BRect(100,100,300,300),TRANSLATE("Edit Transfer"),B_TITLED_WINDOW_LOOK, - B_MODAL_APP_WINDOW_FEEL,B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | - B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS), - fMessenger(target) -{ - InitObject(src,dest,amount); +TransferWindow::TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount) + : BWindow( + BRect(100, 100, 300, 300), TRANSLATE("Edit Transfer"), B_TITLED_WINDOW_LOOK, + B_MODAL_APP_WINDOW_FEEL, + B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS + ), + fMessenger(target) { + InitObject(src, dest, amount); } -void TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) -{ +void +TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { BString temp; - AddShortcut('W',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - AddShortcut('Q',B_COMMAND_KEY,new BMessage(B_QUIT_REQUESTED)); - - BView *back = new BView("back",B_WILL_DRAW); - back->SetViewColor(240,240,240); - BLayoutBuilder::Group<>(this, B_VERTICAL, 0) - .SetInsets(0) - .Add(back) - .End(); - - temp = TRANSLATE("From Account"); temp += ":"; - fFromLabel = new BStringView("fromlabel",temp.String()); - + AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); + + BView *back = new BView("back", B_WILL_DRAW); + back->SetViewColor(240, 240, 240); + BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); + + temp = TRANSLATE("From Account"); + temp += ":"; + fFromLabel = new BStringView("fromlabel", temp.String()); + BRect r(Bounds()); - temp = TRANSLATE("To Account"); temp += ":"; - fToLabel = new BStringView("tolabel",temp.String()); - - fOK = new BButton("okbutton",TRANSLATE("Cancel"), - new BMessage(M_CREATE_TRANSFER)); + temp = TRANSLATE("To Account"); + temp += ":"; + fToLabel = new BStringView("tolabel", temp.String()); + + fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_CREATE_TRANSFER)); fOK->SetLabel(TRANSLATE("OK")); fOK->SetEnabled(false); fOK->MakeDefault(true); - - fCancel = new BButton("cancelbutton",TRANSLATE("Cancel"), - new BMessage(B_QUIT_REQUESTED)); - - temp = TRANSLATE("Memo"); temp += ":"; - fMemo = new BTextControl("memobox",temp.String(),NULL,NULL); - + + fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + + temp = TRANSLATE("Memo"); + temp += ":"; + fMemo = new BTextControl("memobox", temp.String(), NULL, NULL); + BString amt; - gCurrentLocale.CurrencyToString(amount,amt); - temp = TRANSLATE("Amount"); temp += ":"; - fAmount = new CurrencyBox("amountbox",temp.String(),amt.String(),NULL); + gCurrentLocale.CurrencyToString(amount, amt); + temp = TRANSLATE("Amount"); + temp += ":"; + fAmount = new CurrencyBox("amountbox", temp.String(), amt.String(), NULL); fAmount->GetFilter()->SetMessenger(new BMessenger(this)); - - temp = TRANSLATE("Date"); temp += ":"; - fDate = new DateBox("datebox",temp.String(),"",NULL); + + temp = TRANSLATE("Date"); + temp += ":"; + fDate = new DateBox("datebox", temp.String(), "", NULL); fDate->GetFilter()->SetMessenger(new BMessenger(this)); -// fDate->SetEscapeCancel(true); - - if(src && dest) - { + // fDate->SetEscapeCancel(true); + + if (src && dest) { BString datestr; - gDefaultLocale.DateToString(fDate->GetDate(),datestr); + gDefaultLocale.DateToString(fDate->GetDate(), datestr); fDate->SetText(datestr.String()); - } - else - { + } else { BString datestr; - gDefaultLocale.DateToString(fDate->GetDate(),datestr); + gDefaultLocale.DateToString(fDate->GetDate(), datestr); fDate->SetText(datestr.String()); } - + fSourceList = new BListView("sourcelist"); - BScrollView *scrollsrc = new BScrollView("sourcescroll",fSourceList, - 0,false,true); + BScrollView *scrollsrc = new BScrollView("sourcescroll", fSourceList, 0, false, true); fSourceList->SetSelectionMessage(new BMessage(M_SOURCE_SELECTED)); scrollsrc->SetViewColor(back->ViewColor()); - + fDestList = new BListView("destlist"); - BScrollView *scrolldest = new BScrollView("destscroll",fDestList, - 0,false,true); + BScrollView *scrolldest = new BScrollView("destscroll", fDestList, 0, false, true); fDestList->SetSelectionMessage(new BMessage(M_DEST_SELECTED)); scrolldest->SetViewColor(back->ViewColor()); - - int32 current=-1; - for(int32 i=0; iAddItem(new AccountListItem(acc)); fDestList->AddItem(new AccountListItem(acc)); - if(acc == gDatabase.CurrentAccount()) + if (acc == gDatabase.CurrentAccount()) current = i; } - } - - if(current>=0) - { + + if (current >= 0) { fSourceList->Select(current); fDestList->ItemAt(current)->SetEnabled(false); } - - if(gDatabase.CountAccounts()==2) - { + + if (gDatabase.CountAccounts() == 2) { // When there are just 2 accounts, automatically select the other account and set focus // to the amount box - if(fSourceList->CurrentSelection()==0) + if (fSourceList->CurrentSelection() == 0) fDestList->Select(1); else fDestList->Select(0L); - fAmount->MakeFocus(true); - } - else + fAmount->MakeFocus(true); + } else fDestList->MakeFocus(true); BLayoutBuilder::Group<>(back, B_VERTICAL, 0) .SetInsets(10) .AddGrid(4.0f, 1.0f) - .Add(fFromLabel, 0, 0) - .Add(scrollsrc, 0, 1, 2) - .Add(fDate, 0, 2, 2) - .Add(fMemo, 0, 3, 2) - .Add(fToLabel, 2, 0) - .Add(scrolldest,2, 1, 2) - .Add(fAmount, 2, 2, 2) - .AddGrid(1.0f, 1.0f, 2, 3, 2) - .AddGlue(0, 0) - .Add(fCancel, 1, 0) - .Add(fOK, 2, 0) - .End() + .Add(fFromLabel, 0, 0) + .Add(scrollsrc, 0, 1, 2) + .Add(fDate, 0, 2, 2) + .Add(fMemo, 0, 3, 2) + .Add(fToLabel, 2, 0) + .Add(scrolldest, 2, 1, 2) + .Add(fAmount, 2, 2, 2) + .AddGrid(1.0f, 1.0f, 2, 3, 2) + .AddGlue(0, 0) + .Add(fCancel, 1, 0) + .Add(fOK, 2, 0) .End() - .End(); + .End() + .End(); } -void TransferWindow::SetMessage(BMessage msg) -{ +void +TransferWindow::SetMessage(BMessage msg) { fMessage = msg; } -void TransferWindow::MessageReceived(BMessage *msg) -{ - switch(msg->what) - { - case M_SOURCE_SELECTED: - { - for(int32 i=0; iCountItems(); i++) - { - AccountListItem *item = (AccountListItem *)fDestList->ItemAt(i); - if(item && !item->IsEnabled()) - { - item->SetEnabled(true); - fDestList->InvalidateItem(i); - } - } - if(fSourceList->CurrentSelection()>=0) - { - fDestList->ItemAt(fSourceList->CurrentSelection())->SetEnabled(false); - fDestList->InvalidateItem(fSourceList->CurrentSelection()); +void +TransferWindow::MessageReceived(BMessage *msg) { + switch (msg->what) { + case M_SOURCE_SELECTED: { + for (int32 i = 0; i < fDestList->CountItems(); i++) { + AccountListItem *item = (AccountListItem *)fDestList->ItemAt(i); + if (item && !item->IsEnabled()) { + item->SetEnabled(true); + fDestList->InvalidateItem(i); } - break; } - case M_DEST_SELECTED: - { - HandleOKButton(); - break; + if (fSourceList->CurrentSelection() >= 0) { + fDestList->ItemAt(fSourceList->CurrentSelection())->SetEnabled(false); + fDestList->InvalidateItem(fSourceList->CurrentSelection()); } - case M_PREVIOUS_FIELD: - { - // This message is received from the text filter in order to - // use the Enter key to change from one entry field to another but in the - // reverse order from M_NEXT_FIELD - if(fDate->ChildAt(0)->IsFocus()) - { - fDate->Validate(false); - fOK->MakeFocus(true); - } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - fAmount->Validate(false); - fDate->MakeFocus(true); - } - HandleOKButton(); - break; + break; + } + case M_DEST_SELECTED: { + HandleOKButton(); + break; + } + case M_PREVIOUS_FIELD: { + // This message is received from the text filter in order to + // use the Enter key to change from one entry field to another but in the + // reverse order from M_NEXT_FIELD + if (fDate->ChildAt(0)->IsFocus()) { + fDate->Validate(false); + fOK->MakeFocus(true); + } else if (fAmount->ChildAt(0)->IsFocus()) { + fAmount->Validate(false); + fDate->MakeFocus(true); } - case M_NEXT_FIELD: - { - // This message is received from the text filter in order to - // use the Enter key to change from one entry field to another - if(fDate->ChildAt(0)->IsFocus()) - { - fDate->Validate(false); - fAmount->MakeFocus(true); - } - else - if(fAmount->ChildAt(0)->IsFocus()) - { - fAmount->Validate(false); - fMemo->MakeFocus(true); - } - HandleOKButton(); - break; + HandleOKButton(); + break; + } + case M_NEXT_FIELD: { + // This message is received from the text filter in order to + // use the Enter key to change from one entry field to another + if (fDate->ChildAt(0)->IsFocus()) { + fDate->Validate(false); + fAmount->MakeFocus(true); + } else if (fAmount->ChildAt(0)->IsFocus()) { + fAmount->Validate(false); + fMemo->MakeFocus(true); } - case M_CREATE_TRANSFER: - { - if(!fDate->Validate()) - break; - - if(!fAmount->Validate()) - break; - - AccountListItem *sitem = (AccountListItem*)fSourceList->ItemAt(fSourceList->CurrentSelection()); - if(!sitem) - break; - - AccountListItem *ditem = (AccountListItem*)fDestList->ItemAt(fDestList->CurrentSelection()); - if(!ditem) - break; - - Fixed amount; - gCurrentLocale.StringToCurrency(fAmount->Text(),amount); - if(amount==0) - { - ShowAlert(TRANSLATE("Not Transferring Any Money"), - TRANSLATE("If you intend to transfer money, it will need to " - "be an amount that is not zero.")); - break; - } - - fMessage.AddPointer("from",sitem->GetAccount()); - fMessage.AddPointer("to",ditem->GetAccount()); - fMessage.AddString("amount",fAmount->Text()); - fMessage.AddString("memo",fMemo->Text()); - fMessage.AddString("date",fDate->Text()); - fMessenger.SendMessage(&fMessage); - fMessage.MakeEmpty(); - - PostMessage(B_QUIT_REQUESTED); + HandleOKButton(); + break; + } + case M_CREATE_TRANSFER: { + if (!fDate->Validate()) break; - } - default: - { - BWindow::MessageReceived(msg); + + if (!fAmount->Validate()) + break; + + AccountListItem *sitem = + (AccountListItem *)fSourceList->ItemAt(fSourceList->CurrentSelection()); + if (!sitem) + break; + + AccountListItem *ditem = + (AccountListItem *)fDestList->ItemAt(fDestList->CurrentSelection()); + if (!ditem) + break; + + Fixed amount; + gCurrentLocale.StringToCurrency(fAmount->Text(), amount); + if (amount == 0) { + ShowAlert( + TRANSLATE("Not Transferring Any Money"), + TRANSLATE("If you intend to transfer money, it will need to " + "be an amount that is not zero.") + ); break; } + + fMessage.AddPointer("from", sitem->GetAccount()); + fMessage.AddPointer("to", ditem->GetAccount()); + fMessage.AddString("amount", fAmount->Text()); + fMessage.AddString("memo", fMemo->Text()); + fMessage.AddString("date", fDate->Text()); + fMessenger.SendMessage(&fMessage); + fMessage.MakeEmpty(); + + PostMessage(B_QUIT_REQUESTED); + break; + } + default: { + BWindow::MessageReceived(msg); + break; + } } } -void TransferWindow::HandleOKButton(void) -{ - if(fSourceList->CurrentSelection()>=0) - { +void +TransferWindow::HandleOKButton(void) { + if (fSourceList->CurrentSelection() >= 0) { AccountListItem *item = (AccountListItem *)fDestList->ItemAt(fDestList->CurrentSelection()); - if(item && item->IsEnabled()) - { + if (item && item->IsEnabled()) { fOK->SetEnabled(true); return; } } - - if(fOK->IsEnabled()) + + if (fOK->IsEnabled()) fOK->SetEnabled(false); } diff --git a/src/TransferWindow.h b/src/TransferWindow.h index b02f694..7fc9948 100644 --- a/src/TransferWindow.h +++ b/src/TransferWindow.h @@ -1,16 +1,16 @@ #ifndef TRANSFERWINDOW_H #define TRANSFERWINDOW_H -#include -#include -#include -#include +#include "Account.h" +#include "AccountListItem.h" +#include "Fixed.h" #include +#include #include +#include +#include +#include #include -#include "Fixed.h" -#include "Account.h" -#include "AccountListItem.h" #define M_CREATE_TRANSFER 'crtn' #define M_EDIT_TRANSFER 'edtn' @@ -18,28 +18,27 @@ class DateBox; class CurrencyBox; - -class TransferWindow : public BWindow -{ -public: +class TransferWindow : public BWindow { + public: TransferWindow(BHandler *target); - TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount); + TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount); void MessageReceived(BMessage *msg); void SetMessage(BMessage msg); -private: + + private: friend class TransferFilter; - - void InitObject(Account *src, Account *dest, const Fixed &amount); + + void InitObject(Account *src, Account *dest, const Fixed &amount); void HandleOKButton(void); - + BTextControl *fMemo; DateBox *fDate; CurrencyBox *fAmount; - + BButton *fCancel, *fOK; BStringView *fFromLabel, *fToLabel; BListView *fSourceList, *fDestList; - + BMessenger fMessenger; BMessage fMessage; }; From c9671d4bbc5566d45c5a2b950cbc4e5bfb4e1564 Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Thu, 14 Mar 2024 15:50:57 +0300 Subject: [PATCH 2/6] Fix build --- src/ReconcileItem.h | 3 ++- src/TransactionData.h | 4 +++- src/TransactionItem.h | 16 ++++++++++------ 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/ReconcileItem.h b/src/ReconcileItem.h index da817ed..7b61f78 100644 --- a/src/ReconcileItem.h +++ b/src/ReconcileItem.h @@ -1,9 +1,10 @@ #ifndef RECONCILE_ITEM_H #define RECONCILE_ITEM_H +#include "TransactionData.h" + #include -class TransactionData; class ReconcileItem : public BStringItem { public: diff --git a/src/TransactionData.h b/src/TransactionData.h index d9e004c..bb89476 100644 --- a/src/TransactionData.h +++ b/src/TransactionData.h @@ -1,12 +1,14 @@ #ifndef TRANSACTIONDATA_H #define TRANSACTIONDATA_H + #include "Category.h" #include "Fixed.h" #include "TextFile.h" +#include "Transaction.h" + #include -#include "Transaction.h" class TransactionData { public: diff --git a/src/TransactionItem.h b/src/TransactionItem.h index a3a59ed..19ca712 100644 --- a/src/TransactionItem.h +++ b/src/TransactionItem.h @@ -1,9 +1,12 @@ #ifndef TRANSACTION_ITEM_H #define TRANSACTION_ITEM_H + +#include "TransactionData.h" + #include +#include -class TransactionData; void InitTransactionItemLayout(BView *owner); @@ -23,16 +26,17 @@ class TransactionItem : public BListItem { void SetData(const TransactionData &trans); private: - time_t fDate; Account *fAccount; - BString fType; - BString fPayee; - Fixed fAmount; BString fCategory; BString fMemo; + BString fPayee; + BString fType; + Fixed fAmount; + + bigtime_t fTimeStamp; + time_t fDate; uint8 fStatus; uint32 fID; - bigtime_t fTimeStamp; }; #endif From 9b8e6ca8b32793bfb714d71fc16d1556c6186966 Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Thu, 14 Mar 2024 18:22:46 +0300 Subject: [PATCH 3/6] Add catkeys support - Refactor strings according to Haiku HIG --- Makefile | 8 +- README.md | 14 +- locales/en.catkeys | 265 ++++++++++++++++++++++++++++++++++ src/AccountListItem.cpp | 11 +- src/AccountSettingsWindow.cpp | 26 ++-- src/App.cpp | 21 +-- src/Budget.cpp | 18 ++- src/BudgetReport.cpp | 12 +- src/BudgetWindow.cpp | 69 +++++---- src/CashFlowReport.cpp | 16 +- src/CategoryWindow.cpp | 93 ++++++------ src/CheckNumBox.cpp | 12 +- src/CheckView.cpp | 34 +++-- src/CurrencyBox.cpp | 12 +- src/Database.cpp | 4 +- src/DateBox.cpp | 12 +- src/HelpButton.cpp | 10 +- src/Locale.cpp | 10 +- src/MainWindow.cpp | 156 ++++++++++---------- src/NetWorthReport.cpp | 15 +- src/PayeeBox.cpp | 10 +- src/PrefWindow.cpp | 48 +++--- src/QuickTrackerItem.cpp | 16 +- src/ReconcileWindow.cpp | 98 +++++++------ src/RegisterView.cpp | 12 +- src/ReportWindow.cpp | 59 ++++---- src/ReportWindow.h | 3 +- src/ScheduleAddWindow.cpp | 58 ++++---- src/ScheduleListWindow.cpp | 39 +++-- src/ScheduledTransItem.cpp | 13 +- src/SplitView.cpp | 58 ++++---- src/SplitViewFilter.cpp | 10 +- src/TransactionEditWindow.cpp | 10 +- src/TransactionItem.cpp | 15 +- src/TransactionReport.cpp | 40 +++-- src/TransferWindow.cpp | 32 ++-- src/Translate.h | 10 -- src/capitalbe.rdef | 4 +- 38 files changed, 878 insertions(+), 475 deletions(-) create mode 100644 locales/en.catkeys delete mode 100644 src/Translate.h diff --git a/Makefile b/Makefile index 09dbf60..4e41fe9 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ NAME = CapitalBe TYPE = APP # If you plan to use localization, specify the application's MIME signature. -APP_MIME_SIG = +APP_MIME_SIG = application/x-vnd.wgp-CapitalBe # The following lines tell Pe and Eddie where the SRCS, RDEFS, and RSRCS are # so that Pe and Eddie can fill them in for you. @@ -119,7 +119,7 @@ RSRCS = \ # - if your library does not follow the standard library naming scheme, # you need to specify the path to the library and it's name. # (e.g. for mylib.a, specify "mylib.a" or "path/mylib.a") -LIBS = be tracker translation sqlite3 columnlistview $(STDCPPLIBS) +LIBS = be tracker localestub sqlite3 columnlistview $(STDCPPLIBS) # Specify additional paths to directories following the standard libXXX.so # or libXXX.a naming scheme. You can specify full paths or paths relative @@ -131,7 +131,7 @@ LIBPATHS = # Additional paths to look for system headers. These use the form # "#include
". Directories that contain the files in SRCS are # NOT auto-included here. -SYSTEM_INCLUDE_PATHS = /system/develop/headers/private/interface/ +SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) # Additional paths paths to look for local headers. These use the form # #include "header". Directories that contain the files in SRCS are @@ -147,7 +147,7 @@ OPTIMIZE := # will recreate only the "locales/en.catkeys" file. Use it as a template # for creating catkeys for other languages. All localization files must be # placed in the "locales" subdirectory. -LOCALES = +LOCALES = en # Specify all the preprocessor symbols to be defined. The symbols will not # have their values set automatically; you must supply the value (if any) to diff --git a/README.md b/README.md index c318434..a30e264 100644 --- a/README.md +++ b/README.md @@ -6,12 +6,8 @@ Personal finance manager for BeOS, Zeta, and Haiku! ## Features -QuickTracker - Know your net worth at a glance - your total cash minus your total debt. More kinds of calculations (income vs spending, etc.) coming in the first release. - -Fast Balance - Sometimes Capital Be can balance your checkbook for you. If all the unreconciled transactions before the bank statement date have cleared, Capital Be will do all the work for you. - -Fast Entry - Capital Be will automatically complete what you type wherever possible. If you type in the word Split in for the category, it even pops up the Split window for you - no menu work needed. - -Open Format - Capital Be uses the SQLite database to store its information, so there can be no funny business behind your back. Anyone with some experience in database programming can easily see exactly what is stored. - -Easy Reports - Other programs make finding out information to make financial decisions much harder than it needs to be. Not here. +- QuickTracker: Know your net worth at a glance - your total cash minus your total debt. More kinds of calculations (income vs spending, etc.) coming in the first release. +- Fast Balance: Sometimes CapitalBe can balance your checkbook for you. If all the unreconciled transactions before the bank statement date have cleared, CapitalBe will do all the work for you. +- Fast Entry: CapitalBe will automatically complete what you type wherever possible. If you type in the word Split in for the category, it even pops up the Split window for you - no menu work needed. +- Open Format: CapitalBe uses the SQLite database to store its information, so there can be no funny business behind your back. Anyone with some experience in database programming can easily see exactly what is stored. +- Easy Reports: Other programs make finding out information to make financial decisions much harder than it needs to be. Not here. diff --git a/locales/en.catkeys b/locales/en.catkeys new file mode 100644 index 0000000..05a1190 --- /dev/null +++ b/locales/en.catkeys @@ -0,0 +1,265 @@ +1 English application/x-vnd.wgp-CapitalBe 1061653508 +Year ReportWindow Year +Edit transaction TransactionEditWindow Edit transaction +None ReportWindow None +Export to QIF file… MainWindow Export to QIF file… +Transfer from %%PAYEE%% MainWindow Transfer from %%PAYEE%% +Reports ReportWindow Reports +Monthly ScheduleAddWindow Monthly +Annually BudgetWindow Annually +OK PrefWindow OK +Changes will take effect on restart MainWindow Changes will take effect on restart +CapitalBe didn't understand the date you entered. DateBox CapitalBe didn't understand the date you entered. +CapitalBe Preview Edition MainWindow CapitalBe Preview Edition +To account TransferWindow To account +Category CheckView Category +Reports… MainWindow Reports… +Cancel TransferWindow Cancel +Weekly BudgetWindow Weekly +Enter CheckView Enter +Next MainWindow Next +Remove… CategoryWindow Remove… +Cancel CategoryWindow Cancel +Amount BudgetReport Amount +Cancel ScheduleAddWindow Cancel +Payee: %s ScheduleAddWindow Payee: %s +Default account settings: PrefWindow Default account settings: +CapitalBe System name CapitalBe +Import from QIF file… MainWindow Import from QIF file… +Ending date: ReportWindow Ending date: +You need to enter a payee. PayeeBox You need to enter a payee. +Split ScheduledTransItem Split +Could not export your financial data to the file %%FILENAME%%. MainWindow Could not export your financial data to the file %%FILENAME%%. +Separator: PrefWindow Separator: +Program MainWindow Program +Starting balance: ReconcileWindow Starting balance: +CapitalBe uses the words 'Income','Spending', and 'Split' for managing categories, so you can't use them as category names. Please choose a different name for your new category. CategoryWindow CapitalBe uses the words 'Income','Spending', and 'Split' for managing categories, so you can't use them as category names. Please choose a different name for your new category. +Total charges: %s ReconcileWindow Total charges: %s +CapitalBe: MainWindow CapitalBe: +CapitalBe didn't understand the amount. SplitView CapitalBe didn't understand the amount. +You need to select an account in order to reconcile it. MainWindow You need to select an account in order to reconcile it. +Spending category CategoryWindow Spending category +Add… CategoryWindow Add… +Total NetWorthReport Total +Interest earned: ReconcileWindow Interest earned: +Category SplitView Category +Transactions ReportWindow Transactions +Budget: QuickTrackerItem Budget: +Couldn't quick balance. ReconcileWindow Couldn't quick balance. +Total BudgetWindow Total +Memo TransactionReport Memo +Enter SplitView Enter +Category CashFlowReport Category +Reports: ReportWindow Reports: +Subtotal: ReportWindow Subtotal: +CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. ScheduleAddWindow CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. +Highest BudgetWindow Highest +Unknown Budget Unknown +You need to have at least 2 accounts to perform a transfer. MainWindow You need to have at least 2 accounts to perform a transfer. +Monthly ScheduleListWindow Monthly +Category BudgetWindow Category +Frequency BudgetWindow Frequency +Subtotal ReportWindow Subtotal +Memo: ScheduleAddWindow Memo: +Uncategorized SplitView Uncategorized +Frequency ScheduleListWindow Frequency +Cancel ReconcileWindow Cancel +Category TransactionReport Category +Amount ScheduleListWindow Amount +Add Category CategoryWindow Add Category +Spending CategoryWindow Spending +Date TransferWindow Date +There may be a typo or the wrong kind of currency symbol for this account. SplitView There may be a typo or the wrong kind of currency symbol for this account. +Reconcile… MainWindow Reconcile… +Spending BudgetWindow Spending +Type TransactionReport Type +Reopen MainWindow Reopen +Edit… CategoryWindow Edit… +Annually ScheduleAddWindow Annually +Close MainWindow Close +Closed AccountListItem Closed +CapitalBe didn't understand the amount for Bank Charges. ReconcileWindow CapitalBe didn't understand the amount for Bank Charges. +Import MainWindow Import +CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. ReportWindow CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. +Could not import the data in the file %%FILENAME%%. MainWindow Could not import the data in the file %%FILENAME%%. +Once deleted, you will not be able to get back any data on this account. MainWindow Once deleted, you will not be able to get back any data on this account. +Total deposits: %s ReconcileWindow Total deposits: %s +Amount CheckView Amount +Indefinitely ScheduleAddWindow Indefinitely +Cancel MainWindow Cancel +Categories ReportWindow Categories +Appears before amount PrefWindow Appears before amount +Unreconciled total: %s ReconcileWindow Unreconciled total: %s +Date TransactionReport Date +There may be a typo or the wrong kind of currency symbol for this account. ReconcileWindow There may be a typo or the wrong kind of currency symbol for this account. +Really delete account? MainWindow Really delete account? +Payee CheckView Payee +DEP ReconcileWindow DEP +Income BudgetWindow Income +This really shouldn't happen, so you probably should e-mail support about this. MainWindow This really shouldn't happen, so you probably should e-mail support about this. +Quick balance ReconcileWindow Quick balance +This happens when the kind of file is not supported, when the file's data is damaged, or when you feed it a recipe for quiche. MainWindow This happens when the kind of file is not supported, when the file's data is damaged, or when you feed it a recipe for quiche. +Payments ScheduleListWindow Payments +Month ReportWindow Month +Add Item SplitView Add Item +Scheduled transactions… MainWindow Scheduled transactions… +Delete MainWindow Delete +Date format: %s PrefWindow Date format: %s +Bank charges: ReconcileWindow Bank charges: +Quick balance successful! ReconcileWindow Quick balance successful! +Quarter ReportWindow Quarter +Account interest ReconcileWindow Account interest +Schedule this transaction… MainWindow Schedule this transaction… +Payee ScheduleListWindow Payee +Symbol: PrefWindow Symbol: +Transactions TransactionReport Transactions +Split Transaction SplitView Split Transaction +Average BudgetWindow Average +Quarterly Budget Quarterly +Currency PrefWindow Currency +Summary BudgetWindow Summary +Frequency ScheduleAddWindow Frequency +Category BudgetReport Category +Accounts: ReportWindow Accounts: +Options PrefWindow Options +Edit category BudgetWindow Edit category +Reconcile ReconcileWindow Reconcile +Weekly ScheduleListWindow Weekly +Amount SplitView Amount +Reset ReconcileWindow Reset +Frequency: ScheduleAddWindow Frequency: +Category: ScheduleAddWindow Category: +OK AccountSettingsWindow OK +Annually Budget Annually +Payee SplitView Payee +Can't use this category name CategoryWindow Can't use this category name +Budget BudgetWindow Budget +Monthly BudgetWindow Monthly +Transfer to %%PAYEE%% MainWindow Transfer to %%PAYEE%% +OK TransferWindow OK +Total worth NetWorthReport Total worth +Memo CheckView Memo +Show Split SplitView Show Split +times ScheduleAddWindow times +Annually ScheduleListWindow Annually +Oops! MainWindow Oops! +Edit… MainWindow Edit… +OK CategoryWindow OK +Spending ReportWindow Spending +Help HelpButton Help +Total: SplitView Total: +Unlimited ScheduleListWindow Unlimited +Account settings AccountSettingsWindow Account settings +Account name: AccountSettingsWindow Account name: +Set all to zero BudgetWindow Set all to zero +When the split items are added together, they need to add up to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%% SplitView When the split items are added together, they need to add up to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%% +Date is missing. ReconcileWindow Date is missing. +Date: ReconcileWindow Date: +Numbered transactions cannot be scheduled. MainWindow Numbered transactions cannot be scheduled. +New… MainWindow New… +Quick Balance failed. This doesn't mean that you did something wrong - it's just that Quick Balance works on simpler cases in balancing an account than this one. Sorry. ReconcileWindow Quick Balance failed. This doesn't mean that you did something wrong - it's just that Quick Balance works on simpler cases in balancing an account than this one. Sorry. +Transfer BudgetWindow Transfer +Amount: %s ScheduleAddWindow Amount: %s +Starting date: ScheduleAddWindow Starting date: +Settings… MainWindow Settings… +Monthly Budget Monthly +Cancel PrefWindow Cancel +Unreconciled total ReconcileWindow Unreconciled total +Quarterly ScheduleListWindow Quarterly +12 month statistics BudgetWindow 12 month statistics +Not transferring any money TransferWindow Not transferring any money +Split CategoryWindow Split +Income ReportWindow Income +Memo SplitView Memo +Total checks: ReconcileWindow Total checks: +Not enough accounts for a transfer. MainWindow Not enough accounts for a transfer. +Amount TransactionReport Amount +Transaction MainWindow Transaction +Edit transfer TransferWindow Edit transfer +Amount TransferWindow Amount +CapitalBe will be use your language choice the next time it is started. MainWindow CapitalBe will be use your language choice the next time it is started. +Categories CategoryWindow Categories +Language MainWindow Language +Date CheckView Date +Account MainWindow Account +Currency format: %s PrefWindow Currency format: %s +Payee TransactionReport Payee +Total deposits: ReconcileWindow Total deposits: +Categories… MainWindow Categories… +No Memo TransactionItem No Memo +CapitalBe didn't understand the amount. CurrencyBox CapitalBe didn't understand the amount. +Day, Month, Year PrefWindow Day, Month, Year +Remove… ScheduleListWindow Remove… +If you intend to transfer money, it will need to be an amount that is not zero. TransferWindow If you intend to transfer money, it will need to be an amount that is not zero. +Budget… MainWindow Budget… +You can schedule transfers, deposits, or ATM transactions. MainWindow You can schedule transfers, deposits, or ATM transactions. +Success! ReconcileWindow Success! +Income CategoryWindow Income +Edit category CategoryWindow Edit category +QuickTracker RegisterView QuickTracker +Schedule transaction ScheduleAddWindow Schedule transaction +Type: %s ScheduleAddWindow Type: %s +Weekly Budget Weekly +Split SplitFilterView Split +Bank charge ReconcileWindow Bank charge +Cancel AccountSettingsWindow Cancel +Ending balance: ReconcileWindow Ending balance: +Date PrefWindow Date +OK ScheduleAddWindow OK +Date SplitView Date +Lowest BudgetWindow Lowest +Previous MainWindow Previous +New category name: CategoryWindow New category name: +Remove Item SplitView Remove Item +Accounts RegisterView Accounts +Payee is missing. PayeeBox Payee is missing. +Type CheckView Type +Account total: QuickTrackerItem Account total: +Export MainWindow Export +You need to enter a check number or transaction type, such as ATM (for debit card transactions and the like), DEP (for deposits), or your own code for some other kind of expense. CheckNumBox You need to enter a check number or transaction type, such as ATM (for debit card transactions and the like), DEP (for deposits), or your own code for some other kind of expense. +Enter a transfer… MainWindow Enter a transfer… +File MainWindow File +Tools MainWindow Tools +Transaction type is missing. CheckNumBox Transaction type is missing. +Split TransactionItem Split +CapitalBe didn't understand the amount for Interest Earned. ReconcileWindow CapitalBe didn't understand the amount for Interest Earned. +Split SplitView Split +The split total must match the amount box. SplitView The split total must match the amount box. +Delete… MainWindow Delete… +Amount BudgetWindow Amount +About CapitalBe… MainWindow About CapitalBe… +Scheduled transactions ScheduleListWindow Scheduled transactions +Starting date: ReportWindow Starting date: +Amount CashFlowReport Amount +Quarterly ScheduleAddWindow Quarterly +Hide Split SplitView Hide Split +Reconcile: ReconcileWindow Reconcile: +Total charges: ReconcileWindow Total charges: +Total worth ReportWindow Total worth +Category name: CategoryWindow Category name: +Expense CashFlowReport Expense +No transactions TransactionReport No transactions +Please choose a new category for all transactions currently in the %%CATEGORY_NAME%% category. CategoryWindow Please choose a new category for all transactions currently in the %%CATEGORY_NAME%% category. +Add account transfer TransferWindow Add account transfer +You need to have an account created in order to reconcile it. MainWindow You need to have an account created in order to reconcile it. +CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. DateBox CapitalBe understands lots of different ways of entering dates. Apparently, this wasn't one of them. You'll need to change how you entered this date. Sorry. +There may be a typo or the wrong kind of currency symbol for this account. CurrencyBox There may be a typo or the wrong kind of currency symbol for this account. +From account TransferWindow From account +Next Payment ScheduleListWindow Next Payment +Type SplitView Type +Bank Charge ReconcileWindow Bank Charge +Recalculate all BudgetWindow Recalculate all +Date NetWorthReport Date +CapitalBe didn't understand the date you entered. ScheduleAddWindow CapitalBe didn't understand the date you entered. +Income CashFlowReport Income +Memo TransferWindow Memo +Total checks: %s ReconcileWindow Total checks: %s +Quarterly BudgetWindow Quarterly +Remove category CategoryWindow Remove category +Decimal: PrefWindow Decimal: +Month, Day, Year PrefWindow Month, Day, Year +You need to enter the date for the statement to Quick Balance. ReconcileWindow You need to enter the date for the statement to Quick Balance. +Split ScheduleAddWindow Split +Use default currency settings AccountSettingsWindow Use default currency settings +CapitalBe didn't understand the date you entered. ReportWindow CapitalBe didn't understand the date you entered. +Unknown ScheduleListWindow Unknown diff --git a/src/AccountListItem.cpp b/src/AccountListItem.cpp index 445ae39..887c263 100644 --- a/src/AccountListItem.cpp +++ b/src/AccountListItem.cpp @@ -4,13 +4,20 @@ #include "Database.h" #include "Preferences.h" #include "TransactionLayout.h" -#include "Translate.h" + +#include #include #include #include #include + #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "AccountListItem" + + AccountListItem::AccountListItem(Account *acc) : BListItem() { fAccount = acc; fEnabled = true; @@ -63,7 +70,7 @@ AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) { if (fAccount->IsClosed()) { owner->DrawString( - TRANSLATE("Closed"), BPoint(frame.left + 5, frame.top + (font.Size() * 2)) + B_TRANSLATE("Closed"), BPoint(frame.left + 5, frame.top + (font.Size() * 2)) ); } else { BString text; diff --git a/src/AccountSettingsWindow.cpp b/src/AccountSettingsWindow.cpp index e983a4a..b2738a1 100644 --- a/src/AccountSettingsWindow.cpp +++ b/src/AccountSettingsWindow.cpp @@ -1,14 +1,19 @@ -#include "AccountSettingsWindow.h" -#include "Fixed.h" +#include #include #include +#include "AccountSettingsWindow.h" #include "AutoTextControl.h" #include "CBLocale.h" #include "Database.h" #include "EscapeCancelFilter.h" +#include "Fixed.h" #include "PrefWindow.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "AccountSettingsWindow" + #define M_EDIT_ACCOUNT_SETTINGS 'east' #define M_NAME_CHANGED 'nmch' @@ -16,7 +21,7 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) : BWindow( - BRect(0, 0, 1, 1), TRANSLATE("Account Settings"), B_FLOATING_WINDOW_LOOK, + BRect(0, 0, 1, 1), B_TRANSLATE("Account settings"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), @@ -30,8 +35,7 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) BView *back = new BView("back", B_WILL_DRAW); back->SetViewColor(240, 240, 240); - temp = TRANSLATE("Account Name"); - temp += ":"; + temp = B_TRANSLATE("Account name:"); fAccountName = new AutoTextControl( "accname", temp.String(), (fAccount ? fAccount->Name() : NULL), new BMessage(M_NAME_CHANGED) ); @@ -40,8 +44,8 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) fAccountName->MakeFocus(true); fAccountName->SetDivider(fAccountName->StringWidth(temp.String()) + 3); - fUseDefault = new BCheckBox( - "usedefault", "Use Default Currency Settings", new BMessage(M_TOGGLE_USE_DEFAULT) + fUseDefault = new BCheckBox("usedefault", B_TRANSLATE("Use default currency settings"), + new BMessage(M_TOGGLE_USE_DEFAULT) ); if (!fAccount || fAccount->IsUsingDefaultLocale()) fUseDefault->SetValue(B_CONTROL_ON); @@ -51,13 +55,13 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) templocale = fAccount->GetLocale(); fPrefView = new CurrencyPrefView("prefview", &templocale); - fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_ACCOUNT_SETTINGS)); - fOK->SetLabel(TRANSLATE("OK")); + fOK = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_EDIT_ACCOUNT_SETTINGS)); + fOK->SetLabel(B_TRANSLATE("OK")); if (strlen(fAccountName->Text()) < 1) fOK->SetEnabled(false); - fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + fCancel = new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); SetDefaultButton(fOK); diff --git a/src/App.cpp b/src/App.cpp index 10a6695..7668326 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -27,10 +27,10 @@ App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { if (GetCurrentDate() > 1167022800) { ShowAlert( "This beta version has expired.", - "This is only a test version of Capital Be and is intended to work only " + "This is only a test version of CapitalBe and is intended to work only " "for a short period of time to allow the community to help find bugs and " - "make Capital Be the best financial manager possible.\n\nYou can download " - "a new copy of Capital Be from http://www.capitalbe.com/" + "make CapitalBe the best financial manager possible.\n\nYou can download " + "a new copy of CapitalBe from http://www.capitalbe.com/" ); be_app->PostMessage(B_QUIT_REQUESTED); return; @@ -41,11 +41,6 @@ App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { // Load preferences and then initialize the translation system LoadPreferences(PREFERENCES_PATH "/CapitalBeSettings"); - BString languagepath = gAppPath.String(); - languagepath += "R5LanguageFiles"; - language_roster = new LanguageRoster(languagepath.String()); - - // We can skip locking because nothing else is open at this point :) BRect winframe; if (gPreferences.FindRect("mainframe", &winframe) == B_OK) @@ -59,8 +54,8 @@ App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { #ifdef PREVIEW_MODE ShowAlert( - "Welcome to Capital Be's Technology Preview!", - "Welcome and thank you for trying Capital Be, what will be the foremost " + "Welcome to CapitalBe's Technology Preview!", + "Welcome and thank you for trying CapitalBe, what will be the foremost " "personal finance manager for BeOS, Zeta, and Haiku.\n\n" "This preview version may contain bugs and is not feature complete, but " "will give you an idea of what the full version will be like when released.\n\n" @@ -120,10 +115,10 @@ main(void) { void StartFile(void) { - BEntry entry("/boot/develop/projects/Capital Be/cbsql/testdb"); + BEntry entry("/boot/develop/projects/CapitalBe/cbsql/testdb"); if (entry.Exists()) entry.Remove(); - gDatabase.CreateFile("/boot/develop/projects/Capital Be/cbsql/testdb"); + gDatabase.CreateFile("/boot/develop/projects/CapitalBe/cbsql/testdb"); /* gDatabase.AddAccount("Test Account 1",ACCOUNT_BANK); gDatabase.AddAccount("Test Account 2",ACCOUNT_BANK); @@ -174,7 +169,7 @@ StartFile(void) { int main(void) { - // gDatabase.OpenFile("/boot/develop/projects/Capital Be/cbsql/testdb"); + // gDatabase.OpenFile("/boot/develop/projects/CapitalBe/cbsql/testdb"); StartFile(); } diff --git a/src/Budget.cpp b/src/Budget.cpp index 3d73598..7be35e4 100644 --- a/src/Budget.cpp +++ b/src/Budget.cpp @@ -1,5 +1,11 @@ #include "Budget.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "Budget" + BudgetEntry::BudgetEntry(void) { Set("", 0, BUDGET_MONTHLY, true); } @@ -31,23 +37,23 @@ BString BudgetPeriodToString(const BudgetPeriod &period) { switch (period) { case BUDGET_MONTHLY: { - return BString(TRANSLATE("Monthly")); + return BString(B_TRANSLATE("Monthly")); break; } case BUDGET_WEEKLY: { - return BString(TRANSLATE("Weekly")); + return BString(B_TRANSLATE("Weekly")); break; } case BUDGET_QUARTERLY: { - return BString(TRANSLATE("Quarterly")); + return BString(B_TRANSLATE("Quarterly")); break; } case BUDGET_ANNUALLY: { - return BString(TRANSLATE("Annually")); + return BString(B_TRANSLATE("Annually")); break; } default: { - return BString(TRANSLATE("Unknown")); + return BString(B_TRANSLATE("Unknown")); break; } } diff --git a/src/BudgetReport.cpp b/src/BudgetReport.cpp index 12db825..0c9e9ba 100644 --- a/src/BudgetReport.cpp +++ b/src/BudgetReport.cpp @@ -8,6 +8,13 @@ #include "ReportWindow.h" #include "TimeSupport.h" +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "BudgetReport" + + /* Status: Different tack on the same task - go one row at a time by querying once for @@ -84,7 +91,8 @@ ReportWindow::ComputeBudget(void) { // The rest of the array will be initialized in the column-adding loop float maxwidths[count + 1]; maxwidths[0] = be_plain_font->StringWidth("Category") + 20; - fGridView->AddColumn(new BStringColumn("Category", maxwidths[0], 10, 300, B_TRUNCATE_END), 0); + fGridView->AddColumn(new BStringColumn(B_TRANSLATE("Category"), maxwidths[0], 10, 300, + B_TRUNCATE_END), 0); int32 i; for (i = 0; i < timelist.CountItems() - 1; i++) { @@ -109,7 +117,7 @@ ReportWindow::ComputeBudget(void) { break; } default: { - sprintf(columntitle, TRANSLATE("Amount")); + sprintf(columntitle, B_TRANSLATE("Amount")); break; } } diff --git a/src/BudgetWindow.cpp b/src/BudgetWindow.cpp index 08b7cc7..25cc84a 100644 --- a/src/BudgetWindow.cpp +++ b/src/BudgetWindow.cpp @@ -1,6 +1,7 @@ #include "BudgetWindow.h" -#include "ColumnTypes.h" +#include +#include #include #include #include @@ -15,7 +16,11 @@ #include "MsgDefs.h" #include "Preferences.h" #include "TimeSupport.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "BudgetWindow" + enum { M_CATEGORIES_CHANGED = 'mccc', @@ -38,7 +43,7 @@ compare_stringitem(const void *item1, const void *item2); BudgetWindow::BudgetWindow(const BRect &frame) : BWindow( - frame, TRANSLATE("Budget"), B_DOCUMENT_WINDOW, + frame, B_TRANSLATE("Budget"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ), fIncomeGrid(13, 0), fSpendingGrid(13, 0) { @@ -47,8 +52,9 @@ BudgetWindow::BudgetWindow(const BRect &frame) fBackView->SetViewColor(240, 240, 240); fBar = new BMenuBar("menubar"); - fBar->AddItem(new BMenuItem(TRANSLATE("Recalculate All"), new BMessage(M_BUDGET_RECALCULATE))); - fBar->AddItem(new BMenuItem(TRANSLATE("Set All to Zero"), new BMessage(M_BUDGET_ZERO))); + fBar->AddItem(new BMenuItem(B_TRANSLATE("Recalculate all"), + new BMessage(M_BUDGET_RECALCULATE))); + fBar->AddItem(new BMenuItem(B_TRANSLATE("Set all to zero"), new BMessage(M_BUDGET_ZERO))); BuildBudgetSummary(); BuildStatsAndEditor(); @@ -250,8 +256,8 @@ BudgetWindow::RefreshCategories(void) { fCategoryList->AddRow(fIncomeRow); fSpendingRow = new BRow(); fCategoryList->AddRow(fSpendingRow); - fIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); - fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); + fIncomeRow->SetField(new BStringField(B_TRANSLATE("Income")), 0); + fSpendingRow->SetField(new BStringField(B_TRANSLATE("Spending")), 0); CppSQLite3Query query = gDatabase.DBQuery( "select category,amount,period,isexpense from " @@ -439,11 +445,11 @@ BudgetWindow::GenerateBudget(const bool &zero) { if (query.eof()) return; - float maxwidth = fCategoryList->StringWidth(TRANSLATE("Category")); + float maxwidth = fCategoryList->StringWidth(B_TRANSLATE("Category")); while (!query.eof()) { BString catname = DeescapeIllegalCharacters(query.getStringField(0)); - if (catname.ICompare(TRANSLATE("Transfer")) == 0) { + if (catname.ICompare(B_TRANSLATE("Transfer")) == 0) { query.nextRow(); continue; } @@ -643,15 +649,15 @@ BudgetWindow::BuildStatsAndEditor(void) { // Add the category statistics BString temp; rgb_color white = {255, 255, 255, 255}; - float statwidth = fBackView->StringWidth(TRANSLATE("12 Month Statistics")) + 20; + float statwidth = fBackView->StringWidth(B_TRANSLATE("12 month statistics")) + 20; float amountwidth = fBackView->StringWidth("000,000.00") + 20; fCatStat = new BColumnListView("categorystats", B_WILL_DRAW | B_NAVIGABLE, B_FANCY_BORDER); fCatStat->AddColumn( - new BStringColumn(TRANSLATE("12 Month Statistics"), statwidth, 10, 300, B_TRUNCATE_END), 0 + new BStringColumn(B_TRANSLATE("12 month statistics"), statwidth, 10, 300, B_TRUNCATE_END), 0 ); fCatStat->AddColumn( - new BStringColumn(TRANSLATE("Amount"), amountwidth, 10, 300, B_TRUNCATE_END), 1 + new BStringColumn(B_TRANSLATE("Amount"), amountwidth, 10, 300, B_TRUNCATE_END), 1 ); fCatStat->SetSortingEnabled(false); fCatStat->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); @@ -662,9 +668,9 @@ BudgetWindow::BuildStatsAndEditor(void) { fCatStat->AddRow(fStatHighestRow); fCatStat->AddRow(fStatLowestRow); - fStatAverageRow->SetField(new BStringField(TRANSLATE("Average")), 0); - fStatHighestRow->SetField(new BStringField(TRANSLATE("Highest")), 0); - fStatLowestRow->SetField(new BStringField(TRANSLATE("Lowest")), 0); + fStatAverageRow->SetField(new BStringField(B_TRANSLATE("Average")), 0); + fStatHighestRow->SetField(new BStringField(B_TRANSLATE("Highest")), 0); + fStatLowestRow->SetField(new BStringField(B_TRANSLATE("Lowest")), 0); fCatStat->SetColor(B_COLOR_BACKGROUND, white); fCatStat->SetColor(B_COLOR_SELECTION, white); @@ -675,20 +681,21 @@ BudgetWindow::BuildStatsAndEditor(void) { // Add the category editor fCatBox = new BBox("catbox"); - fCatBox->SetLabel(TRANSLATE("Edit Category")); + fCatBox->SetLabel(B_TRANSLATE("Edit category")); fMonthly = - new BRadioButton("monthoption", TRANSLATE("Monthly"), new BMessage(M_SET_PERIOD_MONTH)); - fWeekly = new BRadioButton("weekoption", TRANSLATE("Weekly"), new BMessage(M_SET_PERIOD_WEEK)); + new BRadioButton("monthoption", B_TRANSLATE("Monthly"), new BMessage(M_SET_PERIOD_MONTH)); + fWeekly = new BRadioButton("weekoption", B_TRANSLATE("Weekly"), + new BMessage(M_SET_PERIOD_WEEK)); fQuarterly = new BRadioButton( - "quarteroption", TRANSLATE("Quarterly"), new BMessage(M_SET_PERIOD_QUARTER) + "quarteroption", B_TRANSLATE("Quarterly"), new BMessage(M_SET_PERIOD_QUARTER) ); fAnnually = - new BRadioButton("yearoption", TRANSLATE("Annually"), new BMessage(M_SET_PERIOD_YEAR)); + new BRadioButton("yearoption", B_TRANSLATE("Annually"), new BMessage(M_SET_PERIOD_YEAR)); fMonthly->SetValue(B_CONTROL_ON); - temp = TRANSLATE("Amount"); + temp = B_TRANSLATE("Amount"); temp += ":"; fAmountLabel = new BStringView("amountlabel", temp.String()); @@ -708,7 +715,7 @@ BudgetWindow::BuildBudgetSummary(void) { fBudgetSummary->SetSortingEnabled(false); fBudgetSummary->AddColumn( new BStringColumn( - TRANSLATE("Summary"), fBudgetSummary->StringWidth(TRANSLATE("Spending")) + 20, 10, 300, + B_TRANSLATE("Summary"), fBudgetSummary->StringWidth(B_TRANSLATE("Spending")) + 20, 10, 300, B_TRUNCATE_END ), 0 @@ -718,9 +725,9 @@ BudgetWindow::BuildBudgetSummary(void) { fBudgetSummary->AddRow(fSummaryTotalRow); fBudgetSummary->SetColumnFlags(B_ALLOW_COLUMN_RESIZE); - fSummaryIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); - fSummarySpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); - fSummaryTotalRow->SetField(new BStringField(TRANSLATE("Total")), 0); + fSummaryIncomeRow->SetField(new BStringField(B_TRANSLATE("Income")), 0); + fSummarySpendingRow->SetField(new BStringField(B_TRANSLATE("Spending")), 0); + fSummaryTotalRow->SetField(new BStringField(B_TRANSLATE("Total")), 0); fBudgetSummary->SetColor(B_COLOR_BACKGROUND, white); fBudgetSummary->SetColor(B_COLOR_SELECTION, white); @@ -751,7 +758,7 @@ BudgetWindow::BuildBudgetSummary(void) { } fBudgetSummary->AddColumn( new BStringColumn( - TRANSLATE("Total"), fBudgetSummary->StringWidth(TRANSLATE("Total")) + 20, 10, 300, + B_TRANSLATE("Total"), fBudgetSummary->StringWidth(B_TRANSLATE("Total")) + 20, 10, 300, B_TRUNCATE_END, B_ALIGN_RIGHT ), 13 @@ -775,21 +782,21 @@ BudgetWindow::BuildCategoryList(void) { fCategoryList->SetSelectionMessage(new BMessage(M_SELECT_CATEGORY)); fCategoryList->AddColumn( new BStringColumn( - TRANSLATE("Category"), fCategoryList->StringWidth(TRANSLATE("Category")) + 20, 10, 300, + B_TRANSLATE("Category"), fCategoryList->StringWidth(B_TRANSLATE("Category")) + 20, 10, 300, B_TRUNCATE_END ), 0 ); fCategoryList->AddColumn( new BStringColumn( - TRANSLATE("Amount"), fCategoryList->StringWidth(TRANSLATE("Amount")) + 20, 10, 300, + B_TRANSLATE("Amount"), fCategoryList->StringWidth(B_TRANSLATE("Amount")) + 20, 10, 300, B_TRUNCATE_END, B_ALIGN_RIGHT ), 1 ); fCategoryList->AddColumn( new BStringColumn( - TRANSLATE("Frequency"), fCategoryList->StringWidth(TRANSLATE("Frequency")) + 20, 10, + B_TRANSLATE("Frequency"), fCategoryList->StringWidth(B_TRANSLATE("Frequency")) + 20, 10, 300, B_TRUNCATE_END, B_ALIGN_RIGHT ), 2 @@ -800,8 +807,8 @@ BudgetWindow::BuildCategoryList(void) { fCategoryList->AddRow(fIncomeRow); fSpendingRow = new BRow(); fCategoryList->AddRow(fSpendingRow); - fIncomeRow->SetField(new BStringField(TRANSLATE("Income")), 0); - fSpendingRow->SetField(new BStringField(TRANSLATE("Spending")), 0); + fIncomeRow->SetField(new BStringField(B_TRANSLATE("Income")), 0); + fSpendingRow->SetField(new BStringField(B_TRANSLATE("Spending")), 0); fCategoryList->SetColor(B_COLOR_BACKGROUND, white); fCategoryList->SetColor(B_COLOR_SELECTION, GetColor(BC_SELECTION_FOCUS)); diff --git a/src/CashFlowReport.cpp b/src/CashFlowReport.cpp index 91f3e58..2059c74 100644 --- a/src/CashFlowReport.cpp +++ b/src/CashFlowReport.cpp @@ -6,8 +6,16 @@ #include "ReportGrid.h" #include "ReportWindow.h" #include "TimeSupport.h" + +#include + #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "CashFlowReport" + + void ReportWindow::ComputeCashFlow(void) { // Calculate the number of columns and the starting date for each one @@ -150,7 +158,7 @@ ReportWindow::ComputeCashFlow(void) { // Now that we have all the data, we need to set up the rows and columns for the report grid BColumn *col = new BStringColumn( - TRANSLATE("Category"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, + B_TRANSLATE("Category"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 0); @@ -178,7 +186,7 @@ ReportWindow::ComputeCashFlow(void) { break; } default: { - sprintf(columntitle, TRANSLATE("Amount")); + sprintf(columntitle, B_TRANSLATE("Amount")); break; } } @@ -190,7 +198,7 @@ ReportWindow::ComputeCashFlow(void) { fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Income")), 0); + titlerow->SetField(new BStringField(B_TRANSLATE("Income")), 0); fGridView->AddRow(new BRow()); if (!fGridView->IsHidden()) { @@ -217,7 +225,7 @@ ReportWindow::ComputeCashFlow(void) { fGridView->AddRow(new BRow()); titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Expense")), 0); + titlerow->SetField(new BStringField(B_TRANSLATE("Expense")), 0); fGridView->AddRow(new BRow()); for (i = 0; i < expensegrid.CountItems(); i++) { diff --git a/src/CategoryWindow.cpp b/src/CategoryWindow.cpp index c53f156..ca8fb84 100644 --- a/src/CategoryWindow.cpp +++ b/src/CategoryWindow.cpp @@ -1,6 +1,7 @@ #include "CategoryWindow.h" #include +#include #include #include #include @@ -17,7 +18,11 @@ #include "Database.h" #include "EscapeCancelFilter.h" #include "Preferences.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "CategoryWindow" + enum { M_SHOW_ADD_WINDOW = 'shaw', @@ -104,16 +109,13 @@ CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, f SetViewColor(240, 240, 240); // the buttons - temp = TRANSLATE("Edit"); - temp += "…"; + temp = B_TRANSLATE("Edit…"); fEditButton = new BButton("editbutton", temp.String(), new BMessage(M_SHOW_EDIT_WINDOW)); - temp = TRANSLATE("Remove"); - temp += "…"; + temp = B_TRANSLATE("Remove…"); fRemoveButton = new BButton("removebutton", temp.String(), new BMessage(M_SHOW_REMOVE_WINDOW)); - temp = TRANSLATE("Add"); - temp += "…"; + temp = B_TRANSLATE("Add…"); fAddButton = new BButton("addbutton", temp.String(), new BMessage(M_SHOW_ADD_WINDOW)); // the category list @@ -123,8 +125,8 @@ CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, f ); BScrollView *sv = new BScrollView("scrollview", fListView, 0, false, true); - fIncomeItem = new CategoryItem(TRANSLATE("Income")); - fSpendingItem = new CategoryItem(TRANSLATE("Spending")); + fIncomeItem = new CategoryItem(B_TRANSLATE("Income")); + fSpendingItem = new CategoryItem(B_TRANSLATE("Spending")); RefreshCategoryList(); @@ -205,11 +207,11 @@ CategoryView::MessageReceived(BMessage *msg) { if (msg->FindString("name", &name) != B_OK || msg->FindBool("expense", &expense) != B_OK) break; - if (name.ICompare(TRANSLATE("Income")) == 0 || name.ICompare(TRANSLATE("Spending")) == 0 || - name.ICompare(TRANSLATE("Split")) == 0) { + if (name.ICompare(B_TRANSLATE("Income")) == 0 || name.ICompare(B_TRANSLATE("Spending")) == 0 || + name.ICompare(B_TRANSLATE("Split")) == 0) { ShowAlert( - TRANSLATE("Can't use this category name"), - TRANSLATE("Capital Be uses the words 'Income','Spending', and 'Split' " + B_TRANSLATE("Can't use this category name"), + B_TRANSLATE("CapitalBe uses the words 'Income','Spending', and 'Split' " "for managing categories, so you can't use them as category names. " "Please choose a different name for your new category.") ); @@ -276,12 +278,12 @@ CategoryView::RefreshCategoryList(void) { int32 maxchars; float maxlength; - if (strlen(TRANSLATE("Income")) > strlen(TRANSLATE("Spending"))) { - maxchars = strlen(TRANSLATE("Income")); - maxlength = StringWidth(TRANSLATE("Income")); + if (strlen(B_TRANSLATE("Income")) > strlen(B_TRANSLATE("Spending"))) { + maxchars = strlen(B_TRANSLATE("Income")); + maxlength = StringWidth(B_TRANSLATE("Income")); } else { - maxchars = strlen(TRANSLATE("Spending")); - maxlength = StringWidth(TRANSLATE("Spending")); + maxchars = strlen(B_TRANSLATE("Spending")); + maxlength = StringWidth(B_TRANSLATE("Spending")); } CppSQLite3Query query = gDatabase.DBQuery( @@ -313,7 +315,7 @@ CategoryView::RefreshCategoryList(void) { CategoryWindow::CategoryWindow(const BRect &frame) : BWindow( - frame, TRANSLATE("Categories"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, + frame, B_TRANSLATE("Categories"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ) { AddCommonFilter(new EscapeCancelFilter); @@ -353,7 +355,7 @@ CategoryItem::DrawItem(BView *owner, BRect frame, bool complete) { CategoryInputWindow::CategoryInputWindow(const BRect &frame, BView *target) : BWindow( - frame, TRANSLATE("Add Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Add Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_V_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), @@ -366,20 +368,19 @@ CategoryInputWindow::CategoryInputWindow(const BRect &frame, BView *target) BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(240, 240, 240); - temp = TRANSLATE("Category Name"); - temp += ":"; + temp = B_TRANSLATE("Category name:"); fNameBox = new AutoTextControl("namebox", temp.String(), "", new BMessage(M_NAME_CHANGED)); fNameBox->SetCharacterLimit(32); - fExpenseBox = new BCheckBox("expensebox", TRANSLATE("Spending Category"), NULL); + fExpenseBox = new BCheckBox("expensebox", B_TRANSLATE("Spending category"), NULL); fExpenseBox->SetValue(B_CONTROL_ON); - fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_ADD_CATEGORY)); - fOKButton->SetLabel(TRANSLATE("OK")); + fOKButton = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_ADD_CATEGORY)); + fOKButton->SetLabel(B_TRANSLATE("OK")); fOKButton->MakeDefault(true); fCancelButton = - new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); fNameBox->MakeFocus(true); @@ -423,7 +424,7 @@ CategoryInputWindow::MessageReceived(BMessage *msg) { CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, BView *target) : BWindow( - frame, TRANSLATE("Remove Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Remove category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), fTarget(target) { @@ -439,7 +440,7 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, fDirections->MakeEditable(false); BString directions( - TRANSLATE("Please choose a new category for all transactions currently in the " + B_TRANSLATE("Please choose a new category for all transactions currently in the " "%%CATEGORY_NAME%% category.") ); directions.ReplaceFirst("%%CATEGORY_NAME%%", from); @@ -447,12 +448,10 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, fDirections->SetViewColor(backcolor); fDirections->SetWordWrap(true); - fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_REMOVE_CATEGORY)); - - fOKButton->SetLabel(TRANSLATE("OK")); - + fOKButton = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_REMOVE_CATEGORY)); + fOKButton->SetLabel(B_TRANSLATE("OK")); fCancelButton = - new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); fListView = new BOutlineListView( "categorylist", B_SINGLE_SELECTION_LIST, @@ -460,8 +459,8 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, ); fScrollView = new BScrollView("scrollview", fListView, 0, false, true); - fIncomeItem = new CategoryItem(TRANSLATE("Income")); - fSpendingItem = new CategoryItem(TRANSLATE("Spending")); + fIncomeItem = new CategoryItem(B_TRANSLATE("Income")); + fSpendingItem = new CategoryItem(B_TRANSLATE("Spending")); fListView->AddItem(fIncomeItem); fListView->AddItem(fSpendingItem); @@ -471,12 +470,12 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, int32 maxchars; float maxlength; - if (strlen(TRANSLATE("Income")) > strlen(TRANSLATE("Spending"))) { - maxchars = strlen(TRANSLATE("Income")); - maxlength = view->StringWidth(TRANSLATE("Income")); + if (strlen(B_TRANSLATE("Income")) > strlen(B_TRANSLATE("Spending"))) { + maxchars = strlen(B_TRANSLATE("Income")); + maxlength = view->StringWidth(B_TRANSLATE("Income")); } else { - maxchars = strlen(TRANSLATE("Spending")); - maxlength = view->StringWidth(TRANSLATE("Spending")); + maxchars = strlen(B_TRANSLATE("Spending")); + maxlength = view->StringWidth(B_TRANSLATE("Spending")); } while (!query.eof()) { @@ -542,7 +541,7 @@ CategoryRemoveWindow::FrameResized(float w, float h) {} CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, BView *target) : BWindow( - frame, TRANSLATE("Edit Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Edit category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), @@ -555,22 +554,20 @@ CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(240, 240, 240); - temp = TRANSLATE("Category Name"); - temp << ": " << fOldName; + temp = B_TRANSLATE("Category name:"); BStringView *oldnameView = new BStringView("oldname", temp.String()); - temp = TRANSLATE("New Category Name"); - temp += ":"; + temp = B_TRANSLATE("New category name:"); fNameBox = new AutoTextControl("namebox", temp.String(), "", new BMessage(M_NAME_CHANGED)); fNameBox->SetCharacterLimit(32); - fOKButton = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_CATEGORY)); + fOKButton = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_EDIT_CATEGORY)); fOKButton->SetFlags(fOKButton->Flags() | B_FRAME_EVENTS); - fOKButton->SetLabel(TRANSLATE("OK")); + fOKButton->SetLabel(B_TRANSLATE("OK")); fOKButton->MakeDefault(true); fCancelButton = - new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); fOKButton->SetEnabled(false); fNameBox->MakeFocus(true); diff --git a/src/CheckNumBox.cpp b/src/CheckNumBox.cpp index 4d9e4a9..04005f1 100644 --- a/src/CheckNumBox.cpp +++ b/src/CheckNumBox.cpp @@ -3,7 +3,13 @@ #include "Database.h" #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "CheckNumBox" + CheckNumBoxFilter::CheckNumBoxFilter(CheckNumBox *box) : AutoTextControlFilter(box) {} @@ -110,8 +116,8 @@ bool CheckNumBox::Validate(void) { if (strlen(Text()) < 1) { ShowAlert( - TRANSLATE("Transaction type is missing."), - TRANSLATE("You need to enter a check number or transaction type, such as " + B_TRANSLATE("Transaction type is missing."), + B_TRANSLATE("You need to enter a check number or transaction type, such as " "ATM (for debit card transactions and the like), DEP (for deposits), " "or your own code for some other kind of expense.") ); diff --git a/src/CheckView.cpp b/src/CheckView.cpp index 6a0666e..2b4864f 100644 --- a/src/CheckView.cpp +++ b/src/CheckView.cpp @@ -1,8 +1,9 @@ +#include #include #include #include +#include #include -#include #include "Account.h" #include "BuildOptions.h" @@ -13,6 +14,7 @@ #include "DAlert.h" #include "Database.h" #include "DateBox.h" +#include "LanguageRoster.h" #include "Layout.h" #include "MainWindow.h" #include "MsgDefs.h" @@ -21,27 +23,35 @@ #include "Preferences.h" #include "TimeSupport.h" #include "TransactionData.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "CheckView" + + +Language *gCurrentLanguage = NULL; enum { M_ENTER_TRANSACTION = 'entr' }; CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { - fDateLabel = new BStringView("datelabel", TRANSLATE("Date")); + fDateLabel = new BStringView("datelabel", B_TRANSLATE("Date")); fDate = new DateBox("dateentry", "", NULL, new BMessage(M_DATE_CHANGED)); - fTypeLabel = new BStringView("typelabel", TRANSLATE("Type")); + fTypeLabel = new BStringView("typelabel", B_TRANSLATE("Type")); fType = new CheckNumBox("typeentry", "", NULL, new BMessage(M_TYPE_CHANGED)); - fPayeeLabel = new BStringView("payeelabel", TRANSLATE("Payee")); + fPayeeLabel = new BStringView("payeelabel", B_TRANSLATE("Payee")); fPayee = new PayeeBox("payeeentry", "", NULL, new BMessage(M_PAYEE_CHANGED)); - fAmountLabel = new BStringView("amountlabel", TRANSLATE("Amount")); + fAmountLabel = new BStringView("amountlabel", B_TRANSLATE("Amount")); fAmount = new CurrencyBox("amountentry", "", "", new BMessage(M_AMOUNT_CHANGED)); - fCategoryLabel = new BStringView("categorylabel", TRANSLATE("Category")); + fCategoryLabel = new BStringView("categorylabel", B_TRANSLATE("Category")); fCategory = new CategoryBox("categoryentry", "", NULL, new BMessage(M_CATEGORY_CHANGED)); - fMemoLabel = new BStringView("memolabel", TRANSLATE("Memo")); + fMemoLabel = new BStringView("memolabel", B_TRANSLATE("Memo")); fMemo = new NavTextBox("memoentry", "", NULL, new BMessage(M_MEMO_CHANGED)); fMemo->TextView()->DisallowChar(B_ESCAPE); fMemo->SetCharacterLimit(21); @@ -52,7 +62,7 @@ CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAM rechelp << "helpfiles/" << gCurrentLanguage->Name() << "/Main Window Help"; fHelpButton = new HelpButton("rechelp", rechelp.String()); - fEnter = new BButton("enterbutton", TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); + fEnter = new BButton("enterbutton", B_TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); #ifndef ENTER_NAVIGATION fEnter->MakeDefault(true); @@ -149,11 +159,11 @@ CheckView::MessageReceived(BMessage *msg) { Account *demoacc = gDatabase.CurrentAccount(); if (demoacc && demoacc->CountTransactions() >= 25) { ShowAlert( - TRANSLATE("Demo Mode Limit"), - TRANSLATE( + B_TRANSLATE("Demo mode limit"), + B_TRANSLATE( "The Demo Mode limit has been reached on this account.", "You can manually enter up to 25 transactions per " - "account. We hope that you like Capital Be and will " + "account. We hope that you like CapitalBe and will " "purchase the full version. Have a nice day!" ), B_IDEA_ALERT diff --git a/src/CurrencyBox.cpp b/src/CurrencyBox.cpp index ba211ab..dc66034 100644 --- a/src/CurrencyBox.cpp +++ b/src/CurrencyBox.cpp @@ -3,7 +3,13 @@ #include "Database.h" #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "CurrencyBox" + CurrencyBoxFilter::CurrencyBoxFilter(CurrencyBox *box) : NavTextBoxFilter(box) {} @@ -56,8 +62,8 @@ CurrencyBox::Validate(bool alert) { if (gCurrentLocale.StringToCurrency(Text(), amount) != B_OK) { if (alert) { ShowAlert( - TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " + B_TRANSLATE("CapitalBe didn't understand the amount."), + B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " "for this account.") ); MakeFocus(true); diff --git a/src/Database.cpp b/src/Database.cpp index 7bb6574..f6c8baf 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -28,7 +28,7 @@ Locale gDefaultLocale; // This is the locale is set to whatever is used by the active account in the database Locale gCurrentLocale; -// This global is used to hold all financial data for Capital Be. +// This global is used to hold all financial data for CapitalBe. Database gDatabase; Database::Database(const char *path) : fCurrent(NULL), fList(20, true), fPath(path) {} @@ -189,7 +189,7 @@ Database::OpenFile(const char *path) { UNLOCK; ShowAlert( "Couldn't open account data.", - "Capital Be couldn't open your financial data. " + "CapitalBe couldn't open your financial data. " "If your data is in the old storage format from the Preview Edition 1.0, you " "will need to run the conversion program before you can use your data." ); diff --git a/src/DateBox.cpp b/src/DateBox.cpp index 5bffe33..da6d2a4 100644 --- a/src/DateBox.cpp +++ b/src/DateBox.cpp @@ -3,7 +3,13 @@ #include "Database.h" #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "DateBox" + DateBoxFilter::DateBoxFilter(DateBox *box) : AutoTextControlFilter(box) {} @@ -118,8 +124,8 @@ DateBox::Validate(const bool &alert) { } else if (gDefaultLocale.StringToDate(Text(), tdate) != B_OK) { if (alert) { ShowAlert( - TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE("Capital Be understands lots of different ways of entering dates. " + B_TRANSLATE("CapitalBe didn't understand the date you entered."), + B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " "Apparently, this wasn't one of them. You'll need to change how you " "entered this date. Sorry.") ); diff --git a/src/HelpButton.cpp b/src/HelpButton.cpp index d2f0e4a..6116691 100644 --- a/src/HelpButton.cpp +++ b/src/HelpButton.cpp @@ -1,6 +1,7 @@ #include "HelpButton.h" #include "Preferences.h" -#include "Translate.h" + +#include #include #include #include @@ -8,6 +9,11 @@ #include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "HelpButton" + + class HelpButtonWindow : public BWindow { public: HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref); @@ -43,7 +49,7 @@ HelpButton::MessageReceived(BMessage *msg) { HelpButtonWindow::HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref) : BWindow( - frame, TRANSLATE("Help"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Help"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ) { BView *view = new BView("back", B_WILL_DRAW | B_FRAME_EVENTS); diff --git a/src/Locale.cpp b/src/Locale.cpp index f727369..d0cc09e 100644 --- a/src/Locale.cpp +++ b/src/Locale.cpp @@ -779,8 +779,8 @@ GetVersionString(BString &string) { // test void ShowBug(const char *string) { - BString message = "Capital Be has run into a bug. This shouldn't happen, but it has.\n" - "Would you like to:\n\n1) Have Capital Be make an e-mail to send to Support\n" + BString message = "CapitalBe has run into a bug. This shouldn't happen, but it has.\n" + "Would you like to:\n\n1) Have CapitalBe make an e-mail to send to Support\n" "2) Save the bug to a text file for e-mailing later\n" "3) Just quit and do nothing\n"; @@ -794,7 +794,7 @@ ShowBug(const char *string) { } // Generate the report text - message = "Capital Be Bug Report\n\n"; + message = "CapitalBe Bug Report\n\n"; BString version; GetVersionString(version); @@ -805,12 +805,12 @@ ShowBug(const char *string) { // Make an e-mail to myself. :D BString cmdstring("/boot/beos/apps/BeMail mailto:support@capitalbe.com "); - cmdstring << "-subject 'Capital Be Bug Report' -body '" << message << "'"; + cmdstring << "-subject 'CapitalBe Bug Report' -body '" << message << "'"; cmdstring << " &"; system(cmdstring.String()); } else if (value == 1) { // Generate a text file of the bug on the Desktop - BString filename("/boot/home/Desktop/Capital Be Bug Report "); + BString filename("/boot/home/Desktop/CapitalBe Bug Report "); filename << real_time_clock() << ".txt"; BFile file(filename.String(), B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); file.Write(message.String(), message.Length()); diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 150a88d..0810629 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -1,5 +1,7 @@ #include "MainWindow.h" #include "RegisterView.h" + +#include #include #include #include @@ -10,8 +12,6 @@ #include #include -#include - #include "AccountSettingsWindow.h" #include "BudgetWindow.h" #include "BuildOptions.h" @@ -31,7 +31,13 @@ #include "TextControl.h" #include "TransactionEditWindow.h" #include "TransferWindow.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "MainWindow" + // #define TEST // #define NOSAVE @@ -48,11 +54,11 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BString temp; // Main window title changes in demo mode if (BUILD_MODE == PREVIEW_MODE) - SetTitle(TRANSLATE("Capital Be Preview Edition")); + SetTitle(B_TRANSLATE("CapitalBe Preview Edition")); else if (BUILD_MODE == BETA_MODE) - SetTitle("Capital Be: Beta"); + SetTitle("CapitalBe: Beta"); else - SetTitle("Capital Be"); + SetTitle(B_TRANSLATE_SYSTEM_NAME("CapitalBe")); // These chunks of code will save a lot of headache later on -- // we cache the preferred size of BTextControls to make control layout *much* easier. @@ -99,20 +105,18 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BMenuBar *bar = new BMenuBar("keybar"); #ifdef BETA_MODE - temp = TRANSLATE("Report a Bug"); - temp += "…"; + temp = B_TRANSLATE("Report a bug…"); bar->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_BUG))); #endif - BMenu *menu = new BMenu(TRANSLATE("Program")); + BMenu *menu = new BMenu(B_TRANSLATE("Program")); #ifdef DEMO_MODE - menu->AddItem(new BMenuItem(TRANSLATE("Buy Capital Be"), new BMessage(M_PURCHASE_FULL_VERSION)) + menu->AddItem(new BMenuItem(B_TRANSLATE("Buy CapitalBe"), new BMessage(M_PURCHASE_FULL_VERSION)) ); menu->AddSeparatorItem(); #endif - temp = TRANSLATE("Options"); - temp += "…"; + temp = B_TRANSLATE("Settings…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_OPTIONS_WINDOW), ',')); // Set up language support. Note that we only show the menu at all if there is @@ -120,7 +124,7 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { if (language_roster->CountLanguages() > 1) { menu->AddSeparatorItem(); - fLanguageMenu = new BMenu(TRANSLATE("Language")); + fLanguageMenu = new BMenu(B_TRANSLATE("Language")); fLanguageMenu->SetRadioMode(true); for (int32 i = 0; i < language_roster->CountLanguages(); i++) { Language *language = language_roster->LanguageAt(i); @@ -137,82 +141,68 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { fLanguageMenu = NULL; menu->AddSeparatorItem(); - temp = TRANSLATE("About Capital Be"); - temp += "…"; + temp = B_TRANSLATE("About CapitalBe…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_ABOUT))); bar->AddItem(menu); - menu = new BMenu(TRANSLATE("File")); - temp = TRANSLATE("Categories"); - temp << "…"; + menu = new BMenu(B_TRANSLATE("File")); + temp = B_TRANSLATE("Categories…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_CATEGORY_WINDOW))); - temp = TRANSLATE("Scheduled Transactions"); - temp << "…"; + temp = B_TRANSLATE("Scheduled transactions…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_SCHEDULED_WINDOW))); menu->AddSeparatorItem(); - temp = TRANSLATE("Import from QIF File"); - temp << "…"; + temp = B_TRANSLATE("Import from QIF file…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_IMPORT_PANEL))); - temp = TRANSLATE("Export to QIF File"); - temp << "…"; + temp = B_TRANSLATE("Export to QIF file…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_EXPORT_PANEL))); bar->AddItem(menu); - menu = new BMenu(TRANSLATE("Account")); + menu = new BMenu(B_TRANSLATE("Account")); bar->AddItem(menu); - temp = TRANSLATE("Reconcile"); - temp << "…"; + temp = B_TRANSLATE("Reconcile…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_RECONCILE_WINDOW), 'R')); menu->AddSeparatorItem(); - temp = TRANSLATE("New"); - temp << "…"; + temp = B_TRANSLATE("New…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_NEW_ACCOUNT), 'N')); - temp = TRANSLATE("Delete"); - temp << "…"; + temp = B_TRANSLATE("Delete…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_DELETE_ACCOUNT))); - fAccountClosedItem = new BMenuItem(TRANSLATE("Close"), new BMessage(M_CLOSE_ACCOUNT)); + fAccountClosedItem = new BMenuItem(B_TRANSLATE("Close"), new BMessage(M_CLOSE_ACCOUNT)); menu->AddItem(fAccountClosedItem); menu->AddSeparatorItem(); - temp = TRANSLATE("Settings"); - temp << "…"; + temp = B_TRANSLATE("Settings…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_ACCOUNT_SETTINGS))); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( - TRANSLATE("Previous"), new BMessage(M_PREVIOUS_ACCOUNT), B_UP_ARROW, + B_TRANSLATE("Previous"), new BMessage(M_PREVIOUS_ACCOUNT), B_UP_ARROW, B_COMMAND_KEY | B_SHIFT_KEY )); menu->AddItem(new BMenuItem( - TRANSLATE("Next"), new BMessage(M_NEXT_ACCOUNT), B_DOWN_ARROW, B_COMMAND_KEY | B_SHIFT_KEY + B_TRANSLATE("Next"), new BMessage(M_NEXT_ACCOUNT), B_DOWN_ARROW, B_COMMAND_KEY | B_SHIFT_KEY )); - menu = new BMenu(TRANSLATE("Transaction")); + menu = new BMenu(B_TRANSLATE("Transaction")); bar->AddItem(menu); - temp = TRANSLATE("Edit"); - temp << "…"; + temp = B_TRANSLATE("Edit…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_EDIT_TRANSACTION), 'E')); - temp = TRANSLATE("Enter a Transfer"); - temp << "…"; + temp = B_TRANSLATE("Enter a transfer…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_ENTER_TRANSFER), 'T')); menu->AddSeparatorItem(); - menu->AddItem(new BMenuItem(TRANSLATE("Delete"), new BMessage(M_DELETE_TRANSACTION))); + menu->AddItem(new BMenuItem(B_TRANSLATE("Delete…"), new BMessage(M_DELETE_TRANSACTION))); menu->AddSeparatorItem(); - temp = TRANSLATE("Schedule This Transaction"); - temp << "…"; + temp = B_TRANSLATE("Schedule this transaction…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SCHEDULE_TRANSACTION))); menu->AddSeparatorItem(); menu->AddItem( - new BMenuItem(TRANSLATE("Previous"), new BMessage(M_PREVIOUS_TRANSACTION), B_UP_ARROW) + new BMenuItem(B_TRANSLATE("Previous"), new BMessage(M_PREVIOUS_TRANSACTION), B_UP_ARROW) ); - menu->AddItem(new BMenuItem(TRANSLATE("Next"), new BMessage(M_NEXT_TRANSACTION), B_DOWN_ARROW)); + menu->AddItem(new BMenuItem(B_TRANSLATE("Next"), new BMessage(M_NEXT_TRANSACTION), B_DOWN_ARROW)); - menu = new BMenu(TRANSLATE("Tools")); + menu = new BMenu(B_TRANSLATE("Tools")); bar->AddItem(menu); - temp = TRANSLATE("Budget"); - temp << "…"; + temp = B_TRANSLATE("Budget…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_BUDGET_WINDOW))); - temp = TRANSLATE("Reports"); - temp << "…"; + temp = B_TRANSLATE("Reports…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_REPORTS_WINDOW))); // We load the financial data before we create any of the views because the @@ -226,14 +216,16 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { fImportPanel = new BFilePanel( B_OPEN_PANEL, new BMessenger(this), NULL, B_FILE_NODE, false, new BMessage(M_IMPORT_ACCOUNT) ); - temp = "Capital Be: "; - temp += TRANSLATE("Import"); + temp = B_TRANSLATE("CapitalBe:"); + temp += " "; + temp += B_TRANSLATE("Import"); fImportPanel->Window()->SetTitle(temp.String()); fExportPanel = new BFilePanel( B_SAVE_PANEL, new BMessenger(this), NULL, B_FILE_NODE, false, new BMessage(M_EXPORT_ACCOUNT) ); - temp = "Capital Be: "; - temp += TRANSLATE("Export"); + temp = B_TRANSLATE("CapitalBe:"); + temp += " "; + temp += B_TRANSLATE("Export"); fExportPanel->Window()->SetTitle(temp.String()); gDatabase.AddObserver(this); @@ -249,7 +241,7 @@ MainWindow::~MainWindow(void) { void MainWindow::OpenAbout(void) { - BAboutWindow *abwin = new BAboutWindow("Capital Be", "application/x-vnd.wgp-CapitalBe"); + BAboutWindow *abwin = new BAboutWindow("CapitalBe", "application/x-vnd.wgp-CapitalBe"); const char *authors[] = { "DarkWyrm", @@ -320,8 +312,8 @@ MainWindow::MessageReceived(BMessage *msg) { be_app->PostMessage(B_QUIT_REQUESTED); } else { ShowAlert( - TRANSLATE("Changes will be made on restart"), - TRANSLATE("Capital Be will be use your language choice the next time it is " + B_TRANSLATE("Changes will take effect on restart"), + B_TRANSLATE("CapitalBe will be use your language choice the next time it is " "started."), B_IDEA_ALERT ); @@ -337,9 +329,9 @@ MainWindow::MessageReceived(BMessage *msg) { #ifdef PREVIEW_MODE if (gDatabase.CountAccounts() >= 5) { ShowAlert( - TRANSLATE("Preview Mode Limit"), - TRANSLATE("You can have up to 5 accounts in Capital Be's demo version. " - "We hope that you like Capital Be and will " + B_TRANSLATE("Preview mode limit"), + B_TRANSLATE("You can have up to 5 accounts in CapitalBe's demo version. " + "We hope that you like CapitalBe and will " "purchase the full version. Have a nice day!"), B_IDEA_ALERT ); @@ -374,10 +366,10 @@ MainWindow::MessageReceived(BMessage *msg) { break; DAlert *alert = new DAlert( - TRANSLATE("Really Delete Account?"), - TRANSLATE("Once deleted, you will not be able to " + B_TRANSLATE("Really delete account?"), + B_TRANSLATE("Once deleted, you will not be able to " "get back any data on this account."), - TRANSLATE("Delete"), TRANSLATE("Cancel"), NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT + B_TRANSLATE("Delete"), B_TRANSLATE("Cancel"), NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT ); if (alert->Go() == 0) { @@ -428,18 +420,18 @@ MainWindow::MessageReceived(BMessage *msg) { case M_IMPORT_ACCOUNT: { entry_ref ref; - // BEntry entry("/boot/develop/projects/Capital Be/source/yoderdata.qif"); + // BEntry entry("/boot/develop/projects/CapitalBe/source/yoderdata.qif"); // entry.GetRef(&ref); if (msg->FindRef("refs", &ref) != B_OK) break; if (!gDatabase.ImportFile(ref)) { - BString errmsg(TRANSLATE("Could not import the data in the file %%FILENAME%%.")); + BString errmsg(B_TRANSLATE("Could not import the data in the file %%FILENAME%%.")); errmsg.ReplaceFirst("%%FILENAME%%", ref.name); ShowAlert( errmsg.String(), - TRANSLATE("This happens when the kind of file is not " + B_TRANSLATE("This happens when the kind of file is not " "supported, when the file's data is damaged, or when you feed " "it a recipe for quiche.") ); @@ -465,11 +457,11 @@ MainWindow::MessageReceived(BMessage *msg) { if (!gDatabase.ExportFile(dir)) { BString errmsg( - TRANSLATE("Could not export your financial data to the file %%FILENAME%%.") + B_TRANSLATE("Could not export your financial data to the file %%FILENAME%%.") ); errmsg.ReplaceFirst("%%FILENAME%%", dir.name); ShowAlert( - errmsg.String(), TRANSLATE("This really shouldn't happen, so you probably " + errmsg.String(), B_TRANSLATE("This really shouldn't happen, so you probably " "should e-mail support about this.") ); } @@ -523,8 +515,8 @@ MainWindow::MessageReceived(BMessage *msg) { case M_ENTER_TRANSFER: { if (gDatabase.CountAccounts() < 2) { ShowAlert( - TRANSLATE("Not enough accounts for a transfer."), - TRANSLATE("You need to have at least 2 accounts to perform a transfer.") + B_TRANSLATE("Not enough accounts for a transfer."), + B_TRANSLATE("You need to have at least 2 accounts to perform a transfer.") ); break; } @@ -574,8 +566,8 @@ MainWindow::MessageReceived(BMessage *msg) { if (data.Type().TypeCode() == TRANS_NUMERIC) { ShowAlert( - TRANSLATE("Numbered transactions cannot be scheduled."), - TRANSLATE("You can schedule transfers, deposits, or ATM transactions.") + B_TRANSLATE("Numbered transactions cannot be scheduled."), + B_TRANSLATE("You can schedule transfers, deposits, or ATM transactions.") ); break; } @@ -613,13 +605,13 @@ MainWindow::MessageReceived(BMessage *msg) { if (!acc) { if (gDatabase.CountAccounts() < 1) ShowAlert( - TRANSLATE("Oops!"), - TRANSLATE("You need to have an account created in order to reconcile it.") + B_TRANSLATE("Oops!"), + B_TRANSLATE("You need to have an account created in order to reconcile it.") ); else ShowAlert( - TRANSLATE("Oops!"), - TRANSLATE("You need to select an account in order to reconcile it.") + B_TRANSLATE("Oops!"), + B_TRANSLATE("You need to select an account in order to reconcile it.") ); break; } @@ -676,7 +668,7 @@ MainWindow::LoadData(void) { if (gDatabase.OpenFile(fLastFile.String()) != B_OK) { BEntry entry(fLastFile.String()); if (!entry.Exists()) { - // TODO: Show Capital Be introduction + // TODO: Show CapitalBe introduction // TODO: Show a Create File dialog gDatabase.CreateFile(fLastFile.String()); PostMessage(M_SHOW_NEW_ACCOUNT); @@ -707,7 +699,7 @@ MainWindow::CreateTransfer(BMessage *msg) { // Now that we've gathered all the data from the message sent to us by TransferWindow, // we create the transactions needed for each account. - BString payee = TRANSLATE("Transfer to %%PAYEE%%"); + BString payee = B_TRANSLATE("Transfer to %%PAYEE%%"); payee.ReplaceFirst("%%PAYEE%%", to->Name()); uint32 transid = gDatabase.NextTransactionID(); @@ -717,7 +709,7 @@ MainWindow::CreateTransfer(BMessage *msg) { memo.String() ); - payee = TRANSLATE("Transfer from %%PAYEE%%"); + payee = B_TRANSLATE("Transfer from %%PAYEE%%"); payee.ReplaceFirst("%%PAYEE%%", to->Name()); payee << from->Name(); gDatabase.AddTransaction( @@ -743,9 +735,9 @@ MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { if (value & WATCH_SELECT || value & WATCH_CHANGE) { if (acc->IsClosed()) { - fAccountClosedItem->SetLabel(TRANSLATE("Reopen")); + fAccountClosedItem->SetLabel(B_TRANSLATE("Reopen")); } else { - fAccountClosedItem->SetLabel(TRANSLATE("Close")); + fAccountClosedItem->SetLabel(B_TRANSLATE("Close")); } } } diff --git a/src/NetWorthReport.cpp b/src/NetWorthReport.cpp index f66c22a..36beca5 100644 --- a/src/NetWorthReport.cpp +++ b/src/NetWorthReport.cpp @@ -7,6 +7,13 @@ #include "ReportWindow.h" #include "TimeSupport.h" +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "NetWorthReport" + + void ReportWindow::ComputeNetWorth(void) { // Total of all accounts @@ -42,7 +49,7 @@ ReportWindow::ComputeNetWorth(void) { ReportGrid accountgrid(1, timelist.CountItems()); - BString longestname(TRANSLATE("Total Worth")); + BString longestname(B_TRANSLATE("Total worth")); int longestnamelength = longestname.CountChars(); @@ -87,17 +94,17 @@ ReportWindow::ComputeNetWorth(void) { // Now that we have all the data, we need to set up the rows and columns for the report grid BColumn *col = new BStringColumn( - TRANSLATE("Date"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, + B_TRANSLATE("Date"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 0); - col = new BStringColumn(TRANSLATE("Total"), 75, 10, 300, B_TRUNCATE_END); + col = new BStringColumn(B_TRANSLATE("Total"), 75, 10, 300, B_TRUNCATE_END); fGridView->AddColumn(col, 1); fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Total Worth")), 0); + titlerow->SetField(new BStringField(B_TRANSLATE("Total worth")), 0); fGridView->AddRow(new BRow()); // Now that the grid is set up, start adding data to the grid diff --git a/src/PayeeBox.cpp b/src/PayeeBox.cpp index 31bcecf..8759d20 100644 --- a/src/PayeeBox.cpp +++ b/src/PayeeBox.cpp @@ -3,7 +3,13 @@ #include "Database.h" #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "PayeeBox" + PayeeBoxFilter::PayeeBoxFilter(PayeeBox *box) : AutoTextControlFilter(box) {} @@ -70,7 +76,7 @@ PayeeBox::PayeeBox( bool PayeeBox::Validate(const bool &showalert) { if (showalert && (Text() == NULL || strlen(Text()) < 1)) { - ShowAlert(TRANSLATE("Payee is missing."), TRANSLATE("You need to enter a payee.")); + ShowAlert(B_TRANSLATE("Payee is missing."), B_TRANSLATE("You need to enter a payee.")); MakeFocus(true); return false; } diff --git a/src/PrefWindow.cpp b/src/PrefWindow.cpp index 621301a..db30af5 100644 --- a/src/PrefWindow.cpp +++ b/src/PrefWindow.cpp @@ -1,6 +1,7 @@ #include "PrefWindow.h" #include +#include #include #include #include @@ -8,7 +9,10 @@ #include "Database.h" #include "EscapeCancelFilter.h" -#include "Translate.h" + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "PrefWindow" + // PrefWindow #define M_EDIT_OPTIONS 'edop' @@ -27,7 +31,7 @@ enum { PrefWindow::PrefWindow(const BRect &frame) : BWindow( - frame, TRANSLATE("Options"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Options"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ) { BString temp; @@ -38,8 +42,7 @@ PrefWindow::PrefWindow(const BRect &frame) BView *back = new BView(NULL, B_WILL_DRAW); back->SetViewColor(240, 240, 240); - temp = TRANSLATE("Default Account Settings"); - temp += ":"; + temp = B_TRANSLATE("Default account settings:"); fLabel = new BStringView("windowlabel", temp.String()); fLabel->SetFont(be_bold_font); @@ -47,10 +50,10 @@ PrefWindow::PrefWindow(const BRect &frame) fCurrencyPrefView = new CurrencyPrefView("dateview", &gDefaultLocale); - fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_EDIT_OPTIONS)); - fOK->SetLabel(TRANSLATE("OK")); + fOK = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_EDIT_OPTIONS)); + fOK->SetLabel(B_TRANSLATE("OK")); - fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + fCancel = new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); SetDefaultButton(fOK); @@ -101,28 +104,27 @@ DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) fLocale = gDefaultLocale; BBox *fDateBox = new BBox("DateBox"); - fDateBox->SetLabel(TRANSLATE("Date")); + fDateBox->SetLabel(B_TRANSLATE("Date")); BString datestr; fLocale.DateToString(0, datestr); temp = ""; - temp << TRANSLATE("Date Format") << ": " << datestr; + temp.SetToFormat(B_TRANSLATE("Date format: %s"), datestr); fDateLabel = new BStringView("datelabel", temp.String()); temp = ""; - temp << TRANSLATE("Month") << ", " << TRANSLATE("Day") << ", " << TRANSLATE("Year"); + temp.SetToFormat(B_TRANSLATE("Month, Day, Year")); fDateMDY = new BRadioButton("mdybutton", temp.String(), new BMessage(M_MDY_FORMAT)); temp = ""; - temp << TRANSLATE("Day") << ", " << TRANSLATE("Month") << ", " << TRANSLATE("Year"); + temp.SetToFormat(B_TRANSLATE("Day, Month, Year")); fDateDMY = new BRadioButton("dmybutton", temp.String(), new BMessage(M_DMY_FORMAT)); if (fLocale.DateFormat() == DATE_MDY) fDateMDY->SetValue(B_CONTROL_ON); else fDateDMY->SetValue(B_CONTROL_ON); - temp = TRANSLATE("Separator"); - temp += ":"; + temp = B_TRANSLATE("Separator:"); fDateSeparatorBox = new AutoTextControl( "datesep", temp.String(), fLocale.DateSeparator(), new BMessage(M_NEW_DATE_SEPARATOR) ); @@ -178,7 +180,7 @@ void DatePrefView::UpdateDateLabel(void) { BString temp, label; fLocale.DateToString(0, temp); - label << TRANSLATE("Date Format") << ": " << temp; + label.SetToFormat(B_TRANSLATE("Date format: %s"), temp); fDateLabel->SetText(label.String()); } @@ -200,16 +202,14 @@ CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 fLocale = gDefaultLocale; BBox *fCurrencyBox = new BBox("CurrencyBox"); - fCurrencyBox->SetLabel(TRANSLATE("Currency")); + fCurrencyBox->SetLabel(B_TRANSLATE("Currency")); BString curstr; fLocale.CurrencyToString(fSampleAmount, curstr); - temp = TRANSLATE("Currency Format"); - temp << ": " << curstr; + temp.SetToFormat(B_TRANSLATE("Currency format: %s"), curstr); fCurrencyLabel = new BStringView("datelabel", temp.String()); - temp = TRANSLATE("Symbol"); - temp += ":"; + temp = B_TRANSLATE("Symbol:"); fCurrencySymbolBox = new AutoTextControl( "moneysym", temp.String(), fLocale.CurrencySymbol(), new BMessage(M_NEW_CURRENCY_SYMBOL) ); @@ -217,14 +217,13 @@ CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 fCurrencySymbolBox->SetCharacterLimit(2); fCurrencySymbolPrefix = new BCheckBox( - "prefixcheck", TRANSLATE("Appears Before Amount"), new BMessage(M_TOGGLE_PREFIX) + "prefixcheck", B_TRANSLATE("Appears before amount"), new BMessage(M_TOGGLE_PREFIX) ); fCurrencySymbolPrefix->SetValue( (fLocale.IsCurrencySymbolPrefix()) ? B_CONTROL_ON : B_CONTROL_OFF ); - temp = TRANSLATE("Separator"); - temp += ":"; + temp = B_TRANSLATE("Separator:"); fCurrencySeparatorBox = new AutoTextControl( "moneysep", temp.String(), fLocale.CurrencySeparator(), new BMessage(M_NEW_CURRENCY_SEPARATOR) @@ -232,8 +231,7 @@ CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 fCurrencySeparatorBox->SetDivider(StringWidth(temp.String()) + 5); fCurrencySeparatorBox->SetCharacterLimit(2); - temp = TRANSLATE("Decimal"); - temp += ":"; + temp = B_TRANSLATE("Decimal:"); fCurrencyDecimalBox = new AutoTextControl( "moneydecimal", temp.String(), fLocale.CurrencyDecimal(), new BMessage(M_NEW_CURRENCY_DECIMAL) @@ -305,7 +303,7 @@ void CurrencyPrefView::UpdateCurrencyLabel(void) { BString temp, label; fLocale.CurrencyToString(fSampleAmount, temp); - label << TRANSLATE("Currency Format") << ": " << temp; + label.SetToFormat(B_TRANSLATE("Currency format: %s"), temp); fCurrencyLabel->SetText(label.String()); } diff --git a/src/QuickTrackerItem.cpp b/src/QuickTrackerItem.cpp index 9a2d80a..c07635b 100644 --- a/src/QuickTrackerItem.cpp +++ b/src/QuickTrackerItem.cpp @@ -3,9 +3,15 @@ #include "CBLocale.h" #include "Database.h" #include "Fixed.h" -#include "Translate.h" + +#include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "QuickTrackerItem" + + // Calculates the user's net worth by adding up the balances of all accounts QTNetWorthItem::QTNetWorthItem(const char *name, uint32 flags) : QuickTrackerItem(name, flags), fIgnore(false) { @@ -66,7 +72,7 @@ QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) { Window()->Lock(); BString label, temp; - temp << TRANSLATE("Account Total") << ": "; + temp << B_TRANSLATE("Account total:") << " "; if (gCurrentLocale.CurrencyToString(Fixed(), label) == B_OK) temp << label; SetText(temp.String()); @@ -86,7 +92,7 @@ QTNetWorthItem::Calculate(void) { BString label, temp; Fixed balance; - temp << TRANSLATE("Account Total") << ": "; + temp << B_TRANSLATE("Account total:") << " "; if (gDatabase.CountAccounts() == 0) { if (Window()) @@ -182,7 +188,7 @@ QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) { Window()->Lock(); BString label, temp; - temp << TRANSLATE("Account Total") << ": "; + temp << B_TRANSLATE("Account total:") << " "; if (gCurrentLocale.CurrencyToString(Fixed(), label) == B_OK) temp << label; SetText(temp.String()); @@ -202,7 +208,7 @@ QTBudgetCategoryItem::Calculate(void) { BString label, temp; Fixed variance; - temp << TRANSLATE("Budget") << ": " << fEntry.name; + temp << B_TRANSLATE("Budget:") << " " << fEntry.name; if (gDefaultLocale.CurrencyToString(variance, label) == B_OK) { temp << " \n" << label; diff --git a/src/ReconcileWindow.cpp b/src/ReconcileWindow.cpp index 6750dbc..5963630 100644 --- a/src/ReconcileWindow.cpp +++ b/src/ReconcileWindow.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -8,13 +9,19 @@ #include "DAlert.h" #include "Database.h" #include "DateBox.h" +#include "LanguageRoster.h" #include "MsgDefs.h" #include "Preferences.h" #include "ReconcileItem.h" #include "ReconcileWindow.h" #include "TimeSupport.h" #include "Transaction.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "ReconcileWindow" + +Language *gCurrentLanguage = NULL; enum { M_TOGGLE_DEPOSIT = 'tgdp', @@ -49,8 +56,8 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) // AddCommonFilter(new ReconcileFilter(this)); if (account) { - temp = TRANSLATE("Reconcile"); - temp << ": " << account->Name(); + temp = B_TRANSLATE("Reconcile:"); + temp << " " << account->Name(); SetTitle(temp.String()); gDatabase.AddObserver(this); } @@ -64,8 +71,8 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) back->SetViewColor(240, 240, 240); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); - temp = TRANSLATE("Date"); - temp += ":"; + temp = B_TRANSLATE("Date:"); + temp += " "; float width = back->StringWidth(temp.String()); BString datestr; @@ -74,23 +81,23 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) fDate->GetFilter()->SetMessenger(new BMessenger(this)); - temp = TRANSLATE("Starting Balance"); - temp += ": "; + temp = B_TRANSLATE("Starting balance:"); + temp += " "; fOpening = new CurrencyBox("starting", temp.String(), NULL, new BMessage(M_SET_BALANCES)); fOpening->GetFilter()->SetMessenger(new BMessenger(this)); - temp = TRANSLATE("Ending Balance"); - temp += ":"; + temp = B_TRANSLATE("Ending balance:"); + temp += " "; fClosing = new CurrencyBox("closing", temp.String(), NULL, new BMessage(M_SET_BALANCES)); fClosing->GetFilter()->SetMessenger(new BMessenger(this)); - temp = TRANSLATE("Bank Charges"); - temp += ":"; + temp = B_TRANSLATE("Bank charges:"); + temp += " "; fCharges = new CurrencyBox("charges", temp.String(), NULL, NULL); fCharges->GetFilter()->SetMessenger(new BMessenger(this)); - temp = TRANSLATE("Interest Earned"); - temp += ":"; + temp = B_TRANSLATE("Interest earned:"); + temp += " "; fInterest = new CurrencyBox("interest", temp.String(), NULL, NULL); fInterest->GetFilter()->SetMessenger(new BMessenger(this)); @@ -115,33 +122,30 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) BString label; gCurrentLocale.CurrencyToString(fDepositTotal, label); - temp = TRANSLATE("Total Deposits"); - temp << ": " << label; + temp = B_TRANSLATE("Total deposits:"); + temp << " " << label; fDepLabel = new BStringView("deplabel", temp.String()); fDepLabel->SetAlignment(B_ALIGN_RIGHT); gCurrentLocale.CurrencyToString(fCheckTotal, label); - temp = TRANSLATE("Total Checks"); - temp << ": " << label; + temp = B_TRANSLATE("Total checks:"); + temp << " " << label; fCheckLabel = new BStringView("checklabel", temp.String()); fCheckLabel->SetAlignment(B_ALIGN_RIGHT); gCurrentLocale.CurrencyToString(fChargeTotal, label); - temp = TRANSLATE("Total Charges"); - temp << ": " << label; + temp = B_TRANSLATE("Total charges:"); + temp << " " << label; fChargeLabel = new BStringView("chargelabel", temp.String()); fChargeLabel->SetAlignment(B_ALIGN_RIGHT); - fReconcile = new BButton("reconcile", TRANSLATE("Reconcile"), new BMessage(M_RECONCILE)); - - fCancel = new BButton("cancel", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); - - fReset = new BButton("reset", TRANSLATE("Reset"), new BMessage(M_RESET)); - + fReconcile = new BButton("reconcile", B_TRANSLATE("Reconcile"), new BMessage(M_RECONCILE)); + fCancel = new BButton("cancel", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + fReset = new BButton("reset", B_TRANSLATE("Reset"), new BMessage(M_RESET)); fAutoReconcile = - new BButton("autoreconcile", TRANSLATE("Quick Balance"), new BMessage(M_AUTORECONCILE)); + new BButton("autoreconcile", B_TRANSLATE("Quick balance"), new BMessage(M_AUTORECONCILE)); prefsLock.Lock(); BString rechelp = gAppPath; @@ -149,7 +153,7 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) rechelp << "helpfiles/" << gCurrentLanguage->Name() << "/Reconcile Window Help"; fHelpButton = new HelpButton("rechelp", rechelp.String()); - temp = TRANSLATE("Unreconciled Total"); + temp = B_TRANSLATE("Unreconciled total"); temp += ":"; fTotalLabel = new BStringView("totallabel", temp.String()); @@ -346,12 +350,12 @@ ReconcileWindow::MessageReceived(BMessage *msg) { fDepositList->InvalidateItem(index); fAccount->GetLocale().CurrencyToString(fDepositTotal, label); - temp << TRANSLATE("Total Deposits") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Total deposits: %s"), label); fDepLabel->SetText(label.String()); fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Unreconciled total: %s"), label); fTotalLabel->SetText(label.String()); if ((fTotal + fDifference) == 0) @@ -377,12 +381,12 @@ ReconcileWindow::MessageReceived(BMessage *msg) { fCheckList->InvalidateItem(index); fAccount->GetLocale().CurrencyToString(fCheckTotal, label); - temp << TRANSLATE("TotaChecks") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Total checks: %s"), label); fCheckLabel->SetText(label.String()); fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Unreconciled total: %s"), label); fTotalLabel->SetText(label.String()); if ((fTotal + fDifference) == 0) @@ -408,12 +412,12 @@ ReconcileWindow::MessageReceived(BMessage *msg) { fChargeList->InvalidateItem(index); fAccount->GetLocale().CurrencyToString(fChargeTotal, label); - temp << TRANSLATE("Total Charges") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Total charges: %s"), label); fChargeLabel->SetText(label.String()); fAccount->GetLocale().CurrencyToString(fTotal + fDifference, label); temp = ""; - temp << TRANSLATE("Unreconciled Total") << ": " << label; + temp.SetToFormat(B_TRANSLATE("Unreconciled total: %s"), label); fTotalLabel->SetText(label.String()); if ((fTotal + fDifference) == 0) @@ -433,7 +437,7 @@ ReconcileWindow::MessageReceived(BMessage *msg) { gCurrentLocale.CurrencyToString(fTotal + fDifference, label); label.Prepend(" "); - label.Prepend("Unreconciled Total:"); + label.Prepend("Unreconciled total:"); fTotalLabel->SetText(label.String()); if ((fTotal + fDifference) == 0) @@ -549,8 +553,8 @@ ReconcileWindow::ApplyChargesAndInterest(void) { if (strlen(fCharges->Text()) > 0 && gCurrentLocale.StringToCurrency(fCharges->Text(), charge) == B_OK) { TransactionData chargetrans( - fAccount, fDate->Text(), "ATM", TRANSLATE("Bank Charge"), fCharges->Text(), - TRANSLATE("Bank Charge"), NULL, TRANS_RECONCILED + fAccount, fDate->Text(), "ATM", B_TRANSLATE("Bank charge"), fCharges->Text(), + B_TRANSLATE("Bank Charge"), NULL, TRANS_RECONCILED ); gDatabase.AddTransaction(chargetrans); } @@ -559,8 +563,8 @@ ReconcileWindow::ApplyChargesAndInterest(void) { if (strlen(fInterest->Text()) > 0 && gCurrentLocale.StringToCurrency(fInterest->Text(), interest) == B_OK) { TransactionData interesttrans( - fAccount, fDate->Text(), TRANSLATE("DEP"), TRANSLATE("Account Interest"), - fInterest->Text(), TRANSLATE("Account Interest"), NULL, TRANS_RECONCILED + fAccount, fDate->Text(), B_TRANSLATE("DEP"), B_TRANSLATE("Account interest"), + fInterest->Text(), B_TRANSLATE("Account interest"), NULL, TRANS_RECONCILED ); gDatabase.AddTransaction(interesttrans); } @@ -581,8 +585,8 @@ ReconcileWindow::AutoReconcile(void) { // Do we have an empty date box? if (strlen(fDate->Text()) < 1) { ShowAlert( - TRANSLATE("Date is missing."), - TRANSLATE("You need to enter the date for the statement to Quick Balance.") + B_TRANSLATE("Date is missing."), + B_TRANSLATE("You need to enter the date for the statement to Quick Balance.") ); return false; } @@ -596,8 +600,8 @@ ReconcileWindow::AutoReconcile(void) { bankchrg.Invert(); else { ShowAlert( - TRANSLATE("Capital Be didn't understand the amount for Bank Charges."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " + B_TRANSLATE("CapitalBe didn't understand the amount for Bank Charges."), + B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " "for this account.") ); return false; @@ -607,8 +611,8 @@ ReconcileWindow::AutoReconcile(void) { if (strlen(fInterest->Text()) > 0) { if (gCurrentLocale.StringToCurrency(fInterest->Text(), interest) != B_OK) { ShowAlert( - TRANSLATE("Capital Be didn't understand the amount for Interest Earned."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " + B_TRANSLATE("CapitalBe didn't understand the amount for Interest Earned."), + B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " "for this account.") ); return false; @@ -654,14 +658,14 @@ ReconcileWindow::AutoReconcile(void) { item->SetReconciled(true); } ApplyChargesAndInterest(); - ShowAlert(TRANSLATE("Success!"), TRANSLATE("Quick Balance successful!"), B_IDEA_ALERT); + ShowAlert(B_TRANSLATE("Success!"), B_TRANSLATE("Quick balance successful!"), B_IDEA_ALERT); PostMessage(B_QUIT_REQUESTED); return true; } ShowAlert( - TRANSLATE("Couldn't Quick Balance."), - TRANSLATE("Quick Balance failed. This doesn't mean " + B_TRANSLATE("Couldn't quick balance."), + B_TRANSLATE("Quick Balance failed. This doesn't mean " "that you did something wrong - it's just that Quick Balance works on " "simpler cases in balancing an account than this one. Sorry.") ); diff --git a/src/RegisterView.cpp b/src/RegisterView.cpp index 01e7ea7..71e0902 100644 --- a/src/RegisterView.cpp +++ b/src/RegisterView.cpp @@ -1,4 +1,6 @@ #include "RegisterView.h" + +#include #include #include #include @@ -10,14 +12,18 @@ #include "Database.h" #include "MainWindow.h" #include "QuickTrackerItem.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "RegisterView" + enum { M_SELECT_ACCOUNT = 'slac', M_SELECT_CURRENT }; RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { SetViewColor(240, 240, 240); - BStringView *accountlabel = new BStringView("accountlabel", TRANSLATE("Accounts")); + BStringView *accountlabel = new BStringView("accountlabel", B_TRANSLATE("Accounts")); // fAccountView = new DragListView(r,"accountview"); fAccountView = new BListView("accountview", B_SINGLE_SELECTION_LIST); @@ -40,7 +46,7 @@ RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | gDatabase.AddObserver(this); fTrackBox = new BBox("qtbox"); - fTrackBox->SetLabel(TRANSLATE("QuickTracker")); + fTrackBox->SetLabel(B_TRANSLATE("QuickTracker")); QTNetWorthItem *item; item = new QTNetWorthItem("networth"); diff --git a/src/ReportWindow.cpp b/src/ReportWindow.cpp index c19dce2..82539f9 100644 --- a/src/ReportWindow.cpp +++ b/src/ReportWindow.cpp @@ -3,6 +3,7 @@ #include "Database.h" #include "DateBox.h" #include "HelpButton.h" +#include "LanguageRoster.h" #include "Layout.h" #include "MsgDefs.h" #include "ObjectList.h" @@ -10,13 +11,21 @@ #include "ReportGrid.h" #include "StickyDrawButton.h" #include "TimeSupport.h" + #include +#include #include #include #include #include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "ReportWindow" + +Language *gCurrentLanguage = NULL; + int compare_stringitem(const void *item1, const void *item2); @@ -41,7 +50,7 @@ enum { ReportWindow::ReportWindow(BRect frame) : BWindow( - frame, TRANSLATE("Reports"), B_DOCUMENT_WINDOW, + frame, B_TRANSLATE("Reports"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ), fSubtotalMode(SUBTOTAL_NONE), fReportMode(REPORT_CASH_FLOW), fStartDate(GetCurrentYear()), @@ -71,16 +80,16 @@ ReportWindow::ReportWindow(BRect frame) .Add(layout_) .End(); - BMenu *reportmenu = new BMenu(TRANSLATE("Reports")); + BMenu *reportmenu = new BMenu(B_TRANSLATE("Reports")); reportmenu->SetLabelFromMarked(true); // TODO: Re-enable the Budget report - // reportmenu->AddItem(new BMenuItem(TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET))); - temp << TRANSLATE("Income") << " / " << TRANSLATE("Spending"); + // reportmenu->AddItem(new BMenuItem(B_TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET))); + temp << B_TRANSLATE("Income") << " / " << B_TRANSLATE("Spending"); reportmenu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_CASH_FLOW))); - reportmenu->AddItem(new BMenuItem(TRANSLATE("Total Worth"), new BMessage(M_REPORT_NET_WORTH))); + reportmenu->AddItem(new BMenuItem(B_TRANSLATE("Total worth"), new BMessage(M_REPORT_NET_WORTH))); reportmenu->AddItem( - new BMenuItem(TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS)) + new BMenuItem(B_TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS)) ); reportmenu->SetRadioMode(true); reportmenu->ItemAt(0L)->SetMarked(true); @@ -89,16 +98,16 @@ ReportWindow::ReportWindow(BRect frame) BRect r(10, 10, reportmenu->StringWidth(temp.String()) + 45, 60); - temp = TRANSLATE("Reports"); - temp += ": "; + temp = B_TRANSLATE("Reports:"); + temp += " "; BStringView *sv = new BStringView("reportsv", temp.String()); reportsLayout->AddView(sv); fReportField = new BMenuField("reportfield", "", reportmenu); reportsLayout->AddView(fReportField); - temp = TRANSLATE("Accounts"); - temp += ": "; + temp = B_TRANSLATE("Accounts:"); + temp += " "; sv = new BStringView("accountsv", temp.String()); accountsLayout->AddView(sv); @@ -110,16 +119,16 @@ ReportWindow::ReportWindow(BRect frame) // account added when the report window is shown initially // fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT)); - temp = TRANSLATE("Subtotal"); - temp += ":"; + temp = B_TRANSLATE("Subtotal:"); + temp += " "; sv = new BStringView("subtotalsv", temp.String()); subtotalLayout->AddView(sv); - BMenu *subtotalmenu = new BMenu(TRANSLATE("Subtotal")); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("None"), new BMessage(M_SUBTOTAL_NONE))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Month"), new BMessage(M_SUBTOTAL_MONTH))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Quarter"), new BMessage(M_SUBTOTAL_QUARTER))); - subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Year"), new BMessage(M_SUBTOTAL_YEAR))); + BMenu *subtotalmenu = new BMenu(B_TRANSLATE("Subtotal")); + subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("None"), new BMessage(M_SUBTOTAL_NONE))); + subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("Month"), new BMessage(M_SUBTOTAL_MONTH))); + subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("Quarter"), new BMessage(M_SUBTOTAL_QUARTER))); + subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("Year"), new BMessage(M_SUBTOTAL_YEAR))); subtotalmenu->SetLabelFromMarked(true); subtotalmenu->SetRadioMode(true); subtotalmenu->ItemAt(0)->SetMarked(true); @@ -133,7 +142,7 @@ ReportWindow::ReportWindow(BRect frame) reporthelp << "helpfiles/" << gCurrentLanguage->Name() << "/Report Window Help"; HelpButton *help = new HelpButton("reporthelp", reporthelp.String()); - temp = TRANSLATE("Categories"); + temp = B_TRANSLATE("Categories"); temp += ": "; sv = new BStringView("catsv", temp.String()); categoriesLayout->AddView(sv); @@ -150,8 +159,7 @@ ReportWindow::ReportWindow(BRect frame) BString datestring; gDefaultLocale.DateToString(GetCurrentYear(), datestring); - temp = TRANSLATE("Starting Date"); - temp += ": "; + temp = B_TRANSLATE("Starting date:"); fStartDateBox = new DateBox( "startdate", temp.String(), datestring.String(), new BMessage(M_START_DATE_CHANGED) @@ -162,8 +170,7 @@ ReportWindow::ReportWindow(BRect frame) fStartDateBox->GetFilter()->SetMessenger(new BMessenger(this)); gDefaultLocale.DateToString(GetCurrentDate(), datestring); - temp = TRANSLATE("Ending Date"); - temp += ": "; + temp = B_TRANSLATE("Ending date:"); fEndDateBox = new DateBox( "enddate", temp.String(), datestring.String(), new BMessage(M_END_DATE_CHANGED) @@ -340,8 +347,8 @@ ReportWindow::MessageReceived(BMessage *msg) { RenderReport(); } else { ShowAlert( - TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE("Capital Be understands lots of different ways of entering dates. " + B_TRANSLATE("CapitalBe didn't understand the date you entered."), + B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " "Apparently, this wasn't one of them. You'll need to change how you " "entered this date. Sorry.") ); @@ -364,8 +371,8 @@ ReportWindow::MessageReceived(BMessage *msg) { RenderReport(); } else { ShowAlert( - TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE("Capital Be understands lots of different ways of entering dates. " + B_TRANSLATE("CapitalBe didn't understand the date you entered."), + B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " "Apparently, this wasn't one of them. You'll need to change how you " "entered this date. Sorry.") ); diff --git a/src/ReportWindow.h b/src/ReportWindow.h index af10e2d..d180782 100644 --- a/src/ReportWindow.h +++ b/src/ReportWindow.h @@ -4,7 +4,7 @@ #include "Account.h" #include "DStringList.h" #include "Notifier.h" -#include "Translate.h" + #include #include #include @@ -15,6 +15,7 @@ #include #include #include + #include class StickyDrawButton; diff --git a/src/ScheduleAddWindow.cpp b/src/ScheduleAddWindow.cpp index 35962d9..55f95f7 100644 --- a/src/ScheduleAddWindow.cpp +++ b/src/ScheduleAddWindow.cpp @@ -1,6 +1,8 @@ #include "ScheduleAddWindow.h" + #include #include +#include #include #include #include @@ -15,7 +17,11 @@ #include "Layout.h" #include "NumBox.h" #include "ScheduledTransData.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "ScheduleAddWindow" + enum { M_SCHEDULED_MONTHLY = 'schm', @@ -31,7 +37,7 @@ enum { ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData &data) : BWindow( - frame, TRANSLATE("Schedule Transaction"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Schedule transaction"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), fTransData(data) { @@ -42,60 +48,58 @@ ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData & back->SetViewColor(240, 240, 240); BString label; - label << TRANSLATE("Type") << ": " << data.Type().Type(); + label.SetToFormat(B_TRANSLATE("Type: %s"), data.Type().Type()); BStringView *typelabel = new BStringView("typelabel", label.String()); - label = TRANSLATE("Payee"); - label << ": " << data.Payee(); + label.SetToFormat(B_TRANSLATE("Payee: %s"), data.Payee()); BStringView *payeelabel = new BStringView("payeelabel", label.String()); BString temp; gCurrentLocale.CurrencyToString(data.Amount().AbsoluteValue(), temp); - label = TRANSLATE("Amount"); - label << ": " << temp; + label.SetToFormat(B_TRANSLATE("Amount: %s"), temp); BStringView *amountlabel = new BStringView("amountlabel", label.String()); - label = TRANSLATE("Category"); - label += ": "; + label = B_TRANSLATE("Category:"); + label += " "; if (data.CountCategories() > 1) - label << TRANSLATE("Split"); + label << B_TRANSLATE("Split"); else label << data.NameAt(0); BStringView *categorylabel = new BStringView("categorylabel", label.String()); - label = TRANSLATE("Memo"); - label << ": " << data.Memo(); + label = B_TRANSLATE("Memo:"); + label << " " << data.Memo(); BStringView *memolabel = new BStringView("memolabel", label.String()); // Since layout-api, we need other way to make divider // BBox *divider = new BBox(r); // AddChild(divider); - fIntervalMenu = new BMenu(TRANSLATE("Frequency")); - fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Monthly"), new BMessage(M_SCHEDULED_MONTHLY))); + fIntervalMenu = new BMenu(B_TRANSLATE("Frequency")); + fIntervalMenu->AddItem(new BMenuItem(B_TRANSLATE("Monthly"), new BMessage(M_SCHEDULED_MONTHLY))); fIntervalMenu->AddItem( - new BMenuItem(TRANSLATE("Quarterly"), new BMessage(M_SCHEDULED_QUARTERLY)) + new BMenuItem(B_TRANSLATE("Quarterly"), new BMessage(M_SCHEDULED_QUARTERLY)) ); - fIntervalMenu->AddItem(new BMenuItem(TRANSLATE("Annually"), new BMessage(M_SCHEDULED_ANNUALLY)) + fIntervalMenu->AddItem(new BMenuItem(B_TRANSLATE("Annually"), new BMessage(M_SCHEDULED_ANNUALLY)) ); fIntervalMenu->ItemAt(0)->SetMarked(true); fIntervalMenu->SetLabelFromMarked(true); - temp = TRANSLATE("Frequency"); - temp += ": "; + temp = B_TRANSLATE("Frequency:"); + temp += " "; BMenuField *intervalfield = new BMenuField("intervalfield", temp.String(), fIntervalMenu); - temp = TRANSLATE("Starting Date"); - temp += ": "; + temp = B_TRANSLATE("Starting date:"); + temp += " "; fStartDate = new DateBox("startdate", temp.String(), "", new BMessage(M_DATE_CHANGED)); fStartDate->UseTabFiltering(false); gDefaultLocale.DateToString(data.Date(), temp); fStartDate->SetText(temp.String()); fRepeatAlways = - new BRadioButton("inftimes", TRANSLATE("Indefinitely"), new BMessage(M_REPEAT_ALWAYS)); + new BRadioButton("inftimes", B_TRANSLATE("Indefinitely"), new BMessage(M_REPEAT_ALWAYS)); fRepeatLimited = new BRadioButton("limitedtimes", "", new BMessage(M_REPEAT_LIMITED)); @@ -103,19 +107,19 @@ ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData & fRepeatCount->UseTabFiltering(false); fRepeatCount->SetEnabled(false); - BStringView *timeslabel = new BStringView("timeslabel", TRANSLATE("times")); + BStringView *timeslabel = new BStringView("timeslabel", B_TRANSLATE("times")); fRepeatAlways->SetValue(B_CONTROL_ON); intervalfield->MakeFocus(true); BButton *okbutton = - new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_SCHEDULE_TRANSACTION)); + new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_SCHEDULE_TRANSACTION)); okbutton->MakeDefault(true); - okbutton->SetLabel(TRANSLATE("OK")); + okbutton->SetLabel(B_TRANSLATE("OK")); BButton *cancelbutton = - new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); cancelbutton->MakeDefault(true); BLayoutBuilder::Group<>(back, B_VERTICAL) @@ -201,8 +205,8 @@ ScheduleAddWindow::MessageReceived(BMessage *msg) { if (datestr.CountChars() < 3 || gDefaultLocale.StringToDate(datestr.String(), tempdate) != B_OK) { ShowAlert( - TRANSLATE("Capital Be didn't understand the date you entered."), - TRANSLATE("Capital Be understands lots of different ways of entering dates. " + B_TRANSLATE("CapitalBe didn't understand the date you entered."), + B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " "Apparently, this wasn't one of them. You'll need to change how you " "entered this date. Sorry.") ); diff --git a/src/ScheduleListWindow.cpp b/src/ScheduleListWindow.cpp index 9d7fa1e..5a0e04a 100644 --- a/src/ScheduleListWindow.cpp +++ b/src/ScheduleListWindow.cpp @@ -1,11 +1,13 @@ #include "ScheduleListWindow.h" #include +#include #include #include #include #include #include +#include #include #include #include @@ -17,12 +19,18 @@ #include "ColumnTypes.h" #include "Database.h" #include "EscapeCancelFilter.h" +#include "LanguageRoster.h" #include "HelpButton.h" #include "Preferences.h" #include "ScheduledTransData.h" #include "ScheduledTransItem.h" #include "TransactionLayout.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "ScheduleListWindow" + +Language *gCurrentLanguage = NULL; enum { M_REMOVE_ITEM = 'rmit' }; @@ -50,8 +58,7 @@ ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView SetViewColor(240, 240, 240); // the buttons - temp = TRANSLATE("Remove"); - temp += "…"; + temp = B_TRANSLATE("Remove…"); fRemoveButton = new BButton("removebutton", temp.String(), new BMessage(M_REMOVE_ITEM)); // the transaction list @@ -64,31 +71,31 @@ ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView fListView->SetColor(B_COLOR_BACKGROUND, white); fListView->SetColor(B_COLOR_SELECTION, GetColor(BC_SELECTION_FOCUS)); - fListView->AddColumn(new BStringColumn(TRANSLATE("Payee"), 100, 25, 300, B_ALIGN_LEFT), 0); + fListView->AddColumn(new BStringColumn(B_TRANSLATE("Payee"), 100, 25, 300, B_ALIGN_LEFT), 0); float amountwidth = StringWidth("$000,000.00"); - float amountlabelwidth = StringWidth(TRANSLATE("Amount")); + float amountlabelwidth = StringWidth(B_TRANSLATE("Amount")); fListView->AddColumn( new BStringColumn( - TRANSLATE("Amount"), MAX(amountwidth, amountlabelwidth), 25, 300, B_ALIGN_LEFT + B_TRANSLATE("Amount"), MAX(amountwidth, amountlabelwidth), 25, 300, B_ALIGN_LEFT ), 1 ); fListView->AddColumn( new BStringColumn( - TRANSLATE("Payments"), StringWidth(TRANSLATE("Payments")) + 20, 25, 300, B_ALIGN_LEFT + B_TRANSLATE("Payments"), StringWidth(B_TRANSLATE("Payments")) + 20, 25, 300, B_ALIGN_LEFT ), 2 ); fListView->AddColumn( new BStringColumn( - TRANSLATE("Frequency"), StringWidth(TRANSLATE("Frequency")) + 20, 25, 300, B_ALIGN_LEFT + B_TRANSLATE("Frequency"), StringWidth(B_TRANSLATE("Frequency")) + 20, 25, 300, B_ALIGN_LEFT ), 3 ); fListView->AddColumn( new BStringColumn( - TRANSLATE("Next Payment"), StringWidth(TRANSLATE("Next Payment")) + 20, 25, 300, + B_TRANSLATE("Next Payment"), StringWidth(B_TRANSLATE("Next Payment")) + 20, 25, 300, B_ALIGN_LEFT ), 4 @@ -233,29 +240,29 @@ ScheduleListView::RefreshScheduleList(void) { string = ""; string << sdata->GetCount(); } else - string = TRANSLATE("Unlimited"); + string = B_TRANSLATE("Unlimited"); row->SetField(new BStringField(string.String()), 2); switch (sdata->GetInterval()) { case SCHEDULED_MONTHLY: { - string = TRANSLATE("Monthly"); + string = B_TRANSLATE("Monthly"); break; } case SCHEDULED_WEEKLY: { - string = TRANSLATE("Weekly"); + string = B_TRANSLATE("Weekly"); break; } case SCHEDULED_QUARTERLY: { - string = TRANSLATE("Quarterly"); + string = B_TRANSLATE("Quarterly"); break; } case SCHEDULED_ANNUALLY: { - string = TRANSLATE("Annually"); + string = B_TRANSLATE("Annually"); break; } default: { - string = TRANSLATE("Unknown"); + string = B_TRANSLATE("Unknown"); break; } } @@ -273,7 +280,7 @@ ScheduleListView::RefreshScheduleList(void) { ScheduleListWindow::ScheduleListWindow(const BRect &frame) : BWindow( - frame, TRANSLATE("Scheduled Transactions"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, + frame, B_TRANSLATE("Scheduled transactions"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ) { AddCommonFilter(new EscapeCancelFilter); diff --git a/src/ScheduledTransItem.cpp b/src/ScheduledTransItem.cpp index bccc316..3e8ac09 100644 --- a/src/ScheduledTransItem.cpp +++ b/src/ScheduledTransItem.cpp @@ -7,13 +7,20 @@ #include "Preferences.h" #include "TransactionData.h" #include "TransactionLayout.h" -#include "Translate.h" + +#include #include #include #include + #include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "ScheduledTransItem" + + ScheduledTransItem::ScheduledTransItem(const ScheduledTransData &data) : BListItem(), fAccount(data.GetAccount()), fType(data.Type().Type()), fPayee(data.Payee()), fAmount(""), fCategory(""), fMemo(data.Memo()), fDate(""), fID(data.GetID()) { @@ -22,7 +29,7 @@ ScheduledTransItem::ScheduledTransItem(const ScheduledTransData &data) gDefaultLocale.DateToString(data.Date(), fDate); if (data.CountCategories() > 1) - fCategory = TRANSLATE("Split"); + fCategory = B_TRANSLATE("Split"); else fCategory = data.NameAt(0); } @@ -198,7 +205,7 @@ ScheduledTransItem::SetData(const TransactionData &trans) { fPayee = trans.Payee(); locale.CurrencyToString(trans.Amount().AbsoluteValue(), fAmount); if (trans.CountCategories() > 1) - fCategory = TRANSLATE("Split"); + fCategory = B_TRANSLATE("Split"); else fCategory = trans.NameAt(0); fMemo = trans.Memo(); diff --git a/src/SplitView.cpp b/src/SplitView.cpp index daf175b..9e16f66 100644 --- a/src/SplitView.cpp +++ b/src/SplitView.cpp @@ -1,6 +1,8 @@ #include "SplitView.h" #include "DAlert.h" + #include +#include #include #include #include @@ -15,6 +17,7 @@ #include "Database.h" #include "DateBox.h" #include "HelpButton.h" +#include "LanguageRoster.h" #include "Layout.h" #include "MainWindow.h" #include "MsgDefs.h" @@ -23,7 +26,12 @@ #include "Preferences.h" #include "SplitItem.h" #include "SplitViewFilter.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "SplitView" + +Language *gCurrentLanguage = NULL; SplitView::SplitView(const char *name, const TransactionData &trans, const int32 &flags) : BView(name, flags | B_FRAME_EVENTS), @@ -33,7 +41,7 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 fStartExpanded = false; fCheckNum = fTransaction.GetAccount()->LastCheckNumber(); - fDateLabel = new BStringView("datelabel", TRANSLATE("Date")); + fDateLabel = new BStringView("datelabel", B_TRANSLATE("Date")); fDate = new DateBox("dateentry", "", "text", new BMessage(M_DATE_CHANGED)); // fDate->SetEscapeCancel(true); @@ -47,11 +55,11 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 fType->SetText(fTransaction.Type().Type()); - fTypeLabel = new BStringView("typelabel", TRANSLATE("Type")); + fTypeLabel = new BStringView("typelabel", B_TRANSLATE("Type")); fPayee = new PayeeBox("payeeentry", "", fTransaction.Payee(), new BMessage(M_PAYEE_CHANGED)); - fPayeeLabel = new BStringView("payeelabel", TRANSLATE("Payee")); + fPayeeLabel = new BStringView("payeelabel", B_TRANSLATE("Payee")); fAmount = new CurrencyBox("amountentry", "", NULL, new BMessage(M_AMOUNT_CHANGED)); @@ -61,20 +69,20 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 ); fAmount->SetText(tempstr.String()); - fAmountLabel = new BStringView("amountlabel", TRANSLATE("Amount")); + fAmountLabel = new BStringView("amountlabel", B_TRANSLATE("Amount")); - fCategoryLabel = new BStringView("categorylabel", TRANSLATE("Category")); + fCategoryLabel = new BStringView("categorylabel", B_TRANSLATE("Category")); fCategory = new CategoryBox( "categoryentry", "", fTransaction.NameAt(0), new BMessage(M_CATEGORY_CHANGED) ); - fMemoLabel = new BStringView("memolabel", TRANSLATE("Memo")); + fMemoLabel = new BStringView("memolabel", B_TRANSLATE("Memo")); fMemo = new NavTextBox("memoentry", "", fTransaction.Memo(), new BMessage(M_MEMO_CHANGED)); fSplit = new BButton( - "expander", TRANSLATE("Show Split"), new BMessage(M_EXPANDER_CHANGED), B_WILL_DRAW + "expander", B_TRANSLATE("Show Split"), new BMessage(M_EXPANDER_CHANGED), B_WILL_DRAW ); prefsLock.Lock(); @@ -86,10 +94,10 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 fSplitContainer = new BView("splitcontainer", B_WILL_DRAW); fSplitContainer->SetViewColor(240, 240, 240); - fAddSplit = new BButton("addsplit", TRANSLATE("Add Item"), new BMessage(M_ADD_SPLIT)); + fAddSplit = new BButton("addsplit", B_TRANSLATE("Add Item"), new BMessage(M_ADD_SPLIT)); fRemoveSplit = - new BButton("removesplit", TRANSLATE("Remove Item"), new BMessage(M_REMOVE_SPLIT)); + new BButton("removesplit", B_TRANSLATE("Remove Item"), new BMessage(M_REMOVE_SPLIT)); fSplitCategory = new BTextControl("splitcategory", NULL, NULL, NULL, B_WILL_DRAW); @@ -102,12 +110,12 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 fSplitItems->SetSelectionMessage(new BMessage(M_SELECT_SPLIT)); fSplitScroller = new BScrollView("split scroller", fSplitItems, 0, false, true); - BString totallabel(TRANSLATE("Total")); - totallabel << ": " << fTransaction.Amount().AbsoluteValue().AsFloat(); + BString totallabel(B_TRANSLATE("Total:")); + totallabel << " " << fTransaction.Amount().AbsoluteValue().AsFloat(); fSplitTotal = new BStringView("splittotal", totallabel.String()); fSplitContainer->Hide(); - fEnter = new BButton("enterbutton", TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); + fEnter = new BButton("enterbutton", B_TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); #ifndef ENTER_NAVIGATION fEnter->MakeDefault(true); @@ -131,8 +139,8 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 if (fTransaction.CountCategories() > 1 || - strcmp(fTransaction.NameAt(0), TRANSLATE("Split")) == 0) { - fCategory->SetText(TRANSLATE("Split Transaction")); + strcmp(fTransaction.NameAt(0), B_TRANSLATE("Split")) == 0) { + fCategory->SetText(B_TRANSLATE("Split Transaction")); fStartExpanded = true; } @@ -394,7 +402,7 @@ SplitView::MessageReceived(BMessage *msg) { ToggleSplit(); SplitItem *item = new SplitItem(); - item->SetCategory(TRANSLATE("Uncategorized")); + item->SetCategory(B_TRANSLATE("Uncategorized")); item->SetAmount(fTransaction.Amount().AbsoluteValue() - CalculateTotal().AbsoluteValue()); fSplitItems->AddItem(item); fSplitItems->Select(fSplitItems->IndexOf(item)); @@ -461,7 +469,7 @@ SplitView::MessageReceived(BMessage *msg) { fSplitItems->InvalidateItem(selection); if (strlen(fSplitCategory->Text()) < 1) - fTransaction.SetNameAt(selection, TRANSLATE("Uncategorized")); + fTransaction.SetNameAt(selection, B_TRANSLATE("Uncategorized")); else fTransaction.SetNameAt(selection, fSplitCategory->Text()); break; @@ -578,8 +586,8 @@ SplitView::ValidateSplitAmountField(void) { Fixed amount; if (gCurrentLocale.StringToCurrency(fSplitAmount->Text(), amount) != B_OK) { ShowAlert( - TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " + B_TRANSLATE("CapitalBe didn't understand the amount."), + B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " "for this account.") ); fSplitAmount->MakeFocus(true); @@ -605,8 +613,8 @@ SplitView::ValidateSplitItems(void) { if (gCurrentLocale.StringToCurrency(fAmount->Text(), amount) != B_OK) { fAmount->MakeFocus(true); ShowAlert( - TRANSLATE("Capital Be didn't understand the amount."), - TRANSLATE("There may be a typo or the wrong kind of currency symbol " + B_TRANSLATE("CapitalBe didn't understand the amount."), + B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " "for this account.") ); return false; @@ -617,12 +625,12 @@ SplitView::ValidateSplitItems(void) { BString errormsg, totalstr; gCurrentLocale.CurrencyToString(total, totalstr); - errormsg = TRANSLATE("When the split items are added together, they need to add up " + errormsg = B_TRANSLATE("When the split items are added together, they need to add up " "to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%%"); errormsg.ReplaceFirst("%%ENTERED_AMOUNT%%", fAmount->Text()); errormsg.ReplaceFirst("%%TOTAL_AMOUNT%%", totalstr.String()); - ShowAlert(TRANSLATE("The split total must match the amount box."), errormsg.String()); + ShowAlert(B_TRANSLATE("The split total must match the amount box."), errormsg.String()); fSplitAmount->MakeFocus(true); return false; } @@ -656,7 +664,7 @@ SplitView::ValidateAllFields(void) { void SplitView::ToggleSplit(void) { if (fSplitContainer->IsHidden()) { - fSplit->SetLabel(TRANSLATE("Hide Split")); + fSplit->SetLabel(B_TRANSLATE("Hide Split")); fSplitContainer->Show(); fCategory->SetEnabled(false); @@ -667,7 +675,7 @@ SplitView::ToggleSplit(void) { Invalidate(); fEnter->Invalidate(); } else { - fSplit->SetLabel(TRANSLATE("Show Split")); + fSplit->SetLabel(B_TRANSLATE("Show Split")); fSplitContainer->Hide(); fCategory->SetEnabled(true); diff --git a/src/SplitViewFilter.cpp b/src/SplitViewFilter.cpp index bc36b96..3209535 100644 --- a/src/SplitViewFilter.cpp +++ b/src/SplitViewFilter.cpp @@ -5,10 +5,16 @@ #include "Database.h" #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + +#include #include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "SplitFilterView" + + SplitViewFilter::SplitViewFilter(SplitView *checkview) : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fView(checkview) {} @@ -178,7 +184,7 @@ SplitViewFilter::Filter(BMessage *msg, BHandler **target) { BString autocomplete = acc->AutocompleteCategory(string.String()); - if (autocomplete.CountChars() > 0 && autocomplete != TRANSLATE("Split")) { + if (autocomplete.CountChars() > 0 && autocomplete != B_TRANSLATE("Split")) { BMessage automsg(M_CATEGORY_AUTOCOMPLETE); automsg.AddInt32("start", strlen(text->Text()) + 1); automsg.AddString("string", autocomplete.String()); diff --git a/src/TransactionEditWindow.cpp b/src/TransactionEditWindow.cpp index cd1aaa3..2b7eacf 100644 --- a/src/TransactionEditWindow.cpp +++ b/src/TransactionEditWindow.cpp @@ -1,12 +1,18 @@ #include "TransactionEditWindow.h" -#include "Translate.h" + +#include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "TransactionEditWindow" + + #define M_TOGGLE_SPLIT 'tspl' TransactionEditWindow::TransactionEditWindow(const BRect &frame, const TransactionData &trans) : BWindow( - frame, TRANSLATE("Edit Transaction"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, + frame, B_TRANSLATE("Edit transaction"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, B_AUTO_UPDATE_SIZE_LIMITS ) { fSplitView = new SplitView("splitview", trans, B_WILL_DRAW); diff --git a/src/TransactionItem.cpp b/src/TransactionItem.cpp index 546dcba..a8d5a6e 100644 --- a/src/TransactionItem.cpp +++ b/src/TransactionItem.cpp @@ -7,19 +7,26 @@ #include "Preferences.h" #include "TransactionData.h" #include "TransactionLayout.h" -#include "Translate.h" + +#include #include #include #include + #include #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "TransactionItem" + + TransactionItem::TransactionItem(const TransactionData &trans) : BListItem(), fDate(trans.Date()), fAccount(trans.GetAccount()), fType(trans.Type().Type()), fPayee(trans.Payee()), fAmount(trans.Amount()), fCategory(""), fMemo(trans.Memo()), fStatus(trans.Status()), fID(trans.GetID()), fTimeStamp(trans.GetTimeStamp()) { if (trans.CountCategories() > 1) - fCategory = TRANSLATE("Split"); + fCategory = B_TRANSLATE("Split"); else fCategory = trans.NameAt(0); } @@ -185,7 +192,7 @@ TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->DrawString(fMemo.String(), BPoint(xpos + 5, ypos - 3)); } else { owner->SetHighColor(linecolor); - owner->DrawString(TRANSLATE("No Memo"), BPoint(xpos + 5, ypos - 3)); + owner->DrawString(B_TRANSLATE("No Memo"), BPoint(xpos + 5, ypos - 3)); } owner->ConstrainClippingRegion(NULL); } @@ -204,7 +211,7 @@ TransactionItem::SetData(const TransactionData &trans) { fPayee = trans.Payee(); fAmount = trans.Amount(); if (trans.CountCategories() > 1) - fCategory = TRANSLATE("Split"); + fCategory = B_TRANSLATE("Split"); else fCategory = trans.NameAt(0); fMemo = trans.Memo(); diff --git a/src/TransactionReport.cpp b/src/TransactionReport.cpp index e68b2d1..b5aac8c 100644 --- a/src/TransactionReport.cpp +++ b/src/TransactionReport.cpp @@ -7,8 +7,16 @@ #include "ReportWindow.h" #include "TimeSupport.h" #include "Transaction.h" + +#include + #include + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "TransactionReport" + + void ReportWindow::ComputeTransactions(void) { // Total of all accounts @@ -45,49 +53,49 @@ ReportWindow::ComputeTransactions(void) { timelist.AddItem(new time_t(fEndDate)); } - BString longestname(TRANSLATE("Transactions")); + BString longestname(B_TRANSLATE("Transactions")); // int longestnamelength = 12; BColumn *col = new BStringColumn( - "", fGridView->StringWidth(TRANSLATE("Transactions")) + 20, 10, 300, B_TRUNCATE_END, + "", fGridView->StringWidth(B_TRANSLATE("Transactions")) + 20, 10, 300, B_TRUNCATE_END, B_ALIGN_RIGHT ); fGridView->AddColumn(col, 0); col = new BStringColumn( - TRANSLATE("Date"), fGridView->StringWidth("00-00-0000") + 15, 10, 300, B_TRUNCATE_END + B_TRANSLATE("Date"), fGridView->StringWidth("00-00-0000") + 15, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 1); col = new BStringColumn( - TRANSLATE("Type"), fGridView->StringWidth(TRANSLATE("Type")) + 20, 10, 300, B_TRUNCATE_END + B_TRANSLATE("Type"), fGridView->StringWidth(B_TRANSLATE("Type")) + 20, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 2); - col = new BStringColumn(TRANSLATE("Payee"), 75, 10, 300, B_TRUNCATE_END); + col = new BStringColumn(B_TRANSLATE("Payee"), 75, 10, 300, B_TRUNCATE_END); fGridView->AddColumn(col, 3); // The string we use for calculating width here should work well enough for general purposes col = new BStringColumn( - TRANSLATE("Amount"), fGridView->StringWidth("$00,000.00") + 15, 10, 300, B_TRUNCATE_END + B_TRANSLATE("Amount"), fGridView->StringWidth("$00,000.00") + 15, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 4); col = new BStringColumn( - TRANSLATE("Category"), fGridView->StringWidth("0000000000") + 20, 10, 300, B_TRUNCATE_END + B_TRANSLATE("Category"), fGridView->StringWidth("0000000000") + 20, 10, 300, B_TRUNCATE_END ); fGridView->AddColumn(col, 5); - col = new BStringColumn(TRANSLATE("Memo"), 75, 10, 300, B_TRUNCATE_END); + col = new BStringColumn(B_TRANSLATE("Memo"), 75, 10, 300, B_TRUNCATE_END); fGridView->AddColumn(col, 6); fGridView->AddRow(new BRow()); BRow *titlerow = new BRow(); fGridView->AddRow(titlerow); - titlerow->SetField(new BStringField(TRANSLATE("Transactions")), 0); + titlerow->SetField(new BStringField(B_TRANSLATE("Transactions")), 0); fGridView->AddRow(new BRow()); - int32 payeechars = strlen(TRANSLATE("Payee")), memochars = strlen(TRANSLATE("Memo")), - categorychars = strlen(TRANSLATE("Category")); - float maxpayee = fGridView->StringWidth(TRANSLATE("Payee")), - maxmemo = fGridView->StringWidth(TRANSLATE("Memo")), - maxcategory = fGridView->StringWidth(TRANSLATE("Category")); + int32 payeechars = strlen(B_TRANSLATE("Payee")), memochars = strlen(B_TRANSLATE("Memo")), + categorychars = strlen(B_TRANSLATE("Category")); + float maxpayee = fGridView->StringWidth(B_TRANSLATE("Payee")), + maxmemo = fGridView->StringWidth(B_TRANSLATE("Memo")), + maxcategory = fGridView->StringWidth(B_TRANSLATE("Category")); int32 count = timelist.CountItems() - 1; for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { @@ -132,9 +140,9 @@ ReportWindow::ComputeTransactions(void) { if (query.eof()) { row = new BRow(); fGridView->AddRow(row); - row->SetField(new BStringField(TRANSLATE("No Transactions")), 0); + row->SetField(new BStringField(B_TRANSLATE("No transactions")), 0); fGridView->ColumnAt(0)->SetWidth( - fGridView->StringWidth(TRANSLATE("No Transactions")) + 15 + fGridView->StringWidth(B_TRANSLATE("No transactions")) + 15 ); } else while (!query.eof()) { diff --git a/src/TransferWindow.cpp b/src/TransferWindow.cpp index c45a1d9..5737718 100644 --- a/src/TransferWindow.cpp +++ b/src/TransferWindow.cpp @@ -1,5 +1,7 @@ #include "TransferWindow.h" #include "DAlert.h" + +#include #include #include #include @@ -13,7 +15,11 @@ #include "MsgDefs.h" #include "TimeSupport.h" -#include "Translate.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "TransferWindow" + #define M_SOURCE_SELECTED 'srsl' #define M_DEST_SELECTED 'dssl' @@ -22,7 +28,7 @@ TransferWindow::TransferWindow(BHandler *target) : BWindow( - BRect(100, 100, 500, 350), TRANSLATE("Add Account Transfer"), B_TITLED_WINDOW_LOOK, + BRect(100, 100, 500, 350), B_TRANSLATE("Add account transfer"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), @@ -32,7 +38,7 @@ TransferWindow::TransferWindow(BHandler *target) TransferWindow::TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount) : BWindow( - BRect(100, 100, 300, 300), TRANSLATE("Edit Transfer"), B_TITLED_WINDOW_LOOK, + BRect(100, 100, 300, 300), B_TRANSLATE("Edit transfer"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), @@ -50,34 +56,34 @@ TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { back->SetViewColor(240, 240, 240); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); - temp = TRANSLATE("From Account"); + temp = B_TRANSLATE("From account"); temp += ":"; fFromLabel = new BStringView("fromlabel", temp.String()); BRect r(Bounds()); - temp = TRANSLATE("To Account"); + temp = B_TRANSLATE("To account"); temp += ":"; fToLabel = new BStringView("tolabel", temp.String()); - fOK = new BButton("okbutton", TRANSLATE("Cancel"), new BMessage(M_CREATE_TRANSFER)); - fOK->SetLabel(TRANSLATE("OK")); + fOK = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_CREATE_TRANSFER)); + fOK->SetLabel(B_TRANSLATE("OK")); fOK->SetEnabled(false); fOK->MakeDefault(true); - fCancel = new BButton("cancelbutton", TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); + fCancel = new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); - temp = TRANSLATE("Memo"); + temp = B_TRANSLATE("Memo"); temp += ":"; fMemo = new BTextControl("memobox", temp.String(), NULL, NULL); BString amt; gCurrentLocale.CurrencyToString(amount, amt); - temp = TRANSLATE("Amount"); + temp = B_TRANSLATE("Amount"); temp += ":"; fAmount = new CurrencyBox("amountbox", temp.String(), amt.String(), NULL); fAmount->GetFilter()->SetMessenger(new BMessenger(this)); - temp = TRANSLATE("Date"); + temp = B_TRANSLATE("Date"); temp += ":"; fDate = new DateBox("datebox", temp.String(), "", NULL); fDate->GetFilter()->SetMessenger(new BMessenger(this)); @@ -223,8 +229,8 @@ TransferWindow::MessageReceived(BMessage *msg) { gCurrentLocale.StringToCurrency(fAmount->Text(), amount); if (amount == 0) { ShowAlert( - TRANSLATE("Not Transferring Any Money"), - TRANSLATE("If you intend to transfer money, it will need to " + B_TRANSLATE("Not transferring any money"), + B_TRANSLATE("If you intend to transfer money, it will need to " "be an amount that is not zero.") ); break; diff --git a/src/Translate.h b/src/Translate.h deleted file mode 100644 index b526a01..0000000 --- a/src/Translate.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef TRANSLATE_H -#define TRANSLATE_H - -#include "Language.h" - -extern Language *gCurrentLanguage; - -#define TRANSLATE(x) gCurrentLanguage->Translate(x).String() - -#endif diff --git a/src/capitalbe.rdef b/src/capitalbe.rdef index fe18cf2..d7da7a3 100644 --- a/src/capitalbe.rdef +++ b/src/capitalbe.rdef @@ -9,8 +9,8 @@ resource app_version { variety = B_APPV_DEVELOPMENT, internal = 0, - short_info = "A personal finance app for BeOS", - long_info = "A personal finance app for BeOS" + short_info = "Finance application for Haiku", + long_info = "A personal finance application for Haiku" }; resource large_icon array { From 3984fc218da0a809166c356bbfa08689eb7d58c9 Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Thu, 14 Mar 2024 20:38:25 +0300 Subject: [PATCH 4/6] Remove Preview, Beta, and Demo modes --- .genio | Bin 0 -> 618 bytes Makefile | 2 +- locales/en.catkeys | 4 ++-- src/App.cpp | 37 ++++------------------------------ src/BuildOptions.h | 4 +--- src/CheckView.cpp | 25 +---------------------- src/LanguageRoster.h | 1 + src/Layout.h | 2 +- src/MainWindow.cpp | 40 ++++++------------------------------- src/ReconcileWindow.cpp | 1 - src/ReportWindow.cpp | 1 - src/ScheduleListWindow.cpp | 1 - src/SplitView.cpp | 1 - 13 files changed, 17 insertions(+), 102 deletions(-) create mode 100644 .genio diff --git a/.genio b/.genio new file mode 100644 index 0000000000000000000000000000000000000000..6bfdad7e5bf4136c52a63cc8b7070ce0bc10e074 GIT binary patch literal 618 zcmZ{gOHRWu5I`q{e;2F}NKnL{RX06AD^V7Opupa8lTj6joyv72c0CK{;3`}N(HT2L zSV=8SEWLU2aULG;N9l7ij{x9z#~D-dl=24@dyN;<&4=q^7{Khw_txfO!bDD6$VR`YZO+RC0bX}$@$W(QcCLF{S+nN zv7=?wNsB*iKtou&b+{wr2WGWJL1Wk9)EpP}vUeY!3Af=Vw#~f|?$IOco^5I^3N0)e JRcKiPYyp`SsSyAG literal 0 HcmV?d00001 diff --git a/Makefile b/Makefile index 4e41fe9..3642ff8 100644 --- a/Makefile +++ b/Makefile @@ -119,7 +119,7 @@ RSRCS = \ # - if your library does not follow the standard library naming scheme, # you need to specify the path to the library and it's name. # (e.g. for mylib.a, specify "mylib.a" or "path/mylib.a") -LIBS = be tracker localestub sqlite3 columnlistview $(STDCPPLIBS) +LIBS = be tracker localestub translation sqlite3 columnlistview $(STDCPPLIBS) # Specify additional paths to directories following the standard libXXX.so # or libXXX.a naming scheme. You can specify full paths or paths relative diff --git a/locales/en.catkeys b/locales/en.catkeys index 05a1190..a6f7ced 100644 --- a/locales/en.catkeys +++ b/locales/en.catkeys @@ -1,4 +1,4 @@ -1 English application/x-vnd.wgp-CapitalBe 1061653508 +1 English application/x-vnd.wgp-CapitalBe 548178424 Year ReportWindow Year Edit transaction TransactionEditWindow Edit transaction None ReportWindow None @@ -7,10 +7,10 @@ Transfer from %%PAYEE%% MainWindow Transfer from %%PAYEE%% Reports ReportWindow Reports Monthly ScheduleAddWindow Monthly Annually BudgetWindow Annually +Report a bug… MainWindow Report a bug… OK PrefWindow OK Changes will take effect on restart MainWindow Changes will take effect on restart CapitalBe didn't understand the date you entered. DateBox CapitalBe didn't understand the date you entered. -CapitalBe Preview Edition MainWindow CapitalBe Preview Edition To account TransferWindow To account Category CheckView Category Reports… MainWindow Reports… diff --git a/src/App.cpp b/src/App.cpp index 7668326..215526d 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -19,28 +19,13 @@ bool gRestartApp = false; App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { -#ifdef BETA_MODE - - // To create the UNIX number, run the Terminal command - // date --date="25 Dec 2006" +%s - // and change the date accordingly - if (GetCurrentDate() > 1167022800) { - ShowAlert( - "This beta version has expired.", - "This is only a test version of CapitalBe and is intended to work only " - "for a short period of time to allow the community to help find bugs and " - "make CapitalBe the best financial manager possible.\n\nYou can download " - "a new copy of CapitalBe from http://www.capitalbe.com/" - ); - be_app->PostMessage(B_QUIT_REQUESTED); - return; - } - -#endif - // Load preferences and then initialize the translation system LoadPreferences(PREFERENCES_PATH "/CapitalBeSettings"); + BString languagepath = gAppPath.String(); + languagepath += "R5LanguageFiles"; + language_roster = new LanguageRoster(languagepath.String()); + // We can skip locking because nothing else is open at this point :) BRect winframe; if (gPreferences.FindRect("mainframe", &winframe) == B_OK) @@ -50,20 +35,6 @@ App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { MainWindow *win = new MainWindow(winframe); win->Show(); - -#ifdef PREVIEW_MODE - - ShowAlert( - "Welcome to CapitalBe's Technology Preview!", - "Welcome and thank you for trying CapitalBe, what will be the foremost " - "personal finance manager for BeOS, Zeta, and Haiku.\n\n" - "This preview version may contain bugs and is not feature complete, but " - "will give you an idea of what the full version will be like when released.\n\n" - "Please feel free to experiment and send any feedback to capitalbe@earthlink.net", - B_IDEA_ALERT - ); - -#endif } App::~App(void) { diff --git a/src/BuildOptions.h b/src/BuildOptions.h index 8edfc2e..16c47ba 100644 --- a/src/BuildOptions.h +++ b/src/BuildOptions.h @@ -3,13 +3,11 @@ #include -// Uncomment DEMO_MODE to turn this into the demo package version -enum { NORMAL_MODE = 0, PREVIEW_MODE, BETA_MODE }; #define BUILD_MODE NORMAL_MODE - // Uncomment ENTER_NAVIGATION to enable using the Enter key to navigate fields. // It copies Quicken, but it is also not consistent in its behavior, which is NOT good // #define ENTER_NAVIGATION + #endif diff --git a/src/CheckView.cpp b/src/CheckView.cpp index 2b4864f..8da7583 100644 --- a/src/CheckView.cpp +++ b/src/CheckView.cpp @@ -6,7 +6,6 @@ #include #include "Account.h" -#include "BuildOptions.h" #include "CategoryBox.h" #include "CheckNumBox.h" #include "CheckView.h" @@ -15,7 +14,6 @@ #include "Database.h" #include "DateBox.h" #include "LanguageRoster.h" -#include "Layout.h" #include "MainWindow.h" #include "MsgDefs.h" #include "NavTextBox.h" @@ -31,8 +29,6 @@ #define B_TRANSLATION_CONTEXT "CheckView" -Language *gCurrentLanguage = NULL; - enum { M_ENTER_TRANSACTION = 'entr' }; CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { @@ -59,7 +55,7 @@ CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAM prefsLock.Lock(); BString rechelp = gAppPath; prefsLock.Unlock(); - rechelp << "helpfiles/" << gCurrentLanguage->Name() << "/Main Window Help"; + rechelp << "helpfiles/" << gCurrentLanguage << "/Main Window Help"; fHelpButton = new HelpButton("rechelp", rechelp.String()); fEnter = new BButton("enterbutton", B_TRANSLATE("Enter"), new BMessage(M_ENTER_TRANSACTION)); @@ -155,25 +151,6 @@ CheckView::MessageReceived(BMessage *msg) { // from the Memo field. The CheckView instance should do whatever is // needed to post the transaction into the register -#ifdef DEMO_MODE - Account *demoacc = gDatabase.CurrentAccount(); - if (demoacc && demoacc->CountTransactions() >= 25) { - ShowAlert( - B_TRANSLATE("Demo mode limit"), - B_TRANSLATE( - "The Demo Mode limit has been reached on this account.", - "You can manually enter up to 25 transactions per " - "account. We hope that you like CapitalBe and will " - "purchase the full version. Have a nice day!" - ), - B_IDEA_ALERT - ); - MakeEmpty(); - break; - } - -#endif - if (!fDate->Validate() || !fType->Validate() || !fPayee->Validate() || !fAmount->Validate() || !fCategory->Validate()) break; diff --git a/src/LanguageRoster.h b/src/LanguageRoster.h index d0aeeba..4739b93 100644 --- a/src/LanguageRoster.h +++ b/src/LanguageRoster.h @@ -25,6 +25,7 @@ class LanguageRoster { Language *fDefaultLanguage; }; +extern Language *gCurrentLanguage; extern LanguageRoster *language_roster; #endif diff --git a/src/Layout.h b/src/Layout.h index 648eb1a..c02550c 100644 --- a/src/Layout.h +++ b/src/Layout.h @@ -1,9 +1,9 @@ #ifndef LAYOUT_H #define LAYOUT_H + extern int32 gTextViewHeight; extern int32 gStringViewHeight; -#define TRANSLATE(x) gCurrentLanguage->Translate(x).String() #endif diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 0810629..3d597a8 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -14,7 +14,6 @@ #include "AccountSettingsWindow.h" #include "BudgetWindow.h" -#include "BuildOptions.h" #include "CBLocale.h" #include "CategoryWindow.h" #include "DAlert.h" @@ -45,19 +44,14 @@ // Internal definition of the Haiku services daemon #define B_SERVICES_DAEMON_RESTART 'SDRS' -Language *gCurrentLanguage = NULL; int32 gTextViewHeight = 20; int32 gStringViewHeight = 20; +Language *gCurrentLanguage = NULL; + MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BString temp; - // Main window title changes in demo mode - if (BUILD_MODE == PREVIEW_MODE) - SetTitle(B_TRANSLATE("CapitalBe Preview Edition")); - else if (BUILD_MODE == BETA_MODE) - SetTitle("CapitalBe: Beta"); - else SetTitle(B_TRANSLATE_SYSTEM_NAME("CapitalBe")); // These chunks of code will save a lot of headache later on -- @@ -103,19 +97,10 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BRect r(Bounds()); r.bottom = 20; BMenuBar *bar = new BMenuBar("keybar"); - -#ifdef BETA_MODE - temp = B_TRANSLATE("Report a bug…"); - bar->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_BUG))); -#endif - BMenu *menu = new BMenu(B_TRANSLATE("Program")); -#ifdef DEMO_MODE - menu->AddItem(new BMenuItem(B_TRANSLATE("Buy CapitalBe"), new BMessage(M_PURCHASE_FULL_VERSION)) - ); - menu->AddSeparatorItem(); -#endif + temp = B_TRANSLATE("Report a bug…"); + menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_BUG))); temp = B_TRANSLATE("Settings…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_SHOW_OPTIONS_WINDOW), ',')); @@ -321,24 +306,11 @@ MainWindow::MessageReceived(BMessage *msg) { break; } case M_REPORT_BUG: { - BString cmdstring("/boot/beos/apps/BeMail mailto:support@capitalbe.com &"); - system(cmdstring.String()); + char *argv[2] = {(char*)"https://github.com/HaikuArchives/CapitalBe", NULL}; + be_roster->Launch("text/html", 1, argv); break; } case M_SHOW_NEW_ACCOUNT: { -#ifdef PREVIEW_MODE - if (gDatabase.CountAccounts() >= 5) { - ShowAlert( - B_TRANSLATE("Preview mode limit"), - B_TRANSLATE("You can have up to 5 accounts in CapitalBe's demo version. " - "We hope that you like CapitalBe and will " - "purchase the full version. Have a nice day!"), - B_IDEA_ALERT - ); - break; - } -#endif - AccountSettingsWindow *newaccwin = new AccountSettingsWindow(NULL); BRect r(Frame()); newaccwin->MoveTo( diff --git a/src/ReconcileWindow.cpp b/src/ReconcileWindow.cpp index 5963630..ced9361 100644 --- a/src/ReconcileWindow.cpp +++ b/src/ReconcileWindow.cpp @@ -21,7 +21,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ReconcileWindow" -Language *gCurrentLanguage = NULL; enum { M_TOGGLE_DEPOSIT = 'tgdp', diff --git a/src/ReportWindow.cpp b/src/ReportWindow.cpp index 82539f9..a5106d9 100644 --- a/src/ReportWindow.cpp +++ b/src/ReportWindow.cpp @@ -24,7 +24,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ReportWindow" -Language *gCurrentLanguage = NULL; int compare_stringitem(const void *item1, const void *item2); diff --git a/src/ScheduleListWindow.cpp b/src/ScheduleListWindow.cpp index 5a0e04a..9a0485a 100644 --- a/src/ScheduleListWindow.cpp +++ b/src/ScheduleListWindow.cpp @@ -30,7 +30,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ScheduleListWindow" -Language *gCurrentLanguage = NULL; enum { M_REMOVE_ITEM = 'rmit' }; diff --git a/src/SplitView.cpp b/src/SplitView.cpp index 9e16f66..e621704 100644 --- a/src/SplitView.cpp +++ b/src/SplitView.cpp @@ -31,7 +31,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "SplitView" -Language *gCurrentLanguage = NULL; SplitView::SplitView(const char *name, const TransactionData &trans, const int32 &flags) : BView(name, flags | B_FRAME_EVENTS), From ef3ff554161891e76211dd02456964b640e3f610 Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Sat, 16 Mar 2024 00:10:51 +0300 Subject: [PATCH 5/6] Add Genio project files to .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 96586cd..51b6e11 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ +.genio + objects*/ From d823c2b9677db50b819108b1c30079411f81fc0c Mon Sep 17 00:00:00 2001 From: Emir SARI Date: Mon, 18 Mar 2024 16:50:57 +0300 Subject: [PATCH 6/6] Change pointer alignment to left --- .clang-format | 4 +- src/Account.cpp | 60 ++-- src/Account.h | 33 +- src/AccountListItem.cpp | 28 +- src/AccountListItem.h | 10 +- src/AccountSettingsWindow.cpp | 16 +- src/AccountSettingsWindow.h | 12 +- src/App.cpp | 22 +- src/App.h | 2 +- src/AutoTextControl.cpp | 68 +++-- src/AutoTextControl.h | 44 +-- src/Budget.cpp | 23 +- src/Budget.h | 12 +- src/BudgetReport.cpp | 43 +-- src/BudgetWindow.cpp | 92 +++--- src/BudgetWindow.h | 26 +- src/CBLocale.h | 60 ++-- src/CashFlowReport.cpp | 41 +-- src/Category.cpp | 93 +++--- src/Category.h | 38 +-- src/CategoryBox.cpp | 17 +- src/CategoryBox.h | 6 +- src/CategoryWindow.cpp | 143 +++++---- src/CategoryWindow.h | 2 +- src/CheckNumBox.cpp | 32 +- src/CheckNumBox.h | 6 +- src/CheckView.cpp | 71 +++-- src/CheckView.h | 24 +- src/CppSQLite3.cpp | 550 +++++++++++++++++++++------------- src/CppSQLite3.h | 142 ++++----- src/CurrencyBox.cpp | 21 +- src/CurrencyBox.h | 6 +- src/DAlert.cpp | 184 +++++++----- src/DAlert.h | 44 +-- src/DStringList.cpp | 54 ++-- src/DStringList.h | 32 +- src/Database.cpp | 251 ++++++++++------ src/Database.h | 120 ++++---- src/DateBox.cpp | 37 ++- src/DateBox.h | 12 +- src/EscapeCancelFilter.h | 5 +- src/Fixed.cpp | 117 +++++--- src/Fixed.h | 44 +-- src/HelpButton.cpp | 30 +- src/HelpButton.h | 4 +- src/Import.cpp | 57 ++-- src/Import.h | 4 +- src/Language.cpp | 23 +- src/Language.h | 10 +- src/LanguageRoster.cpp | 37 ++- src/LanguageRoster.h | 20 +- src/Locale.cpp | 153 ++++++---- src/MainWindow.cpp | 126 ++++---- src/MainWindow.h | 12 +- src/NavTextBox.cpp | 15 +- src/NavTextBox.h | 10 +- src/NetWorthReport.cpp | 25 +- src/Notifier.cpp | 3 +- src/Notifier.h | 28 +- src/NumBox.cpp | 18 +- src/NumBox.h | 10 +- src/ObjectList.h | 398 +++++++++++++----------- src/PayeeBox.cpp | 16 +- src/PayeeBox.h | 8 +- src/PrefWindow.cpp | 48 +-- src/PrefWindow.h | 30 +- src/Preferences.cpp | 12 +- src/Preferences.h | 8 +- src/QuickTrackerItem.cpp | 77 +++-- src/QuickTrackerItem.h | 16 +- src/ReconcileItem.cpp | 18 +- src/ReconcileItem.h | 7 +- src/ReconcileWindow.cpp | 128 ++++---- src/ReconcileWindow.h | 20 +- src/RegisterView.cpp | 51 ++-- src/RegisterView.h | 18 +- src/ReportGrid.cpp | 77 +++-- src/ReportGrid.h | 28 +- src/ReportWindow.cpp | 128 ++++---- src/ReportWindow.h | 27 +- src/ScheduleAddWindow.cpp | 41 +-- src/ScheduleAddWindow.h | 10 +- src/ScheduleListWindow.cpp | 56 ++-- src/ScheduleListWindow.h | 2 +- src/ScheduledExecutor.cpp | 3 +- src/ScheduledTransData.cpp | 35 ++- src/ScheduledTransData.h | 18 +- src/ScheduledTransItem.cpp | 21 +- src/ScheduledTransItem.h | 14 +- src/Settings.cpp | 90 ++++++ src/Settings.h | 34 +++ src/SettingsWindow.cpp | 58 ++++ src/SettingsWindow.h | 37 +++ src/SplitItem.cpp | 25 +- src/SplitItem.h | 10 +- src/SplitView.cpp | 145 +++++---- src/SplitView.h | 40 +-- src/SplitViewFilter.cpp | 35 ++- src/SplitViewFilter.h | 6 +- src/StickyDrawButton.cpp | 38 ++- src/StickyDrawButton.h | 8 +- src/TextFile.cpp | 27 +- src/TextFile.h | 10 +- src/TimeSupport.cpp | 69 +++-- src/TimeSupport.h | 20 +- src/Transaction.cpp | 3 +- src/Transaction.h | 8 +- src/TransactionData.cpp | 65 ++-- src/TransactionData.h | 58 ++-- src/TransactionEditWindow.cpp | 12 +- src/TransactionEditWindow.h | 6 +- src/TransactionItem.cpp | 24 +- src/TransactionItem.h | 14 +- src/TransactionLayout.cpp | 18 +- src/TransactionLayout.h | 2 +- src/TransactionReport.cpp | 27 +- src/TransactionView.cpp | 120 +++++--- src/TransactionView.h | 22 +- src/TransferWindow.cpp | 55 ++-- src/TransferWindow.h | 14 +- 120 files changed, 3375 insertions(+), 2272 deletions(-) create mode 100644 src/Settings.cpp create mode 100644 src/Settings.h create mode 100644 src/SettingsWindow.cpp create mode 100644 src/SettingsWindow.h diff --git a/.clang-format b/.clang-format index 3ef6673..a782e4d 100755 --- a/.clang-format +++ b/.clang-format @@ -80,7 +80,7 @@ BreakAfterJavaFieldAnnotations: false BreakArrays: true BreakBeforeBinaryOperators: None BreakBeforeConceptDeclarations: Always -BreakBeforeBraces: Attach +BreakBeforeBraces: Stroustrup BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon @@ -165,7 +165,7 @@ PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right +PointerAlignment: Left PPIndentWidth: -1 QualifierAlignment: Leave ReferenceAlignment: Pointer diff --git a/src/Account.cpp b/src/Account.cpp index 4dc9edf..b8dcdb9 100644 --- a/src/Account.cpp +++ b/src/Account.cpp @@ -3,19 +3,23 @@ #include #include -Account::Account(const char *name, const bool &isclosed) +Account::Account(const char* name, const bool& isclosed) : fName(name), fID(0), fClosed(isclosed), fCurrentTransaction(0), fLastCheckNumber(0), - fUseDefaultLocale(true) {} + fUseDefaultLocale(true) +{ +} Account::~Account(void) {} void -Account::SetName(const char *name) { +Account::SetName(const char* name) +{ fName = name; } bool -Account::SetCurrentTransaction(const uint32 &id) { +Account::SetCurrentTransaction(const uint32& id) +{ if (gDatabase.HasTransaction(id)) { if (id != fCurrentTransaction) { BMessage msg; @@ -29,7 +33,8 @@ Account::SetCurrentTransaction(const uint32 &id) { } uint16 -Account::LookupLastCheckNumber(void) { +Account::LookupLastCheckNumber(void) +{ BString command("select max(type) from account_"); command << fID << " where type between 0 and 65536;"; @@ -41,7 +46,8 @@ Account::LookupLastCheckNumber(void) { } Fixed -Account::Balance(void) { +Account::Balance(void) +{ BString command("select sum(amount) from account_"); command << fID << ";"; @@ -59,7 +65,8 @@ Account::Balance(void) { } Fixed -Account::BalanceAt(const time_t &date) { +Account::BalanceAt(const time_t& date) +{ BString command("select sum(amount) from account_"); command << fID << " where date <= " << date << " order by payee;"; @@ -77,7 +84,8 @@ Account::BalanceAt(const time_t &date) { } Fixed -Account::BalanceAtTransaction(const time_t &time, const char *payee) { +Account::BalanceAtTransaction(const time_t& time, const char* payee) +{ if (!payee) return Fixed(); @@ -93,7 +101,8 @@ Account::BalanceAtTransaction(const time_t &time, const char *payee) { date = query.getInt64Field(0); if (date < time) { amount += query.getInt64Field(2); - } else { + } + else { BString temp(DeescapeIllegalCharacters(query.getStringField(1))); if (strcmp(temp.String(), payee) < 1) amount += query.getInt64Field(2); @@ -108,7 +117,8 @@ Account::BalanceAtTransaction(const time_t &time, const char *payee) { } BString -Account::AutocompleteCategory(const char *input) { +Account::AutocompleteCategory(const char* input) +{ if (!input) return BString(); @@ -131,7 +141,8 @@ Account::AutocompleteCategory(const char *input) { } BString -Account::AutocompletePayee(const char *input) { +Account::AutocompletePayee(const char* input) +{ if (!input) return BString(); @@ -147,7 +158,8 @@ Account::AutocompletePayee(const char *input) { } BString -Account::AutocompleteType(const char *input) { +Account::AutocompleteType(const char* input) +{ if (!input) return BString(); @@ -155,11 +167,13 @@ Account::AutocompleteType(const char *input) { int32 inputlength = strlen(input); if (strncasecmp(input, "ATM", inputlength) == 0) return BString("ATM"); - } else if (toupper(input[0]) == (int)'D') { + } + else if (toupper(input[0]) == (int)'D') { int32 inputlength = strlen(input); if (strncasecmp(input, "DEP", inputlength) == 0) return BString("DEP"); - } else { + } + else { // Numeric autocompletion BString str; str << fLastCheckNumber; @@ -179,12 +193,14 @@ Account::AutocompleteType(const char *input) { } Locale -Account::GetLocale(void) const { +Account::GetLocale(void) const +{ return fUseDefaultLocale ? gDefaultLocale : fLocale; } void -Account::SetLocale(const Locale &locale) { +Account::SetLocale(const Locale& locale) +{ if (fUseDefaultLocale) { ShowBug("Calling SetLocale on an account with default locale settings"); return; @@ -201,7 +217,8 @@ Account::SetLocale(const Locale &locale) { } uint32 -Account::CountTransactions(void) { +Account::CountTransactions(void) +{ BString command("select * from account_"); command << GetID() << " order by transid"; CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::CountTransactions"); @@ -221,7 +238,8 @@ Account::CountTransactions(void) { } void -Account::DoForEachTransaction(void (*func)(const TransactionData &, void *), void *ptr) { +Account::DoForEachTransaction(void (*func)(const TransactionData&, void*), void* ptr) +{ BString command("select * from account_"); command << GetID() << " order by date,transid"; CppSQLite3Query query = gDatabase.DBQuery(command.String(), "Account::DoForEachTransaction"); @@ -300,7 +318,8 @@ Account::DoForEachTransaction(void (*func)(const TransactionData &, void *), voi } void -Account::UseDefaultLocale(const bool &usedefault) { +Account::UseDefaultLocale(const bool& usedefault) +{ if (usedefault == fUseDefaultLocale) return; @@ -310,7 +329,8 @@ Account::UseDefaultLocale(const bool &usedefault) { if (fUseDefaultLocale) { command = "delete from accountlocale where accountid = "; command << fID << ";"; - } else { + } + else { // update the local copy in case it changed since the program was opened fLocale = gDefaultLocale; diff --git a/src/Account.h b/src/Account.h index 0cbe5be..727c7b0 100644 --- a/src/Account.h +++ b/src/Account.h @@ -12,49 +12,48 @@ typedef enum { ACCOUNT_BANK = 0, ACCOUNT_CASH, ACCOUNT_CREDIT } AccountType; class Account : public Notifier { public: - Account(const char *name = NULL, const bool &isclosed = false); + Account(const char* name = NULL, const bool& isclosed = false); ~Account(void); - void SetName(const char *name); + void SetName(const char* name); - const char *Name(void) const { return fName.String(); } + const char* Name(void) const { return fName.String(); } - void SetID(const time_t &id) { fID = id; } + void SetID(const time_t& id) { fID = id; } uint32 GetID(void) const { return fID; } - void SetClosed(const bool &value) { fClosed = value; } + void SetClosed(const bool& value) { fClosed = value; } bool IsClosed(void) const { return fClosed; } uint32 CurrentTransaction(void) const { return fCurrentTransaction; } - bool SetCurrentTransaction(const uint32 &id); + bool SetCurrentTransaction(const uint32& id); uint16 LastCheckNumber(void) const { return fLastCheckNumber; } uint16 LookupLastCheckNumber(void); - void SetLastCheckNumber(const uint16 &value) { fLastCheckNumber = value; } + void SetLastCheckNumber(const uint16& value) { fLastCheckNumber = value; } - BString AutocompleteCategory(const char *input); - BString AutocompletePayee(const char *input); - BString AutocompleteType(const char *input); + BString AutocompleteCategory(const char* input); + BString AutocompletePayee(const char* input); + BString AutocompleteType(const char* input); Fixed Balance(void); - Fixed BalanceAt(const time_t &time); - Fixed BalanceAtTransaction(const time_t &time, const char *payee); + Fixed BalanceAt(const time_t& time); + Fixed BalanceAtTransaction(const time_t& time, const char* payee); Locale GetLocale(void) const; - void SetLocale(const Locale &locale); + void SetLocale(const Locale& locale); uint32 CountTransactions(void); - void DoForEachTransaction( - void (*TransactionIteratorFunc)(const TransactionData &, void *), void *ptr - ); + void + DoForEachTransaction(void (*TransactionIteratorFunc)(const TransactionData&, void*), void* ptr); - void UseDefaultLocale(const bool &usedefault); + void UseDefaultLocale(const bool& usedefault); bool IsUsingDefaultLocale(void) const { return fUseDefaultLocale; } diff --git a/src/AccountListItem.cpp b/src/AccountListItem.cpp index 887c263..f1af2fa 100644 --- a/src/AccountListItem.cpp +++ b/src/AccountListItem.cpp @@ -17,37 +17,43 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "AccountListItem" - -AccountListItem::AccountListItem(Account *acc) : BListItem() { +AccountListItem::AccountListItem(Account* acc) : BListItem() +{ fAccount = acc; fEnabled = true; } void -AccountListItem::SetEnabled(bool enabled) { +AccountListItem::SetEnabled(bool enabled) +{ fEnabled = enabled; } void -AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) { +AccountListItem::DrawItem(BView* owner, BRect frame, bool complete) +{ if (IsSelected()) { if (IsEnabled()) { if (fAccount->IsClosed()) { owner->SetHighColor(GetColor(BC_SELECTION_NOFOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_NOFOCUS)); - } else { + } + else { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); } - } else { + } + else { owner->SetHighColor(230, 230, 230); owner->SetLowColor(230, 230, 230); } - } else { + } + else { if (fAccount->IsClosed()) { owner->SetHighColor(240, 240, 240, 128); owner->SetLowColor(240, 240, 240, 128); - } else { + } + else { owner->SetHighColor(255, 255, 255, 128); owner->SetLowColor(255, 255, 255, 128); } @@ -72,7 +78,8 @@ AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->DrawString( B_TRANSLATE("Closed"), BPoint(frame.left + 5, frame.top + (font.Size() * 2)) ); - } else { + } + else { BString text; fAccount->GetLocale().CurrencyToString(fAccount->Balance(), text); owner->DrawString(text.String(), BPoint(frame.left + 5, frame.top + (font.Size() * 2))); @@ -80,7 +87,8 @@ AccountListItem::DrawItem(BView *owner, BRect frame, bool complete) { } void -AccountListItem::Update(BView *owner, const BFont *finfo) { +AccountListItem::Update(BView* owner, const BFont* finfo) +{ BListItem::Update(owner, finfo); // We can afford to make this call because the row height is just a sane diff --git a/src/AccountListItem.h b/src/AccountListItem.h index 605b864..79b3e1e 100644 --- a/src/AccountListItem.h +++ b/src/AccountListItem.h @@ -7,18 +7,18 @@ class Account; class AccountListItem : public BListItem { public: - AccountListItem(Account *acc); + AccountListItem(Account* acc); void SetEnabled(bool enabled); bool IsEnabled(void) const { return fEnabled; } - void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView *owner, const BFont *finfo); + void DrawItem(BView* owner, BRect frame, bool complete = false); + void Update(BView* owner, const BFont* finfo); - Account *GetAccount(void) const { return fAccount; } + Account* GetAccount(void) const { return fAccount; } private: - Account *fAccount; + Account* fAccount; bool fEnabled; }; diff --git a/src/AccountSettingsWindow.cpp b/src/AccountSettingsWindow.cpp index b2738a1..6b7430e 100644 --- a/src/AccountSettingsWindow.cpp +++ b/src/AccountSettingsWindow.cpp @@ -19,20 +19,21 @@ #define M_NAME_CHANGED 'nmch' #define M_TOGGLE_USE_DEFAULT 'tgud' -AccountSettingsWindow::AccountSettingsWindow(Account *account) +AccountSettingsWindow::AccountSettingsWindow(Account* account) : BWindow( BRect(0, 0, 1, 1), B_TRANSLATE("Account settings"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fAccount(account) { + fAccount(account) +{ AddCommonFilter(new EscapeCancelFilter); BString temp; AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *back = new BView("back", B_WILL_DRAW); + BView* back = new BView("back", B_WILL_DRAW); back->SetViewColor(240, 240, 240); temp = B_TRANSLATE("Account name:"); @@ -44,7 +45,8 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) fAccountName->MakeFocus(true); fAccountName->SetDivider(fAccountName->StringWidth(temp.String()) + 3); - fUseDefault = new BCheckBox("usedefault", B_TRANSLATE("Use default currency settings"), + fUseDefault = new BCheckBox( + "usedefault", B_TRANSLATE("Use default currency settings"), new BMessage(M_TOGGLE_USE_DEFAULT) ); if (!fAccount || fAccount->IsUsingDefaultLocale()) @@ -86,7 +88,8 @@ AccountSettingsWindow::AccountSettingsWindow(Account *account) } void -AccountSettingsWindow::MessageReceived(BMessage *msg) { +AccountSettingsWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_EDIT_ACCOUNT_SETTINGS: { Locale temp; @@ -95,7 +98,8 @@ AccountSettingsWindow::MessageReceived(BMessage *msg) { temp = gDefaultLocale; fPrefView->GetSettings(temp); gDatabase.AddAccount(fAccountName->Text(), ACCOUNT_BANK, "Open", &temp); - } else { + } + else { if (strcmp(fAccountName->Text(), fAccount->Name()) != 0) gDatabase.RenameAccount(fAccount, fAccountName->Text()); diff --git a/src/AccountSettingsWindow.h b/src/AccountSettingsWindow.h index ec51fc7..09ed167 100644 --- a/src/AccountSettingsWindow.h +++ b/src/AccountSettingsWindow.h @@ -13,17 +13,17 @@ class Account; class AccountSettingsWindow : public BWindow { public: - AccountSettingsWindow(Account *name); - void MessageReceived(BMessage *msg); + AccountSettingsWindow(Account* name); + void MessageReceived(BMessage* msg); private: friend class NewAccountFilter; - AutoTextControl *fAccountName; + AutoTextControl* fAccountName; BButton *fCancel, *fOK; - CurrencyPrefView *fPrefView; - Account *fAccount; - BCheckBox *fUseDefault; + CurrencyPrefView* fPrefView; + Account* fAccount; + BCheckBox* fUseDefault; }; #endif diff --git a/src/App.cpp b/src/App.cpp index 215526d..b5c5e15 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -18,7 +18,8 @@ bool gRestartApp = false; -App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { +App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") +{ // Load preferences and then initialize the translation system LoadPreferences(PREFERENCES_PATH "/CapitalBeSettings"); @@ -33,17 +34,19 @@ App::App(void) : BApplication("application/x-vnd.wgp-CapitalBe") { else winframe.Set(100, 100, 620, 360); - MainWindow *win = new MainWindow(winframe); + MainWindow* win = new MainWindow(winframe); win->Show(); } -App::~App(void) { +App::~App(void) +{ delete language_roster; language_roster = NULL; } void -App::MessageReceived(BMessage *msg) { +App::MessageReceived(BMessage* msg) +{ if (msg->what == M_QUIT_NOW) Quit(); else @@ -51,7 +54,8 @@ App::MessageReceived(BMessage *msg) { } int -main(void) { +main(void) +{ // Attempt to load the default data file BEntry entry("/boot/home/config/settings/CapitalBe"); @@ -66,7 +70,7 @@ main(void) { file.Unset(); } - App *app = new App; + App* app = new App; app->Run(); delete app; @@ -84,7 +88,8 @@ main(void) { #include void -StartFile(void) { +StartFile(void) +{ BEntry entry("/boot/develop/projects/CapitalBe/cbsql/testdb"); if (entry.Exists()) @@ -139,7 +144,8 @@ StartFile(void) { } int -main(void) { +main(void) +{ // gDatabase.OpenFile("/boot/develop/projects/CapitalBe/cbsql/testdb"); StartFile(); diff --git a/src/App.h b/src/App.h index 84e77ff..80f0f01 100644 --- a/src/App.h +++ b/src/App.h @@ -10,7 +10,7 @@ class App : public BApplication { public: App(void); ~App(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); }; extern bool gRestartApp; diff --git a/src/AutoTextControl.cpp b/src/AutoTextControl.cpp index 2524033..7f07f6d 100644 --- a/src/AutoTextControl.cpp +++ b/src/AutoTextControl.cpp @@ -27,26 +27,30 @@ static property_info sProperties[] = { }; AutoTextControl::AutoTextControl( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : BTextControl(name, label, text, msg, flags), fFilter(NULL), fCharLimit(0) { + : BTextControl(name, label, text, msg, flags), fFilter(NULL), fCharLimit(0) +{ SetFilter(new AutoTextControlFilter(this)); } -AutoTextControl::~AutoTextControl(void) { +AutoTextControl::~AutoTextControl(void) +{ if (Window()) Window()->RemoveCommonFilter(fFilter); delete fFilter; } -AutoTextControl::AutoTextControl(BMessage *data) : BTextControl(data) { - if (data->FindInt32("_charlimit", (int32 *)&fCharLimit) != B_OK) +AutoTextControl::AutoTextControl(BMessage* data) : BTextControl(data) +{ + if (data->FindInt32("_charlimit", (int32*)&fCharLimit) != B_OK) fCharLimit = 0; } -BArchivable * -AutoTextControl::Instantiate(BMessage *data) { +BArchivable* +AutoTextControl::Instantiate(BMessage* data) +{ if (validate_instantiation(data, "AutoTextControl")) return new AutoTextControl(data); @@ -54,7 +58,8 @@ AutoTextControl::Instantiate(BMessage *data) { } status_t -AutoTextControl::Archive(BMessage *data, bool deep) const { +AutoTextControl::Archive(BMessage* data, bool deep) const +{ status_t status = BTextControl::Archive(data, deep); if (status == B_OK) @@ -67,7 +72,8 @@ AutoTextControl::Archive(BMessage *data, bool deep) const { } status_t -AutoTextControl::GetSupportedSuites(BMessage *msg) { +AutoTextControl::GetSupportedSuites(BMessage* msg) +{ msg->AddString("suites", "suite/vnd.DW-autotextcontrol"); BPropertyInfo prop_info(sProperties); @@ -75,15 +81,17 @@ AutoTextControl::GetSupportedSuites(BMessage *msg) { return BTextControl::GetSupportedSuites(msg); } -BHandler * +BHandler* AutoTextControl::ResolveSpecifier( - BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property -) { + BMessage* msg, int32 index, BMessage* specifier, int32 form, const char* property +) +{ return BControl::ResolveSpecifier(msg, index, specifier, form, property); } void -AutoTextControl::AttachedToWindow(void) { +AutoTextControl::AttachedToWindow(void) +{ BTextControl::AttachedToWindow(); if (fFilter) { Window()->AddCommonFilter(fFilter); @@ -92,7 +100,8 @@ AutoTextControl::AttachedToWindow(void) { } void -AutoTextControl::DetachedFromWindow(void) { +AutoTextControl::DetachedFromWindow(void) +{ if (fFilter) { fFilter->SetMessenger(NULL); Window()->RemoveCommonFilter(fFilter); @@ -101,17 +110,20 @@ AutoTextControl::DetachedFromWindow(void) { } void -AutoTextControl::SetCharacterLimit(const uint32 &limit) { +AutoTextControl::SetCharacterLimit(const uint32& limit) +{ fCharLimit = limit; } uint32 -AutoTextControl::GetCharacterLimit(const uint32 &limit) { +AutoTextControl::GetCharacterLimit(const uint32& limit) +{ return fCharLimit; } void -AutoTextControl::SetFilter(AutoTextControlFilter *filter) { +AutoTextControl::SetFilter(AutoTextControlFilter* filter) +{ if (fFilter) { if (Window()) Window()->RemoveCommonFilter(fFilter); @@ -123,23 +135,26 @@ AutoTextControl::SetFilter(AutoTextControlFilter *filter) { Window()->AddCommonFilter(fFilter); } -AutoTextControlFilter::AutoTextControlFilter(AutoTextControl *box) +AutoTextControlFilter::AutoTextControlFilter(AutoTextControl* box) : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fBox(box), - fCurrentMessage(NULL), fMessenger(NULL) {} + fCurrentMessage(NULL), fMessenger(NULL) +{ +} AutoTextControlFilter::~AutoTextControlFilter(void) {} filter_result -AutoTextControlFilter::Filter(BMessage *msg, BHandler **target) { +AutoTextControlFilter::Filter(BMessage* msg, BHandler** target) +{ int32 rawchar, mod; msg->FindInt32("raw_char", &rawchar); msg->FindInt32("modifiers", &mod); - BView *view = dynamic_cast(*target); + BView* view = dynamic_cast(*target); if (!view || strcmp("_input_", view->Name()) != 0) return B_DISPATCH_MESSAGE; - AutoTextControl *text = dynamic_cast(view->Parent()); + AutoTextControl* text = dynamic_cast(view->Parent()); if (!text || text != fBox) return B_DISPATCH_MESSAGE; @@ -162,7 +177,8 @@ AutoTextControlFilter::Filter(BMessage *msg, BHandler **target) { } filter_result -AutoTextControlFilter::KeyFilter(const int32 &rawchar, const int32 &mod) { +AutoTextControlFilter::KeyFilter(const int32& rawchar, const int32& mod) +{ if (fBox) fBox->Invoke(); @@ -170,13 +186,15 @@ AutoTextControlFilter::KeyFilter(const int32 &rawchar, const int32 &mod) { } void -AutoTextControlFilter::SendMessage(BMessage *msg) { +AutoTextControlFilter::SendMessage(BMessage* msg) +{ if (fMessenger && msg) fMessenger->SendMessage(msg); } void -AutoTextControlFilter::SetMessenger(BMessenger *msgr) { +AutoTextControlFilter::SetMessenger(BMessenger* msgr) +{ if (fMessenger) delete fMessenger; fMessenger = msgr; diff --git a/src/AutoTextControl.h b/src/AutoTextControl.h index 3dd4d61..91f6792 100644 --- a/src/AutoTextControl.h +++ b/src/AutoTextControl.h @@ -23,17 +23,17 @@ class AutoTextControlFilter; class AutoTextControl : public BTextControl { public: AutoTextControl( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); - AutoTextControl(BMessage *data); - static BArchivable *Instantiate(BMessage *data); - virtual status_t Archive(BMessage *data, bool deep = true) const; + AutoTextControl(BMessage* data); + static BArchivable* Instantiate(BMessage* data); + virtual status_t Archive(BMessage* data, bool deep = true) const; - virtual status_t GetSupportedSuites(BMessage *msg); - virtual BHandler *ResolveSpecifier( - BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property + virtual status_t GetSupportedSuites(BMessage* msg); + virtual BHandler* ResolveSpecifier( + BMessage* msg, int32 index, BMessage* specifier, int32 form, const char* property ); virtual ~AutoTextControl(void); @@ -41,17 +41,17 @@ class AutoTextControl : public BTextControl { virtual void AttachedToWindow(void); virtual void DetachedFromWindow(void); - void SetFilter(AutoTextControlFilter *filter); + void SetFilter(AutoTextControlFilter* filter); - AutoTextControlFilter *GetFilter(void) { return fFilter; } + AutoTextControlFilter* GetFilter(void) { return fFilter; } - void SetCharacterLimit(const uint32 &limit); - uint32 GetCharacterLimit(const uint32 &limit); + void SetCharacterLimit(const uint32& limit); + uint32 GetCharacterLimit(const uint32& limit); private: friend class AutoTextControlFilter; - AutoTextControlFilter *fFilter; + AutoTextControlFilter* fFilter; uint32 fCharLimit; }; @@ -66,22 +66,22 @@ class AutoTextControl : public BTextControl { */ class AutoTextControlFilter : public BMessageFilter { public: - AutoTextControlFilter(AutoTextControl *checkview); + AutoTextControlFilter(AutoTextControl* checkview); ~AutoTextControlFilter(void); - virtual filter_result Filter(BMessage *msg, BHandler **target); - virtual filter_result KeyFilter(const int32 &key, const int32 &mod); + virtual filter_result Filter(BMessage* msg, BHandler** target); + virtual filter_result KeyFilter(const int32& key, const int32& mod); - AutoTextControl *TextControl(void) const { return fBox; } + AutoTextControl* TextControl(void) const { return fBox; } - BMessage *GetCurrentMessage(void) { return fCurrentMessage; } + BMessage* GetCurrentMessage(void) { return fCurrentMessage; } - void SendMessage(BMessage *msg); - void SetMessenger(BMessenger *msgr); + void SendMessage(BMessage* msg); + void SetMessenger(BMessenger* msgr); private: - AutoTextControl *fBox; - BMessage *fCurrentMessage; - BMessenger *fMessenger; + AutoTextControl* fBox; + BMessage* fCurrentMessage; + BMessenger* fMessenger; }; #endif diff --git a/src/Budget.cpp b/src/Budget.cpp index 7be35e4..5f0b5be 100644 --- a/src/Budget.cpp +++ b/src/Budget.cpp @@ -6,27 +6,30 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Budget" - BudgetEntry::BudgetEntry(void) { Set("", 0, BUDGET_MONTHLY, true); } BudgetEntry::BudgetEntry( - const char *nm, const Fixed &amt, const BudgetPeriod &per, const bool &isexp -) { + const char* nm, const Fixed& amt, const BudgetPeriod& per, const bool& isexp +) +{ Set(nm, amt, per, isexp); } -BudgetEntry::BudgetEntry(const BudgetEntry &from) { +BudgetEntry::BudgetEntry(const BudgetEntry& from) +{ Set(from.name.String(), from.amount, from.period, from.isexpense); } -BudgetEntry & -BudgetEntry::operator=(const BudgetEntry &from) { +BudgetEntry& +BudgetEntry::operator=(const BudgetEntry& from) +{ Set(from.name.String(), from.amount, from.period, from.isexpense); return *this; } void -BudgetEntry::Set(const char *nm, const Fixed &amt, const BudgetPeriod &per, const bool &isexp) { +BudgetEntry::Set(const char* nm, const Fixed& amt, const BudgetPeriod& per, const bool& isexp) +{ name = nm; amount = amt; period = per; @@ -34,7 +37,8 @@ BudgetEntry::Set(const char *nm, const Fixed &amt, const BudgetPeriod &per, cons } BString -BudgetPeriodToString(const BudgetPeriod &period) { +BudgetPeriodToString(const BudgetPeriod& period) +{ switch (period) { case BUDGET_MONTHLY: { return BString(B_TRANSLATE("Monthly")); @@ -60,7 +64,8 @@ BudgetPeriodToString(const BudgetPeriod &period) { } BudgetPeriod -StringToBudgetPeriod(const char *string) { +StringToBudgetPeriod(const char* string) +{ // TODO: Does this need translated? BString str(string); if (str.CountChars() < 1) diff --git a/src/Budget.h b/src/Budget.h index e76102b..58c6d7e 100644 --- a/src/Budget.h +++ b/src/Budget.h @@ -19,12 +19,12 @@ class BudgetEntry { public: BudgetEntry(void); BudgetEntry( - const char *name, const Fixed &amount, const BudgetPeriod &period, const bool &isexpense + const char* name, const Fixed& amount, const BudgetPeriod& period, const bool& isexpense ); - BudgetEntry(const BudgetEntry &from); - BudgetEntry &operator=(const BudgetEntry &from); + BudgetEntry(const BudgetEntry& from); + BudgetEntry& operator=(const BudgetEntry& from); void - Set(const char *name, const Fixed &amount, const BudgetPeriod &period, const bool &isexpense); + Set(const char* name, const Fixed& amount, const BudgetPeriod& period, const bool& isexpense); BString name; Fixed amount; @@ -33,8 +33,8 @@ class BudgetEntry { }; BString -BudgetPeriodToString(const BudgetPeriod &period); +BudgetPeriodToString(const BudgetPeriod& period); BudgetPeriod -StringToBudgetPeriod(const char *string); +StringToBudgetPeriod(const char* string); #endif diff --git a/src/BudgetReport.cpp b/src/BudgetReport.cpp index 0c9e9ba..9dc3f88 100644 --- a/src/BudgetReport.cpp +++ b/src/BudgetReport.cpp @@ -14,7 +14,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "BudgetReport" - /* Status: Different tack on the same task - go one row at a time by querying once for @@ -31,21 +30,23 @@ typedef enum { MAP_UNCHANGED = 0, MAP_CHANGED = 1, MAP_BAD_VALUE = -1 } map_stat map_status MapBudgetToSubtotal( - Fixed &fixed, const int &budgetperiod, const int &subtotal, const time_t &start, - const time_t &end + Fixed& fixed, const int& budgetperiod, const int& subtotal, const time_t& start, + const time_t& end ); void -ReportWindow::ComputeBudget(void) { +ReportWindow::ComputeBudget(void) +{ BObjectList timelist(20, true); // Calculate the number of columns and the starting date for each one if (fSubtotalMode == SUBTOTAL_NONE) { timelist.AddItem(new time_t(fStartDate)); timelist.AddItem(new time_t(fEndDate)); - } else { + } + else { for (time_t t = fStartDate; t < fEndDate;) { - time_t *item = new time_t(t); + time_t* item = new time_t(t); timelist.AddItem(item); switch (fSubtotalMode) { @@ -91,13 +92,14 @@ ReportWindow::ComputeBudget(void) { // The rest of the array will be initialized in the column-adding loop float maxwidths[count + 1]; maxwidths[0] = be_plain_font->StringWidth("Category") + 20; - fGridView->AddColumn(new BStringColumn(B_TRANSLATE("Category"), maxwidths[0], 10, 300, - B_TRUNCATE_END), 0); + fGridView->AddColumn( + new BStringColumn(B_TRANSLATE("Category"), maxwidths[0], 10, 300, B_TRUNCATE_END), 0 + ); int32 i; for (i = 0; i < timelist.CountItems() - 1; i++) { char columntitle[128]; - struct tm *timestruct = localtime((time_t *)timelist.ItemAt(i)); + struct tm* timestruct = localtime((time_t*)timelist.ItemAt(i)); BString formatstring; switch (fSubtotalMode) { @@ -128,7 +130,7 @@ ReportWindow::ComputeBudget(void) { } // Later this will iterate over all items in the category list - BStringItem *stringitem = (BStringItem *)fCategoryList->ItemAt(0); + BStringItem* stringitem = (BStringItem*)fCategoryList->ItemAt(0); if (!stringitem) { ShowBug("NULL category BStringItem in ReportWindow::ComputeBudget"); return; @@ -155,7 +157,7 @@ ReportWindow::ComputeBudget(void) { BString escaped = EscapeIllegalCharacters(stringitem->Text()); int32 accountcount = 0; for (i = 0; i < fAccountList->CountItems(); i++) { - AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + AccountItem* item = (AccountItem*)fAccountList->ItemAt(i); if (!item || !item->IsSelected()) continue; @@ -174,15 +176,15 @@ ReportWindow::ComputeBudget(void) { if (query.eof()) return; - BRow *budrow = new BRow(); + BRow* budrow = new BRow(); fGridView->AddRow(budrow); budrow->SetField(new BStringField(stringitem->Text()), 0); - BRow *amtrow = new BRow(); + BRow* amtrow = new BRow(); fGridView->AddRow(amtrow); amtrow->SetField(new BStringField(""), 0); - BRow *diffrow = new BRow(); + BRow* diffrow = new BRow(); fGridView->AddRow(diffrow); diffrow->SetField(new BStringField(""), 0); @@ -199,8 +201,8 @@ ReportWindow::ComputeBudget(void) { // This loop places values for a row into corresponding places in each grid for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { - time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); - time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + time_t subtotal_start = *((time_t*)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t*)timelist.ItemAt(subtotal_index + 1)); Fixed budamount = budgetentry.amount; map_status mapstatus = MapBudgetToSubtotal( @@ -240,7 +242,7 @@ ReportWindow::ComputeBudget(void) { budamount.AsLong() ); BString string; - BStringField *field; + BStringField* field; string << budamount.AbsoluteValue().AsFloat(); field = new BStringField(string.String()); @@ -265,9 +267,10 @@ ReportWindow::ComputeBudget(void) { map_status MapBudgetToSubtotal( - Fixed &fixed, const int &budgetperiod, const int &subtotal, const time_t &start, - const time_t &end -) { + Fixed& fixed, const int& budgetperiod, const int& subtotal, const time_t& start, + const time_t& end +) +{ // Converts a Fixed value into the proper period. When the value is actually // converted (Subtotal-Monthly + Budget-Weekly, etc.), MAP_CHANGED is returned and // the actual value is found in the Fixed parameter originally passed to it. diff --git a/src/BudgetWindow.cpp b/src/BudgetWindow.cpp index 25cc84a..f3cd177 100644 --- a/src/BudgetWindow.cpp +++ b/src/BudgetWindow.cpp @@ -21,7 +21,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "BudgetWindow" - enum { M_CATEGORIES_CHANGED = 'mccc', @@ -39,21 +38,22 @@ enum { }; extern int -compare_stringitem(const void *item1, const void *item2); +compare_stringitem(const void* item1, const void* item2); -BudgetWindow::BudgetWindow(const BRect &frame) +BudgetWindow::BudgetWindow(const BRect& frame) : BWindow( frame, B_TRANSLATE("Budget"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ), - fIncomeGrid(13, 0), fSpendingGrid(13, 0) { + fIncomeGrid(13, 0), fSpendingGrid(13, 0) +{ fBackView = new BView("background", B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f).SetInsets(0).Add(fBackView).End(); fBackView->SetViewColor(240, 240, 240); fBar = new BMenuBar("menubar"); - fBar->AddItem(new BMenuItem(B_TRANSLATE("Recalculate all"), - new BMessage(M_BUDGET_RECALCULATE))); + fBar->AddItem(new BMenuItem(B_TRANSLATE("Recalculate all"), new BMessage(M_BUDGET_RECALCULATE)) + ); fBar->AddItem(new BMenuItem(B_TRANSLATE("Set all to zero"), new BMessage(M_BUDGET_ZERO))); BuildBudgetSummary(); @@ -104,7 +104,8 @@ BudgetWindow::BudgetWindow(const BRect &frame) BudgetWindow::~BudgetWindow(void) {} void -BudgetWindow::MessageReceived(BMessage *msg) { +BudgetWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_SELECT_CATEGORY: { HandleCategorySelection(); @@ -124,7 +125,7 @@ BudgetWindow::MessageReceived(BMessage *msg) { str.Truncate(str.FindFirst(gDefaultLocale.CurrencyDecimal())); str.RemoveFirst(gDefaultLocale.CurrencySymbol()); - BRow *row = fCategoryList->CurrentSelection(); + BRow* row = fCategoryList->CurrentSelection(); if (!row) break; @@ -132,7 +133,7 @@ BudgetWindow::MessageReceived(BMessage *msg) { fCategoryList->UpdateRow(row); BudgetEntry entry; - gDatabase.GetBudgetEntry(((BStringField *)row->GetField(0))->String(), entry); + gDatabase.GetBudgetEntry(((BStringField*)row->GetField(0))->String(), entry); entry.amount = f; if (entry.isexpense) entry.amount.Invert(); @@ -191,8 +192,9 @@ BudgetWindow::MessageReceived(BMessage *msg) { } void -BudgetWindow::HandleCategorySelection(void) { - BRow *row = fCategoryList->CurrentSelection(); +BudgetWindow::HandleCategorySelection(void) +{ + BRow* row = fCategoryList->CurrentSelection(); if (!row) { fAmountBox->SetText(""); fMonthly->SetValue(B_CONTROL_ON); @@ -202,7 +204,7 @@ BudgetWindow::HandleCategorySelection(void) { } BudgetEntry entry; - BStringField *strfield = (BStringField *)row->GetField(0); + BStringField* strfield = (BStringField*)row->GetField(0); if (!gDatabase.GetBudgetEntry(strfield->String(), entry)) return; @@ -250,7 +252,8 @@ BudgetWindow::HandleCategorySelection(void) { } void -BudgetWindow::RefreshCategories(void) { +BudgetWindow::RefreshCategories(void) +{ fCategoryList->Clear(); fIncomeRow = new BRow(); fCategoryList->AddRow(fIncomeRow); @@ -271,7 +274,7 @@ BudgetWindow::RefreshCategories(void) { amount.SetPremultiplied(query.getInt64Field(1)); BudgetPeriod period = (BudgetPeriod)query.getIntField(2); - BRow *row = new BRow(); + BRow* row = new BRow(); if (query.getIntField(3) == 0) fCategoryList->AddRow(row, fIncomeRow); @@ -300,7 +303,8 @@ BudgetWindow::RefreshCategories(void) { } void -BudgetWindow::RefreshBudgetSummary(void) { +BudgetWindow::RefreshBudgetSummary(void) +{ Fixed itotal, stotal, mtotal, f; Fixed irowtotal, srowtotal, ttotal; for (int32 i = 0; i < 12; i++) { @@ -338,9 +342,9 @@ BudgetWindow::RefreshBudgetSummary(void) { stemp.RemoveFirst(gDefaultLocale.CurrencySymbol()); mtemp.RemoveFirst(gDefaultLocale.CurrencySymbol()); - BRow *irow = fBudgetSummary->RowAt(0); - BRow *srow = fBudgetSummary->RowAt(1); - BRow *mrow = fBudgetSummary->RowAt(2); + BRow* irow = fBudgetSummary->RowAt(0); + BRow* srow = fBudgetSummary->RowAt(1); + BRow* mrow = fBudgetSummary->RowAt(2); irow->SetField(new BStringField(itemp.String()), i + 1); srow->SetField(new BStringField(stemp.String()), i + 1); @@ -380,7 +384,8 @@ BudgetWindow::RefreshBudgetSummary(void) { } void -BudgetWindow::RefreshBudgetGrid(void) { +BudgetWindow::RefreshBudgetGrid(void) +{ fIncomeGrid.MakeEmpty(); fSpendingGrid.MakeEmpty(); @@ -395,7 +400,7 @@ BudgetWindow::RefreshBudgetGrid(void) { amount.SetPremultiplied(query.getInt64Field(1)); BudgetPeriod period = (BudgetPeriod)query.getIntField(2); - ReportGrid *grid = (amount.IsPositive()) ? &fIncomeGrid : &fSpendingGrid; + ReportGrid* grid = (amount.IsPositive()) ? &fIncomeGrid : &fSpendingGrid; int32 index = grid->CountItems(); grid->AddItem(); @@ -431,7 +436,8 @@ BudgetWindow::RefreshBudgetGrid(void) { } void -BudgetWindow::GenerateBudget(const bool &zero) { +BudgetWindow::GenerateBudget(const bool& zero) +{ // Generate a budget based on the last year's transactions ReportGrid income(1, 0), spending(1, 0); @@ -459,7 +465,8 @@ BudgetWindow::GenerateBudget(const bool &zero) { if (isexpense) { spending.AddItem(); spending.SetRowTitle(spending.CountItems() - 1, catname.String()); - } else { + } + else { income.AddItem(); income.SetRowTitle(income.CountItems() - 1, catname.String()); } @@ -481,7 +488,7 @@ BudgetWindow::GenerateBudget(const bool &zero) { if (!zero) { for (int32 j = 0; j < gDatabase.CountAccounts(); j++) { - Account *acc = gDatabase.AccountAt(j); + Account* acc = gDatabase.AccountAt(j); querystring = "select sum(amount) from account_"; querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(income.RowTitle(i)) << "' and date > " @@ -505,7 +512,7 @@ BudgetWindow::GenerateBudget(const bool &zero) { if (!zero) { for (int32 j = 0; j < gDatabase.CountAccounts(); j++) { - Account *acc = gDatabase.AccountAt(j); + Account* acc = gDatabase.AccountAt(j); querystring = "select sum(amount) from account_"; querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(spending.RowTitle(i)) << "';"; @@ -524,7 +531,8 @@ BudgetWindow::GenerateBudget(const bool &zero) { } void -BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { +BudgetWindow::CalcStats(const char* cat, Fixed& high, Fixed& low, Fixed& avg) +{ if (!cat) return; @@ -534,7 +542,7 @@ BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { // find the average amount for (int32 j = 0; j < gDatabase.CountAccounts(); j++) { - Account *acc = gDatabase.AccountAt(j); + Account* acc = gDatabase.AccountAt(j); querystring = "select sum(amount) from account_"; querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; @@ -548,7 +556,7 @@ BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { // find the highest amount cattotal = 0; for (int32 j = 0; j < gDatabase.CountAccounts(); j++) { - Account *acc = gDatabase.AccountAt(j); + Account* acc = gDatabase.AccountAt(j); querystring = "select max(amount) from account_"; querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; @@ -563,7 +571,7 @@ BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { // find the lowest amount cattotal = 0; for (int32 j = 0; j < gDatabase.CountAccounts(); j++) { - Account *acc = gDatabase.AccountAt(j); + Account* acc = gDatabase.AccountAt(j); querystring = "select min(amount) from account_"; querystring << acc->GetID() << " where category = '" << EscapeIllegalCharacters(cat) << "';"; @@ -577,13 +585,14 @@ BudgetWindow::CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg) { } void -BudgetWindow::SetPeriod(const BudgetPeriod &period) { - BRow *row = fCategoryList->CurrentSelection(); +BudgetWindow::SetPeriod(const BudgetPeriod& period) +{ + BRow* row = fCategoryList->CurrentSelection(); if (!row) return; BudgetEntry entry; - BStringField *strfield = (BStringField *)row->GetField(0); + BStringField* strfield = (BStringField*)row->GetField(0); if (!gDatabase.GetBudgetEntry(strfield->String(), entry)) return; @@ -645,7 +654,8 @@ BudgetWindow::SetPeriod(const BudgetPeriod &period) { } void -BudgetWindow::BuildStatsAndEditor(void) { +BudgetWindow::BuildStatsAndEditor(void) +{ // Add the category statistics BString temp; rgb_color white = {255, 255, 255, 255}; @@ -685,8 +695,8 @@ BudgetWindow::BuildStatsAndEditor(void) { fMonthly = new BRadioButton("monthoption", B_TRANSLATE("Monthly"), new BMessage(M_SET_PERIOD_MONTH)); - fWeekly = new BRadioButton("weekoption", B_TRANSLATE("Weekly"), - new BMessage(M_SET_PERIOD_WEEK)); + fWeekly = + new BRadioButton("weekoption", B_TRANSLATE("Weekly"), new BMessage(M_SET_PERIOD_WEEK)); fQuarterly = new BRadioButton( "quarteroption", B_TRANSLATE("Quarterly"), new BMessage(M_SET_PERIOD_QUARTER) ); @@ -703,7 +713,8 @@ BudgetWindow::BuildStatsAndEditor(void) { } void -BudgetWindow::BuildBudgetSummary(void) { +BudgetWindow::BuildBudgetSummary(void) +{ rgb_color white = {255, 255, 255, 255}; fSummaryIncomeRow = new BRow(); @@ -715,8 +726,8 @@ BudgetWindow::BuildBudgetSummary(void) { fBudgetSummary->SetSortingEnabled(false); fBudgetSummary->AddColumn( new BStringColumn( - B_TRANSLATE("Summary"), fBudgetSummary->StringWidth(B_TRANSLATE("Spending")) + 20, 10, 300, - B_TRUNCATE_END + B_TRANSLATE("Summary"), fBudgetSummary->StringWidth(B_TRANSLATE("Spending")) + 20, 10, + 300, B_TRUNCATE_END ), 0 ); @@ -773,7 +784,8 @@ BudgetWindow::BuildBudgetSummary(void) { } void -BudgetWindow::BuildCategoryList(void) { +BudgetWindow::BuildCategoryList(void) +{ rgb_color white = {255, 255, 255, 255}; fCategoryList = @@ -782,8 +794,8 @@ BudgetWindow::BuildCategoryList(void) { fCategoryList->SetSelectionMessage(new BMessage(M_SELECT_CATEGORY)); fCategoryList->AddColumn( new BStringColumn( - B_TRANSLATE("Category"), fCategoryList->StringWidth(B_TRANSLATE("Category")) + 20, 10, 300, - B_TRUNCATE_END + B_TRANSLATE("Category"), fCategoryList->StringWidth(B_TRANSLATE("Category")) + 20, 10, + 300, B_TRUNCATE_END ), 0 ); diff --git a/src/BudgetWindow.h b/src/BudgetWindow.h index 25b1d51..2951c5a 100644 --- a/src/BudgetWindow.h +++ b/src/BudgetWindow.h @@ -22,9 +22,9 @@ class CurrencyBox; class BudgetWindow : public BWindow { public: - BudgetWindow(const BRect &frame); + BudgetWindow(const BRect& frame); ~BudgetWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); private: void BuildStatsAndEditor(void); @@ -34,26 +34,26 @@ class BudgetWindow : public BWindow { void RefreshCategories(void); void RefreshBudgetSummary(void); void RefreshBudgetGrid(void); - void GenerateBudget(const bool &zero); - void CalcStats(const char *cat, Fixed &high, Fixed &low, Fixed &avg); + void GenerateBudget(const bool& zero); + void CalcStats(const char* cat, Fixed& high, Fixed& low, Fixed& avg); void HandleCategorySelection(void); - void SetPeriod(const BudgetPeriod &period); + void SetPeriod(const BudgetPeriod& period); - BMenuBar *fBar; - BView *fBackView; + BMenuBar* fBar; + BView* fBackView; - BColumnListView *fCategoryList; + BColumnListView* fCategoryList; BRow *fIncomeRow, *fSpendingRow; - BColumnListView *fBudgetSummary; + BColumnListView* fBudgetSummary; BRow *fSummaryIncomeRow, *fSummarySpendingRow, *fSummaryTotalRow; - BBox *fCatBox; - CurrencyBox *fAmountBox; - BStringView *fAmountLabel; + BBox* fCatBox; + CurrencyBox* fAmountBox; + BStringView* fAmountLabel; BRadioButton *fMonthly, *fWeekly, *fQuarterly, *fAnnually; - BColumnListView *fCatStat; + BColumnListView* fCatStat; BRow *fStatAverageRow, *fStatHighestRow, *fStatLowestRow; ReportGrid fIncomeGrid, fSpendingGrid; diff --git a/src/CBLocale.h b/src/CBLocale.h index 845da59..99b13a2 100644 --- a/src/CBLocale.h +++ b/src/CBLocale.h @@ -15,47 +15,47 @@ class Locale { Locale(void); ~Locale(void); - bool operator==(const Locale &other) const; - bool operator!=(const Locale &other) const; + bool operator==(const Locale& other) const; + bool operator!=(const Locale& other) const; - void Flatten(BFile *file); + void Flatten(BFile* file); - status_t CurrencyToString(const Fixed &amount, BString &string); - status_t DateToString(time_t date, BString &string); - status_t StringToCurrency(const char *string, Fixed &amount); - status_t PremultipliedStringToCurrency(const char *string, Fixed &amount); - status_t StringToDate(const char *instring, time_t &date); - void NumberToCurrency(const Fixed &number, BString &string); + status_t CurrencyToString(const Fixed& amount, BString& string); + status_t DateToString(time_t date, BString& string); + status_t StringToCurrency(const char* string, Fixed& amount); + status_t PremultipliedStringToCurrency(const char* string, Fixed& amount); + status_t StringToDate(const char* instring, time_t& date); + void NumberToCurrency(const Fixed& number, BString& string); - void SetDateFormat(const date_format &format); + void SetDateFormat(const date_format& format); date_format DateFormat(void) const { return fDateFormat; } - void SetCurrencySymbol(const char *symbol); + void SetCurrencySymbol(const char* symbol); - const char *CurrencySymbol(void) const { return fCurrencySymbol.String(); } + const char* CurrencySymbol(void) const { return fCurrencySymbol.String(); } - void SetCurrencySeparator(const char *symbol); + void SetCurrencySeparator(const char* symbol); - const char *CurrencySeparator(void) const { return fCurrencySeparator.String(); } + const char* CurrencySeparator(void) const { return fCurrencySeparator.String(); } - void SetCurrencyDecimal(const char *symbol); + void SetCurrencyDecimal(const char* symbol); - const char *CurrencyDecimal(void) const { return fCurrencyDecimal.String(); } + const char* CurrencyDecimal(void) const { return fCurrencyDecimal.String(); } - void SetCurrencySymbolPrefix(const bool &value); + void SetCurrencySymbolPrefix(const bool& value); bool IsCurrencySymbolPrefix(void) const { return fPrefixSymbol; } - void SetCurrencyDecimalPlace(const uint8 &place); + void SetCurrencyDecimalPlace(const uint8& place); uint8 CurrencyDecimalPlace(void) const { return fCurrencyDecimalPlace; } - void SetDateSeparator(const char *symbol); + void SetDateSeparator(const char* symbol); - const char *DateSeparator(void) const { return fDateSeparator.String(); } + const char* DateSeparator(void) const { return fDateSeparator.String(); } - void SetDST(const bool &value); + void SetDST(const bool& value); bool UseDST(void) const { return fUseDST; } @@ -63,8 +63,8 @@ class Locale { friend class CapitalBeParser; void SetDefaults(void); - status_t ConstructDateStringMDY(const char *in, BString &out); - status_t ConstructDateStringDMY(const char *in, BString &out); + status_t ConstructDateStringMDY(const char* in, BString& out); + status_t ConstructDateStringDMY(const char* in, BString& out); // Like BeFinancial, we just use two different date formats: mmddyyyy (0) and // ddmmyyyy (1) @@ -79,18 +79,18 @@ class Locale { }; void -ShowAlert(const char *header, const char *message, alert_type type = B_INFO_ALERT); +ShowAlert(const char* header, const char* message, alert_type type = B_INFO_ALERT); void -ShowBug(const char *string); +ShowBug(const char* string); void -GetVersionString(BString &string); +GetVersionString(BString& string); void -CapitalizeEachWord(BString &string); -const char * +CapitalizeEachWord(BString& string); +const char* GetCurrencyOnlyMask(void); -const char * +const char* GetDateOnlyMask(void); void -IllegalCharsToEntities(BString *string); +IllegalCharsToEntities(BString* string); #endif diff --git a/src/CashFlowReport.cpp b/src/CashFlowReport.cpp index 2059c74..164b251 100644 --- a/src/CashFlowReport.cpp +++ b/src/CashFlowReport.cpp @@ -15,14 +15,14 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CashFlowReport" - void -ReportWindow::ComputeCashFlow(void) { +ReportWindow::ComputeCashFlow(void) +{ // Calculate the number of columns and the starting date for each one BObjectList timelist(20, true); for (time_t t = fStartDate; t < fEndDate;) { - time_t *item = new time_t(t); + time_t* item = new time_t(t); timelist.AddItem(item); switch (fSubtotalMode) { @@ -50,7 +50,7 @@ ReportWindow::ComputeCashFlow(void) { BString longestname(""); for (int32 i = 0; i < fCategoryList->CountItems(); i++) { - BStringItem *catitem = (BStringItem *)fCategoryList->ItemAt(i); + BStringItem* catitem = (BStringItem*)fCategoryList->ItemAt(i); if (!catitem || !catitem->IsSelected() || strlen(catitem->Text()) < 1) continue; @@ -82,13 +82,13 @@ ReportWindow::ComputeCashFlow(void) { int32 count = timelist.CountItems() - 1; for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { - time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); - time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + time_t subtotal_start = *((time_t*)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t*)timelist.ItemAt(subtotal_index + 1)); accountcount = 0; command = expcommand = ""; for (int32 i = 0; i < fAccountList->CountItems(); i++) { - AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + AccountItem* item = (AccountItem*)fAccountList->ItemAt(i); if (!item || !item->IsSelected()) continue; @@ -128,7 +128,8 @@ ReportWindow::ComputeCashFlow(void) { incomegrid.SetRowTitle(incomegrid.CountItems() - 1, catitem->Text()); incomegrid.SetValue(subtotal_index, incomegrid.CountItems() - 1, inctotal); } - } else + } + else incomegrid.SetValue(subtotal_index, incomegrid.CountItems() - 1, Fixed()); // query for spending in this category @@ -147,7 +148,8 @@ ReportWindow::ComputeCashFlow(void) { expensegrid.SetRowTitle(expensegrid.CountItems() - 1, catitem->Text()); expensegrid.SetValue(subtotal_index, expensegrid.CountItems() - 1, exptotal); } - } else + } + else expensegrid.SetValue(subtotal_index, expensegrid.CountItems() - 1, Fixed()); query.finalize(); @@ -157,7 +159,7 @@ ReportWindow::ComputeCashFlow(void) { expensegrid.Sort(); // Now that we have all the data, we need to set up the rows and columns for the report grid - BColumn *col = new BStringColumn( + BColumn* col = new BStringColumn( B_TRANSLATE("Category"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, B_TRUNCATE_END ); @@ -166,7 +168,7 @@ ReportWindow::ComputeCashFlow(void) { int32 i; for (i = 0; i < timelist.CountItems() - 1; i++) { char columntitle[128]; - struct tm *timestruct = localtime((time_t *)timelist.ItemAt(i)); + struct tm* timestruct = localtime((time_t*)timelist.ItemAt(i)); BString formatstring; switch (fSubtotalMode) { @@ -196,7 +198,7 @@ ReportWindow::ComputeCashFlow(void) { } fGridView->AddRow(new BRow()); - BRow *titlerow = new BRow(); + BRow* titlerow = new BRow(); fGridView->AddRow(titlerow); titlerow->SetField(new BStringField(B_TRANSLATE("Income")), 0); fGridView->AddRow(new BRow()); @@ -204,10 +206,10 @@ ReportWindow::ComputeCashFlow(void) { if (!fGridView->IsHidden()) { // Now that the grid is set up, start adding data to the grid for (i = 0; i < incomegrid.CountItems(); i++) { - BRow *row = new BRow(); + BRow* row = new BRow(); fGridView->AddRow(row); - BStringField *catname = new BStringField(incomegrid.RowTitle(i)); + BStringField* catname = new BStringField(incomegrid.RowTitle(i)); row->SetField(catname, 0); for (int32 columnindex = 0; columnindex < timelist.CountItems(); columnindex++) { @@ -217,7 +219,7 @@ ReportWindow::ComputeCashFlow(void) { incomegrid.ValueAt(columnindex, i, f); gCurrentLocale.CurrencyToString(f, temp); - BStringField *amountfield = new BStringField(temp.String()); + BStringField* amountfield = new BStringField(temp.String()); row->SetField(amountfield, columnindex + 1); } } @@ -229,10 +231,10 @@ ReportWindow::ComputeCashFlow(void) { fGridView->AddRow(new BRow()); for (i = 0; i < expensegrid.CountItems(); i++) { - BRow *row = new BRow(); + BRow* row = new BRow(); fGridView->AddRow(row); - BStringField *catname = new BStringField(expensegrid.RowTitle(i)); + BStringField* catname = new BStringField(expensegrid.RowTitle(i)); row->SetField(catname, 0); for (int32 columnindex = 0; columnindex < timelist.CountItems(); columnindex++) { @@ -242,11 +244,12 @@ ReportWindow::ComputeCashFlow(void) { expensegrid.ValueAt(columnindex, i, f); gCurrentLocale.CurrencyToString(f, temp); - BStringField *amountfield = new BStringField(temp.String()); + BStringField* amountfield = new BStringField(temp.String()); row->SetField(amountfield, columnindex + 1); } } - } else { + } + else { // Graph view is showing. Render the graph // TODO: Implement as line graph diff --git a/src/Category.cpp b/src/Category.cpp index 835f5ba..ea7a847 100644 --- a/src/Category.cpp +++ b/src/Category.cpp @@ -5,16 +5,18 @@ #include #include -Category::Category(const char *string, const Fixed &fixed, const char *memo) { +Category::Category(const char* string, const Fixed& fixed, const char* memo) +{ fList = new BObjectList(20, true); if (string) fList->AddItem(new CatItem(string, fixed, memo)); } -Category::Category(const Category &from) { +Category::Category(const Category& from) +{ fList = new BObjectList(20, true); for (int32 i = 0; i < from.fList->CountItems(); i++) { - CatItem *item = from.fList->ItemAt(i); + CatItem* item = from.fList->ItemAt(i); if (item) fList->AddItem(new CatItem(*item)); } @@ -23,56 +25,63 @@ Category::Category(const Category &from) { Category::~Category(void) { delete fList; } void -Category::SetNameAt(const int32 &index, const char *string) { - CatItem *item = fList->ItemAt(index); +Category::SetNameAt(const int32& index, const char* string) +{ + CatItem* item = fList->ItemAt(index); if (item) item->string = string; } void -Category::SetAmountAt(const int32 &index, const Fixed &fixed) { - CatItem *item = fList->ItemAt(index); +Category::SetAmountAt(const int32& index, const Fixed& fixed) +{ + CatItem* item = fList->ItemAt(index); if (item) item->amount = fixed; } void -Category::SetMemoAt(const int32 &index, const char *string) { - CatItem *item = fList->ItemAt(index); +Category::SetMemoAt(const int32& index, const char* string) +{ + CatItem* item = fList->ItemAt(index); if (item) item->memo = string; } -const char * -Category::NameAt(const int32 &index) const { - CatItem *item = fList->ItemAt(index); +const char* +Category::NameAt(const int32& index) const +{ + CatItem* item = fList->ItemAt(index); return item ? item->string.String() : NULL; } Fixed -Category::AmountAt(const int32 &index) const { - CatItem *item = fList->ItemAt(index); +Category::AmountAt(const int32& index) const +{ + CatItem* item = fList->ItemAt(index); return item ? item->amount : Fixed(0); } -const char * -Category::MemoAt(const int32 &index) const { - CatItem *item = fList->ItemAt(index); +const char* +Category::MemoAt(const int32& index) const +{ + CatItem* item = fList->ItemAt(index); return item ? item->memo.String() : NULL; } bool -Category::AddItem(const char *name, const Fixed &amount, const char *memo) { +Category::AddItem(const char* name, const Fixed& amount, const char* memo) +{ if (!name) return false; - CatItem *item = fList->ItemAt(0); + CatItem* item = fList->ItemAt(0); if (item) { if (item->string.CountChars() == 0) { fList->RemoveItemAt(0L); @@ -84,10 +93,11 @@ Category::AddItem(const char *name, const Fixed &amount, const char *memo) { } bool -Category::HasItem(const char *name) { +Category::HasItem(const char* name) +{ // Prevent duplicates for (int32 i = 0; i < fList->CountItems(); i++) { - CatItem *data = fList->ItemAt(i); + CatItem* data = fList->ItemAt(i); if (data->string == name) return true; } @@ -95,14 +105,15 @@ Category::HasItem(const char *name) { } bool -Category::RemoveItem(const char *name) { +Category::RemoveItem(const char* name) +{ if (!name) return false; // Find item and remove - CatItem *item = NULL; + CatItem* item = NULL; for (int32 i = 0; i < fList->CountItems(); i++) { - CatItem *data = fList->ItemAt(i); + CatItem* data = fList->ItemAt(i); if (data->string == name) { item = data; break; @@ -115,8 +126,9 @@ Category::RemoveItem(const char *name) { } bool -Category::RemoveItem(const int32 &index) { - CatItem *item = fList->RemoveItemAt(index); +Category::RemoveItem(const int32& index) +{ + CatItem* item = fList->RemoveItemAt(index); if (!item) return false; @@ -125,11 +137,12 @@ Category::RemoveItem(const int32 &index) { } void -Category::Flatten(BFile *file) { +Category::Flatten(BFile* file) +{ BString str("\t\t\n"); for (int32 i = 0; i < fList->CountItems(); i++) { - CatItem *data = fList->ItemAt(i); + CatItem* data = fList->ItemAt(i); BString temp(data->string.String()); IllegalCharsToEntities(&temp); str << "\t\t\tamount.AsFixed() @@ -141,11 +154,12 @@ Category::Flatten(BFile *file) { } void -Category::PrintToStream(void) const { +Category::PrintToStream(void) const +{ BString str(" "); for (int32 i = 0; i < fList->CountItems(); i++) { - CatItem *data = fList->ItemAt(i); + CatItem* data = fList->ItemAt(i); str << data->string.String() << " " << data->amount.AsFixed(); if (i == fList->CountItems() - 1) str << " "; @@ -156,35 +170,40 @@ Category::PrintToStream(void) const { printf(str.String()); } -Category & -Category::operator=(const Category &from) { +Category& +Category::operator=(const Category& from) +{ fList->MakeEmpty(); for (int32 i = 0; i < from.CountItems(); i++) { - CatItem *item = from.fList->ItemAt(i); + CatItem* item = from.fList->ItemAt(i); fList->AddItem(new CatItem(item->string.String(), item->amount, item->memo.String())); } return *this; } void -Category::MakeEmpty(void) { +Category::MakeEmpty(void) +{ fList->MakeEmpty(); } void -Category::Sort(void) { +Category::Sort(void) +{ fList->SortItems(CompareCatItem); } int -Category::CompareCatItem(const CatItem *item1, const CatItem *item2) { +Category::CompareCatItem(const CatItem* item1, const CatItem* item2) +{ if (!item1) { if (item2) return 1; else return 0; - } else if (!item2) { + } + else if (!item2) { if (item1) return -1; else diff --git a/src/Category.h b/src/Category.h index 19eaaa6..2ccb516 100644 --- a/src/Category.h +++ b/src/Category.h @@ -8,42 +8,44 @@ class Category { public: - Category(const char *string = NULL, const Fixed &fixed = 0, const char *memo = NULL); - Category(const Category &from); + Category(const char* string = NULL, const Fixed& fixed = 0, const char* memo = NULL); + Category(const Category& from); ~Category(void); - void SetNameAt(const int32 &index, const char *string); - void SetAmountAt(const int32 &index, const Fixed &fixed); - void SetMemoAt(const int32 &index, const char *string); + void SetNameAt(const int32& index, const char* string); + void SetAmountAt(const int32& index, const Fixed& fixed); + void SetMemoAt(const int32& index, const char* string); - const char *NameAt(const int32 &index) const; - const char *MemoAt(const int32 &index) const; - Fixed AmountAt(const int32 &index) const; + const char* NameAt(const int32& index) const; + const char* MemoAt(const int32& index) const; + Fixed AmountAt(const int32& index) const; - bool AddItem(const char *name, const Fixed &amount, const char *memo = NULL); - bool HasItem(const char *name); - bool RemoveItem(const char *name); - bool RemoveItem(const int32 &index); + bool AddItem(const char* name, const Fixed& amount, const char* memo = NULL); + bool HasItem(const char* name); + bool RemoveItem(const char* name); + bool RemoveItem(const int32& index); int32 CountItems(void) const { return fList->CountItems(); } - void Flatten(BFile *file); + void Flatten(BFile* file); void PrintToStream(void) const; void Sort(void); - Category &operator=(const Category &from); + Category& operator=(const Category& from); void MakeEmpty(void); private: class CatItem { public: - CatItem(const char *str = NULL, const Fixed &fixed = 0, const char *str2 = NULL) { + CatItem(const char* str = NULL, const Fixed& fixed = 0, const char* str2 = NULL) + { string = str; amount = fixed; memo = str2; } - CatItem(const CatItem &from) { + CatItem(const CatItem& from) + { string = from.string; amount = from.amount; memo = from.memo; @@ -54,8 +56,8 @@ class Category { BString memo; }; - static int CompareCatItem(const CatItem *item1, const CatItem *item2); - BObjectList *fList; + static int CompareCatItem(const CatItem* item1, const CatItem* item2); + BObjectList* fList; }; #endif diff --git a/src/CategoryBox.cpp b/src/CategoryBox.cpp index 3557346..bf11eba 100644 --- a/src/CategoryBox.cpp +++ b/src/CategoryBox.cpp @@ -4,10 +4,11 @@ #include "MsgDefs.h" #include "TimeSupport.h" -CategoryBoxFilter::CategoryBoxFilter(CategoryBox *box) : AutoTextControlFilter(box) {} +CategoryBoxFilter::CategoryBoxFilter(CategoryBox* box) : AutoTextControlFilter(box) {} filter_result -CategoryBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +CategoryBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. if (key == B_TAB) { if (mod & B_SHIFT_KEY) @@ -31,7 +32,7 @@ CategoryBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (!acc) return B_DISPATCH_MESSAGE; @@ -59,17 +60,19 @@ CategoryBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { } CategoryBox::CategoryBox( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : AutoTextControl(name, label, text, msg, flags) { + : AutoTextControl(name, label, text, msg, flags) +{ SetFilter(new CategoryBoxFilter(this)); SetCharacterLimit(32); } bool -CategoryBox::Validate(void) { +CategoryBox::Validate(void) +{ if (strlen(Text()) < 1) { - DAlert *alert = new DAlert( + DAlert* alert = new DAlert( "Category is missing.", "Do you want to add this transaction " "without a category?", diff --git a/src/CategoryBox.h b/src/CategoryBox.h index 6666dfd..c44eb6d 100644 --- a/src/CategoryBox.h +++ b/src/CategoryBox.h @@ -9,14 +9,14 @@ enum { M_CATEGORY_AUTOCOMPLETE = 'cata' }; class CategoryBoxFilter : public AutoTextControlFilter { public: - CategoryBoxFilter(CategoryBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + CategoryBoxFilter(CategoryBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class CategoryBox : public AutoTextControl { public: CategoryBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); diff --git a/src/CategoryWindow.cpp b/src/CategoryWindow.cpp index ca8fb84..019369b 100644 --- a/src/CategoryWindow.cpp +++ b/src/CategoryWindow.cpp @@ -23,7 +23,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CategoryWindow" - enum { M_SHOW_ADD_WINDOW = 'shaw', M_SHOW_REMOVE_WINDOW, @@ -36,20 +35,20 @@ enum { class CategoryItem : public BStringItem { public: - CategoryItem(const BString &name); - void DrawItem(BView *owner, BRect frame, bool complete = false); + CategoryItem(const BString& name); + void DrawItem(BView* owner, BRect frame, bool complete = false); }; class CategoryView : public BView { public: - CategoryView(const char *name, const int32 &flags); + CategoryView(const char* name, const int32& flags); void AttachedToWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); private: float RefreshCategoryList(void); - BOutlineListView *fListView; + BOutlineListView* fListView; BButton *fAddButton, *fRemoveButton, *fEditButton; @@ -59,52 +58,53 @@ class CategoryView : public BView { class CategoryInputWindow : public BWindow { public: - CategoryInputWindow(const BRect &frame, BView *target); - void MessageReceived(BMessage *msg); + CategoryInputWindow(const BRect& frame, BView* target); + void MessageReceived(BMessage* msg); private: - AutoTextControl *fNameBox; + AutoTextControl* fNameBox; BButton *fOKButton, *fCancelButton; - BCheckBox *fExpenseBox; - BView *fTarget; + BCheckBox* fExpenseBox; + BView* fTarget; }; class CategoryEditWindow : public BWindow { public: - CategoryEditWindow(const BRect &frame, const char *oldname, BView *target); - void MessageReceived(BMessage *msg); + CategoryEditWindow(const BRect& frame, const char* oldname, BView* target); + void MessageReceived(BMessage* msg); private: - AutoTextControl *fNameBox; + AutoTextControl* fNameBox; BButton *fOKButton, *fCancelButton; BString fOldName; - BView *fTarget; + BView* fTarget; }; class CategoryRemoveWindow : public BWindow { public: - CategoryRemoveWindow(const BRect &frame, const char *from, BView *target); - void MessageReceived(BMessage *msg); + CategoryRemoveWindow(const BRect& frame, const char* from, BView* target); + void MessageReceived(BMessage* msg); void FrameResized(float w, float h); private: - BOutlineListView *fListView; + BOutlineListView* fListView; CategoryItem *fIncomeItem, *fSpendingItem; - BTextView *fDirections; + BTextView* fDirections; BButton *fOKButton, *fCancelButton; - BView *fTarget; - BScrollView *fScrollView; + BView* fTarget; + BScrollView* fScrollView; }; -CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, flags) { +CategoryView::CategoryView(const char* name, const int32& flags) : BView(name, flags) +{ BString temp; SetViewColor(240, 240, 240); @@ -123,7 +123,7 @@ CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, f "categorylist", B_SINGLE_SELECTION_LIST, B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE | B_FULL_UPDATE_ON_RESIZE ); - BScrollView *sv = new BScrollView("scrollview", fListView, 0, false, true); + BScrollView* sv = new BScrollView("scrollview", fListView, 0, false, true); fIncomeItem = new CategoryItem(B_TRANSLATE("Income")); fSpendingItem = new CategoryItem(B_TRANSLATE("Spending")); @@ -145,7 +145,8 @@ CategoryView::CategoryView(const char *name, const int32 &flags) : BView(name, f } void -CategoryView::AttachedToWindow(void) { +CategoryView::AttachedToWindow(void) +{ fListView->SetTarget(this); fEditButton->SetTarget(this); fAddButton->SetTarget(this); @@ -157,11 +158,12 @@ CategoryView::AttachedToWindow(void) { } void -CategoryView::MessageReceived(BMessage *msg) { +CategoryView::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_SHOW_ADD_WINDOW: { BRect r(Window()->Frame()); - CategoryInputWindow *catwin = new CategoryInputWindow(BRect(100, 100, 300, 225), this); + CategoryInputWindow* catwin = new CategoryInputWindow(BRect(100, 100, 300, 225), this); catwin->MoveTo( r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) @@ -171,13 +173,13 @@ CategoryView::MessageReceived(BMessage *msg) { } case M_SHOW_REMOVE_WINDOW: { int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + CategoryItem* item = (CategoryItem*)fListView->ItemAt(index); if (!item || item == fIncomeItem || item == fSpendingItem) break; BRect r(Window()->Frame()); - CategoryRemoveWindow *catwin = new CategoryRemoveWindow(r, item->Text(), this); + CategoryRemoveWindow* catwin = new CategoryRemoveWindow(r, item->Text(), this); catwin->MoveTo( r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) @@ -187,13 +189,13 @@ CategoryView::MessageReceived(BMessage *msg) { } case M_SHOW_EDIT_WINDOW: { int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + CategoryItem* item = (CategoryItem*)fListView->ItemAt(index); if (!item || item == fIncomeItem || item == fSpendingItem) break; BRect r(Window()->Frame()); - CategoryEditWindow *catwin = new CategoryEditWindow(r, item->Text(), this); + CategoryEditWindow* catwin = new CategoryEditWindow(r, item->Text(), this); catwin->MoveTo( r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) @@ -207,13 +209,14 @@ CategoryView::MessageReceived(BMessage *msg) { if (msg->FindString("name", &name) != B_OK || msg->FindBool("expense", &expense) != B_OK) break; - if (name.ICompare(B_TRANSLATE("Income")) == 0 || name.ICompare(B_TRANSLATE("Spending")) == 0 || + if (name.ICompare(B_TRANSLATE("Income")) == 0 || + name.ICompare(B_TRANSLATE("Spending")) == 0 || name.ICompare(B_TRANSLATE("Split")) == 0) { ShowAlert( B_TRANSLATE("Can't use this category name"), B_TRANSLATE("CapitalBe uses the words 'Income','Spending', and 'Split' " - "for managing categories, so you can't use them as category names. " - "Please choose a different name for your new category.") + "for managing categories, so you can't use them as category names. " + "Please choose a different name for your new category.") ); break; } @@ -228,7 +231,7 @@ CategoryView::MessageReceived(BMessage *msg) { break; int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + CategoryItem* item = (CategoryItem*)fListView->ItemAt(index); if (!item || item == fIncomeItem || item == fSpendingItem) break; @@ -246,7 +249,7 @@ CategoryView::MessageReceived(BMessage *msg) { break; int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + CategoryItem* item = (CategoryItem*)fListView->ItemAt(index); if (!item || item == fIncomeItem || item == fSpendingItem) break; @@ -264,7 +267,8 @@ CategoryView::MessageReceived(BMessage *msg) { } float -CategoryView::RefreshCategoryList(void) { +CategoryView::RefreshCategoryList(void) +{ if (fListView->CountItems() > 0) { if (fListView->HasItem(fIncomeItem)) fListView->RemoveItem(fIncomeItem); @@ -281,7 +285,8 @@ CategoryView::RefreshCategoryList(void) { if (strlen(B_TRANSLATE("Income")) > strlen(B_TRANSLATE("Spending"))) { maxchars = strlen(B_TRANSLATE("Income")); maxlength = StringWidth(B_TRANSLATE("Income")); - } else { + } + else { maxchars = strlen(B_TRANSLATE("Spending")); maxlength = StringWidth(B_TRANSLATE("Spending")); } @@ -313,14 +318,15 @@ CategoryView::RefreshCategoryList(void) { return maxlength; } -CategoryWindow::CategoryWindow(const BRect &frame) +CategoryWindow::CategoryWindow(const BRect& frame) : BWindow( frame, B_TRANSLATE("Categories"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS - ) { + ) +{ AddCommonFilter(new EscapeCancelFilter); - CategoryView *view = new CategoryView("categoryview", B_WILL_DRAW); + CategoryView* view = new CategoryView("categoryview", B_WILL_DRAW); AddShortcut('A', B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW), view); AddShortcut('R', B_COMMAND_KEY, new BMessage(M_REMOVE_CATEGORY), view); @@ -328,14 +334,16 @@ CategoryWindow::CategoryWindow(const BRect &frame) BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); } -CategoryItem::CategoryItem(const BString &name) : BStringItem(name.String()) {} +CategoryItem::CategoryItem(const BString& name) : BStringItem(name.String()) {} void -CategoryItem::DrawItem(BView *owner, BRect frame, bool complete) { +CategoryItem::DrawItem(BView* owner, BRect frame, bool complete) +{ if (IsSelected()) { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); - } else { + } + else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); } @@ -353,18 +361,19 @@ CategoryItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->ConstrainClippingRegion(NULL); } -CategoryInputWindow::CategoryInputWindow(const BRect &frame, BView *target) +CategoryInputWindow::CategoryInputWindow(const BRect& frame, BView* target) : BWindow( frame, B_TRANSLATE("Add Category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_V_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fTarget(target) { + fTarget(target) +{ BString temp; AddCommonFilter(new EscapeCancelFilter); AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *view = new BView("background", B_WILL_DRAW); + BView* view = new BView("background", B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(240, 240, 240); @@ -396,13 +405,15 @@ CategoryInputWindow::CategoryInputWindow(const BRect &frame, BView *target) } void -CategoryInputWindow::MessageReceived(BMessage *msg) { +CategoryInputWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_NAME_CHANGED: { if (strlen(fNameBox->Text()) > 0) { if (!fOKButton->IsEnabled()) fOKButton->SetEnabled(true); - } else { + } + else { if (fOKButton->IsEnabled()) fOKButton->SetEnabled(false); } @@ -422,17 +433,18 @@ CategoryInputWindow::MessageReceived(BMessage *msg) { } } -CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, BView *target) +CategoryRemoveWindow::CategoryRemoveWindow(const BRect& frame, const char* from, BView* target) : BWindow( frame, B_TRANSLATE("Remove category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fTarget(target) { + fTarget(target) +{ rgb_color backcolor = {240, 240, 240, 255}; AddCommonFilter(new EscapeCancelFilter); AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); + BView* view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(backcolor); @@ -441,7 +453,7 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, BString directions( B_TRANSLATE("Please choose a new category for all transactions currently in the " - "%%CATEGORY_NAME%% category.") + "%%CATEGORY_NAME%% category.") ); directions.ReplaceFirst("%%CATEGORY_NAME%%", from); fDirections->SetText(directions.String()); @@ -473,7 +485,8 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, if (strlen(B_TRANSLATE("Income")) > strlen(B_TRANSLATE("Spending"))) { maxchars = strlen(B_TRANSLATE("Income")); maxlength = view->StringWidth(B_TRANSLATE("Income")); - } else { + } + else { maxchars = strlen(B_TRANSLATE("Spending")); maxlength = view->StringWidth(B_TRANSLATE("Spending")); } @@ -513,11 +526,12 @@ CategoryRemoveWindow::CategoryRemoveWindow(const BRect &frame, const char *from, } void -CategoryRemoveWindow::MessageReceived(BMessage *msg) { +CategoryRemoveWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_REMOVE_CATEGORY: { int32 index = fListView->CurrentSelection(); - CategoryItem *item = (CategoryItem *)fListView->ItemAt(index); + CategoryItem* item = (CategoryItem*)fListView->ItemAt(index); if (!item || item == fIncomeItem || item == fSpendingItem) break; @@ -537,25 +551,28 @@ CategoryRemoveWindow::MessageReceived(BMessage *msg) { } void -CategoryRemoveWindow::FrameResized(float w, float h) {} +CategoryRemoveWindow::FrameResized(float w, float h) +{ +} -CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, BView *target) +CategoryEditWindow::CategoryEditWindow(const BRect& frame, const char* oldname, BView* target) : BWindow( frame, B_TRANSLATE("Edit category"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fOldName(oldname), fTarget(target) { + fOldName(oldname), fTarget(target) +{ BString temp; AddCommonFilter(new EscapeCancelFilter); AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); + BView* view = new BView("background", B_WILL_DRAW | B_FRAME_EVENTS); BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); view->SetViewColor(240, 240, 240); temp = B_TRANSLATE("Category name:"); - BStringView *oldnameView = new BStringView("oldname", temp.String()); + BStringView* oldnameView = new BStringView("oldname", temp.String()); temp = B_TRANSLATE("New category name:"); fNameBox = new AutoTextControl("namebox", temp.String(), "", new BMessage(M_NAME_CHANGED)); @@ -584,13 +601,15 @@ CategoryEditWindow::CategoryEditWindow(const BRect &frame, const char *oldname, } void -CategoryEditWindow::MessageReceived(BMessage *msg) { +CategoryEditWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_NAME_CHANGED: { if (strlen(fNameBox->Text()) > 0) { if (!fOKButton->IsEnabled()) fOKButton->SetEnabled(true); - } else { + } + else { if (fOKButton->IsEnabled()) fOKButton->SetEnabled(false); } diff --git a/src/CategoryWindow.h b/src/CategoryWindow.h index e84b323..a234080 100644 --- a/src/CategoryWindow.h +++ b/src/CategoryWindow.h @@ -5,7 +5,7 @@ class CategoryWindow : public BWindow { public: - CategoryWindow(const BRect &frame); + CategoryWindow(const BRect& frame); }; #endif diff --git a/src/CheckNumBox.cpp b/src/CheckNumBox.cpp index 04005f1..0e64196 100644 --- a/src/CheckNumBox.cpp +++ b/src/CheckNumBox.cpp @@ -10,11 +10,11 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CheckNumBox" - -CheckNumBoxFilter::CheckNumBoxFilter(CheckNumBox *box) : AutoTextControlFilter(box) {} +CheckNumBoxFilter::CheckNumBoxFilter(CheckNumBox* box) : AutoTextControlFilter(box) {} filter_result -CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +CheckNumBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. if (key == B_TAB) { if (mod & B_SHIFT_KEY) @@ -38,7 +38,7 @@ CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (!acc) return B_DISPATCH_MESSAGE; @@ -56,26 +56,30 @@ CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { acc->SetLastCheckNumber(num); string << (num + 1); - } else + } + else string << acc->LastCheckNumber() + 1; TextControl()->SetText(string.String()); TextControl()->TextView()->SelectAll(); return B_SKIP_MESSAGE; - } else if (keystring == "-") { + } + else if (keystring == "-") { // if(strlen(TextControl()->Text())>0) if (length > 0) { uint16 num = acc->LastCheckNumber() - 1; acc->SetLastCheckNumber(num); string << (num + 1); - } else + } + else string << acc->LastCheckNumber() + 1; TextControl()->SetText(string.String()); TextControl()->TextView()->SelectAll(); return B_SKIP_MESSAGE; - } else + } + else // if(end == (int32)strlen(TextControl()->Text())) if (end == length) { TextControl()->TextView()->Delete(start, end); @@ -97,9 +101,10 @@ CheckNumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { } CheckNumBox::CheckNumBox( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : AutoTextControl(name, label, text, msg, flags) { + : AutoTextControl(name, label, text, msg, flags) +{ SetFilter(new CheckNumBoxFilter(this)); const char type_disallowed[] = "`~!@#$%^&*()_-+={[}]|\\;:'\"<>?"; @@ -113,13 +118,14 @@ CheckNumBox::CheckNumBox( } bool -CheckNumBox::Validate(void) { +CheckNumBox::Validate(void) +{ if (strlen(Text()) < 1) { ShowAlert( B_TRANSLATE("Transaction type is missing."), B_TRANSLATE("You need to enter a check number or transaction type, such as " - "ATM (for debit card transactions and the like), DEP (for deposits), " - "or your own code for some other kind of expense.") + "ATM (for debit card transactions and the like), DEP (for deposits), " + "or your own code for some other kind of expense.") ); MakeFocus(true); return false; diff --git a/src/CheckNumBox.h b/src/CheckNumBox.h index 27a2f97..6f3f814 100644 --- a/src/CheckNumBox.h +++ b/src/CheckNumBox.h @@ -9,14 +9,14 @@ class CheckNumBox; class CheckNumBoxFilter : public AutoTextControlFilter { public: - CheckNumBoxFilter(CheckNumBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + CheckNumBoxFilter(CheckNumBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class CheckNumBox : public AutoTextControl { public: CheckNumBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); diff --git a/src/CheckView.cpp b/src/CheckView.cpp index 8da7583..1bef44d 100644 --- a/src/CheckView.cpp +++ b/src/CheckView.cpp @@ -28,10 +28,10 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CheckView" - enum { M_ENTER_TRANSACTION = 'entr' }; -CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { +CheckView::CheckView(const char* name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) +{ fDateLabel = new BStringView("datelabel", B_TRANSLATE("Date")); fDate = new DateBox("dateentry", "", NULL, new BMessage(M_DATE_CHANGED)); @@ -94,7 +94,8 @@ CheckView::CheckView(const char *name, int32 flags) : BView(name, flags | B_FRAM CheckView::~CheckView(void) {} void -CheckView::AttachedToWindow(void) { +CheckView::AttachedToWindow(void) +{ SetViewColor(Parent()->ViewColor()); fDate->GetFilter()->SetMessenger(new BMessenger(this)); fPayee->GetFilter()->SetMessenger(new BMessenger(this)); @@ -107,7 +108,8 @@ CheckView::AttachedToWindow(void) { } void -CheckView::MessageReceived(BMessage *msg) { +CheckView::MessageReceived(BMessage* msg) +{ int32 start; BString string; switch (msg->what) { @@ -155,7 +157,7 @@ CheckView::MessageReceived(BMessage *msg) { !fAmount->Validate() || !fCategory->Validate()) break; - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (!acc) break; @@ -193,15 +195,18 @@ CheckView::MessageReceived(BMessage *msg) { fMemo->MakeFocus(true); } break; - } else if (fType->ChildAt(0)->IsFocus()) + } + else if (fType->ChildAt(0)->IsFocus()) fDate->MakeFocus(true); else if (fPayee->ChildAt(0)->IsFocus()) { if (fPayee->Validate(false)) fType->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { if (fAmount->Validate(false)) fPayee->MakeFocus(true); - } else if (fCategory->ChildAt(0)->IsFocus()) { + } + else if (fCategory->ChildAt(0)->IsFocus()) { // if(fCategory->Validate()) fAmount->MakeFocus(true); } @@ -221,9 +226,10 @@ CheckView::MessageReceived(BMessage *msg) { void CheckView::SetFields( - const char *date, const char *type, const char *payee, const char *amount, const char *category, - const char *memo -) { + const char* date, const char* type, const char* payee, const char* amount, const char* category, + const char* memo +) +{ fDate->SetText(date); fType->SetText(type); fPayee->SetText(payee); @@ -233,13 +239,14 @@ CheckView::SetFields( } void -CheckView::HandleNotify(const uint64 &value, const BMessage *msg) { +CheckView::HandleNotify(const uint64& value, const BMessage* msg) +{ if (value & WATCH_SELECT) { if (value & WATCH_ACCOUNT) { MakeEmpty(); - Account *account; - if (msg->FindPointer("item", (void **)&account) == B_OK) { + Account* account; + if (msg->FindPointer("item", (void**)&account) == B_OK) { if (account && !account->HasObserver(this)) account->AddObserver(this); } @@ -260,16 +267,18 @@ CheckView::HandleNotify(const uint64 &value, const BMessage *msg) { BString text; gDefaultLocale.DateToString(data.Date(), text); fDate->SetText(text.String()); - } else { + } + else { BString text; gDefaultLocale.DateToString(GetCurrentDate(), text); fDate->SetText(text.String()); } fDate->MakeFocus(true); - } else if (value & WATCH_TRANSACTION) { + } + else if (value & WATCH_TRANSACTION) { uint32 id; - if (msg->FindInt32("id", (int32 *)&id) == B_OK) { + if (msg->FindInt32("id", (int32*)&id) == B_OK) { if (gDatabase.CurrentAccount()) { TransactionData data; gDatabase.GetTransaction(id, data); @@ -285,7 +294,8 @@ CheckView::HandleNotify(const uint64 &value, const BMessage *msg) { } void -CheckView::MakeEmpty(void) { +CheckView::MakeEmpty(void) +{ fDate->SetText(""); fType->SetText(""); fPayee->SetText(""); @@ -295,15 +305,19 @@ CheckView::MakeEmpty(void) { } void -CheckView::MakeFocus(bool value) { +CheckView::MakeFocus(bool value) +{ fDate->MakeFocus(value); } void -CheckView::FrameResized(float width, float height) {} +CheckView::FrameResized(float width, float height) +{ +} void -CheckView::DoNextField(void) { +CheckView::DoNextField(void) +{ if (fDate->ChildAt(0)->IsFocus()) { if (fDate->Validate(false)) { if (gDatabase.CurrentAccount() && strlen(fDate->Text()) > 0) { @@ -313,15 +327,18 @@ CheckView::DoNextField(void) { } } fType->MakeFocus(true); - } else if (fType->ChildAt(0)->IsFocus()) + } + else if (fType->ChildAt(0)->IsFocus()) fPayee->MakeFocus(true); else if (fPayee->ChildAt(0)->IsFocus()) { if (fPayee->Validate(false)) fAmount->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { if (fAmount->Validate(false)) fCategory->MakeFocus(true); - } else if (fCategory->ChildAt(0)->IsFocus()) { + } + else if (fCategory->ChildAt(0)->IsFocus()) { // TODO: don't force entering a transaction when going to the // split window via key editing if (strcmp(fCategory->Text(), "Split") == 0) { @@ -331,9 +348,11 @@ CheckView::DoNextField(void) { } fMemo->MakeFocus(true); - } else if (fMemo->ChildAt(0)->IsFocus()) { + } + else if (fMemo->ChildAt(0)->IsFocus()) { fEnter->MakeFocus(true); - } else { + } + else { // We should *never* be here ShowBug("M_NEXT_FIELD received for unknown view in CheckView"); } diff --git a/src/CheckView.h b/src/CheckView.h index 277982a..68145d1 100644 --- a/src/CheckView.h +++ b/src/CheckView.h @@ -32,16 +32,16 @@ class PayeeBox; class CheckView : public BView, public Observer { public: - CheckView(const char *name, int32 flags); + CheckView(const char* name, int32 flags); ~CheckView(void); void AttachedToWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); void SetFields( - const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo + const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo ); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); void MakeEmpty(void); void MakeFocus(bool value = true); void FrameResized(float width, float height); @@ -49,17 +49,17 @@ class CheckView : public BView, public Observer { private: void DoNextField(void); - DateBox *fDate; - CheckNumBox *fType; - PayeeBox *fPayee; - CurrencyBox *fAmount; - CategoryBox *fCategory; - NavTextBox *fMemo; + DateBox* fDate; + CheckNumBox* fType; + PayeeBox* fPayee; + CurrencyBox* fAmount; + CategoryBox* fCategory; + NavTextBox* fMemo; BStringView *fDateLabel, *fTypeLabel, *fPayeeLabel, *fAmountLabel, *fCategoryLabel, *fMemoLabel; BButton *fEnter, *fTransfer; - HelpButton *fHelpButton; + HelpButton* fHelpButton; }; diff --git a/src/CppSQLite3.cpp b/src/CppSQLite3.cpp index 23969ba..87e441d 100644 --- a/src/CppSQLite3.cpp +++ b/src/CppSQLite3.cpp @@ -46,17 +46,18 @@ static const bool DONT_DELETE_MSG = false; // from SQLite encode.c //////////////////////////////////////////////////////////////////////////////// int -sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out); +sqlite3_encode_binary(const unsigned char* in, int n, unsigned char* out); int -sqlite3_decode_binary(const unsigned char *in, unsigned char *out); +sqlite3_decode_binary(const unsigned char* in, unsigned char* out); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// CppSQLite3Exception:: - CppSQLite3Exception(const int nErrCode, char *szErrMess, bool bDeleteMsg /*=true*/) - : mnErrCode(nErrCode) { + CppSQLite3Exception(const int nErrCode, char* szErrMess, bool bDeleteMsg /*=true*/) + : mnErrCode(nErrCode) +{ mpszErrMess = sqlite3_mprintf( "%s[%d]: %s", errorCodeAsString(nErrCode), nErrCode, szErrMess ? szErrMess : "" ); @@ -66,15 +67,17 @@ CppSQLite3Exception:: } } -CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception &e) : mnErrCode(e.mnErrCode) { +CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception& e) : mnErrCode(e.mnErrCode) +{ mpszErrMess = 0; if (e.mpszErrMess) { mpszErrMess = sqlite3_mprintf("%s", e.mpszErrMess); } } -const char * -CppSQLite3Exception::errorCodeAsString(int nErrCode) { +const char* +CppSQLite3Exception::errorCodeAsString(int nErrCode) +{ switch (nErrCode) { case SQLITE_OK: return "SQLITE_OK"; @@ -139,7 +142,8 @@ CppSQLite3Exception::errorCodeAsString(int nErrCode) { } } -CppSQLite3Exception::~CppSQLite3Exception() { +CppSQLite3Exception::~CppSQLite3Exception() +{ if (mpszErrMess) { sqlite3_free(mpszErrMess); mpszErrMess = 0; @@ -153,15 +157,17 @@ CppSQLite3Buffer::CppSQLite3Buffer() { mpBuf = 0; } CppSQLite3Buffer::~CppSQLite3Buffer() { clear(); } void -CppSQLite3Buffer::clear() { +CppSQLite3Buffer::clear() +{ if (mpBuf) { sqlite3_free(mpBuf); mpBuf = 0; } } -const char * -CppSQLite3Buffer::format(const char *szFormat, ...) { +const char* +CppSQLite3Buffer::format(const char* szFormat, ...) +{ clear(); va_list va; va_start(va, szFormat); @@ -173,24 +179,28 @@ CppSQLite3Buffer::format(const char *szFormat, ...) { //////////////////////////////////////////////////////////////////////////////// CppSQLite3Binary::CppSQLite3Binary() - : mpBuf(0), mnBinaryLen(0), mnBufferLen(0), mnEncodedLen(0), mbEncoded(false) {} + : mpBuf(0), mnBinaryLen(0), mnBufferLen(0), mnEncodedLen(0), mbEncoded(false) +{ +} CppSQLite3Binary::~CppSQLite3Binary() { clear(); } void -CppSQLite3Binary::setBinary(const unsigned char *pBuf, int nLen) { +CppSQLite3Binary::setBinary(const unsigned char* pBuf, int nLen) +{ mpBuf = allocBuffer(nLen); memcpy(mpBuf, pBuf, nLen); } void -CppSQLite3Binary::setEncoded(const unsigned char *pBuf) { +CppSQLite3Binary::setEncoded(const unsigned char* pBuf) +{ clear(); - mnEncodedLen = strlen((const char *)pBuf); + mnEncodedLen = strlen((const char*)pBuf); mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator - mpBuf = (unsigned char *)malloc(mnBufferLen); + mpBuf = (unsigned char*)malloc(mnBufferLen); if (!mpBuf) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Cannot allocate memory", DONT_DELETE_MSG); @@ -200,10 +210,11 @@ CppSQLite3Binary::setEncoded(const unsigned char *pBuf) { mbEncoded = true; } -const unsigned char * -CppSQLite3Binary::getEncoded() { +const unsigned char* +CppSQLite3Binary::getEncoded() +{ if (!mbEncoded) { - unsigned char *ptmp = (unsigned char *)malloc(mnBinaryLen); + unsigned char* ptmp = (unsigned char*)malloc(mnBinaryLen); memcpy(ptmp, mpBuf, mnBinaryLen); mnEncodedLen = sqlite3_encode_binary(ptmp, mnBinaryLen, mpBuf); free(ptmp); @@ -213,8 +224,9 @@ CppSQLite3Binary::getEncoded() { return mpBuf; } -const unsigned char * -CppSQLite3Binary::getBinary() { +const unsigned char* +CppSQLite3Binary::getBinary() +{ if (mbEncoded) { // in/out buffers can be the same mnBinaryLen = sqlite3_decode_binary(mpBuf, mpBuf); @@ -230,13 +242,15 @@ CppSQLite3Binary::getBinary() { } int -CppSQLite3Binary::getBinaryLength() { +CppSQLite3Binary::getBinaryLength() +{ getBinary(); return mnBinaryLen; } -unsigned char * -CppSQLite3Binary::allocBuffer(int nLen) { +unsigned char* +CppSQLite3Binary::allocBuffer(int nLen) +{ clear(); // Allow extra space for encoded binary as per comments in @@ -245,7 +259,7 @@ CppSQLite3Binary::allocBuffer(int nLen) { mnBinaryLen = nLen; mnBufferLen = 3 + (257 * nLen) / 254; - mpBuf = (unsigned char *)malloc(mnBufferLen); + mpBuf = (unsigned char*)malloc(mnBufferLen); if (!mpBuf) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Cannot allocate memory", DONT_DELETE_MSG); @@ -257,7 +271,8 @@ CppSQLite3Binary::allocBuffer(int nLen) { } void -CppSQLite3Binary::clear() { +CppSQLite3Binary::clear() +{ if (mpBuf) { mnBinaryLen = 0; mnBufferLen = 0; @@ -268,24 +283,26 @@ CppSQLite3Binary::clear() { //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Query::CppSQLite3Query() { +CppSQLite3Query::CppSQLite3Query() +{ mpVM = 0; mbEof = true; mnCols = 0; mbOwnVM = false; } -CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query &rQuery) { +CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery) +{ mpVM = rQuery.mpVM; // Only one object can own the VM - const_cast(rQuery).mpVM = 0; + const_cast(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; } -CppSQLite3Query:: - CppSQLite3Query(sqlite3 *pDB, sqlite3_stmt *pVM, bool bEof, bool bOwnVM /*=true*/) { +CppSQLite3Query::CppSQLite3Query(sqlite3* pDB, sqlite3_stmt* pVM, bool bEof, bool bOwnVM /*=true*/) +{ mpDB = pDB; mpVM = pVM; mbEof = bEof; @@ -293,22 +310,26 @@ CppSQLite3Query:: mbOwnVM = bOwnVM; } -CppSQLite3Query::~CppSQLite3Query() { +CppSQLite3Query::~CppSQLite3Query() +{ try { finalize(); - } catch (...) { + } + catch (...) { } } -CppSQLite3Query & -CppSQLite3Query::operator=(const CppSQLite3Query &rQuery) { +CppSQLite3Query& +CppSQLite3Query::operator=(const CppSQLite3Query& rQuery) +{ try { finalize(); - } catch (...) { + } + catch (...) { } mpVM = rQuery.mpVM; // Only one object can own the VM - const_cast(rQuery).mpVM = 0; + const_cast(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; @@ -316,13 +337,15 @@ CppSQLite3Query::operator=(const CppSQLite3Query &rQuery) { } int -CppSQLite3Query::numFields() { +CppSQLite3Query::numFields() +{ checkVM(); return mnCols; } -const char * -CppSQLite3Query::fieldValue(int nField) { +const char* +CppSQLite3Query::fieldValue(int nField) +{ checkVM(); if (nField < 0 || nField > mnCols - 1) { @@ -331,77 +354,91 @@ CppSQLite3Query::fieldValue(int nField) { ); } - return (const char *)sqlite3_column_text(mpVM, nField); + return (const char*)sqlite3_column_text(mpVM, nField); } -const char * -CppSQLite3Query::fieldValue(const char *szField) { +const char* +CppSQLite3Query::fieldValue(const char* szField) +{ int nField = fieldIndex(szField); - return (const char *)sqlite3_column_text(mpVM, nField); + return (const char*)sqlite3_column_text(mpVM, nField); } int -CppSQLite3Query::getIntField(int nField, int nNullValue /*=0*/) { +CppSQLite3Query::getIntField(int nField, int nNullValue /*=0*/) +{ if (fieldDataType(nField) == SQLITE_NULL) { return nNullValue; - } else { + } + else { return sqlite3_column_int(mpVM, nField); } } int -CppSQLite3Query::getIntField(const char *szField, int nNullValue /*=0*/) { +CppSQLite3Query::getIntField(const char* szField, int nNullValue /*=0*/) +{ int nField = fieldIndex(szField); return getIntField(nField, nNullValue); } sqlite_int64 -CppSQLite3Query::getInt64Field(int nField, sqlite_int64 nNullValue /*=0*/) { +CppSQLite3Query::getInt64Field(int nField, sqlite_int64 nNullValue /*=0*/) +{ if (fieldDataType(nField) == SQLITE_NULL) { return nNullValue; - } else { + } + else { return sqlite3_column_int64(mpVM, nField); } } sqlite_int64 -CppSQLite3Query::getInt64Field(const char *szField, sqlite_int64 nNullValue /*=0*/) { +CppSQLite3Query::getInt64Field(const char* szField, sqlite_int64 nNullValue /*=0*/) +{ int nField = fieldIndex(szField); return getInt64Field(nField, nNullValue); } double -CppSQLite3Query::getFloatField(int nField, double fNullValue /*=0.0*/) { +CppSQLite3Query::getFloatField(int nField, double fNullValue /*=0.0*/) +{ if (fieldDataType(nField) == SQLITE_NULL) { return fNullValue; - } else { + } + else { return sqlite3_column_double(mpVM, nField); } } double -CppSQLite3Query::getFloatField(const char *szField, double fNullValue /*=0.0*/) { +CppSQLite3Query::getFloatField(const char* szField, double fNullValue /*=0.0*/) +{ int nField = fieldIndex(szField); return getFloatField(nField, fNullValue); } -const char * -CppSQLite3Query::getStringField(int nField, const char *szNullValue /*=""*/) { +const char* +CppSQLite3Query::getStringField(int nField, const char* szNullValue /*=""*/) +{ if (fieldDataType(nField) == SQLITE_NULL) { return szNullValue; - } else { - return (const char *)sqlite3_column_text(mpVM, nField); + } + else { + return (const char*)sqlite3_column_text(mpVM, nField); } } -const char * -CppSQLite3Query::getStringField(const char *szField, const char *szNullValue /*=""*/) { +const char* +CppSQLite3Query::getStringField(const char* szField, const char* szNullValue /*=""*/) +{ int nField = fieldIndex(szField); return getStringField(nField, szNullValue); } -const unsigned char * -CppSQLite3Query::getBlobField(int nField, int &nLen) { +const unsigned char* +CppSQLite3Query::getBlobField(int nField, int& nLen) +{ checkVM(); if (nField < 0 || nField > mnCols - 1) { @@ -411,33 +448,37 @@ CppSQLite3Query::getBlobField(int nField, int &nLen) { } nLen = sqlite3_column_bytes(mpVM, nField); - return (const unsigned char *)sqlite3_column_blob(mpVM, nField); + return (const unsigned char*)sqlite3_column_blob(mpVM, nField); } -const unsigned char * -CppSQLite3Query::getBlobField(const char *szField, int &nLen) { +const unsigned char* +CppSQLite3Query::getBlobField(const char* szField, int& nLen) +{ int nField = fieldIndex(szField); return getBlobField(nField, nLen); } bool -CppSQLite3Query::fieldIsNull(int nField) { +CppSQLite3Query::fieldIsNull(int nField) +{ return (fieldDataType(nField) == SQLITE_NULL); } bool -CppSQLite3Query::fieldIsNull(const char *szField) { +CppSQLite3Query::fieldIsNull(const char* szField) +{ int nField = fieldIndex(szField); return (fieldDataType(nField) == SQLITE_NULL); } int -CppSQLite3Query::fieldIndex(const char *szField) { +CppSQLite3Query::fieldIndex(const char* szField) +{ checkVM(); if (szField) { for (int nField = 0; nField < mnCols; nField++) { - const char *szTemp = sqlite3_column_name(mpVM, nField); + const char* szTemp = sqlite3_column_name(mpVM, nField); if (strcmp(szField, szTemp) == 0) { return nField; @@ -448,8 +489,9 @@ CppSQLite3Query::fieldIndex(const char *szField) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Invalid field name requested", DONT_DELETE_MSG); } -const char * -CppSQLite3Query::fieldName(int nCol) { +const char* +CppSQLite3Query::fieldName(int nCol) +{ checkVM(); if (nCol < 0 || nCol > mnCols - 1) { @@ -461,8 +503,9 @@ CppSQLite3Query::fieldName(int nCol) { return sqlite3_column_name(mpVM, nCol); } -const char * -CppSQLite3Query::fieldDeclType(int nCol) { +const char* +CppSQLite3Query::fieldDeclType(int nCol) +{ checkVM(); if (nCol < 0 || nCol > mnCols - 1) { @@ -475,7 +518,8 @@ CppSQLite3Query::fieldDeclType(int nCol) { } int -CppSQLite3Query::fieldDataType(int nCol) { +CppSQLite3Query::fieldDataType(int nCol) +{ checkVM(); if (nCol < 0 || nCol > mnCols - 1) { @@ -488,13 +532,15 @@ CppSQLite3Query::fieldDataType(int nCol) { } bool -CppSQLite3Query::eof() { +CppSQLite3Query::eof() +{ checkVM(); return mbEof; } void -CppSQLite3Query::nextRow() { +CppSQLite3Query::nextRow() +{ checkVM(); int nRet = sqlite3_step(mpVM); @@ -502,30 +548,34 @@ CppSQLite3Query::nextRow() { if (nRet == SQLITE_DONE) { // no rows mbEof = true; - } else if (nRet == SQLITE_ROW) { + } + else if (nRet == SQLITE_ROW) { // more rows, nothing to do - } else { + } + else { nRet = sqlite3_finalize(mpVM); mpVM = 0; - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } void -CppSQLite3Query::finalize() { +CppSQLite3Query::finalize() +{ if (mpVM && mbOwnVM) { int nRet = sqlite3_finalize(mpVM); mpVM = 0; if (nRet != SQLITE_OK) { - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } } void -CppSQLite3Query::checkVM() { +CppSQLite3Query::checkVM() +{ if (mpVM == 0) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Virtual Machine pointer", DONT_DELETE_MSG); } @@ -533,45 +583,52 @@ CppSQLite3Query::checkVM() { //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Table::CppSQLite3Table() { +CppSQLite3Table::CppSQLite3Table() +{ mpaszResults = 0; mnRows = 0; mnCols = 0; mnCurrentRow = 0; } -CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table &rTable) { +CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table& rTable) +{ mpaszResults = rTable.mpaszResults; // Only one object can own the results - const_cast(rTable).mpaszResults = 0; + const_cast(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; } -CppSQLite3Table::CppSQLite3Table(char **paszResults, int nRows, int nCols) { +CppSQLite3Table::CppSQLite3Table(char** paszResults, int nRows, int nCols) +{ mpaszResults = paszResults; mnRows = nRows; mnCols = nCols; mnCurrentRow = 0; } -CppSQLite3Table::~CppSQLite3Table() { +CppSQLite3Table::~CppSQLite3Table() +{ try { finalize(); - } catch (...) { + } + catch (...) { } } -CppSQLite3Table & -CppSQLite3Table::operator=(const CppSQLite3Table &rTable) { +CppSQLite3Table& +CppSQLite3Table::operator=(const CppSQLite3Table& rTable) +{ try { finalize(); - } catch (...) { + } + catch (...) { } mpaszResults = rTable.mpaszResults; // Only one object can own the results - const_cast(rTable).mpaszResults = 0; + const_cast(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; @@ -579,7 +636,8 @@ CppSQLite3Table::operator=(const CppSQLite3Table &rTable) { } void -CppSQLite3Table::finalize() { +CppSQLite3Table::finalize() +{ if (mpaszResults) { sqlite3_free_table(mpaszResults); mpaszResults = 0; @@ -587,19 +645,22 @@ CppSQLite3Table::finalize() { } int -CppSQLite3Table::numFields() { +CppSQLite3Table::numFields() +{ checkResults(); return mnCols; } int -CppSQLite3Table::numRows() { +CppSQLite3Table::numRows() +{ checkResults(); return mnRows; } -const char * -CppSQLite3Table::fieldValue(int nField) { +const char* +CppSQLite3Table::fieldValue(int nField) +{ checkResults(); if (nField < 0 || nField > mnCols - 1) { @@ -612,8 +673,9 @@ CppSQLite3Table::fieldValue(int nField) { return mpaszResults[nIndex]; } -const char * -CppSQLite3Table::fieldValue(const char *szField) { +const char* +CppSQLite3Table::fieldValue(const char* szField) +{ checkResults(); if (szField) { @@ -629,73 +691,88 @@ CppSQLite3Table::fieldValue(const char *szField) { } int -CppSQLite3Table::getIntField(int nField, int nNullValue /*=0*/) { +CppSQLite3Table::getIntField(int nField, int nNullValue /*=0*/) +{ if (fieldIsNull(nField)) { return nNullValue; - } else { + } + else { return atoi(fieldValue(nField)); } } int -CppSQLite3Table::getIntField(const char *szField, int nNullValue /*=0*/) { +CppSQLite3Table::getIntField(const char* szField, int nNullValue /*=0*/) +{ if (fieldIsNull(szField)) { return nNullValue; - } else { + } + else { return atoi(fieldValue(szField)); } } double -CppSQLite3Table::getFloatField(int nField, double fNullValue /*=0.0*/) { +CppSQLite3Table::getFloatField(int nField, double fNullValue /*=0.0*/) +{ if (fieldIsNull(nField)) { return fNullValue; - } else { + } + else { return atof(fieldValue(nField)); } } double -CppSQLite3Table::getFloatField(const char *szField, double fNullValue /*=0.0*/) { +CppSQLite3Table::getFloatField(const char* szField, double fNullValue /*=0.0*/) +{ if (fieldIsNull(szField)) { return fNullValue; - } else { + } + else { return atof(fieldValue(szField)); } } -const char * -CppSQLite3Table::getStringField(int nField, const char *szNullValue /*=""*/) { +const char* +CppSQLite3Table::getStringField(int nField, const char* szNullValue /*=""*/) +{ if (fieldIsNull(nField)) { return szNullValue; - } else { + } + else { return fieldValue(nField); } } -const char * -CppSQLite3Table::getStringField(const char *szField, const char *szNullValue /*=""*/) { +const char* +CppSQLite3Table::getStringField(const char* szField, const char* szNullValue /*=""*/) +{ if (fieldIsNull(szField)) { return szNullValue; - } else { + } + else { return fieldValue(szField); } } bool -CppSQLite3Table::fieldIsNull(int nField) { +CppSQLite3Table::fieldIsNull(int nField) +{ checkResults(); return (fieldValue(nField) == 0); } bool -CppSQLite3Table::fieldIsNull(const char *szField) { +CppSQLite3Table::fieldIsNull(const char* szField) +{ checkResults(); return (fieldValue(szField) == 0); } -const char * -CppSQLite3Table::fieldName(int nCol) { +const char* +CppSQLite3Table::fieldName(int nCol) +{ checkResults(); if (nCol < 0 || nCol > mnCols - 1) { @@ -708,7 +785,8 @@ CppSQLite3Table::fieldName(int nCol) { } void -CppSQLite3Table::setRow(int nRow) { +CppSQLite3Table::setRow(int nRow) +{ checkResults(); if (nRow < 0 || nRow > mnRows - 1) { @@ -719,7 +797,8 @@ CppSQLite3Table::setRow(int nRow) { } void -CppSQLite3Table::checkResults() { +CppSQLite3Table::checkResults() +{ if (mpaszResults == 0) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Results pointer", DONT_DELETE_MSG); } @@ -727,45 +806,52 @@ CppSQLite3Table::checkResults() { //////////////////////////////////////////////////////////////////////////////// -CppSQLite3Statement::CppSQLite3Statement() { +CppSQLite3Statement::CppSQLite3Statement() +{ mpDB = 0; mpVM = 0; } -CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement &rStatement) { +CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement) +{ mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM - const_cast(rStatement).mpVM = 0; + const_cast(rStatement).mpVM = 0; } -CppSQLite3Statement::CppSQLite3Statement(sqlite3 *pDB, sqlite3_stmt *pVM) { +CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM) +{ mpDB = pDB; mpVM = pVM; } -CppSQLite3Statement::~CppSQLite3Statement() { +CppSQLite3Statement::~CppSQLite3Statement() +{ try { finalize(); - } catch (...) { + } + catch (...) { } } -CppSQLite3Statement & -CppSQLite3Statement::operator=(const CppSQLite3Statement &rStatement) { +CppSQLite3Statement& +CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement) +{ mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM - const_cast(rStatement).mpVM = 0; + const_cast(rStatement).mpVM = 0; return *this; } int -CppSQLite3Statement::execDML() { +CppSQLite3Statement::execDML() +{ checkDB(); checkVM(); - const char *szError = 0; + const char* szError = 0; int nRet = sqlite3_step(mpVM); @@ -776,19 +862,21 @@ CppSQLite3Statement::execDML() { if (nRet != SQLITE_OK) { szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } return nRowsChanged; - } else { + } + else { nRet = sqlite3_reset(mpVM); szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } CppSQLite3Query -CppSQLite3Statement::execQuery() { +CppSQLite3Statement::execQuery() +{ checkDB(); checkVM(); @@ -797,18 +885,21 @@ CppSQLite3Statement::execQuery() { if (nRet == SQLITE_DONE) { // no rows return CppSQLite3Query(mpDB, mpVM, true /*eof*/, false); - } else if (nRet == SQLITE_ROW) { + } + else if (nRet == SQLITE_ROW) { // at least 1 row return CppSQLite3Query(mpDB, mpVM, false /*eof*/, false); - } else { + } + else { nRet = sqlite3_reset(mpVM); - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } void -CppSQLite3Statement::bind(int nParam, const char *szValue) { +CppSQLite3Statement::bind(int nParam, const char* szValue) +{ checkVM(); int nRes = sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT); @@ -818,7 +909,8 @@ CppSQLite3Statement::bind(int nParam, const char *szValue) { } void -CppSQLite3Statement::bind(int nParam, const int nValue) { +CppSQLite3Statement::bind(int nParam, const int nValue) +{ checkVM(); int nRes = sqlite3_bind_int(mpVM, nParam, nValue); @@ -828,7 +920,8 @@ CppSQLite3Statement::bind(int nParam, const int nValue) { } void -CppSQLite3Statement::bind(int nParam, const double dValue) { +CppSQLite3Statement::bind(int nParam, const double dValue) +{ checkVM(); int nRes = sqlite3_bind_double(mpVM, nParam, dValue); @@ -838,9 +931,10 @@ CppSQLite3Statement::bind(int nParam, const double dValue) { } void -CppSQLite3Statement::bind(int nParam, const unsigned char *blobValue, int nLen) { +CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen) +{ checkVM(); - int nRes = sqlite3_bind_blob(mpVM, nParam, (const void *)blobValue, nLen, SQLITE_TRANSIENT); + int nRes = sqlite3_bind_blob(mpVM, nParam, (const void*)blobValue, nLen, SQLITE_TRANSIENT); if (nRes != SQLITE_OK) { throw CppSQLite3Exception(nRes, "Error binding blob param", DONT_DELETE_MSG); @@ -848,7 +942,8 @@ CppSQLite3Statement::bind(int nParam, const unsigned char *blobValue, int nLen) } void -CppSQLite3Statement::bindNull(int nParam) { +CppSQLite3Statement::bindNull(int nParam) +{ checkVM(); int nRes = sqlite3_bind_null(mpVM, nParam); @@ -858,14 +953,15 @@ CppSQLite3Statement::bindNull(int nParam) { } int -CppSQLite3Statement::bindParameterIndex(const char *szParam) { +CppSQLite3Statement::bindParameterIndex(const char* szParam) +{ checkVM(); int nParam = sqlite3_bind_parameter_index(mpVM, szParam); int nn = sqlite3_bind_parameter_count(mpVM); - const char *sz1 = sqlite3_bind_parameter_name(mpVM, 1); - const char *sz2 = sqlite3_bind_parameter_name(mpVM, 2); + const char* sz1 = sqlite3_bind_parameter_name(mpVM, 1); + const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2); if (!nParam) { char buf[128]; @@ -877,69 +973,78 @@ CppSQLite3Statement::bindParameterIndex(const char *szParam) { } void -CppSQLite3Statement::bind(const char *szParam, const char *szValue) { +CppSQLite3Statement::bind(const char* szParam, const char* szValue) +{ int nParam = bindParameterIndex(szParam); bind(nParam, szValue); } void -CppSQLite3Statement::bind(const char *szParam, const int nValue) { +CppSQLite3Statement::bind(const char* szParam, const int nValue) +{ int nParam = bindParameterIndex(szParam); bind(nParam, nValue); } void -CppSQLite3Statement::bind(const char *szParam, const double dwValue) { +CppSQLite3Statement::bind(const char* szParam, const double dwValue) +{ int nParam = bindParameterIndex(szParam); bind(nParam, dwValue); } void -CppSQLite3Statement::bind(const char *szParam, const unsigned char *blobValue, int nLen) { +CppSQLite3Statement::bind(const char* szParam, const unsigned char* blobValue, int nLen) +{ int nParam = bindParameterIndex(szParam); bind(nParam, blobValue, nLen); } void -CppSQLite3Statement::bindNull(const char *szParam) { +CppSQLite3Statement::bindNull(const char* szParam) +{ int nParam = bindParameterIndex(szParam); bindNull(nParam); } void -CppSQLite3Statement::reset() { +CppSQLite3Statement::reset() +{ if (mpVM) { int nRet = sqlite3_reset(mpVM); if (nRet != SQLITE_OK) { - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } } void -CppSQLite3Statement::finalize() { +CppSQLite3Statement::finalize() +{ if (mpVM) { int nRet = sqlite3_finalize(mpVM); mpVM = 0; if (nRet != SQLITE_OK) { - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } } void -CppSQLite3Statement::checkDB() { +CppSQLite3Statement::checkDB() +{ if (mpDB == 0) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Database not open", DONT_DELETE_MSG); } } void -CppSQLite3Statement::checkVM() { +CppSQLite3Statement::checkVM() +{ if (mpVM == 0) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Null Virtual Machine pointer", DONT_DELETE_MSG); } @@ -947,63 +1052,73 @@ CppSQLite3Statement::checkVM() { //////////////////////////////////////////////////////////////////////////////// -CppSQLite3DB::CppSQLite3DB() { +CppSQLite3DB::CppSQLite3DB() +{ mpDB = 0; mnBusyTimeoutMs = 60000; // 60 seconds } -CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB &db) { +CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db) +{ mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds } -CppSQLite3DB::~CppSQLite3DB() { +CppSQLite3DB::~CppSQLite3DB() +{ try { close(); - } catch (...) { + } + catch (...) { } } -CppSQLite3DB & -CppSQLite3DB::operator=(const CppSQLite3DB &db) { +CppSQLite3DB& +CppSQLite3DB::operator=(const CppSQLite3DB& db) +{ mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds return *this; } void -CppSQLite3DB::open(const char *szFile) { +CppSQLite3DB::open(const char* szFile) +{ int nRet = sqlite3_open(szFile, &mpDB); if (nRet != SQLITE_OK) { - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } setBusyTimeout(mnBusyTimeoutMs); } void -CppSQLite3DB::close() { +CppSQLite3DB::close() +{ if (mpDB) { if (sqlite3_close(mpDB) == SQLITE_OK) { mpDB = 0; - } else { + } + else { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Unable to close database", DONT_DELETE_MSG); } } } CppSQLite3Statement -CppSQLite3DB::compileStatement(const char *szSQL) { +CppSQLite3DB::compileStatement(const char* szSQL) +{ checkDB(); - sqlite3_stmt *pVM = compile(szSQL); + sqlite3_stmt* pVM = compile(szSQL); return CppSQLite3Statement(mpDB, pVM); } bool -CppSQLite3DB::tableExists(const char *szTable) { +CppSQLite3DB::tableExists(const char* szTable) +{ char szSQL[256]; sprintf(szSQL, "select count(*) from sqlite_master where type='table' and name='%s'", szTable); int nRet = execScalar(szSQL); @@ -1011,43 +1126,49 @@ CppSQLite3DB::tableExists(const char *szTable) { } int -CppSQLite3DB::execDML(const char *szSQL) { +CppSQLite3DB::execDML(const char* szSQL) +{ checkDB(); - char *szError = 0; + char* szError = 0; int nRet = sqlite3_exec(mpDB, szSQL, 0, 0, &szError); if (nRet == SQLITE_OK) { return sqlite3_changes(mpDB); - } else { + } + else { throw CppSQLite3Exception(nRet, szError); } } CppSQLite3Query -CppSQLite3DB::execQuery(const char *szSQL) { +CppSQLite3DB::execQuery(const char* szSQL) +{ checkDB(); - sqlite3_stmt *pVM = compile(szSQL); + sqlite3_stmt* pVM = compile(szSQL); int nRet = sqlite3_step(pVM); if (nRet == SQLITE_DONE) { // no rows return CppSQLite3Query(mpDB, pVM, true /*eof*/); - } else if (nRet == SQLITE_ROW) { + } + else if (nRet == SQLITE_ROW) { // at least 1 row return CppSQLite3Query(mpDB, pVM, false /*eof*/); - } else { + } + else { nRet = sqlite3_finalize(pVM); - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } } int -CppSQLite3DB::execScalar(const char *szSQL, int nNullValue /*=0*/) { +CppSQLite3DB::execScalar(const char* szSQL, int nNullValue /*=0*/) +{ CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) { @@ -1058,11 +1179,12 @@ CppSQLite3DB::execScalar(const char *szSQL, int nNullValue /*=0*/) { } CppSQLite3Table -CppSQLite3DB::getTable(const char *szSQL) { +CppSQLite3DB::getTable(const char* szSQL) +{ checkDB(); - char *szError = 0; - char **paszResults = 0; + char* szError = 0; + char** paszResults = 0; int nRet; int nRows(0); int nCols(0); @@ -1071,48 +1193,54 @@ CppSQLite3DB::getTable(const char *szSQL) { if (nRet == SQLITE_OK) { return CppSQLite3Table(paszResults, nRows, nCols); - } else { + } + else { throw CppSQLite3Exception(nRet, szError); } } sqlite_int64 -CppSQLite3DB::lastRowId() { +CppSQLite3DB::lastRowId() +{ return sqlite3_last_insert_rowid(mpDB); } void -CppSQLite3DB::setBusyTimeout(int nMillisecs) { +CppSQLite3DB::setBusyTimeout(int nMillisecs) +{ mnBusyTimeoutMs = nMillisecs; sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs); } void -CppSQLite3DB::checkDB() { +CppSQLite3DB::checkDB() +{ if (!mpDB) { throw CppSQLite3Exception(CPPSQLITE_ERROR, "Database not open", DONT_DELETE_MSG); } } -sqlite3_stmt * -CppSQLite3DB::compile(const char *szSQL) { +sqlite3_stmt* +CppSQLite3DB::compile(const char* szSQL) +{ checkDB(); - const char *szTail = 0; - sqlite3_stmt *pVM; + const char* szTail = 0; + sqlite3_stmt* pVM; int nRet = sqlite3_prepare_v2(mpDB, szSQL, -1, &pVM, &szTail); if (nRet != SQLITE_OK) { - const char *szError = sqlite3_errmsg(mpDB); - throw CppSQLite3Exception(nRet, (char *)szError, DONT_DELETE_MSG); + const char* szError = sqlite3_errmsg(mpDB); + throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } return pVM; } bool -CppSQLite3DB::IsAutoCommitOn() { +CppSQLite3DB::IsAutoCommitOn() +{ checkDB(); return sqlite3_get_autocommit(mpDB) ? true : false; } @@ -1239,7 +1367,8 @@ CppSQLite3DB::IsAutoCommitOn() { ** string, excluding the "\000" terminator. */ int -sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out) { +sqlite3_encode_binary(const unsigned char* in, int n, unsigned char* out) +{ int i, j, e, m; int cnt[256]; if (n <= 0) { @@ -1271,13 +1400,16 @@ sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out) { if (c == 0) { out[j++] = 1; out[j++] = 1; - } else if (c == 1) { + } + else if (c == 1) { out[j++] = 1; out[j++] = 2; - } else if (c == '\'') { + } + else if (c == '\'') { out[j++] = 1; out[j++] = 3; - } else { + } + else { out[j++] = c; } } @@ -1296,7 +1428,8 @@ sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out) { ** to decode a string in place. */ int -sqlite3_decode_binary(const unsigned char *in, unsigned char *out) { +sqlite3_decode_binary(const unsigned char* in, unsigned char* out) +{ int i, c, e; e = *(in++); i = 0; @@ -1305,11 +1438,14 @@ sqlite3_decode_binary(const unsigned char *in, unsigned char *out) { c = *(in++); if (c == 1) { c = 0; - } else if (c == 2) { + } + else if (c == 2) { c = 1; - } else if (c == 3) { + } + else if (c == 3) { c = '\''; - } else { + } + else { return -1; } } diff --git a/src/CppSQLite3.h b/src/CppSQLite3.h index 7ba12c8..3df75cc 100644 --- a/src/CppSQLite3.h +++ b/src/CppSQLite3.h @@ -41,21 +41,21 @@ class CppSQLite3Exception { public: - CppSQLite3Exception(const int nErrCode, char *szErrMess, bool bDeleteMsg = true); + CppSQLite3Exception(const int nErrCode, char* szErrMess, bool bDeleteMsg = true); - CppSQLite3Exception(const CppSQLite3Exception &e); + CppSQLite3Exception(const CppSQLite3Exception& e); virtual ~CppSQLite3Exception(); const int errorCode() { return mnErrCode; } - const char *errorMessage() { return mpszErrMess; } + const char* errorMessage() { return mpszErrMess; } - static const char *errorCodeAsString(int nErrCode); + static const char* errorCodeAsString(int nErrCode); private: int mnErrCode; - char *mpszErrMess; + char* mpszErrMess; }; class CppSQLite3Buffer { @@ -64,14 +64,14 @@ class CppSQLite3Buffer { ~CppSQLite3Buffer(); - const char *format(const char *szFormat, ...); + const char* format(const char* szFormat, ...); - operator const char *() { return mpBuf; } + operator const char*() { return mpBuf; } void clear(); private: - char *mpBuf; + char* mpBuf; }; class CppSQLite3Binary { @@ -80,20 +80,20 @@ class CppSQLite3Binary { ~CppSQLite3Binary(); - void setBinary(const unsigned char *pBuf, int nLen); - void setEncoded(const unsigned char *pBuf); + void setBinary(const unsigned char* pBuf, int nLen); + void setEncoded(const unsigned char* pBuf); - const unsigned char *getEncoded(); - const unsigned char *getBinary(); + const unsigned char* getEncoded(); + const unsigned char* getBinary(); int getBinaryLength(); - unsigned char *allocBuffer(int nLen); + unsigned char* allocBuffer(int nLen); void clear(); private: - unsigned char *mpBuf; + unsigned char* mpBuf; int mnBinaryLen; int mnBufferLen; int mnEncodedLen; @@ -104,42 +104,42 @@ class CppSQLite3Query { public: CppSQLite3Query(); - CppSQLite3Query(const CppSQLite3Query &rQuery); + CppSQLite3Query(const CppSQLite3Query& rQuery); - CppSQLite3Query(sqlite3 *pDB, sqlite3_stmt *pVM, bool bEof, bool bOwnVM = true); + CppSQLite3Query(sqlite3* pDB, sqlite3_stmt* pVM, bool bEof, bool bOwnVM = true); - CppSQLite3Query &operator=(const CppSQLite3Query &rQuery); + CppSQLite3Query& operator=(const CppSQLite3Query& rQuery); virtual ~CppSQLite3Query(); int numFields(); - int fieldIndex(const char *szField); - const char *fieldName(int nCol); + int fieldIndex(const char* szField); + const char* fieldName(int nCol); - const char *fieldDeclType(int nCol); + const char* fieldDeclType(int nCol); int fieldDataType(int nCol); - const char *fieldValue(int nField); - const char *fieldValue(const char *szField); + const char* fieldValue(int nField); + const char* fieldValue(const char* szField); int getIntField(int nField, int nNullValue = 0); - int getIntField(const char *szField, int nNullValue = 0); + int getIntField(const char* szField, int nNullValue = 0); sqlite_int64 getInt64Field(int nField, sqlite_int64 nNullValue = 0); - sqlite_int64 getInt64Field(const char *szField, sqlite_int64 nNullValue = 0); + sqlite_int64 getInt64Field(const char* szField, sqlite_int64 nNullValue = 0); double getFloatField(int nField, double fNullValue = 0.0); - double getFloatField(const char *szField, double fNullValue = 0.0); + double getFloatField(const char* szField, double fNullValue = 0.0); - const char *getStringField(int nField, const char *szNullValue = ""); - const char *getStringField(const char *szField, const char *szNullValue = ""); + const char* getStringField(int nField, const char* szNullValue = ""); + const char* getStringField(const char* szField, const char* szNullValue = ""); - const unsigned char *getBlobField(int nField, int &nLen); - const unsigned char *getBlobField(const char *szField, int &nLen); + const unsigned char* getBlobField(int nField, int& nLen); + const unsigned char* getBlobField(const char* szField, int& nLen); bool fieldIsNull(int nField); - bool fieldIsNull(const char *szField); + bool fieldIsNull(const char* szField); bool eof(); @@ -150,8 +150,8 @@ class CppSQLite3Query { private: void checkVM(); - sqlite3 *mpDB; - sqlite3_stmt *mpVM; + sqlite3* mpDB; + sqlite3_stmt* mpVM; bool mbEof; int mnCols; bool mbOwnVM; @@ -161,34 +161,34 @@ class CppSQLite3Table { public: CppSQLite3Table(); - CppSQLite3Table(const CppSQLite3Table &rTable); + CppSQLite3Table(const CppSQLite3Table& rTable); - CppSQLite3Table(char **paszResults, int nRows, int nCols); + CppSQLite3Table(char** paszResults, int nRows, int nCols); virtual ~CppSQLite3Table(); - CppSQLite3Table &operator=(const CppSQLite3Table &rTable); + CppSQLite3Table& operator=(const CppSQLite3Table& rTable); int numFields(); int numRows(); - const char *fieldName(int nCol); + const char* fieldName(int nCol); - const char *fieldValue(int nField); - const char *fieldValue(const char *szField); + const char* fieldValue(int nField); + const char* fieldValue(const char* szField); int getIntField(int nField, int nNullValue = 0); - int getIntField(const char *szField, int nNullValue = 0); + int getIntField(const char* szField, int nNullValue = 0); double getFloatField(int nField, double fNullValue = 0.0); - double getFloatField(const char *szField, double fNullValue = 0.0); + double getFloatField(const char* szField, double fNullValue = 0.0); - const char *getStringField(int nField, const char *szNullValue = ""); - const char *getStringField(const char *szField, const char *szNullValue = ""); + const char* getStringField(int nField, const char* szNullValue = ""); + const char* getStringField(const char* szField, const char* szNullValue = ""); bool fieldIsNull(int nField); - bool fieldIsNull(const char *szField); + bool fieldIsNull(const char* szField); void setRow(int nRow); @@ -200,37 +200,37 @@ class CppSQLite3Table { int mnCols; int mnRows; int mnCurrentRow; - char **mpaszResults; + char** mpaszResults; }; class CppSQLite3Statement { public: CppSQLite3Statement(); - CppSQLite3Statement(const CppSQLite3Statement &rStatement); + CppSQLite3Statement(const CppSQLite3Statement& rStatement); - CppSQLite3Statement(sqlite3 *pDB, sqlite3_stmt *pVM); + CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM); virtual ~CppSQLite3Statement(); - CppSQLite3Statement &operator=(const CppSQLite3Statement &rStatement); + CppSQLite3Statement& operator=(const CppSQLite3Statement& rStatement); int execDML(); CppSQLite3Query execQuery(); - void bind(int nParam, const char *szValue); + void bind(int nParam, const char* szValue); void bind(int nParam, const int nValue); void bind(int nParam, const double dwValue); - void bind(int nParam, const unsigned char *blobValue, int nLen); + void bind(int nParam, const unsigned char* blobValue, int nLen); void bindNull(int nParam); - int bindParameterIndex(const char *szParam); - void bind(const char *szParam, const char *szValue); - void bind(const char *szParam, const int nValue); - void bind(const char *szParam, const double dwValue); - void bind(const char *szParam, const unsigned char *blobValue, int nLen); - void bindNull(const char *szParam); + int bindParameterIndex(const char* szParam); + void bind(const char* szParam, const char* szValue); + void bind(const char* szParam, const int nValue); + void bind(const char* szParam, const double dwValue); + void bind(const char* szParam, const unsigned char* blobValue, int nLen); + void bindNull(const char* szParam); void reset(); @@ -240,8 +240,8 @@ class CppSQLite3Statement { void checkDB(); void checkVM(); - sqlite3 *mpDB; - sqlite3_stmt *mpVM; + sqlite3* mpDB; + sqlite3_stmt* mpVM; }; class CppSQLite3DB { @@ -250,21 +250,21 @@ class CppSQLite3DB { virtual ~CppSQLite3DB(); - void open(const char *szFile); + void open(const char* szFile); void close(); - bool tableExists(const char *szTable); + bool tableExists(const char* szTable); - int execDML(const char *szSQL); + int execDML(const char* szSQL); - CppSQLite3Query execQuery(const char *szSQL); + CppSQLite3Query execQuery(const char* szSQL); - int execScalar(const char *szSQL, int nNullValue = 0); + int execScalar(const char* szSQL, int nNullValue = 0); - CppSQLite3Table getTable(const char *szSQL); + CppSQLite3Table getTable(const char* szSQL); - CppSQLite3Statement compileStatement(const char *szSQL); + CppSQLite3Statement compileStatement(const char* szSQL); sqlite_int64 lastRowId(); @@ -272,25 +272,25 @@ class CppSQLite3DB { void setBusyTimeout(int nMillisecs); - static const char *SQLiteVersion() { return SQLITE_VERSION; } + static const char* SQLiteVersion() { return SQLITE_VERSION; } - static const char *SQLiteHeaderVersion() { return SQLITE_VERSION; } + static const char* SQLiteHeaderVersion() { return SQLITE_VERSION; } - static const char *SQLiteLibraryVersion() { return sqlite3_libversion(); } + static const char* SQLiteLibraryVersion() { return sqlite3_libversion(); } static int SQLiteLibraryVersionNumber() { return sqlite3_libversion_number(); } bool IsAutoCommitOn(); private: - CppSQLite3DB(const CppSQLite3DB &db); - CppSQLite3DB &operator=(const CppSQLite3DB &db); + CppSQLite3DB(const CppSQLite3DB& db); + CppSQLite3DB& operator=(const CppSQLite3DB& db); - sqlite3_stmt *compile(const char *szSQL); + sqlite3_stmt* compile(const char* szSQL); void checkDB(); - sqlite3 *mpDB; + sqlite3* mpDB; int mnBusyTimeoutMs; }; diff --git a/src/CurrencyBox.cpp b/src/CurrencyBox.cpp index dc66034..d87289d 100644 --- a/src/CurrencyBox.cpp +++ b/src/CurrencyBox.cpp @@ -10,13 +10,13 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CurrencyBox" - -CurrencyBoxFilter::CurrencyBoxFilter(CurrencyBox *box) : NavTextBoxFilter(box) {} +CurrencyBoxFilter::CurrencyBoxFilter(CurrencyBox* box) : NavTextBoxFilter(box) {} filter_result -CurrencyBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +CurrencyBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. - if (key == B_TAB && ((NavTextBox *)TextControl())->IsTabFiltering()) { + if (key == B_TAB && ((NavTextBox*)TextControl())->IsTabFiltering()) { if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else @@ -38,9 +38,10 @@ CurrencyBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { } CurrencyBox::CurrencyBox( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : NavTextBox(name, label, text, msg, flags) { + : NavTextBox(name, label, text, msg, flags) +{ SetFilter(new CurrencyBoxFilter(this)); const char amount_disallowed[] = " `~!@#%^&*()_-+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" @@ -54,7 +55,8 @@ CurrencyBox::CurrencyBox( } bool -CurrencyBox::Validate(bool alert) { +CurrencyBox::Validate(bool alert) +{ if (strlen(Text()) < 1) SetText("0"); @@ -64,12 +66,13 @@ CurrencyBox::Validate(bool alert) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the amount."), B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.") + "for this account.") ); MakeFocus(true); } return false; - } else { + } + else { BString string; gCurrentLocale.CurrencyToString(amount, string); SetText(string.String()); diff --git a/src/CurrencyBox.h b/src/CurrencyBox.h index a2a54dd..bfb5120 100644 --- a/src/CurrencyBox.h +++ b/src/CurrencyBox.h @@ -7,14 +7,14 @@ class CurrencyBox; class CurrencyBoxFilter : public NavTextBoxFilter { public: - CurrencyBoxFilter(CurrencyBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + CurrencyBoxFilter(CurrencyBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class CurrencyBox : public NavTextBox { public: CurrencyBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); diff --git a/src/DAlert.cpp b/src/DAlert.cpp index c1173cc..7f81ca9 100644 --- a/src/DAlert.cpp +++ b/src/DAlert.cpp @@ -90,11 +90,11 @@ static const int kTextBottomOffset = 45; class TAlertView : public BView { public: TAlertView(BRect frame); - TAlertView(BMessage *archive); + TAlertView(BMessage* archive); ~TAlertView(); - static TAlertView *Instantiate(BMessage *archive); - status_t Archive(BMessage *archive, bool deep = true); + static TAlertView* Instantiate(BMessage* archive); + status_t Archive(BMessage* archive, bool deep = true); virtual void Draw(BRect updateRect); @@ -102,12 +102,12 @@ class TAlertView : public BView { // dump. I can only assume that the bitmap is a public var in the // original implementation -- or DAlert is a friend of TAlertView. // Neither one is necessary, since I can just add these. - void SetBitmap(BBitmap *Icon) { fIconBitmap = Icon; } + void SetBitmap(BBitmap* Icon) { fIconBitmap = Icon; } - BBitmap *Bitmap() { return fIconBitmap; } + BBitmap* Bitmap() { return fIconBitmap; } private: - BBitmap *fIconBitmap; + BBitmap* fIconBitmap; }; //------------------------------------------------------------------------------ @@ -117,17 +117,18 @@ class TAlertView : public BView { // on DAlert so here we go. class _DAlertFilter_ : public BMessageFilter { public: - _DAlertFilter_(DAlert *Alert); + _DAlertFilter_(DAlert* Alert); ~_DAlertFilter_(); - virtual filter_result Filter(BMessage *msg, BHandler **target); + virtual filter_result Filter(BMessage* msg, BHandler** target); private: - DAlert *fAlert; + DAlert* fAlert; }; static float -width_from_label(BButton *button) { +width_from_label(BButton* button) +{ // BButton::GetPreferredSize() does not return the minimum width // required to fit the label. Thus, the width is computed here. return button->StringWidth(button->Label()) + 20.0f; @@ -137,43 +138,47 @@ width_from_label(BButton *button) { DAlert::DAlert( - const char *title, const char *text, const char *button1, const char *button2, - const char *button3, button_width width, alert_type type + const char* title, const char* text, const char* button1, const char* button2, + const char* button3, button_width width, alert_type type ) : BWindow( DEFAULT_RECT, title, B_MODAL_WINDOW, B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS - ) { + ) +{ InitObject(text, button1, button2, button3, width, B_EVEN_SPACING, type); } DAlert::DAlert( - const char *title, const char *text, const char *button1, const char *button2, - const char *button3, button_width width, button_spacing spacing, alert_type type + const char* title, const char* text, const char* button1, const char* button2, + const char* button3, button_width width, button_spacing spacing, alert_type type ) : BWindow( DEFAULT_RECT, title, B_MODAL_WINDOW, B_NOT_CLOSABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS - ) { + ) +{ InitObject(text, button1, button2, button3, width, spacing, type); } -DAlert::~DAlert() { +DAlert::~DAlert() +{ // Probably not necessary, but it makes me feel better. if (fAlertSem >= B_OK) delete_sem(fAlertSem); } -DAlert::DAlert(BMessage *data) : BWindow(data) { +DAlert::DAlert(BMessage* data) : BWindow(data) +{ fInvoker = NULL; fAlertSem = -1; fAlertVal = -1; - fTextView = (BTextView *)FindView("_tv_"); + fTextView = (BTextView*)FindView("_tv_"); - fButtons[0] = (BButton *)FindView("_b0_"); - fButtons[1] = (BButton *)FindView("_b1_"); - fButtons[2] = (BButton *)FindView("_b2_"); + fButtons[0] = (BButton*)FindView("_b0_"); + fButtons[1] = (BButton*)FindView("_b1_"); + fButtons[2] = (BButton*)FindView("_b2_"); if (fButtons[2]) SetDefaultButton(fButtons[2]); @@ -182,14 +187,14 @@ DAlert::DAlert(BMessage *data) : BWindow(data) { else if (fButtons[0]) SetDefaultButton(fButtons[0]); - TAlertView *master = (TAlertView *)FindView("_master_"); + TAlertView* master = (TAlertView*)FindView("_master_"); if (master) master->SetBitmap(InitIcon()); // Get keys char key; for (int32 i = 0; i < 3; ++i) { - if (data->FindInt8("_but_key", i, (int8 *)&key) == B_OK) + if (data->FindInt8("_but_key", i, (int8*)&key) == B_OK) fKeys[i] = key; } @@ -205,8 +210,9 @@ DAlert::DAlert(BMessage *data) : BWindow(data) { AddCommonFilter(new _DAlertFilter_(this)); } -BArchivable * -DAlert::Instantiate(BMessage *data) { +BArchivable* +DAlert::Instantiate(BMessage* data) +{ if (!validate_instantiation(data, "DAlert")) return NULL; @@ -214,7 +220,8 @@ DAlert::Instantiate(BMessage *data) { } status_t -DAlert::Archive(BMessage *data, bool deep) const { +DAlert::Archive(BMessage* data, bool deep) const +{ status_t ret = BWindow::Archive(data, deep); // Stow the text @@ -245,13 +252,15 @@ DAlert::Archive(BMessage *data, bool deep) const { } void -DAlert::SetShortcut(int32 index, char key) { +DAlert::SetShortcut(int32 index, char key) +{ if (index >= 0 && index < 3) fKeys[index] = key; } char -DAlert::Shortcut(int32 index) const { +DAlert::Shortcut(int32 index) const +{ if (index >= 0 && index < 3) return fKeys[index]; @@ -259,7 +268,8 @@ DAlert::Shortcut(int32 index) const { } int32 -DAlert::Go() { +DAlert::Go() +{ fAlertSem = create_sem(0, "AlertSem"); if (fAlertSem < B_OK) { Quit(); @@ -267,7 +277,7 @@ DAlert::Go() { } // Get the originating window, if it exists - BWindow *window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); + BWindow* window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); Show(); @@ -287,7 +297,8 @@ DAlert::Go() { } window->UpdateIfNeeded(); } - } else { + } + else { // No window to update, so just hang out until we're done. while (acquire_sem(fAlertSem) == B_INTERRUPTED) { } @@ -302,14 +313,16 @@ DAlert::Go() { } status_t -DAlert::Go(BInvoker *invoker) { +DAlert::Go(BInvoker* invoker) +{ fInvoker = invoker; Show(); return B_OK; } void -DAlert::MessageReceived(BMessage *msg) { +DAlert::MessageReceived(BMessage* msg) +{ if (msg->what != kAlertButtonMsg) return BWindow::MessageReceived(msg); @@ -318,13 +331,14 @@ DAlert::MessageReceived(BMessage *msg) { if (fAlertSem < B_OK) { // Semaphore hasn't been created; we're running asynchronous if (fInvoker) { - BMessage *out = fInvoker->Message(); + BMessage* out = fInvoker->Message(); if (out && (out->ReplaceInt32("which", which) == B_OK || out->AddInt32("which", which) == B_OK)) fInvoker->Invoke(); } PostMessage(B_QUIT_REQUESTED); - } else { + } + else { // Created semaphore means were running synchronously fAlertVal = which; @@ -340,55 +354,64 @@ DAlert::MessageReceived(BMessage *msg) { } void -DAlert::FrameResized(float newWidth, float newHeight) { +DAlert::FrameResized(float newWidth, float newHeight) +{ BWindow::FrameResized(newWidth, newHeight); } -BButton * -DAlert::ButtonAt(int32 index) const { +BButton* +DAlert::ButtonAt(int32 index) const +{ if (index >= 0 && index < 3) return fButtons[index]; return NULL; } -BTextView * -DAlert::TextView() const { +BTextView* +DAlert::TextView() const +{ return fTextView; } -BHandler * +BHandler* DAlert::ResolveSpecifier( - BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property -) { + BMessage* msg, int32 index, BMessage* specifier, int32 form, const char* property +) +{ return BWindow::ResolveSpecifier(msg, index, specifier, form, property); } status_t -DAlert::GetSupportedSuites(BMessage *data) { +DAlert::GetSupportedSuites(BMessage* data) +{ return BWindow::GetSupportedSuites(data); } void -DAlert::DispatchMessage(BMessage *msg, BHandler *handler) { +DAlert::DispatchMessage(BMessage* msg, BHandler* handler) +{ BWindow::DispatchMessage(msg, handler); } void -DAlert::Quit() { +DAlert::Quit() +{ BWindow::Quit(); } bool -DAlert::QuitRequested() { +DAlert::QuitRequested() +{ return BWindow::QuitRequested(); } BPoint -DAlert::AlertPosition(float width, float height) { +DAlert::AlertPosition(float width, float height) +{ BPoint result(100, 100); - BWindow *window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); + BWindow* window = dynamic_cast(BLooper::LooperForThread(find_thread(NULL))); BScreen screen(window); BRect screenFrame(0, 0, 640, 480); @@ -405,24 +428,32 @@ DAlert::AlertPosition(float width, float height) { } status_t -DAlert::Perform(perform_code d, void *arg) { +DAlert::Perform(perform_code d, void* arg) +{ return BWindow::Perform(d, arg); } void -DAlert::_ReservedAlert1() {} +DAlert::_ReservedAlert1() +{ +} void -DAlert::_ReservedAlert2() {} +DAlert::_ReservedAlert2() +{ +} void -DAlert::_ReservedAlert3() {} +DAlert::_ReservedAlert3() +{ +} void DAlert::InitObject( - const char *text, const char *button0, const char *button1, const char *button2, + const char* text, const char* button0, const char* button1, const char* button2, button_width width, button_spacing spacing, alert_type type -) { +) +{ fInvoker = NULL; fAlertSem = -1; fAlertVal = -1; @@ -433,7 +464,7 @@ DAlert::InitObject( fButtonWidth = width; // Set up the "_master_" view - TAlertView *masterView = new TAlertView(Bounds()); + TAlertView* masterView = new TAlertView(Bounds()); AddChild(masterView); masterView->SetBitmap(InitIcon()); @@ -510,7 +541,8 @@ DAlert::InitObject( buttonY -= kButtonBottomOffset; else buttonY -= kDefButtonBottomOffset; - } else { + } + else { buttonX = fButtons[i + 1]->Frame().left - fButtons[i]->Frame().Width() - kButtonSpaceOffset; buttonY -= kButtonBottomOffset; @@ -533,7 +565,8 @@ DAlert::InitObject( kButtonMinOffsetSpaceOffset; } } - } else if (buttonCount == 3) + } + else if (buttonCount == 3) buttonX -= 3; } } @@ -554,7 +587,8 @@ DAlert::InitObject( totalWidth = max(kWindowOffsetMinWidth, totalWidth); else totalWidth = max(kWindowMinWidth, totalWidth); - } else { + } + else { totalWidth += 5; totalWidth = max(kWindowMinWidth, totalWidth); } @@ -603,9 +637,10 @@ DAlert::InitObject( MoveTo(AlertPosition(Frame().Width(), Frame().Height())); } -BBitmap * -DAlert::InitIcon() { - BBitmap *icon = NULL; +BBitmap* +DAlert::InitIcon() +{ + BBitmap* icon = NULL; switch (fMsgType) { case B_INFO_ALERT: @@ -640,17 +675,19 @@ DAlert::InitIcon() { TAlertView::TAlertView(BRect frame) - : BView(frame, "TAlertView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW), fIconBitmap(NULL) { + : BView(frame, "TAlertView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW), fIconBitmap(NULL) +{ // SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); SetViewColor(240, 240, 240); } -TAlertView::TAlertView(BMessage *archive) : BView(archive), fIconBitmap(NULL) {} +TAlertView::TAlertView(BMessage* archive) : BView(archive), fIconBitmap(NULL) {} TAlertView::~TAlertView() { delete fIconBitmap; } -TAlertView * -TAlertView::Instantiate(BMessage *archive) { +TAlertView* +TAlertView::Instantiate(BMessage* archive) +{ if (!validate_instantiation(archive, "TAlertView")) return NULL; @@ -658,12 +695,14 @@ TAlertView::Instantiate(BMessage *archive) { } status_t -TAlertView::Archive(BMessage *archive, bool deep) { +TAlertView::Archive(BMessage* archive, bool deep) +{ return BView::Archive(archive, deep); } void -TAlertView::Draw(BRect updateRect) { +TAlertView::Draw(BRect updateRect) +{ // Here's the fun stuff if (fIconBitmap) { /* BRect stripeRect = Bounds(); @@ -682,15 +721,16 @@ TAlertView::Draw(BRect updateRect) { // #pragma mark - _DAlertFilter_ -_DAlertFilter_::_DAlertFilter_(DAlert *alert) : BMessageFilter(B_KEY_DOWN), fAlert(alert) {} +_DAlertFilter_::_DAlertFilter_(DAlert* alert) : BMessageFilter(B_KEY_DOWN), fAlert(alert) {} _DAlertFilter_::~_DAlertFilter_() {} filter_result -_DAlertFilter_::Filter(BMessage *msg, BHandler **target) { +_DAlertFilter_::Filter(BMessage* msg, BHandler** target) +{ if (msg->what == B_KEY_DOWN) { char byte; - if (msg->FindInt8("byte", (int8 *)&byte) == B_OK) { + if (msg->FindInt8("byte", (int8*)&byte) == B_OK) { for (int i = 0; i < 3; ++i) { if (byte == fAlert->Shortcut(i) && fAlert->ButtonAt(i)) { char space = ' '; diff --git a/src/DAlert.h b/src/DAlert.h index 0fc47b9..2aaaeb0 100644 --- a/src/DAlert.h +++ b/src/DAlert.h @@ -56,47 +56,47 @@ enum button_spacing { B_EVEN_SPACING = 0, B_OFFSET_SPACING }; class DAlert : public BWindow { public: DAlert( - const char *title, const char *text, const char *button1, const char *button2 = NULL, - const char *button3 = NULL, button_width width = B_WIDTH_AS_USUAL, + const char* title, const char* text, const char* button1, const char* button2 = NULL, + const char* button3 = NULL, button_width width = B_WIDTH_AS_USUAL, alert_type type = B_INFO_ALERT ); DAlert( - const char *title, const char *text, const char *button1, const char *button2, - const char *button3, button_width width, button_spacing spacing, + const char* title, const char* text, const char* button1, const char* button2, + const char* button3, button_width width, button_spacing spacing, alert_type type = B_INFO_ALERT ); virtual ~DAlert(); // Archiving - DAlert(BMessage *data); - static BArchivable *Instantiate(BMessage *data); - virtual status_t Archive(BMessage *data, bool deep = true) const; + DAlert(BMessage* data); + static BArchivable* Instantiate(BMessage* data); + virtual status_t Archive(BMessage* data, bool deep = true) const; // DAlert guts void SetShortcut(int32 button_index, char key); char Shortcut(int32 button_index) const; int32 Go(); - status_t Go(BInvoker *invoker); + status_t Go(BInvoker* invoker); - virtual void MessageReceived(BMessage *an_event); + virtual void MessageReceived(BMessage* an_event); virtual void FrameResized(float new_width, float new_height); - BButton *ButtonAt(int32 index) const; - BTextView *TextView() const; + BButton* ButtonAt(int32 index) const; + BTextView* TextView() const; - virtual BHandler *ResolveSpecifier( - BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property + virtual BHandler* ResolveSpecifier( + BMessage* msg, int32 index, BMessage* specifier, int32 form, const char* property ); - virtual status_t GetSupportedSuites(BMessage *data); + virtual status_t GetSupportedSuites(BMessage* data); - virtual void DispatchMessage(BMessage *msg, BHandler *handler); + virtual void DispatchMessage(BMessage* msg, BHandler* handler); virtual void Quit(); virtual bool QuitRequested(); static BPoint AlertPosition(float width, float height); // Private or reserved --------------------------------------------------------- - virtual status_t Perform(perform_code d, void *arg); + virtual status_t Perform(perform_code d, void* arg); private: friend class _DAlertFilter_; @@ -106,20 +106,20 @@ class DAlert : public BWindow { virtual void _ReservedAlert3(); void InitObject( - const char *text, const char *button1, const char *button2 = NULL, - const char *button3 = NULL, button_width width = B_WIDTH_AS_USUAL, + const char* text, const char* button1, const char* button2 = NULL, + const char* button3 = NULL, button_width width = B_WIDTH_AS_USUAL, button_spacing spacing = B_EVEN_SPACING, alert_type type = B_INFO_ALERT ); - BBitmap *InitIcon(); + BBitmap* InitIcon(); sem_id fAlertSem; int32 fAlertVal; - BButton *fButtons[3]; - BTextView *fTextView; + BButton* fButtons[3]; + BTextView* fTextView; char fKeys[3]; alert_type fMsgType; button_width fButtonWidth; - BInvoker *fInvoker; + BInvoker* fInvoker; uint32 _reserved[4]; }; diff --git a/src/DStringList.cpp b/src/DStringList.cpp index eb66be4..14dc259 100644 --- a/src/DStringList.cpp +++ b/src/DStringList.cpp @@ -6,7 +6,8 @@ DStringList::DStringList(int32 itemsPerBlock, bool owner) : fList(itemsPerBlock) DStringList::~DStringList() { MakeEmpty(fOwner); } bool -DStringList::AddItem(const char *string) { +DStringList::AddItem(const char* string) +{ if (!string) return false; @@ -14,7 +15,8 @@ DStringList::AddItem(const char *string) { } bool -DStringList::AddItem(const char *string, int32 atIndex) { +DStringList::AddItem(const char* string, int32 atIndex) +{ if (!string) return false; @@ -22,7 +24,8 @@ DStringList::AddItem(const char *string, int32 atIndex) { } bool -DStringList::AddList(DStringList *newItems) { +DStringList::AddList(DStringList* newItems) +{ if (!newItems) return false; @@ -32,7 +35,8 @@ DStringList::AddList(DStringList *newItems) { } bool -DStringList::AddList(DStringList *newItems, int32 atIndex) { +DStringList::AddList(DStringList* newItems, int32 atIndex) +{ if (!newItems) return false; @@ -42,45 +46,51 @@ DStringList::AddList(DStringList *newItems, int32 atIndex) { } bool -DStringList::RemoveItem(BString *item) { +DStringList::RemoveItem(BString* item) +{ return fList.RemoveItem(item); } -BString * -DStringList::RemoveItem(int32 index) { - return (BString *)fList.RemoveItem(index); +BString* +DStringList::RemoveItem(int32 index) +{ + return (BString*)fList.RemoveItem(index); } bool -DStringList::RemoveItems(int32 index, int32 count) { - return (BString *)fList.RemoveItems(index, count); +DStringList::RemoveItems(int32 index, int32 count) +{ + return (BString*)fList.RemoveItems(index, count); } bool -DStringList::ReplaceItem(int32 index, BString *newItem) { +DStringList::ReplaceItem(int32 index, BString* newItem) +{ return fList.ReplaceItem(index, newItem); } bool -DStringList::HasItem(const char *string) const { +DStringList::HasItem(const char* string) const +{ if (!string) return false; for (int32 i = 0; i < CountItems(); i++) { - BString *item = ItemAt(i); + BString* item = ItemAt(i); if (item->Compare(string) == 0) return true; } return false; } -BString * -DStringList::FindItem(const char *string) const { +BString* +DStringList::FindItem(const char* string) const +{ if (!string) return NULL; for (int32 i = 0; i < CountItems(); i++) { - BString *item = ItemAt(i); + BString* item = ItemAt(i); if (item->Compare(string) == 0) return item; } @@ -88,11 +98,12 @@ DStringList::FindItem(const char *string) const { } void -DStringList::MakeEmpty(bool freemem) { +DStringList::MakeEmpty(bool freemem) +{ if (freemem) { - BString *str; + BString* str; for (int32 i = 0; i < fList.CountItems(); i++) { - str = (BString *)fList.ItemAtFast(i); + str = (BString*)fList.ItemAtFast(i); if (str) delete str; } @@ -101,8 +112,9 @@ DStringList::MakeEmpty(bool freemem) { } void -DStringList::PrintToStream(void) { - BString *str; +DStringList::PrintToStream(void) +{ + BString* str; printf("DStringList: %ld items\n", fList.CountItems()); diff --git a/src/DStringList.h b/src/DStringList.h index 2938e32..35b2dd7 100644 --- a/src/DStringList.h +++ b/src/DStringList.h @@ -11,14 +11,14 @@ class DStringList { DStringList(int32 itemsPerBlock = 20, bool owner = true); virtual ~DStringList(); - bool AddItem(const char *string); - bool AddItem(const char *string, int32 atIndex); - bool AddList(DStringList *newItems); - bool AddList(DStringList *newItems, int32 atIndex); - bool RemoveItem(BString *item); - BString *RemoveItem(int32 index); + bool AddItem(const char* string); + bool AddItem(const char* string, int32 atIndex); + bool AddList(DStringList* newItems); + bool AddList(DStringList* newItems, int32 atIndex); + bool RemoveItem(BString* item); + BString* RemoveItem(int32 index); bool RemoveItems(int32 index, int32 count); - bool ReplaceItem(int32 index, BString *newItem); + bool ReplaceItem(int32 index, BString* newItem); void MakeEmpty(bool freemem = false); // void SortItems(void); @@ -26,23 +26,23 @@ class DStringList { bool MoveItem(int32 fromIndex, int32 toIndex) { return fList.MoveItem(fromIndex, toIndex); } - BString *FindItem(const char *string) const; + BString* FindItem(const char* string) const; - BString *ItemAt(int32 index) const { return (BString *)fList.ItemAtFast(index); } + BString* ItemAt(int32 index) const { return (BString*)fList.ItemAtFast(index); } - BString *ItemAtFast(int32 index) const { return (BString *)fList.ItemAtFast(index); } + BString* ItemAtFast(int32 index) const { return (BString*)fList.ItemAtFast(index); } - BString *FirstItem() const { return (BString *)fList.FirstItem(); } + BString* FirstItem() const { return (BString*)fList.FirstItem(); } - BString *LastItem() const { return (BString *)fList.LastItem(); } + BString* LastItem() const { return (BString*)fList.LastItem(); } - BString *Items() const { return (BString *)fList.Items(); } + BString* Items() const { return (BString*)fList.Items(); } - bool HasItem(const char *string) const; + bool HasItem(const char* string) const; - bool HasItem(BString *item) const { return fList.HasItem(item); } + bool HasItem(BString* item) const { return fList.HasItem(item); } - int32 IndexOf(BString *item) const { return fList.IndexOf(item); } + int32 IndexOf(BString* item) const { return fList.IndexOf(item); } int32 CountItems() const { return fList.CountItems(); } diff --git a/src/Database.cpp b/src/Database.cpp index f6c8baf..8afa3bf 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -31,12 +31,13 @@ Locale gCurrentLocale; // This global is used to hold all financial data for CapitalBe. Database gDatabase; -Database::Database(const char *path) : fCurrent(NULL), fList(20, true), fPath(path) {} +Database::Database(const char* path) : fCurrent(NULL), fList(20, true), fPath(path) {} Database::~Database(void) {} void -Database::CloseAccount(Account *item) { +Database::CloseAccount(Account* item) +{ if (!item) return; @@ -48,13 +49,14 @@ Database::CloseAccount(Account *item) { item->SetClosed(true); BMessage msg; - msg.AddPointer("item", (void *)item); + msg.AddPointer("item", (void*)item); Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } void -Database::RenameAccount(Account *item, const char *name) { +Database::RenameAccount(Account* item, const char* name) +{ if (item && name) { LOCK; BString command = "update accountlist set name = '"; @@ -65,14 +67,15 @@ Database::RenameAccount(Account *item, const char *name) { item->SetName(name); BMessage msg; - msg.AddPointer("item", (void *)item); + msg.AddPointer("item", (void*)item); Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } } void -Database::ReopenAccount(Account *item) { +Database::ReopenAccount(Account* item) +{ if (!item) return; @@ -83,13 +86,14 @@ Database::ReopenAccount(Account *item) { item->SetClosed(false); BMessage msg; - msg.AddPointer("item", (void *)item); + msg.AddPointer("item", (void*)item); Notify(WATCH_CHANGE | WATCH_ACCOUNT, &msg); UNLOCK; } void -Database::CreateFile(const char *path) { +Database::CreateFile(const char* path) +{ if (!path) return; @@ -99,7 +103,8 @@ Database::CreateFile(const char *path) { try { fDB.open(path); - } catch (...) { + } + catch (...) { BString error = "Couldn't create database file '"; error << path << "'."; ShowBug(error.String()); @@ -168,7 +173,8 @@ Database::CreateFile(const char *path) { } status_t -Database::OpenFile(const char *path) { +Database::OpenFile(const char* path) +{ if (!path) return B_ERROR; @@ -185,7 +191,8 @@ Database::OpenFile(const char *path) { try { fDB.open(path); - } catch (...) { + } + catch (...) { UNLOCK; ShowAlert( "Couldn't open account data.", @@ -206,7 +213,7 @@ Database::OpenFile(const char *path) { // BString type = query.getStringField(2); BString status = DeescapeIllegalCharacters(query.getStringField(3)); - Account *account = new Account(name.String(), status.ICompare("open") != 0); + Account* account = new Account(name.String(), status.ICompare("open") != 0); account->SetID(id); if (UsesDefaultLocale(id)) { account->UseDefaultLocale(false); @@ -215,7 +222,7 @@ Database::OpenFile(const char *path) { fList.AddItem(account); BMessage msg; - msg.AddPointer("item", (void *)account); + msg.AddPointer("item", (void*)account); Notify(WATCH_CREATE | WATCH_ACCOUNT, &msg); query.nextRow(); @@ -224,7 +231,7 @@ Database::OpenFile(const char *path) { // Set the current transaction and last check number for each account for (int32 i = 0; i < fList.CountItems(); i++) { - Account *acc = fList.ItemAt(i); + Account* acc = fList.ItemAt(i); BString command("select transid from account_"); command << acc->GetID() << " order by date,transid;"; @@ -238,20 +245,22 @@ Database::OpenFile(const char *path) { gDefaultLocale = GetDefaultLocale(); - fCurrent = (Account *)fList.ItemAt(0); + fCurrent = (Account*)fList.ItemAt(0); UNLOCK; return B_OK; } void -Database::CloseFile(void) { +Database::CloseFile(void) +{ LOCK; fDB.close(); UNLOCK; } bool -Database::ImportFile(const entry_ref &ref) { +Database::ImportFile(const entry_ref& ref) +{ LOCK; Notify(WATCH_MASS_EDIT, NULL); bool value = ImportQIF(ref); @@ -262,7 +271,8 @@ Database::ImportFile(const entry_ref &ref) { } bool -Database::ExportFile(const entry_ref &ref) { +Database::ExportFile(const entry_ref& ref) +{ LOCK; bool value = ExportQIF(ref); UNLOCK; @@ -270,16 +280,17 @@ Database::ExportFile(const entry_ref &ref) { return value; } -Account * -Database::SetCurrentAccount(const int32 &index) { +Account* +Database::SetCurrentAccount(const int32& index) +{ // We actually permit a NULL pointer here because sometimes we don't *have* an account // to operate on LOCK; - Account *acc = (Account *)fList.ItemAt(index); + Account* acc = (Account*)fList.ItemAt(index); fCurrent = acc; BMessage msg; - msg.AddPointer("item", (void *)acc); + msg.AddPointer("item", (void*)acc); Notify(WATCH_SELECT | WATCH_ACCOUNT, &msg); UNLOCK; @@ -287,7 +298,8 @@ Database::SetCurrentAccount(const int32 &index) { } int32 -Database::SetCurrentAccount(Account *account) { +Database::SetCurrentAccount(Account* account) +{ if (!account) { LOCK; SetCurrentAccount(-1); @@ -304,7 +316,7 @@ Database::SetCurrentAccount(Account *account) { fCurrent = account; BMessage msg; - msg.AddPointer("item", (void *)account); + msg.AddPointer("item", (void*)account); Notify(WATCH_SELECT | WATCH_ACCOUNT, &msg); int32 value = fList.IndexOf(account); @@ -312,10 +324,11 @@ Database::SetCurrentAccount(Account *account) { return value; } -Account * +Account* Database::AddAccount( - const char *name, const AccountType &type, const char *status, const Locale *locale -) { + const char* name, const AccountType& type, const char* status, const Locale* locale +) +{ if (!name || !status) return NULL; @@ -345,7 +358,7 @@ Database::AddAccount( DBCommand(command.String(), "Database::AddAccount:create account"); - Account *account = new Account(name); + Account* account = new Account(name); account->SetID(id); if (strcmp(status, "closed") == 0) account->SetClosed(true); @@ -355,7 +368,7 @@ Database::AddAccount( fCurrent = account; BMessage msg; - msg.AddPointer("item", (void *)account); + msg.AddPointer("item", (void*)account); Notify(WATCH_CREATE | WATCH_ACCOUNT, &msg); UNLOCK; @@ -363,7 +376,8 @@ Database::AddAccount( } bool -Database::RemoveAccount(const int &accountid) { +Database::RemoveAccount(const int& accountid) +{ LOCK; BString command; command << "select accountid from accountlist where accountid = " << accountid << ";"; @@ -372,10 +386,10 @@ Database::RemoveAccount(const int &accountid) { if (!query.eof()) { query.finalize(); - Account *item = AccountByID(accountid); + Account* item = AccountByID(accountid); if (item) { BMessage msg; - msg.AddPointer("item", (void *)item); + msg.AddPointer("item", (void*)item); Notify(WATCH_DELETE | WATCH_ACCOUNT, &msg); } @@ -404,28 +418,31 @@ Database::RemoveAccount(const int &accountid) { } void -Database::RemoveAccount(Account *account) { +Database::RemoveAccount(Account* account) +{ if (account) RemoveAccount(account->GetID()); } -Account * -Database::AccountByName(const char *name) { +Account* +Database::AccountByName(const char* name) +{ if (!name) return NULL; for (int32 i = 0; i < fList.CountItems(); i++) { - Account *acc = fList.ItemAt(i); + Account* acc = fList.ItemAt(i); if (acc && acc->Name() && strcmp(name, acc->Name()) == 0) return acc; } return NULL; } -Account * -Database::AccountByID(const uint32 &accountid) { +Account* +Database::AccountByID(const uint32& accountid) +{ for (int32 i = 0; i < fList.CountItems(); i++) { - Account *acc = fList.ItemAt(i); + Account* acc = fList.ItemAt(i); if (acc && acc->GetID() == accountid) return acc; } @@ -433,7 +450,8 @@ Database::AccountByID(const uint32 &accountid) { } void -Database::AddBudgetEntry(const BudgetEntry &entry) { +Database::AddBudgetEntry(const BudgetEntry& entry) +{ if (entry.name.CountChars() < 1 || !HasCategory(entry.name.String())) return; @@ -473,7 +491,8 @@ Database::AddBudgetEntry(const BudgetEntry &entry) { } bool -Database::RemoveBudgetEntry(const char *category) { +Database::RemoveBudgetEntry(const char* category) +{ if (!category || !HasBudgetEntry(category)) return false; @@ -488,7 +507,8 @@ Database::RemoveBudgetEntry(const char *category) { } bool -Database::HasBudgetEntry(const char *category) { +Database::HasBudgetEntry(const char* category) +{ if (!category) return false; @@ -504,7 +524,8 @@ Database::HasBudgetEntry(const char *category) { } bool -Database::GetBudgetEntry(const char *name, BudgetEntry &entry) { +Database::GetBudgetEntry(const char* name, BudgetEntry& entry) +{ if (!name) return false; @@ -524,7 +545,8 @@ Database::GetBudgetEntry(const char *name, BudgetEntry &entry) { } int32 -Database::CountBudgetEntries(void) { +Database::CountBudgetEntries(void) +{ CppSQLite3Query query = gDatabase.DBQuery("select category from budgetlist", "Database::CountBudgetEntries"); @@ -537,7 +559,8 @@ Database::CountBudgetEntries(void) { } void -Database::SetAccountLocale(const uint32 &accountid, const Locale &data) { +Database::SetAccountLocale(const uint32& accountid, const Locale& data) +{ LOCK; BString command("select accountid from accountlocale where accountid = "); command << accountid << ";"; @@ -586,7 +609,8 @@ Database::SetAccountLocale(const uint32 &accountid, const Locale &data) { } Locale -Database::LocaleForAccount(const uint32 &id) { +Database::LocaleForAccount(const uint32& id) +{ LOCK; BString command; command << "select * from accountlocale where accountid = " << id << ";"; @@ -612,7 +636,8 @@ Database::LocaleForAccount(const uint32 &id) { } void -Database::SetDefaultLocale(const Locale &data) { +Database::SetDefaultLocale(const Locale& data) +{ LOCK; BString command; @@ -644,7 +669,8 @@ Database::SetDefaultLocale(const Locale &data) { } Locale -Database::GetDefaultLocale(void) { +Database::GetDefaultLocale(void) +{ LOCK; CppSQLite3Query query = DBQuery("select * from defaultlocale;", "Database::GetDefaultLocale"); @@ -668,7 +694,8 @@ Database::GetDefaultLocale(void) { } bool -Database::UsesDefaultLocale(const uint32 &id) { +Database::UsesDefaultLocale(const uint32& id) +{ LOCK; BString command = "select accountid from accountlocale where accountid = "; @@ -682,10 +709,11 @@ Database::UsesDefaultLocale(const uint32 &id) { bool Database::AddTransaction( - const uint32 &accountid, const uint32 &id, const time_t &date, const TransactionType &type, - const char *payee, const Fixed &amount, const char *category, const char *memo, - const uint8 &status -) { + const uint32& accountid, const uint32& id, const time_t& date, const TransactionType& type, + const char* payee, const Fixed& amount, const char* category, const char* memo, + const uint8& status +) +{ if (!payee || !category) return false; @@ -719,7 +747,7 @@ Database::AddTransaction( DBCommand(command.String(), "Database::AddTransaction:insert into account"); - Account *account = AccountByID(accountid); + Account* account = AccountByID(accountid); if (account) { if (account->CurrentTransaction() == 0) { // It appears that the account is empty. Make sure and, if so, set the just-added @@ -740,7 +768,7 @@ Database::AddTransaction( TransactionData data; GetTransaction(id, data); msg.AddInt32("accountid", accountid); - msg.AddPointer("item", (void *)&data); + msg.AddPointer("item", (void*)&data); Notify(WATCH_CREATE | WATCH_TRANSACTION, &msg); } UNLOCK; @@ -749,7 +777,8 @@ Database::AddTransaction( } bool -Database::AddTransaction(TransactionData &data, const bool &newid) { +Database::AddTransaction(TransactionData& data, const bool& newid) +{ if (!data.IsValid()) return false; @@ -766,7 +795,8 @@ Database::AddTransaction(TransactionData &data, const bool &newid) { data.GetAccount()->GetID(), id, data.Date(), data.Type(), data.Payee(), data.Amount(), data.NameAt(0), data.Memo(), data.Status() ); - } else { + } + else { if (newid) { id = NextTransactionID(); data.SetID(id); @@ -799,7 +829,8 @@ Database::AddTransaction(TransactionData &data, const bool &newid) { } bool -Database::RemoveTransaction(const uint32 &transid) { +Database::RemoveTransaction(const uint32& transid) +{ if (!HasTransaction(transid)) return false; @@ -841,7 +872,7 @@ Database::RemoveTransaction(const uint32 &transid) { DBCommand(command.String(), "Database::RemoveTransaction:delete from account"); // determine if the account is empty and set the current to 0 if it is. - Account *account = AccountByID(accountid); + Account* account = AccountByID(accountid); if (account) { command = "select * from account_"; command << accountid << ";"; @@ -861,7 +892,8 @@ Database::RemoveTransaction(const uint32 &transid) { } uint32 -Database::NextTransactionID(void) { +Database::NextTransactionID(void) +{ LOCK; uint32 key = GetLastKey("transactionlist", "transid"); key++; @@ -870,7 +902,8 @@ Database::NextTransactionID(void) { } bool -Database::HasTransaction(const uint32 &transid) { +Database::HasTransaction(const uint32& transid) +{ if (transid < 0) return false; @@ -885,7 +918,8 @@ Database::HasTransaction(const uint32 &transid) { } bool -Database::GetTransaction(const uint32 &transid, const uint32 &accountid, TransactionData &data) { +Database::GetTransaction(const uint32& transid, const uint32& accountid, TransactionData& data) +{ LOCK; BString command; @@ -928,7 +962,8 @@ Database::GetTransaction(const uint32 &transid, const uint32 &accountid, Transac } bool -Database::GetTransaction(const uint32 &transid, TransactionData &data) { +Database::GetTransaction(const uint32& transid, TransactionData& data) +{ LOCK; BString command; @@ -945,7 +980,8 @@ Database::GetTransaction(const uint32 &transid, TransactionData &data) { } void -Database::SetTransactionStatus(const uint32 &transid, const uint8 &status) { +Database::SetTransactionStatus(const uint32& transid, const uint8& status) +{ LOCK; BString command; @@ -973,14 +1009,15 @@ Database::SetTransactionStatus(const uint32 &transid, const uint8 &status) { TransactionData data; GetTransaction(transid, data); msg.AddInt32("accountid", accountid); - msg.AddPointer("item", (void *)&data); + msg.AddPointer("item", (void*)&data); Notify(WATCH_CHANGE | WATCH_TRANSACTION, &msg); UNLOCK; } bool -Database::GetTransferCounterpart(const uint32 &transid, TransactionData &data) { +Database::GetTransferCounterpart(const uint32& transid, TransactionData& data) +{ LOCK; BString command; @@ -1000,7 +1037,8 @@ Database::GetTransferCounterpart(const uint32 &transid, TransactionData &data) { } void -Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &newid) { +Database::AddScheduledTransaction(const ScheduledTransData& data, const bool& newid) +{ if (!data.IsValid()) return; @@ -1010,7 +1048,8 @@ Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &ne if (newid) { id = GetLastKey("scheduledlist", "transid"); id++; - } else + } + else id = data.GetID(); time_t nextdate = data.GetNextDueDate(); @@ -1047,7 +1086,8 @@ Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &ne id, data.GetAccount()->GetID(), data.Date(), data.Type(), data.Payee(), data.Amount(), data.NameAt(0), data.Memo(), data.GetInterval(), nextdate, data.GetCount() ); - } else { + } + else { // We are disabling notifications for the moment so that we don't end up with // multiple single-category transaction entries in the transaction view. SetNotify(false); @@ -1076,7 +1116,8 @@ Database::AddScheduledTransaction(const ScheduledTransData &data, const bool &ne } void -Database::RemoveScheduledTransaction(const uint32 &id) { +Database::RemoveScheduledTransaction(const uint32& id) +{ LOCK; BString command = "delete from scheduledlist where transid = "; command << id << ";"; @@ -1088,7 +1129,8 @@ Database::RemoveScheduledTransaction(const uint32 &id) { } bool -Database::GetScheduledTransaction(const uint32 &transid, ScheduledTransData &data) { +Database::GetScheduledTransaction(const uint32& transid, ScheduledTransData& data) +{ LOCK; BString command; @@ -1135,7 +1177,8 @@ Database::GetScheduledTransaction(const uint32 &transid, ScheduledTransData &dat } uint32 -Database::CountScheduledTransactions(void) { +Database::CountScheduledTransactions(void) +{ CppSQLite3Query query = gDatabase.DBQuery( "select count(*) from scheduledlist", "ScheduleListView::RefreshScheduleList: count transactions" @@ -1148,10 +1191,11 @@ Database::CountScheduledTransactions(void) { bool Database::InsertSchedTransaction( - const uint32 &id, const uint32 &accountid, const time_t &startdate, const TransactionType &type, - const char *payee, const Fixed &amount, const char *category, const char *memo, - const TransactionInterval &interval, const time_t &nextdate, const int32 &count -) { + const uint32& id, const uint32& accountid, const time_t& startdate, const TransactionType& type, + const char* payee, const Fixed& amount, const char* category, const char* memo, + const TransactionInterval& interval, const time_t& nextdate, const int32& count +) +{ // Internal method. No locking required if (!payee || !category) return false; @@ -1179,7 +1223,8 @@ Database::InsertSchedTransaction( } int32 -Database::GetLastKey(const char *table, const char *column) { +Database::GetLastKey(const char* table, const char* column) +{ // Internal method. No locking required if (!table || !column) return B_ERROR; @@ -1197,7 +1242,8 @@ Database::GetLastKey(const char *table, const char *column) { } void -Database::AddCategory(const char *name, const bool &isexpense) { +Database::AddCategory(const char* name, const bool& isexpense) +{ if (!name || HasCategory(name)) return; @@ -1210,7 +1256,8 @@ Database::AddCategory(const char *name, const bool &isexpense) { } void -Database::RemoveCategory(const char *name) { +Database::RemoveCategory(const char* name) +{ if (!name || !HasCategory(name)) return; @@ -1220,7 +1267,8 @@ Database::RemoveCategory(const char *name) { } bool -Database::RenameCategory(const char *oldname, const char *newname) { +Database::RenameCategory(const char* oldname, const char* newname) +{ if ((!oldname && !newname) || strcmp(oldname, newname) == 0) return false; @@ -1243,7 +1291,8 @@ Database::RenameCategory(const char *oldname, const char *newname) { } bool -Database::HasCategory(const char *name) { +Database::HasCategory(const char* name) +{ BString command; CppSQLite3Query query; @@ -1270,7 +1319,8 @@ Database::HasCategory(const char *name) { } bool -Database::IsCategoryExpense(const char *name) { +Database::IsCategoryExpense(const char* name) +{ if (!name) return false; @@ -1289,7 +1339,8 @@ Database::IsCategoryExpense(const char *name) { } void -Database::SetCategoryExpense(const char *name, const bool &isexpense) { +Database::SetCategoryExpense(const char* name, const bool& isexpense) +{ if (!name || !HasCategory(name)) return; @@ -1300,7 +1351,8 @@ Database::SetCategoryExpense(const char *name, const bool &isexpense) { } void -Database::RecategorizeTransactions(const char *from, const char *to) { +Database::RecategorizeTransactions(const char* from, const char* to) +{ if (!HasCategory(from)) return; @@ -1311,7 +1363,7 @@ Database::RecategorizeTransactions(const char *from, const char *to) { BString command; for (int32 i = 0; i < CountAccounts(); i++) { - Account *acc = AccountAt(i); + Account* acc = AccountAt(i); if (!acc) continue; @@ -1332,7 +1384,8 @@ Database::RecategorizeTransactions(const char *from, const char *to) { } BString -AccountTypeToString(const AccountType &type) { +AccountTypeToString(const AccountType& type) +{ switch (type) { case ACCOUNT_BANK: return BString("Bank"); @@ -1345,29 +1398,30 @@ AccountTypeToString(const AccountType &type) { // This will prevent SQL injection attacks -static const char *sIllegalCharacters[] = {"!", "@", "#", "$", "%", "^", "&", "*", "(", +static const char* sIllegalCharacters[] = {"!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "+", "=", "{", "}", "[", "]", "\\", "|", ";", ":", "'", "\"", "<", ">", ",", ".", "/", "?", "`", "~", " ", NULL}; -static const char *sReplacementCharacters[] = { +static const char* sReplacementCharacters[] = { "£21£", "£40£", "£23£", "£24£", "£25£", "£5e£", "£26£", "£2a£", "£28£", "£29£", "£2d£", "£2b£", "£3d£", "£7b£", "£7d£", "£5b£", "£5d£", "£5c£", "£7c£", "£3b£", "£3a£", "£27£", "£22£", "£3c£", "£3e£", "£2c£", "£2e£", "£2f£", "£3f£", "£60£", "£7e£", "£20£", NULL }; -static const char *sIllegalWords[] = {" select ", " drop ", " create ", " delete ", " where ", +static const char* sIllegalWords[] = {" select ", " drop ", " create ", " delete ", " where ", " update ", " order ", " by ", " and ", " or ", " in ", " between ", " aliases ", " join ", " union ", " alter ", " functions ", " group ", " into ", " view ", NULL}; -static const char *sReplacementWords[] = { +static const char* sReplacementWords[] = { " ¥select ", " ¥drop ", " ¥create ", " ¥delete ", " ¥where ", " ¥update ", " ¥order ", " ¥by ", " ¥and ", " ¥or ", " ¥in ", " ¥between ", " ¥aliases ", " ¥join ", " ¥union ", " ¥alter ", " ¥functions ", " ¥group ", " ¥into ", " ¥view ", NULL }; BString -EscapeIllegalCharacters(const char *instr) { +EscapeIllegalCharacters(const char* instr) +{ // Because the £ symbol isn't allowed in a category but is a valid database character, // we'll use it as the escape character for illegal characters @@ -1395,7 +1449,8 @@ EscapeIllegalCharacters(const char *instr) { } BString -DeescapeIllegalCharacters(const char *instr) { +DeescapeIllegalCharacters(const char* instr) +{ BString string(instr); if (string.CountChars() < 1) return string; @@ -1417,7 +1472,8 @@ DeescapeIllegalCharacters(const char *instr) { } void -Database::DBCommand(const char *command, const char *functionname) { +Database::DBCommand(const char* command, const char* functionname) +{ if (!command) ShowBug("NULL database command in Database::DBCommand"); if (!functionname) @@ -1425,7 +1481,8 @@ Database::DBCommand(const char *command, const char *functionname) { try { fDB.execDML(command); - } catch (CppSQLite3Exception &e) { + } + catch (CppSQLite3Exception& e) { BString msg("Database Exception in "); msg << functionname << ".\n\n" << e.errorMessage() << "\n\nDatabase Exception Command: " << command << "\n"; @@ -1435,7 +1492,8 @@ Database::DBCommand(const char *command, const char *functionname) { } CppSQLite3Query -Database::DBQuery(const char *query, const char *functionname) { +Database::DBQuery(const char* query, const char* functionname) +{ if (!query) ShowBug("NULL database command in Database::DBQuery"); if (!functionname) @@ -1443,7 +1501,8 @@ Database::DBQuery(const char *query, const char *functionname) { try { return fDB.execQuery(query); - } catch (CppSQLite3Exception &e) { + } + catch (CppSQLite3Exception& e) { BString msg("Database Exception in "); msg << functionname << ".\n\n" << e.errorMessage() << "\n\nDatabase Exception Query: " << query << "\n"; diff --git a/src/Database.h b/src/Database.h index d0e7469..e235af6 100644 --- a/src/Database.h +++ b/src/Database.h @@ -17,108 +17,108 @@ class TransactionData; class ScheduledTransData; BString -AccountTypeToString(const AccountType &type); +AccountTypeToString(const AccountType& type); class Database : public Notifier { public: - Database(const char *file = NULL); + Database(const char* file = NULL); ~Database(void); // --------------------------------------------------------------------------- // Old API functions (list-based) // --------------------------------------------------------------------------- - Account *SetCurrentAccount(const int32 &index); - int32 SetCurrentAccount(Account *account); + Account* SetCurrentAccount(const int32& index); + int32 SetCurrentAccount(Account* account); - Account *CurrentAccount(void) const { return fCurrent; } + Account* CurrentAccount(void) const { return fCurrent; } - Account *AccountAt(int32 index) { return fList.ItemAt(index); } + Account* AccountAt(int32 index) { return fList.ItemAt(index); } - Account *AccountByName(const char *name); - Account *AccountByID(const uint32 &accountid); + Account* AccountByName(const char* name); + Account* AccountByID(const uint32& accountid); int32 CountAccounts(void) { return fList.CountItems(); } void PrintToStream(void) const; - int32 IndexOf(Account *acc) { return fList.IndexOf(acc); } + int32 IndexOf(Account* acc) { return fList.IndexOf(acc); } - void CloseAccount(Account *item); - void ReopenAccount(Account *item); + void CloseAccount(Account* item); + void ReopenAccount(Account* item); - bool ImportFile(const entry_ref &ref); - bool ExportFile(const entry_ref &ref); + bool ImportFile(const entry_ref& ref); + bool ExportFile(const entry_ref& ref); // --------------------------------------------------------------------------- // SQLite-based functions // --------------------------------------------------------------------------- - void CreateFile(const char *path); - status_t OpenFile(const char *path); + void CreateFile(const char* path); + status_t OpenFile(const char* path); void CloseFile(void); - Account *AddAccount( - const char *name, const AccountType &type, const char *status = "Open", - const Locale *locale = NULL + Account* AddAccount( + const char* name, const AccountType& type, const char* status = "Open", + const Locale* locale = NULL ); - bool RemoveAccount(const int &accountid); - void RemoveAccount(Account *item); - void RenameAccount(Account *item, const char *name); - - void AddBudgetEntry(const BudgetEntry &entry); - bool RemoveBudgetEntry(const char *category); - bool HasBudgetEntry(const char *category); - bool GetBudgetEntry(const char *name, BudgetEntry &entry); + bool RemoveAccount(const int& accountid); + void RemoveAccount(Account* item); + void RenameAccount(Account* item, const char* name); + + void AddBudgetEntry(const BudgetEntry& entry); + bool RemoveBudgetEntry(const char* category); + bool HasBudgetEntry(const char* category); + bool GetBudgetEntry(const char* name, BudgetEntry& entry); int32 CountBudgetEntries(void); - void SetAccountLocale(const uint32 &accountid, const Locale &data); - Locale LocaleForAccount(const uint32 &id); - void SetDefaultLocale(const Locale &data); + void SetAccountLocale(const uint32& accountid, const Locale& data); + Locale LocaleForAccount(const uint32& id); + void SetDefaultLocale(const Locale& data); Locale GetDefaultLocale(void); - bool UsesDefaultLocale(const uint32 &id); + bool UsesDefaultLocale(const uint32& id); bool AddTransaction( - const uint32 &accountid, const uint32 &id, const time_t &date, const TransactionType &type, - const char *payee, const Fixed &amount, const char *category, const char *memo, - const uint8 &status = TRANS_OPEN + const uint32& accountid, const uint32& id, const time_t& date, const TransactionType& type, + const char* payee, const Fixed& amount, const char* category, const char* memo, + const uint8& status = TRANS_OPEN ); - bool AddTransaction(TransactionData &data, const bool &newid = true); - bool RemoveTransaction(const uint32 &transid); + bool AddTransaction(TransactionData& data, const bool& newid = true); + bool RemoveTransaction(const uint32& transid); uint32 NextTransactionID(void); - bool HasTransaction(const uint32 &transid); - bool GetTransaction(const uint32 &transid, TransactionData &data); - bool GetTransaction(const uint32 &transid, const uint32 &accountid, TransactionData &data); - void SetTransactionStatus(const uint32 &transid, const uint8 &status); + bool HasTransaction(const uint32& transid); + bool GetTransaction(const uint32& transid, TransactionData& data); + bool GetTransaction(const uint32& transid, const uint32& accountid, TransactionData& data); + void SetTransactionStatus(const uint32& transid, const uint8& status); - bool GetTransferCounterpart(const uint32 &transid, TransactionData &data); + bool GetTransferCounterpart(const uint32& transid, TransactionData& data); - void AddScheduledTransaction(const ScheduledTransData &data, const bool &newid = true); - void RemoveScheduledTransaction(const uint32 &id); - bool GetScheduledTransaction(const uint32 &transid, ScheduledTransData &data); + void AddScheduledTransaction(const ScheduledTransData& data, const bool& newid = true); + void RemoveScheduledTransaction(const uint32& id); + bool GetScheduledTransaction(const uint32& transid, ScheduledTransData& data); uint32 CountScheduledTransactions(void); - void AddCategory(const char *name, const bool &isexpense); - void RemoveCategory(const char *name); - bool RenameCategory(const char *oldname, const char *newname); - bool HasCategory(const char *name); - bool IsCategoryExpense(const char *name); - void SetCategoryExpense(const char *name, const bool &isexpense); - void RecategorizeTransactions(const char *from, const char *to); + void AddCategory(const char* name, const bool& isexpense); + void RemoveCategory(const char* name); + bool RenameCategory(const char* oldname, const char* newname); + bool HasCategory(const char* name); + bool IsCategoryExpense(const char* name); + void SetCategoryExpense(const char* name, const bool& isexpense); + void RecategorizeTransactions(const char* from, const char* to); - void DBCommand(const char *command, const char *functionname); - CppSQLite3Query DBQuery(const char *query, const char *functionname); + void DBCommand(const char* command, const char* functionname); + CppSQLite3Query DBQuery(const char* query, const char* functionname); private: - int32 GetLastKey(const char *table, const char *column); + int32 GetLastKey(const char* table, const char* column); // Used to allow split scheduled transactions bool InsertSchedTransaction( - const uint32 &id, const uint32 &accountid, const time_t &startdate, - const TransactionType &type, const char *payee, const Fixed &amount, const char *category, - const char *memo, const TransactionInterval &interval, const time_t &nextdate, - const int32 &count = -1 + const uint32& id, const uint32& accountid, const time_t& startdate, + const TransactionType& type, const char* payee, const Fixed& amount, const char* category, + const char* memo, const TransactionInterval& interval, const time_t& nextdate, + const int32& count = -1 ); - Account *fCurrent; + Account* fCurrent; BObjectList fList; BLocker fLocker; @@ -127,9 +127,9 @@ class Database : public Notifier { }; BString -EscapeIllegalCharacters(const char *string); +EscapeIllegalCharacters(const char* string); BString -DeescapeIllegalCharacters(const char *string); +DeescapeIllegalCharacters(const char* string); extern Locale gDefaultLocale; extern Locale gCurrentLocale; diff --git a/src/DateBox.cpp b/src/DateBox.cpp index da6d2a4..156cbe6 100644 --- a/src/DateBox.cpp +++ b/src/DateBox.cpp @@ -10,14 +10,14 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "DateBox" - -DateBoxFilter::DateBoxFilter(DateBox *box) : AutoTextControlFilter(box) {} +DateBoxFilter::DateBoxFilter(DateBox* box) : AutoTextControlFilter(box) {} filter_result -DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +DateBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. if (key == B_TAB) { - if (!((DateBox *)TextControl())->IsTabFiltering()) + if (!((DateBox*)TextControl())->IsTabFiltering()) return B_DISPATCH_MESSAGE; if (mod & B_SHIFT_KEY) @@ -42,7 +42,7 @@ DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { return B_DISPATCH_MESSAGE; int32 start, end; - DateBox *box = (DateBox *)TextControl(); + DateBox* box = (DateBox*)TextControl(); box->TextView()->GetSelection(&start, &end); BString keystring; @@ -58,7 +58,8 @@ DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } else if (keystring == "-") { + } + else if (keystring == "-") { if (strlen(box->Text()) > 0) box->fCurrentDate = DecrementDateByDay(box->fCurrentDate); gDefaultLocale.DateToString(box->fCurrentDate, string); @@ -66,7 +67,8 @@ DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } else if (key == B_PAGE_UP) { + } + else if (key == B_PAGE_UP) { if (strlen(box->Text()) > 0) { if (mod & B_SHIFT_KEY) box->fCurrentDate = IncrementDateByYear(box->fCurrentDate); @@ -78,7 +80,8 @@ DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { box->TextView()->SelectAll(); TextControl()->Invoke(); return B_SKIP_MESSAGE; - } else if (key == B_PAGE_DOWN) { + } + else if (key == B_PAGE_DOWN) { if (strlen(box->Text()) > 0) { if (mod & B_SHIFT_KEY) box->fCurrentDate = DecrementDateByYear(box->fCurrentDate); @@ -95,8 +98,9 @@ DateBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { return B_DISPATCH_MESSAGE; } -DateBox::DateBox(const char *name, const char *label, const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) { +DateBox::DateBox(const char* name, const char* label, const char* text, BMessage* msg, uint32 flags) + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) +{ SetFilter(new DateBoxFilter(this)); fCurrentDate = GetCurrentDate(); @@ -114,25 +118,28 @@ DateBox::DateBox(const char *name, const char *label, const char *text, BMessage } bool -DateBox::Validate(const bool &alert) { +DateBox::Validate(const bool& alert) +{ BString date; time_t tdate; if (strlen(Text()) < 1) { BString date; gDefaultLocale.DateToString(fCurrentDate, date); SetText(date.String()); - } else if (gDefaultLocale.StringToDate(Text(), tdate) != B_OK) { + } + else if (gDefaultLocale.StringToDate(Text(), tdate) != B_OK) { if (alert) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the date you entered."), B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.") + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") ); MakeFocus(true); } return false; - } else { + } + else { fCurrentDate = tdate; gDefaultLocale.DateToString(fCurrentDate, date); SetText(date.String()); diff --git a/src/DateBox.h b/src/DateBox.h index 6df39fe..8a6b01e 100644 --- a/src/DateBox.h +++ b/src/DateBox.h @@ -7,24 +7,24 @@ class DateBox; class DateBoxFilter : public AutoTextControlFilter { public: - DateBoxFilter(DateBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + DateBoxFilter(DateBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class DateBox : public AutoTextControl { public: DateBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); - void SetDate(const time_t &date) { fCurrentDate = date; } + void SetDate(const time_t& date) { fCurrentDate = date; } time_t GetDate(void) const { return fCurrentDate; } - bool Validate(const bool &alert = true); + bool Validate(const bool& alert = true); - void UseTabFiltering(const bool &value) { fFilterTab = value; } + void UseTabFiltering(const bool& value) { fFilterTab = value; } bool IsTabFiltering(void) const { return fFilterTab; } diff --git a/src/EscapeCancelFilter.h b/src/EscapeCancelFilter.h index 139f98c..a9dd37d 100644 --- a/src/EscapeCancelFilter.h +++ b/src/EscapeCancelFilter.h @@ -12,12 +12,13 @@ class EscapeCancelFilter : public BMessageFilter { ~EscapeCancelFilter(void) {} - filter_result Filter(BMessage *msg, BHandler **target) { + filter_result Filter(BMessage* msg, BHandler** target) + { int32 rawchar; msg->FindInt32("raw_char", &rawchar); if (rawchar == B_ESCAPE) { - BLooper *loop = (*target)->Looper(); + BLooper* loop = (*target)->Looper(); if (loop) { BMessenger msgr(loop); msgr.SendMessage(B_QUIT_REQUESTED); diff --git a/src/Fixed.cpp b/src/Fixed.cpp index f48786d..1f18e33 100644 --- a/src/Fixed.cpp +++ b/src/Fixed.cpp @@ -9,37 +9,44 @@ Fixed::Fixed(long val, bool premult) { fValue = premult ? val : val * 100; } Fixed::Fixed(int val) { fValue = val * 100; } float -Fixed::AsFloat(void) const { +Fixed::AsFloat(void) const +{ return float(fValue / 100.0); } double -Fixed::AsDouble(void) const { +Fixed::AsDouble(void) const +{ return double(fValue / 100.0); } long -Fixed::AsLong(void) const { +Fixed::AsLong(void) const +{ return fValue / 100; } long -Fixed::AsFixed(void) const { +Fixed::AsFixed(void) const +{ return fValue; } long -Fixed::IntegerPart(void) const { +Fixed::IntegerPart(void) const +{ return fValue / 100; } double -Fixed::DecimalPart(void) const { +Fixed::DecimalPart(void) const +{ return (fValue / 100.0) - (double)(fValue / 100); } Fixed -Fixed::AbsoluteValue(void) const { +Fixed::AbsoluteValue(void) const +{ Fixed f(*this); if (f.IsNegative()) f.Invert(); @@ -47,7 +54,8 @@ Fixed::AbsoluteValue(void) const { } void -Fixed::Round(void) { +Fixed::Round(void) +{ int32 integerpart = (fValue / 100) * 100; int32 decimalpart; @@ -56,96 +64,114 @@ Fixed::Round(void) { if (fValue > 0) { if (decimalpart > 49) fValue += 100; - } else { + } + else { if (decimalpart < -49) fValue -= 100; } } void -Fixed::SetPremultiplied(long value) { +Fixed::SetPremultiplied(long value) +{ fValue = value; } void -Fixed::AddPremultiplied(long value) { +Fixed::AddPremultiplied(long value) +{ fValue += value; } void -Fixed::SubtractPremultiplied(long value) { +Fixed::SubtractPremultiplied(long value) +{ fValue += value; } Fixed -Fixed::InvertAsCopy(void) const { +Fixed::InvertAsCopy(void) const +{ Fixed f; f.SetPremultiplied(-fValue); return f; } void -Fixed::Invert(void) { +Fixed::Invert(void) +{ fValue = -fValue; } bool -Fixed::IsNegative(void) const { +Fixed::IsNegative(void) const +{ return fValue < 0; } bool -Fixed::IsPositive(void) const { +Fixed::IsPositive(void) const +{ return fValue > 0; } bool -Fixed::IsZero(void) const { +Fixed::IsZero(void) const +{ return fValue == 0; } bool -Fixed::operator!=(const Fixed &from) const { +Fixed::operator!=(const Fixed& from) const +{ return (fValue != from.fValue); } bool -Fixed::operator==(const Fixed &from) const { +Fixed::operator==(const Fixed& from) const +{ return (fValue == from.fValue); } Fixed -Fixed::operator+(const Fixed &from) { +Fixed::operator+(const Fixed& from) +{ return Fixed(fValue + from.fValue, true); } Fixed -Fixed::operator-(const Fixed &from) { +Fixed::operator-(const Fixed& from) +{ return Fixed(fValue - from.fValue, true); } Fixed -Fixed::operator+(const double &from) { +Fixed::operator+(const double& from) +{ return Fixed((double(fValue) / 100.0) + from); } Fixed -Fixed::operator-(const double &from) { +Fixed::operator-(const double& from) +{ return Fixed((double(fValue) / 100.0) - from); } Fixed -Fixed::operator+=(const double &from) { +Fixed::operator+=(const double& from) +{ return Fixed(fValue += int32(from * 100)); } Fixed -Fixed::operator-=(const double &from) { +Fixed::operator-=(const double& from) +{ return Fixed(fValue -= int32(from * 100)); } Fixed -Fixed::operator*=(const double &from) { +Fixed::operator*=(const double& from) +{ // Use 64-bit processing to prevent out-of-range errors int64 start = fValue * 100; int64 mult = int64(from); @@ -155,7 +181,8 @@ Fixed::operator*=(const double &from) { } Fixed -Fixed::operator/=(const double &from) { +Fixed::operator/=(const double& from) +{ // Use 64-bit processing to prevent out-of-range errors int64 start = fValue * 100; int64 div = int64(from * 100.0); @@ -165,54 +192,64 @@ Fixed::operator/=(const double &from) { } bool -Fixed::operator<(const long &from) const { +Fixed::operator<(const long& from) const +{ return fValue < (from * 100); } bool -Fixed::operator>(const long &from) const { +Fixed::operator>(const long& from) const +{ return fValue > (from * 100); } bool -Fixed::operator<(const Fixed &from) const { +Fixed::operator<(const Fixed& from) const +{ return fValue < from.fValue; } bool -Fixed::operator>(const Fixed &from) const { +Fixed::operator>(const Fixed& from) const +{ return fValue > from.fValue; } bool -Fixed::operator<=(const Fixed &from) const { +Fixed::operator<=(const Fixed& from) const +{ return fValue <= from.fValue; } bool -Fixed::operator>=(const Fixed &from) const { +Fixed::operator>=(const Fixed& from) const +{ return fValue >= from.fValue; } bool -Fixed::operator==(const long &from) const { +Fixed::operator==(const long& from) const +{ return fValue == (from * 100); } -Fixed & -Fixed::operator+=(const Fixed &from) { +Fixed& +Fixed::operator+=(const Fixed& from) +{ fValue += from.fValue; return *this; } -Fixed & -Fixed::operator-=(const Fixed &from) { +Fixed& +Fixed::operator-=(const Fixed& from) +{ fValue -= from.fValue; return *this; } -Fixed & -Fixed::operator=(const long &from) { +Fixed& +Fixed::operator=(const long& from) +{ fValue = from * 100; return *this; } diff --git a/src/Fixed.h b/src/Fixed.h index 721fe40..761c17f 100644 --- a/src/Fixed.h +++ b/src/Fixed.h @@ -30,28 +30,28 @@ class Fixed { bool IsPositive(void) const; bool IsZero(void) const; - Fixed operator+(const Fixed &from); - Fixed operator-(const Fixed &from); - bool operator<(const Fixed &from) const; - bool operator>(const Fixed &from) const; - bool operator<=(const Fixed &from) const; - bool operator>=(const Fixed &from) const; - bool operator!=(const Fixed &from) const; - bool operator==(const Fixed &from) const; - - Fixed operator+(const double &from); - Fixed operator-(const double &from); - Fixed operator+=(const double &from); - Fixed operator-=(const double &from); - Fixed operator*=(const double &from); - Fixed operator/=(const double &from); - bool operator<(const long &from) const; - bool operator>(const long &from) const; - bool operator==(const long &from) const; - - Fixed &operator+=(const Fixed &from); - Fixed &operator-=(const Fixed &from); - Fixed &operator=(const long &from); + Fixed operator+(const Fixed& from); + Fixed operator-(const Fixed& from); + bool operator<(const Fixed& from) const; + bool operator>(const Fixed& from) const; + bool operator<=(const Fixed& from) const; + bool operator>=(const Fixed& from) const; + bool operator!=(const Fixed& from) const; + bool operator==(const Fixed& from) const; + + Fixed operator+(const double& from); + Fixed operator-(const double& from); + Fixed operator+=(const double& from); + Fixed operator-=(const double& from); + Fixed operator*=(const double& from); + Fixed operator/=(const double& from); + bool operator<(const long& from) const; + bool operator>(const long& from) const; + bool operator==(const long& from) const; + + Fixed& operator+=(const Fixed& from); + Fixed& operator-=(const Fixed& from); + Fixed& operator=(const long& from); private: int32 fValue; diff --git a/src/HelpButton.cpp b/src/HelpButton.cpp index 6116691..9d663fa 100644 --- a/src/HelpButton.cpp +++ b/src/HelpButton.cpp @@ -13,17 +13,17 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "HelpButton" - class HelpButtonWindow : public BWindow { public: - HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref); + HelpButtonWindow(const BRect& frame, const entry_ref& helpfileref); private: - BTextView *fTextView; + BTextView* fTextView; }; -HelpButton::HelpButton(const char *name, const char *path) - : BButton(name, "", new BMessage(M_HELPBUTTON_PRESSED)) { +HelpButton::HelpButton(const char* name, const char* path) + : BButton(name, "", new BMessage(M_HELPBUTTON_PRESSED)) +{ get_ref_for_path(path, &fRef); SetIcon(BTranslationUtils::GetBitmap('PNG ', "HelpButtonUp.png")); } @@ -31,28 +31,32 @@ HelpButton::HelpButton(const char *name, const char *path) HelpButton::~HelpButton(void) {} void -HelpButton::AttachedToWindow() { +HelpButton::AttachedToWindow() +{ SetTarget(this); BButton::AttachedToWindow(); } void -HelpButton::MessageReceived(BMessage *msg) { +HelpButton::MessageReceived(BMessage* msg) +{ if (msg->what == M_HELPBUTTON_PRESSED) { BRect frame = Window()->Frame(); - HelpButtonWindow *help = new HelpButtonWindow(frame, fRef); + HelpButtonWindow* help = new HelpButtonWindow(frame, fRef); help->Show(); - } else { + } + else { BButton::MessageReceived(msg); } } -HelpButtonWindow::HelpButtonWindow(const BRect &frame, const entry_ref &helpfileref) +HelpButtonWindow::HelpButtonWindow(const BRect& frame, const entry_ref& helpfileref) : BWindow( frame, B_TRANSLATE("Help"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS - ) { - BView *view = new BView("back", B_WILL_DRAW | B_FRAME_EVENTS); + ) +{ + BView* view = new BView("back", B_WILL_DRAW | B_FRAME_EVENTS); view->SetViewColor(235, 235, 255); BLayoutBuilder::Group<>(this, B_VERTICAL).Add(view).End(); @@ -61,7 +65,7 @@ HelpButtonWindow::HelpButtonWindow(const BRect &frame, const entry_ref &helpfile fTextView->SetStylable(true); fTextView->SetWordWrap(true); - BScrollView *sv = new BScrollView("scrollview", fTextView, B_FRAME_EVENTS, false, true); + BScrollView* sv = new BScrollView("scrollview", fTextView, B_FRAME_EVENTS, false, true); BFile file(&helpfileref, B_READ_ONLY); SetTitle(helpfileref.name); diff --git a/src/HelpButton.h b/src/HelpButton.h index b5c183b..05cbe04 100644 --- a/src/HelpButton.h +++ b/src/HelpButton.h @@ -9,11 +9,11 @@ class HelpButton : public BButton { public: - HelpButton(const char *name, const char *path); + HelpButton(const char* name, const char* path); ~HelpButton(void); virtual void AttachedToWindow(); - virtual void MessageReceived(BMessage *msg); + virtual void MessageReceived(BMessage* msg); private: entry_ref fRef; diff --git a/src/Import.cpp b/src/Import.cpp index 2735fc0..aa5ac1a 100644 --- a/src/Import.cpp +++ b/src/Import.cpp @@ -37,19 +37,20 @@ bool debuggerflag = false; */ BString -ReadCategories(BObjectList &list, TextFile &file); +ReadCategories(BObjectList& list, TextFile& file); BString -ReadTransactions(Account *account, TextFile &file); +ReadTransactions(Account* account, TextFile& file); BString -ReadAccounts(BObjectList &list, TextFile &file); +ReadAccounts(BObjectList& list, TextFile& file); BString -DateToQIFDate(const time_t &date); +DateToQIFDate(const time_t& date); BString -MakeCategoryString(const DStringList &list, const bool &isexpense); +MakeCategoryString(const DStringList& list, const bool& isexpense); bool -ImportQIF(const entry_ref &ref) { +ImportQIF(const entry_ref& ref) +{ TextFile file(ref, B_READ_ONLY); STRACE(("Importing QIF file\n")); @@ -60,7 +61,7 @@ ImportQIF(const entry_ref &ref) { BString string = file.ReadLine(); while (!file.IsEOF()) { - Account *currentaccount; + Account* currentaccount; BString accountname; if (string.CountChars() < 1) @@ -70,7 +71,8 @@ ImportQIF(const entry_ref &ref) { if (string.FindFirst("!Type:Cat") != B_ERROR) { string = ReadCategories(catlist, file); - } else if (string.FindFirst("!Type:Bank") != B_ERROR) { + } + else if (string.FindFirst("!Type:Bank") != B_ERROR) { STRACE(("Bank Account\n")); accountindex++; accountname = "Bank Account "; @@ -78,14 +80,16 @@ ImportQIF(const entry_ref &ref) { currentaccount = gDatabase.AddAccount(accountname.String(), ACCOUNT_BANK, "open"); string = ReadTransactions(currentaccount, file); - } else if (string.FindFirst("!Type:Cash") != B_ERROR) { + } + else if (string.FindFirst("!Type:Cash") != B_ERROR) { accountindex++; accountname = "Cash Account "; accountname << accountindex; currentaccount = gDatabase.AddAccount(accountname.String(), ACCOUNT_CASH, "open"); string = ReadTransactions(currentaccount, file); - } else if (string.FindFirst("!Type:CCard") != B_ERROR) { + } + else if (string.FindFirst("!Type:CCard") != B_ERROR) { accountindex++; accountname = "Credit Card Account "; accountname << accountindex; @@ -122,12 +126,13 @@ ImportQIF(const entry_ref &ref) { } BString -ReadCategories(BObjectList &list, TextFile &file) { +ReadCategories(BObjectList& list, TextFile& file) +{ STRACE(("Importing category list\n")); BString catdata = file.ReadLine(); catdata.RemoveAll("\r"); - Category *cat = new Category(); + Category* cat = new Category(); while (catdata.ByteAt(0) != '!' && !file.IsEOF()) { /* switch(catdata.ByteAt(0)) { @@ -172,7 +177,8 @@ ReadCategories(BObjectList &list, TextFile &file) { } BString -ReadAccounts(BObjectList &list, TextFile &file) { +ReadAccounts(BObjectList& list, TextFile& file) +{ STRACE(("Importing accounts\n")); BString accdata = file.ReadLine(); @@ -189,7 +195,7 @@ ReadAccounts(BObjectList &list, TextFile &file) { if (accname.CountChars() < 1) break; - Account *acc = gDatabase.AddAccount(accname.String(), ACCOUNT_BANK); + Account* acc = gDatabase.AddAccount(accname.String(), ACCOUNT_BANK); list.AddItem(acc); accname = ""; break; @@ -204,7 +210,8 @@ ReadAccounts(BObjectList &list, TextFile &file) { } BString -ReadTransactions(Account *account, TextFile &file) { +ReadTransactions(Account* account, TextFile& file) +{ gDatabase.SetNotify(false); gDatabase.DBCommand("BEGIN EXCLUSIVE", "Import:Turn off autocommit"); STRACE(("Importing bank transactions to %s\n", account ? account->Name() : "")); @@ -332,7 +339,8 @@ ReadTransactions(Account *account, TextFile &file) { } bool -ExportQIF(const entry_ref &ref) { +ExportQIF(const entry_ref& ref) +{ BFile file(&ref, B_CREATE_FILE | B_READ_WRITE | B_FAIL_IF_EXISTS); if (file.InitCheck() != B_OK) return false; @@ -368,7 +376,7 @@ ExportQIF(const entry_ref &ref) { // Export account list text << "!Account\n"; for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); text << "N" << account->Name() << "\nBank\n^\n"; } @@ -378,7 +386,7 @@ ExportQIF(const entry_ref &ref) { // Export accounts text << "!Account\n"; for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); text << "N" << account->Name() << "\nTBank\n^\n!Type:Bank\n"; command = "select * from account_"; @@ -418,8 +426,9 @@ ExportQIF(const entry_ref &ref) { } BString -DateToQIFDate(const time_t &date) { - struct tm *timestruct; +DateToQIFDate(const time_t& date) +{ + struct tm* timestruct; timestruct = localtime(&date); @@ -428,7 +437,8 @@ DateToQIFDate(const time_t &date) { if (timestruct->tm_year < 100) { qifdate << (timestruct->tm_mon + 1) << "/" << timestruct->tm_mday << "/" << timestruct->tm_year; - } else { + } + else { qifdate << (timestruct->tm_mon + 1) << "/"; if (timestruct->tm_mday < 10) @@ -445,12 +455,13 @@ DateToQIFDate(const time_t &date) { } BString -MakeCategoryString(const DStringList &list, const bool &isexpense) { +MakeCategoryString(const DStringList& list, const bool& isexpense) +{ BString text; CppSQLite3Query query; for (int32 i = 0; i < list.CountItems(); i++) { - BString *category = list.ItemAt(i); + BString* category = list.ItemAt(i); BString unescaped(DeescapeIllegalCharacters(category->String())); text << "N" << unescaped << "\nD" << unescaped << "\n" << (isexpense ? "E" : "I") << "\n"; diff --git a/src/Import.h b/src/Import.h index 036a72f..ec5b44b 100644 --- a/src/Import.h +++ b/src/Import.h @@ -4,8 +4,8 @@ #include bool -ImportQIF(const entry_ref &ref); +ImportQIF(const entry_ref& ref); bool -ExportQIF(const entry_ref &ref); +ExportQIF(const entry_ref& ref); #endif diff --git a/src/Language.cpp b/src/Language.cpp index 3e91f87..88d2ce2 100644 --- a/src/Language.cpp +++ b/src/Language.cpp @@ -12,14 +12,15 @@ to be rewritten or replaced later. */ -Language::Language(const entry_ref &ref) : fInit(false), fName(ref.name), fFileRef(ref) {} +Language::Language(const entry_ref& ref) : fInit(false), fName(ref.name), fFileRef(ref) {} Language::Language(void) : fInit(false) {} Language::~Language(void) {} void -Language::Initialize(void) { +Language::Initialize(void) +{ // Here we load the dictionary file for the app fInit = true; @@ -54,10 +55,12 @@ Language::Initialize(void) { if (line[i] == '#' || line[i] == ';') { nextline = true; break; - } else { + } + else { key += line[i]; } - } else { + } + else { key += line[i]; } } @@ -78,7 +81,8 @@ Language::Initialize(void) { } BString -Language::Translate(const char *instring) { +Language::Translate(const char* instring) +{ if (!instring) return NULL; @@ -97,7 +101,7 @@ Language::Translate(const char *instring) { return BString(instring); } -LanguageLogger::LanguageLogger(const entry_ref &ref) +LanguageLogger::LanguageLogger(const entry_ref& ref) : Language(ref), fFile(&ref, B_CREATE_FILE | B_ERASE_FILE | B_READ_WRITE) { @@ -107,10 +111,13 @@ LanguageLogger::LanguageLogger(const entry_ref &ref) LanguageLogger::~LanguageLogger(void) { fFile.Unset(); } void -LanguageLogger::Initialize(void) {} +LanguageLogger::Initialize(void) +{ +} BString -LanguageLogger::Translate(const char *instring) { +LanguageLogger::Translate(const char* instring) +{ if (!instring) return BString(); diff --git a/src/Language.h b/src/Language.h index 5ffecdd..d74c7d0 100644 --- a/src/Language.h +++ b/src/Language.h @@ -12,7 +12,7 @@ typedef std::map LanguageEntryList; class Language { public: - Language(const entry_ref &ref); + Language(const entry_ref& ref); Language(void); virtual ~Language(void); @@ -21,9 +21,9 @@ class Language { bool IsInitialized(void) const { return fInit; } - const char *Name(void) { return fName.String(); } + const char* Name(void) { return fName.String(); } - virtual BString Translate(const char *instring); + virtual BString Translate(const char* instring); protected: void SetInitialized(bool value) { fInit = value; } @@ -38,10 +38,10 @@ class Language { // Debugging class used to generate language files quickly class LanguageLogger : public Language { public: - LanguageLogger(const entry_ref &ref); + LanguageLogger(const entry_ref& ref); ~LanguageLogger(void); void Initialize(void); - BString Translate(const char *instring); + BString Translate(const char* instring); LanguageEntryList fLogList; BFile fFile; diff --git a/src/LanguageRoster.cpp b/src/LanguageRoster.cpp index 569c7f6..2d579d5 100644 --- a/src/LanguageRoster.cpp +++ b/src/LanguageRoster.cpp @@ -7,10 +7,11 @@ // #define BUILD_LOGFILE -LanguageRoster *language_roster = NULL; +LanguageRoster* language_roster = NULL; -LanguageRoster::LanguageRoster(const char *path) - : fLanguagePath(path), fCurrentLanguage(NULL), fDefaultLanguage(NULL) { +LanguageRoster::LanguageRoster(const char* path) + : fLanguagePath(path), fCurrentLanguage(NULL), fDefaultLanguage(NULL) +{ BDirectory dir(fLanguagePath.String()); if (dir.InitCheck() != B_OK) @@ -28,38 +29,43 @@ LanguageRoster::LanguageRoster(const char *path) fCurrentLanguage->Initialize(); fLanguageList.AddItem(fDefaultLanguage); while (dir.GetNextRef(&ref) == B_OK) { - Language *loc = new Language(ref); + Language* loc = new Language(ref); fLanguageList.AddItem(loc); } } -LanguageRoster::~LanguageRoster(void) { +LanguageRoster::~LanguageRoster(void) +{ for (int32 i = 0; i < fLanguageList.CountItems(); i++) { - Language *loc = (Language *)fLanguageList.ItemAt(i); + Language* loc = (Language*)fLanguageList.ItemAt(i); delete loc; } fLanguageList.MakeEmpty(); } int32 -LanguageRoster::CountLanguages(void) const { +LanguageRoster::CountLanguages(void) const +{ return fLanguageList.CountItems(); } -Language * -LanguageRoster::LanguageAt(const int32 &index) { - return (Language *)fLanguageList.ItemAt(index); +Language* +LanguageRoster::LanguageAt(const int32& index) +{ + return (Language*)fLanguageList.ItemAt(index); } void -LanguageRoster::SetLanguage(const int32 &index) { - Language *language = (Language *)fLanguageList.ItemAt(index); +LanguageRoster::SetLanguage(const int32& index) +{ + Language* language = (Language*)fLanguageList.ItemAt(index); SetLanguage(language); } void -LanguageRoster::SetLanguage(Language *language) { +LanguageRoster::SetLanguage(Language* language) +{ if (language) { if (!language->IsInitialized()) language->Initialize(); @@ -73,12 +79,13 @@ LanguageRoster::SetLanguage(Language *language) { } bool -LanguageRoster::SetLanguage(const char *name) { +LanguageRoster::SetLanguage(const char* name) +{ if (!name) return false; for (int32 i = 0; i < fLanguageList.CountItems(); i++) { - Language *language = (Language *)fLanguageList.ItemAt(i); + Language* language = (Language*)fLanguageList.ItemAt(i); if (language && strcmp(language->Name(), name) == 0) { SetLanguage(language); return true; diff --git a/src/LanguageRoster.h b/src/LanguageRoster.h index 4739b93..6e1fa87 100644 --- a/src/LanguageRoster.h +++ b/src/LanguageRoster.h @@ -6,26 +6,26 @@ class LanguageRoster { public: - LanguageRoster(const char *path); + LanguageRoster(const char* path); ~LanguageRoster(void); int32 CountLanguages(void) const; - Language *LanguageAt(const int32 &index); + Language* LanguageAt(const int32& index); - void SetLanguage(const int32 &index); - void SetLanguage(Language *language); - bool SetLanguage(const char *name); + void SetLanguage(const int32& index); + void SetLanguage(Language* language); + bool SetLanguage(const char* name); - Language *GetLanguage(void) { return fCurrentLanguage; } + Language* GetLanguage(void) { return fCurrentLanguage; } private: BString fLanguagePath; BList fLanguageList; - Language *fCurrentLanguage; - Language *fDefaultLanguage; + Language* fCurrentLanguage; + Language* fDefaultLanguage; }; -extern Language *gCurrentLanguage; -extern LanguageRoster *language_roster; +extern Language* gCurrentLanguage; +extern LanguageRoster* language_roster; #endif diff --git a/src/Locale.cpp b/src/Locale.cpp index d0cc09e..b49a80b 100644 --- a/src/Locale.cpp +++ b/src/Locale.cpp @@ -17,12 +17,14 @@ Locale::Locale(void) { SetDefaults(); } Locale::~Locale(void) {} bool -Locale::operator!=(const Locale &other) const { +Locale::operator!=(const Locale& other) const +{ return !(*this == other); } bool -Locale::operator==(const Locale &other) const { +Locale::operator==(const Locale& other) const +{ if (fDateFormat != other.fDateFormat || fCurrencySymbol != other.fCurrencySymbol || fPrefixSymbol != other.fPrefixSymbol || fCurrencySeparator != other.fCurrencySeparator || fCurrencyDecimal != other.fCurrencyDecimal || fDateSeparator != other.fDateSeparator || @@ -32,7 +34,8 @@ Locale::operator==(const Locale &other) const { } void -Locale::Flatten(BFile *file) { +Locale::Flatten(BFile* file) +{ BString str("\t\n"); if (fDateFormat == DATE_MDY) @@ -55,7 +58,8 @@ Locale::Flatten(BFile *file) { } status_t -Locale::CurrencyToString(const Fixed &amount, BString &string) { +Locale::CurrencyToString(const Fixed& amount, BString& string) +{ string = ""; BString dollars; @@ -87,7 +91,8 @@ Locale::CurrencyToString(const Fixed &amount, BString &string) { } status_t -Locale::StringToCurrency(const char *string, Fixed &amount) { +Locale::StringToCurrency(const char* string, Fixed& amount) +{ // This is going to be a royal pain. We have to deal with separators (or lack // thereof) and the mere possibility of a cents separator. Yuck. @@ -103,7 +108,8 @@ Locale::StringToCurrency(const char *string, Fixed &amount) { if (index < 0) { // We're working with whole dollars here. :) cents = "00"; - } else { + } + else { cents = dollars.String() + index + 1; dollars.Truncate(index); if (dollars == "-0") @@ -120,7 +126,8 @@ Locale::StringToCurrency(const char *string, Fixed &amount) { } status_t -Locale::PremultipliedStringToCurrency(const char *string, Fixed &amount) { +Locale::PremultipliedStringToCurrency(const char* string, Fixed& amount) +{ // This function is an optimized version of StringToCurrency which expects // the input string to represent the premultiplied version of a Fixed value. // As a result, everything which is not a number is stripped out, converted @@ -141,9 +148,10 @@ Locale::PremultipliedStringToCurrency(const char *string, Fixed &amount) { } status_t -Locale::DateToString(time_t date, BString &string) { +Locale::DateToString(time_t date, BString& string) +{ char buffer[10]; - struct tm *timestruct = localtime(&date); + struct tm* timestruct = localtime(&date); BString datestr; if (fDateFormat == DATE_MDY) @@ -168,7 +176,8 @@ Locale::DateToString(time_t date, BString &string) { } status_t -Locale::ConstructDateStringDMY(const char *in, BString &out) { +Locale::ConstructDateStringDMY(const char* in, BString& out) +{ // This constructs a proper date string given a list of numbers if (!in) return B_ERROR; @@ -211,13 +220,15 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { ddm = false; else ddm = true; - } else if (num2 > 1) + } + else if (num2 > 1) ddm = true; else if (num2 == 0) { // Although we can't say for sure, it's unlikely that the user entered a leading // zero for the month. ddm = true; - } else { + } + else { // [1-2][0-1]x. charstring[0] = in[2]; num = atoi(charstring); @@ -261,7 +272,8 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { ddmm = false; else ddmm = true; - } else if (num2 == 0) + } + else if (num2 == 0) ddmm = true; else { // [1-2][1-2]xx @@ -312,10 +324,12 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { // we'll go with dmyyyy. if ((in[2] == '1' && in[3] == '9') || (in[2] == '2' && in[3] == '0')) { ddmm = false; - } else + } + else ddmm = true; } - } else { + } + else { // Getting this far, we know that [1-9][1-9]xxxx charstring[0] = in[2]; num = atoi(charstring); @@ -330,7 +344,8 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { ddmm = false; else ddmm = true; - } else { + } + else { // At this point, we have [1-9][1-9]0xxx. We'll check to see if // digit 3 is 0, but if it happens to be nonzero, it's a little // hard to definitively know which the user meant. Of course, it @@ -348,7 +363,8 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { if (ddmm) { out.Insert(fDateSeparator, 2); out.Insert(fDateSeparator, 5); - } else { + } + else { out.Insert(fDateSeparator, 1); out.Insert(fDateSeparator, 3); } @@ -370,7 +386,8 @@ Locale::ConstructDateStringDMY(const char *in, BString &out) { } status_t -Locale::ConstructDateStringMDY(const char *in, BString &out) { +Locale::ConstructDateStringMDY(const char* in, BString& out) +{ // This constructs a proper date string given a list of numbers if (!in) return B_ERROR; @@ -494,7 +511,8 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { // choose mmdd mdyy = false; } - } else { + } + else { // Getting this far means we can't tell. Date is in format 1[1,2][1,2]x // Example dates: 1124 could be either 1/1/24 or 11/24. Just as above, the user @@ -507,7 +525,8 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { if (mdyy) { out.Insert(fDateSeparator, 1); out.Insert(fDateSeparator, 3); - } else + } + else out.Insert(fDateSeparator, 2); break; } @@ -544,11 +563,13 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { mmddyy = false; else mmddyy = true; - } else if (num == 0) { + } + else if (num == 0) { // It's *much* less likely that the user will type in a year with a leading // zero, so choose mmddyy mmddyy = true; - } else { + } + else { // 01[1-2]xxx or 11[1-2]xxx. At this point, it's not possible to tell for sure // which it is, but probability points to x119xx or x120xx if it's a year. // Otherwise, we'll assume mmddyy @@ -559,12 +580,14 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { mmddyy = false; else mmddyy = true; - } else if (num == 2) { + } + else if (num == 2) { if (num2 == 0) mmddyy = false; else mmddyy = true; - } else + } + else mmddyy = true; } } @@ -573,7 +596,8 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { if (mmddyy) { out.Insert(fDateSeparator, 2); out.Insert(fDateSeparator, 5); - } else { + } + else { out.Insert(fDateSeparator, 1); out.Insert(fDateSeparator, 4); } @@ -597,7 +621,8 @@ Locale::ConstructDateStringMDY(const char *in, BString &out) { } status_t -Locale::StringToDate(const char *instring, time_t &date) { +Locale::StringToDate(const char* instring, time_t& date) +{ // Input recognized for MM/DD/YY: // 1) MM/DD // 2) MM/DD/YYYY @@ -633,11 +658,13 @@ Locale::StringToDate(const char *instring, time_t &date) { if (daystr.CountChars() != 1 && daystr.CountChars() != 2) return B_ERROR; yearstr = ""; - } else { + } + else { daystr.Truncate(index); yearstr = daystr.String() + index + 1; } - } else { + } + else { daystr = string; index = daystr.FindFirst(fDateSeparator); if (index < 0) { @@ -660,7 +687,8 @@ Locale::StringToDate(const char *instring, time_t &date) { if (monthstr.CountChars() != 1 && monthstr.CountChars() != 2) return B_ERROR; yearstr = ""; - } else { + } + else { yearstr = monthstr.String() + index + 1; monthstr.Truncate(index); } @@ -677,7 +705,8 @@ Locale::StringToDate(const char *instring, time_t &date) { timestruct.tm_year = atoi(yearstr.String()); if (timestruct.tm_year < 10) timestruct.tm_year += 100; - } else + } + else timestruct.tm_year = atoi(yearstr.String()) - 1900; } timestruct.tm_sec = 1; @@ -698,7 +727,8 @@ Locale::StringToDate(const char *instring, time_t &date) { } void -Locale::NumberToCurrency(const Fixed &number, BString &string) { +Locale::NumberToCurrency(const Fixed& number, BString& string) +{ string = ""; string << number.IntegerPart(); @@ -718,7 +748,8 @@ Locale::NumberToCurrency(const Fixed &number, BString &string) { } void -Locale::SetDefaults(void) { +Locale::SetDefaults(void) +{ fDateFormat = DATE_MDY; fCurrencySymbol = "$"; fPrefixSymbol = true; @@ -730,13 +761,15 @@ Locale::SetDefaults(void) { } void -ShowAlert(const char *header, const char *message, alert_type type) { - DAlert *alert = new DAlert(header, message, "OK", NULL, NULL, B_WIDTH_AS_USUAL, type); +ShowAlert(const char* header, const char* message, alert_type type) +{ + DAlert* alert = new DAlert(header, message, "OK", NULL, NULL, B_WIDTH_AS_USUAL, type); alert->Go(); } void -GetVersionString(BString &string) { +GetVersionString(BString& string) +{ app_info ai; version_info vi; be_app->GetAppInfo(&ai); @@ -778,13 +811,14 @@ GetVersionString(BString &string) { // This function saves typing and makes debug messages more friendly and easier to // test void -ShowBug(const char *string) { +ShowBug(const char* string) +{ BString message = "CapitalBe has run into a bug. This shouldn't happen, but it has.\n" "Would you like to:\n\n1) Have CapitalBe make an e-mail to send to Support\n" "2) Save the bug to a text file for e-mailing later\n" "3) Just quit and do nothing\n"; - DAlert *alert = + DAlert* alert = new DAlert("Agh! Bug!", message.String(), "Make an E-mail", "Save to File", "Quit"); int32 value = alert->Go(); @@ -808,7 +842,8 @@ ShowBug(const char *string) { cmdstring << "-subject 'CapitalBe Bug Report' -body '" << message << "'"; cmdstring << " &"; system(cmdstring.String()); - } else if (value == 1) { + } + else if (value == 1) { // Generate a text file of the bug on the Desktop BString filename("/boot/home/Desktop/CapitalBe Bug Report "); filename << real_time_clock() << ".txt"; @@ -822,11 +857,12 @@ ShowBug(const char *string) { // Code from Haiku's String.cpp void -CapitalizeEachWord(BString &string) { +CapitalizeEachWord(BString& string) +{ if (string.CountChars() < 1) return; - char *index = string.LockBuffer(string.Length()); + char* index = string.LockBuffer(string.Length()); int32 count = 0; int32 length = string.Length(); @@ -855,63 +891,74 @@ CapitalizeEachWord(BString &string) { } void -Locale::SetDateFormat(const date_format &format) { +Locale::SetDateFormat(const date_format& format) +{ fDateFormat = format; } void -Locale::SetCurrencySymbol(const char *symbol) { +Locale::SetCurrencySymbol(const char* symbol) +{ if (symbol) fCurrencySymbol = symbol; } void -Locale::SetCurrencySeparator(const char *symbol) { +Locale::SetCurrencySeparator(const char* symbol) +{ if (symbol) fCurrencySeparator = symbol; } void -Locale::SetCurrencyDecimal(const char *symbol) { +Locale::SetCurrencyDecimal(const char* symbol) +{ if (symbol) fCurrencyDecimal = symbol; } void -Locale::SetCurrencySymbolPrefix(const bool &value) { +Locale::SetCurrencySymbolPrefix(const bool& value) +{ fPrefixSymbol = value; } void -Locale::SetCurrencyDecimalPlace(const uint8 &place) { +Locale::SetCurrencyDecimalPlace(const uint8& place) +{ fCurrencyDecimalPlace = place; } void -Locale::SetDateSeparator(const char *symbol) { +Locale::SetDateSeparator(const char* symbol) +{ if (symbol) fDateSeparator = symbol; } void -Locale::SetDST(const bool &value) { +Locale::SetDST(const bool& value) +{ fUseDST = value; } -const char * -GetCurrencyOnlyMask(void) { +const char* +GetCurrencyOnlyMask(void) +{ return "zxcvbnm/" "<>?asdfghjkl;':\"qwertyuiop[]\\{}|`-=~!@#%^&*()_" "à¡™∞ô¶•«»–≠œ∑鮆øπ‘¬å∫∂ƒ©Ωfi∆◊æäñ≈ç√ßñµ…÷"; } -const char * -GetDateOnlyMask(void) { +const char* +GetDateOnlyMask(void) +{ return "`~!@#$%^&*()_=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"ZXCVBNM,.<>?qwertyuiopasdfghjklzxcvbnm"; } void -IllegalCharsToEntities(BString *string) { +IllegalCharsToEntities(BString* string) +{ if (!string) return; diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 3d597a8..d1c6e2f 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -48,11 +48,12 @@ int32 gTextViewHeight = 20; int32 gStringViewHeight = 20; -Language *gCurrentLanguage = NULL; +Language* gCurrentLanguage = NULL; -MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { +MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) +{ BString temp; - SetTitle(B_TRANSLATE_SYSTEM_NAME("CapitalBe")); + SetTitle(B_TRANSLATE_SYSTEM_NAME("CapitalBe")); // These chunks of code will save a lot of headache later on -- // we cache the preferred size of BTextControls to make control layout *much* easier. @@ -60,14 +61,14 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { // be moved into its own init function that is called from here. float pw, ph; - BTextControl *temptc = new BTextControl(BRect(0, 0, 1, 1), "temptc", "", "", NULL); + BTextControl* temptc = new BTextControl(BRect(0, 0, 1, 1), "temptc", "", "", NULL); AddChild(temptc); temptc->GetPreferredSize(&pw, &ph); gTextViewHeight = (int32)ph; RemoveChild(temptc); delete temptc; - BStringView *tempsv = new BStringView(BRect(0, 0, 1, 1), "tempsv", "Foo"); + BStringView* tempsv = new BStringView(BRect(0, 0, 1, 1), "tempsv", "Foo"); AddChild(tempsv); tempsv->GetPreferredSize(&pw, &ph); gStringViewHeight = (int32)ph; @@ -96,8 +97,8 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BRect r(Bounds()); r.bottom = 20; - BMenuBar *bar = new BMenuBar("keybar"); - BMenu *menu = new BMenu(B_TRANSLATE("Program")); + BMenuBar* bar = new BMenuBar("keybar"); + BMenu* menu = new BMenu(B_TRANSLATE("Program")); temp = B_TRANSLATE("Report a bug…"); menu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_BUG))); @@ -112,17 +113,18 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { fLanguageMenu = new BMenu(B_TRANSLATE("Language")); fLanguageMenu->SetRadioMode(true); for (int32 i = 0; i < language_roster->CountLanguages(); i++) { - Language *language = language_roster->LanguageAt(i); - BMessage *langmsg = new BMessage(M_SET_LANGUAGE); + Language* language = language_roster->LanguageAt(i); + BMessage* langmsg = new BMessage(M_SET_LANGUAGE); langmsg->AddInt32("index", i); fLanguageMenu->AddItem(new BMenuItem(language->Name(), langmsg)); } menu->AddItem(fLanguageMenu); - BMenuItem *markeditem = fLanguageMenu->FindItem(fLanguage.String()); + BMenuItem* markeditem = fLanguageMenu->FindItem(fLanguage.String()); if (markeditem) markeditem->SetMarked(true); - } else + } + else fLanguageMenu = NULL; menu->AddSeparatorItem(); @@ -181,7 +183,8 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { menu->AddItem( new BMenuItem(B_TRANSLATE("Previous"), new BMessage(M_PREVIOUS_TRANSACTION), B_UP_ARROW) ); - menu->AddItem(new BMenuItem(B_TRANSLATE("Next"), new BMessage(M_NEXT_TRANSACTION), B_DOWN_ARROW)); + menu->AddItem(new BMenuItem(B_TRANSLATE("Next"), new BMessage(M_NEXT_TRANSACTION), B_DOWN_ARROW) + ); menu = new BMenu(B_TRANSLATE("Tools")); bar->AddItem(menu); @@ -219,16 +222,18 @@ MainWindow::MainWindow(BRect frame) : BWindow(frame, "", B_DOCUMENT_WINDOW, 0) { BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(bar).Add(fRegisterView).End(); } -MainWindow::~MainWindow(void) { +MainWindow::~MainWindow(void) +{ SavePreferences(PREFERENCES_PATH "/CapitalBeSettings"); delete fImportPanel; } void -MainWindow::OpenAbout(void) { - BAboutWindow *abwin = new BAboutWindow("CapitalBe", "application/x-vnd.wgp-CapitalBe"); +MainWindow::OpenAbout(void) +{ + BAboutWindow* abwin = new BAboutWindow("CapitalBe", "application/x-vnd.wgp-CapitalBe"); - const char *authors[] = { + const char* authors[] = { "DarkWyrm", "Jérôme Duval", "Panagiotis Vasilopoulos", @@ -238,7 +243,7 @@ MainWindow::OpenAbout(void) { NULL }; - const char *thanks[] = {"Tanausú Gómez (Spanish translation)", NULL}; + const char* thanks[] = {"Tanausú Gómez (Spanish translation)", NULL}; abwin->AddCopyright(2009, "DarkWyrm"); abwin->AddText("Distributed under the terms of the MIT License"); @@ -249,7 +254,8 @@ MainWindow::OpenAbout(void) { } bool -MainWindow::QuitRequested(void) { +MainWindow::QuitRequested(void) +{ #ifndef NOSAVE SaveData(); #endif @@ -263,7 +269,8 @@ MainWindow::QuitRequested(void) { } void -MainWindow::InitSettings(void) { +MainWindow::InitSettings(void) +{ // This loads all the settings from disk and uses sane defaults if a setting // is non-existent or invalid if (gPreferences.FindString("lastfile", &fLastFile) != B_OK) @@ -271,8 +278,9 @@ MainWindow::InitSettings(void) { } void -MainWindow::MessageReceived(BMessage *msg) { - Account *acc = gDatabase.CurrentAccount(); +MainWindow::MessageReceived(BMessage* msg) +{ + Account* acc = gDatabase.CurrentAccount(); switch (msg->what) { case M_SET_LANGUAGE: { @@ -280,7 +288,7 @@ MainWindow::MessageReceived(BMessage *msg) { if (msg->FindInt32("index", &language) != B_OK) break; - BMenuItem *item = fLanguageMenu->ItemAt(language); + BMenuItem* item = fLanguageMenu->ItemAt(language); if (!item) break; @@ -295,23 +303,24 @@ MainWindow::MessageReceived(BMessage *msg) { msg.AddString("signature", "application/x-vnd.wgp-CapitalBe"); msgr.SendMessage(&msg); be_app->PostMessage(B_QUIT_REQUESTED); - } else { + } + else { ShowAlert( B_TRANSLATE("Changes will take effect on restart"), B_TRANSLATE("CapitalBe will be use your language choice the next time it is " - "started."), + "started."), B_IDEA_ALERT ); } break; } case M_REPORT_BUG: { - char *argv[2] = {(char*)"https://github.com/HaikuArchives/CapitalBe", NULL}; - be_roster->Launch("text/html", 1, argv); + char* argv[2] = {(char*)"https://github.com/HaikuArchives/CapitalBe", NULL}; + be_roster->Launch("text/html", 1, argv); break; } case M_SHOW_NEW_ACCOUNT: { - AccountSettingsWindow *newaccwin = new AccountSettingsWindow(NULL); + AccountSettingsWindow* newaccwin = new AccountSettingsWindow(NULL); BRect r(Frame()); newaccwin->MoveTo( r.left + ((Bounds().Width() - newaccwin->Bounds().Width()) / 2), @@ -324,7 +333,7 @@ MainWindow::MessageReceived(BMessage *msg) { if (!acc) break; - AccountSettingsWindow *accwin = new AccountSettingsWindow(acc); + AccountSettingsWindow* accwin = new AccountSettingsWindow(acc); BRect r(Frame()); accwin->MoveTo( r.left + ((Bounds().Width() - accwin->Bounds().Width()) / 2), @@ -337,10 +346,10 @@ MainWindow::MessageReceived(BMessage *msg) { if (!acc) break; - DAlert *alert = new DAlert( + DAlert* alert = new DAlert( B_TRANSLATE("Really delete account?"), B_TRANSLATE("Once deleted, you will not be able to " - "get back any data on this account."), + "get back any data on this account."), B_TRANSLATE("Delete"), B_TRANSLATE("Cancel"), NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT ); @@ -348,7 +357,8 @@ MainWindow::MessageReceived(BMessage *msg) { int32 index = gDatabase.IndexOf(acc); if (index == 0) { gDatabase.SetCurrentAccount(1); - } else if (index > 0) { + } + else if (index > 0) { gDatabase.SetCurrentAccount(index - 1); } gDatabase.RemoveAccount(acc); @@ -404,8 +414,8 @@ MainWindow::MessageReceived(BMessage *msg) { ShowAlert( errmsg.String(), B_TRANSLATE("This happens when the kind of file is not " - "supported, when the file's data is damaged, or when you feed " - "it a recipe for quiche.") + "supported, when the file's data is damaged, or when you feed " + "it a recipe for quiche.") ); } break; @@ -434,7 +444,7 @@ MainWindow::MessageReceived(BMessage *msg) { errmsg.ReplaceFirst("%%FILENAME%%", dir.name); ShowAlert( errmsg.String(), B_TRANSLATE("This really shouldn't happen, so you probably " - "should e-mail support about this.") + "should e-mail support about this.") ); } break; @@ -493,7 +503,7 @@ MainWindow::MessageReceived(BMessage *msg) { break; } - TransferWindow *tnwin = new TransferWindow(this); + TransferWindow* tnwin = new TransferWindow(this); BRect r(Frame()); tnwin->MoveTo( r.left + ((Bounds().Width() - tnwin->Bounds().Width()) / 2), @@ -516,7 +526,7 @@ MainWindow::MessageReceived(BMessage *msg) { BRect r(Frame()); r.right = r.left + 400; r.bottom = r.top + 300; - TransactionEditWindow *transwin = new TransactionEditWindow(r, data); + TransactionEditWindow* transwin = new TransactionEditWindow(r, data); transwin->MoveTo( r.left + ((Bounds().Width() - transwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - transwin->Bounds().Height()) / 2) @@ -548,7 +558,7 @@ MainWindow::MessageReceived(BMessage *msg) { r.right = r.left + 400; r.bottom = r.top + 300; - ScheduleAddWindow *schedwin = new ScheduleAddWindow(r, data); + ScheduleAddWindow* schedwin = new ScheduleAddWindow(r, data); schedwin->MoveTo( r.left + ((Bounds().Width() - schedwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - schedwin->Bounds().Height()) / 2) @@ -561,7 +571,7 @@ MainWindow::MessageReceived(BMessage *msg) { break; } case M_SHOW_OPTIONS_WINDOW: { - PrefWindow *pwin = new PrefWindow(Frame()); + PrefWindow* pwin = new PrefWindow(Frame()); pwin->Show(); break; } @@ -569,7 +579,7 @@ MainWindow::MessageReceived(BMessage *msg) { // While it seems kind of silly to show the reports window if // there is no data, it seems more like a bug to not bother showing it - ReportWindow *rwin = new ReportWindow(Frame()); + ReportWindow* rwin = new ReportWindow(Frame()); rwin->Show(); break; } @@ -589,7 +599,7 @@ MainWindow::MessageReceived(BMessage *msg) { } BRect r(Frame()); - ReconcileWindow *recwin = new ReconcileWindow(BRect(100, 100, 600, 425), acc); + ReconcileWindow* recwin = new ReconcileWindow(BRect(100, 100, 600, 425), acc); recwin->MoveTo( r.left + ((Bounds().Width() - recwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - recwin->Bounds().Height()) / 2) @@ -599,7 +609,7 @@ MainWindow::MessageReceived(BMessage *msg) { } case M_SHOW_SCHEDULED_WINDOW: { BRect r(Frame()); - ScheduleListWindow *schedwin = new ScheduleListWindow(BRect(100, 100, 600, 425)); + ScheduleListWindow* schedwin = new ScheduleListWindow(BRect(100, 100, 600, 425)); schedwin->MoveTo( r.left + ((Bounds().Width() - schedwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - schedwin->Bounds().Height()) / 2) @@ -608,13 +618,13 @@ MainWindow::MessageReceived(BMessage *msg) { break; } case M_SHOW_BUDGET_WINDOW: { - BudgetWindow *bwin = new BudgetWindow(Frame()); + BudgetWindow* bwin = new BudgetWindow(Frame()); bwin->Show(); break; } case M_SHOW_CATEGORY_WINDOW: { BRect r(Frame()); - CategoryWindow *catwin = new CategoryWindow(BRect(100, 100, 600, 425)); + CategoryWindow* catwin = new CategoryWindow(BRect(100, 100, 600, 425)); catwin->MoveTo( r.left + ((Bounds().Width() - catwin->Bounds().Width()) / 2), r.top + ((Bounds().Height() - catwin->Bounds().Height()) / 2) @@ -636,7 +646,8 @@ MainWindow::MessageReceived(BMessage *msg) { } void -MainWindow::LoadData(void) { +MainWindow::LoadData(void) +{ if (gDatabase.OpenFile(fLastFile.String()) != B_OK) { BEntry entry(fLastFile.String()); if (!entry.Exists()) { @@ -649,17 +660,20 @@ MainWindow::LoadData(void) { } void -MainWindow::SaveData(void) {} +MainWindow::SaveData(void) +{ +} void -MainWindow::CreateTransfer(BMessage *msg) { +MainWindow::CreateTransfer(BMessage* msg) +{ Account *from, *to; BString amount, memo, datestr; Fixed fixed; time_t date; - if ((msg->FindPointer("from", (void **)&from) != B_OK) || - (msg->FindPointer("to", (void **)&to) != B_OK) || + if ((msg->FindPointer("from", (void**)&from) != B_OK) || + (msg->FindPointer("to", (void**)&to) != B_OK) || (msg->FindString("amount", &amount) != B_OK) || (gCurrentLocale.StringToCurrency(amount.String(), fixed) != B_OK) || (msg->FindString("date", &datestr) != B_OK) || @@ -690,7 +704,8 @@ MainWindow::CreateTransfer(BMessage *msg) { } void -MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { +MainWindow::HandleNotify(const uint64& value, const BMessage* msg) +{ bool lockwin = false; if (!IsLocked()) { Lock(); @@ -698,8 +713,8 @@ MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { } if (value & WATCH_ACCOUNT) { - Account *acc; - if (msg->FindPointer("item", (void **)&acc) != B_OK || !acc) { + Account* acc; + if (msg->FindPointer("item", (void**)&acc) != B_OK || !acc) { if (lockwin) Unlock(); return; @@ -708,7 +723,8 @@ MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { if (value & WATCH_SELECT || value & WATCH_CHANGE) { if (acc->IsClosed()) { fAccountClosedItem->SetLabel(B_TRANSLATE("Reopen")); - } else { + } + else { fAccountClosedItem->SetLabel(B_TRANSLATE("Close")); } } @@ -719,7 +735,8 @@ MainWindow::HandleNotify(const uint64 &value, const BMessage *msg) { } void -MainWindow::ReadLanguageSettings(void) { +MainWindow::ReadLanguageSettings(void) +{ BFile file("/boot/home/config/settings/CapitalBe/CurrentLocale", B_READ_ONLY); if (file.InitCheck() != B_OK) @@ -737,7 +754,8 @@ MainWindow::ReadLanguageSettings(void) { } void -MainWindow::WriteLanguageSettings(void) { +MainWindow::WriteLanguageSettings(void) +{ BFile file( "/boot/home/config/settings/CapitalBe/CurrentLocale", B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE diff --git a/src/MainWindow.h b/src/MainWindow.h index 9bc85a1..13488c6 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -61,8 +61,8 @@ class MainWindow : public BWindow, public Observer { void OpenAbout(void); bool QuitRequested(void); - void MessageReceived(BMessage *msg); - void HandleNotify(const uint64 &value, const BMessage *msg); + void MessageReceived(BMessage* msg); + void HandleNotify(const uint64& value, const BMessage* msg); void ReadLanguageSettings(void); void WriteLanguageSettings(void); @@ -71,14 +71,14 @@ class MainWindow : public BWindow, public Observer { void LoadData(void); void SaveData(void); - void CreateTransfer(BMessage *msg); + void CreateTransfer(BMessage* msg); - RegisterView *fRegisterView; + RegisterView* fRegisterView; BFilePanel *fImportPanel, *fExportPanel; BString fLastFile; - BMenuItem *fAccountClosedItem; - BMenu *fLanguageMenu; + BMenuItem* fAccountClosedItem; + BMenu* fLanguageMenu; bool fLoadError; BString fLanguage; diff --git a/src/NavTextBox.cpp b/src/NavTextBox.cpp index 7517808..eccef32 100644 --- a/src/NavTextBox.cpp +++ b/src/NavTextBox.cpp @@ -4,12 +4,13 @@ #include "MsgDefs.h" #include "TimeSupport.h" -NavTextBoxFilter::NavTextBoxFilter(NavTextBox *box) : AutoTextControlFilter(box) {} +NavTextBoxFilter::NavTextBoxFilter(NavTextBox* box) : AutoTextControlFilter(box) {} filter_result -NavTextBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +NavTextBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. - if (key == B_TAB && ((NavTextBox *)TextControl())->IsTabFiltering()) { + if (key == B_TAB && ((NavTextBox*)TextControl())->IsTabFiltering()) { if (mod & B_SHIFT_KEY) SendMessage(new BMessage(M_PREVIOUS_FIELD)); else @@ -28,13 +29,15 @@ NavTextBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { } NavTextBox::NavTextBox( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) { + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true) +{ SetFilter(new NavTextBoxFilter(this)); } bool -NavTextBox::Validate(const bool &alert) { +NavTextBox::Validate(const bool& alert) +{ return true; } diff --git a/src/NavTextBox.h b/src/NavTextBox.h index 561fb8a..a95dc08 100644 --- a/src/NavTextBox.h +++ b/src/NavTextBox.h @@ -7,19 +7,19 @@ class NavTextBox; class NavTextBoxFilter : public AutoTextControlFilter { public: - NavTextBoxFilter(NavTextBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + NavTextBoxFilter(NavTextBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class NavTextBox : public AutoTextControl { public: NavTextBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); - virtual bool Validate(const bool &alert = true); + virtual bool Validate(const bool& alert = true); - void UseTabFiltering(const bool &value) { fFilterTab = value; } + void UseTabFiltering(const bool& value) { fFilterTab = value; } bool IsTabFiltering(void) const { return fFilterTab; } diff --git a/src/NetWorthReport.cpp b/src/NetWorthReport.cpp index 36beca5..0ada494 100644 --- a/src/NetWorthReport.cpp +++ b/src/NetWorthReport.cpp @@ -13,16 +13,16 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "NetWorthReport" - void -ReportWindow::ComputeNetWorth(void) { +ReportWindow::ComputeNetWorth(void) +{ // Total of all accounts // Calculate the number of columns and the starting date for each one BObjectList timelist(20, true); if (fSubtotalMode != SUBTOTAL_NONE) { for (time_t t = fStartDate; t < fEndDate;) { - time_t *item = new time_t(t); + time_t* item = new time_t(t); timelist.AddItem(item); switch (fSubtotalMode) { @@ -54,16 +54,17 @@ ReportWindow::ComputeNetWorth(void) { for (int32 subtotal_index = 0; subtotal_index < timelist.CountItems(); subtotal_index++) { - time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); + time_t subtotal_start = *((time_t*)timelist.ItemAt(subtotal_index)); char rowtitle[128]; - struct tm *timestruct = localtime(&subtotal_start); + struct tm* timestruct = localtime(&subtotal_start); BString formatstring; if (gCurrentLocale.DateFormat() == DATE_MDY) { formatstring << "%m" << gCurrentLocale.DateSeparator() << "%d" << gCurrentLocale.DateSeparator() << "%Y"; - } else { + } + else { formatstring << "%d" << gCurrentLocale.DateSeparator() << "%m" << gCurrentLocale.DateSeparator() << "%Y"; } @@ -80,7 +81,7 @@ ReportWindow::ComputeNetWorth(void) { Fixed accounttotal; for (int32 i = 0; i < fAccountList->CountItems(); i++) { - AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + AccountItem* item = (AccountItem*)fAccountList->ItemAt(i); if (!item) continue; @@ -93,7 +94,7 @@ ReportWindow::ComputeNetWorth(void) { if (fGraphView->IsHidden()) { // Now that we have all the data, we need to set up the rows and columns for the report grid - BColumn *col = new BStringColumn( + BColumn* col = new BStringColumn( B_TRANSLATE("Date"), fGridView->StringWidth(longestname.String()) + 20, 10, 300, B_TRUNCATE_END ); @@ -102,17 +103,17 @@ ReportWindow::ComputeNetWorth(void) { fGridView->AddColumn(col, 1); fGridView->AddRow(new BRow()); - BRow *titlerow = new BRow(); + BRow* titlerow = new BRow(); fGridView->AddRow(titlerow); titlerow->SetField(new BStringField(B_TRANSLATE("Total worth")), 0); fGridView->AddRow(new BRow()); // Now that the grid is set up, start adding data to the grid for (int32 rowindex = 0; rowindex < accountgrid.CountItems(); rowindex++) { - BRow *row = new BRow(); + BRow* row = new BRow(); fGridView->AddRow(row); - BStringField *catname = new BStringField(accountgrid.RowTitle(rowindex)); + BStringField* catname = new BStringField(accountgrid.RowTitle(rowindex)); row->SetField(catname, 0); BString temp; @@ -121,7 +122,7 @@ ReportWindow::ComputeNetWorth(void) { accountgrid.ValueAt(0, rowindex, f); gCurrentLocale.CurrencyToString(f, temp); - BStringField *amountfield = new BStringField(temp.String()); + BStringField* amountfield = new BStringField(temp.String()); row->SetField(amountfield, 1); } } diff --git a/src/Notifier.cpp b/src/Notifier.cpp index db58b84..f0a2a41 100644 --- a/src/Notifier.cpp +++ b/src/Notifier.cpp @@ -4,7 +4,8 @@ #include void -PrintNotification(const uint64 &value, const BMessage *msg) { +PrintNotification(const uint64& value, const BMessage* msg) +{ BString action; if (value & WATCH_CREATE) action << "WATCH_CREATE "; diff --git a/src/Notifier.h b/src/Notifier.h index e1920a2..7b999fc 100644 --- a/src/Notifier.h +++ b/src/Notifier.h @@ -23,27 +23,28 @@ #define WATCH_ALL 0xFFFFFFFFFFFFFFFFLL void -PrintNotification(const uint64 &value, const BMessage *msg); +PrintNotification(const uint64& value, const BMessage* msg); class Observer { public: - Observer(const uint64 &flags = WATCH_ALL) { + Observer(const uint64& flags = WATCH_ALL) + { AddWatch(flags); fEnabled = true; } virtual ~Observer(void) {} - void AddWatch(const uint64 &flags) { fFlags |= flags; } + void AddWatch(const uint64& flags) { fFlags |= flags; } - void RemoveWatch(const uint64 &flags) { fFlags &= ~flags; } + void RemoveWatch(const uint64& flags) { fFlags &= ~flags; } - bool IsWatching(const uint64 &flags) { return fFlags & flags; } + bool IsWatching(const uint64& flags) { return fFlags & flags; } // Implement this to do whatever you want it to. - virtual void HandleNotify(const uint64 &value, const BMessage *msg) {} + virtual void HandleNotify(const uint64& value, const BMessage* msg) {} - virtual void SetObserving(const bool &value) { fEnabled = value; } + virtual void SetObserving(const bool& value) { fEnabled = value; } bool IsObserving(void) const { return fEnabled; } @@ -60,18 +61,19 @@ class Notifier { // If these methods are subclassed, please make sure that these versions // are also called. - virtual void AddObserver(Observer *obs) { fObserverList.AddItem(obs); } + virtual void AddObserver(Observer* obs) { fObserverList.AddItem(obs); } - virtual void RemoveObserver(Observer *obs) { fObserverList.RemoveItem(obs); } + virtual void RemoveObserver(Observer* obs) { fObserverList.RemoveItem(obs); } - bool HasObserver(Observer *obs) { return fObserverList.HasItem(obs); } + bool HasObserver(Observer* obs) { return fObserverList.HasItem(obs); } - virtual void Notify(const uint64 &value, const BMessage *msg = NULL) { + virtual void Notify(const uint64& value, const BMessage* msg = NULL) + { if (!fEnabled) return; for (int32 i = 0; i < fObserverList.CountItems(); i++) { - Observer *obs = (Observer *)fObserverList.ItemAt(i); + Observer* obs = (Observer*)fObserverList.ItemAt(i); if (!obs) continue; @@ -81,7 +83,7 @@ class Notifier { } } - void SetNotify(const bool &value) { fEnabled = value; } + void SetNotify(const bool& value) { fEnabled = value; } bool IsNotifying(void) const { return fEnabled; } diff --git a/src/NumBox.cpp b/src/NumBox.cpp index fca7b94..c3f12c2 100644 --- a/src/NumBox.cpp +++ b/src/NumBox.cpp @@ -4,13 +4,14 @@ #include "MsgDefs.h" #include "TimeSupport.h" -NumBoxFilter::NumBoxFilter(NumBox *box) : AutoTextControlFilter(box) {} +NumBoxFilter::NumBoxFilter(NumBox* box) : AutoTextControlFilter(box) {} filter_result -NumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +NumBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. if (key == B_TAB) { - if (!((NumBox *)TextControl())->IsTabFiltering()) + if (!((NumBox*)TextControl())->IsTabFiltering()) return B_DISPATCH_MESSAGE; if (mod & B_SHIFT_KEY) @@ -33,8 +34,9 @@ NumBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { return B_DISPATCH_MESSAGE; } -NumBox::NumBox(const char *name, const char *label, const char *text, BMessage *msg, uint32 flags) - : AutoTextControl(name, label, text, msg, flags), fFilterTab(true), fAllowNegatives(true) { +NumBox::NumBox(const char* name, const char* label, const char* text, BMessage* msg, uint32 flags) + : AutoTextControl(name, label, text, msg, flags), fFilterTab(true), fAllowNegatives(true) +{ SetFilter(new NumBoxFilter(this)); const char num_disallowed[] = " `~!@#%^&*()_+=QWERTYUIOP{[}]|\\ASDFGHJKL;:'\"" @@ -47,7 +49,8 @@ NumBox::NumBox(const char *name, const char *label, const char *text, BMessage * } bool -NumBox::Validate(bool alert) { +NumBox::Validate(bool alert) +{ if (strlen(Text()) < 1) SetText("0"); @@ -55,7 +58,8 @@ NumBox::Validate(bool alert) { } void -NumBox::AllowNegatives(const bool &value) { +NumBox::AllowNegatives(const bool& value) +{ if (fAllowNegatives != value) { fAllowNegatives = value; if (fAllowNegatives) diff --git a/src/NumBox.h b/src/NumBox.h index 5b812ab..a3eb1fb 100644 --- a/src/NumBox.h +++ b/src/NumBox.h @@ -7,24 +7,24 @@ class NumBox; class NumBoxFilter : public AutoTextControlFilter { public: - NumBoxFilter(NumBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + NumBoxFilter(NumBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class NumBox : public AutoTextControl { public: NumBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); bool Validate(bool alert = true); - void UseTabFiltering(const bool &value) { fFilterTab = value; } + void UseTabFiltering(const bool& value) { fFilterTab = value; } bool IsTabFiltering(void) const { return fFilterTab; } - void AllowNegatives(const bool &value); + void AllowNegatives(const bool& value); bool AllowsNegatives(void) const { return fAllowNegatives; } diff --git a/src/ObjectList.h b/src/ObjectList.h index 5a77505..7c17fa1 100644 --- a/src/ObjectList.h +++ b/src/ObjectList.h @@ -72,7 +72,7 @@ template class BObjectList; template struct UnaryPredicate { - virtual int operator()(const T *) const + virtual int operator()(const T*) const // virtual could be avoided here if FindBinaryInsertionIndex, // etc. were member template functions { @@ -80,43 +80,44 @@ template struct UnaryPredicate { } private: - static int _unary_predicate_glue(const void *item, void *context); + static int _unary_predicate_glue(const void* item, void* context); friend class BObjectList; }; template int -UnaryPredicate::_unary_predicate_glue(const void *item, void *context) { - return ((UnaryPredicate *)context)->operator()((const T *)item); +UnaryPredicate::_unary_predicate_glue(const void* item, void* context) +{ + return ((UnaryPredicate*)context)->operator()((const T*)item); } class _PointerList_ : public BList { public: - _PointerList_(const _PointerList_ &list); + _PointerList_(const _PointerList_& list); _PointerList_(int32 itemsPerBlock = 20, bool owning = false); ~_PointerList_(); - typedef void *(*GenericEachFunction)(void *, void *); - typedef int (*GenericCompareFunction)(const void *, const void *); - typedef int (*GenericCompareFunctionWithState)(const void *, const void *, void *); - typedef int (*UnaryPredicateGlue)(const void *, void *); + typedef void* (*GenericEachFunction)(void*, void*); + typedef int (*GenericCompareFunction)(const void*, const void*); + typedef int (*GenericCompareFunctionWithState)(const void*, const void*, void*); + typedef int (*UnaryPredicateGlue)(const void*, void*); - void *EachElement(GenericEachFunction, void *); + void* EachElement(GenericEachFunction, void*); void SortItems(GenericCompareFunction); - void SortItems(GenericCompareFunctionWithState, void *state); + void SortItems(GenericCompareFunctionWithState, void* state); void HSortItems(GenericCompareFunction); - void HSortItems(GenericCompareFunctionWithState, void *state); + void HSortItems(GenericCompareFunctionWithState, void* state); - void *BinarySearch(const void *, GenericCompareFunction) const; - void *BinarySearch(const void *, GenericCompareFunctionWithState, void *state) const; + void* BinarySearch(const void*, GenericCompareFunction) const; + void* BinarySearch(const void*, GenericCompareFunctionWithState, void* state) const; - int32 BinarySearchIndex(const void *, GenericCompareFunction) const; - int32 BinarySearchIndex(const void *, GenericCompareFunctionWithState, void *state) const; - int32 BinarySearchIndexByPredicate(const void *, UnaryPredicateGlue) const; + int32 BinarySearchIndex(const void*, GenericCompareFunction) const; + int32 BinarySearchIndex(const void*, GenericCompareFunctionWithState, void* state) const; + int32 BinarySearchIndexByPredicate(const void*, UnaryPredicateGlue) const; bool Owning() const; - bool ReplaceItem(int32, void *); + bool ReplaceItem(int32, void*); protected: bool owning; @@ -125,118 +126,118 @@ class _PointerList_ : public BList { template class BObjectList : private _PointerList_ { public: // iteration and sorting - typedef T *(*EachFunction)(T *, void *); - typedef const T *(*ConstEachFunction)(const T *, void *); - typedef int (*CompareFunction)(const T *, const T *); - typedef int (*CompareFunctionWithState)(const T *, const T *, void *state); + typedef T* (*EachFunction)(T*, void*); + typedef const T* (*ConstEachFunction)(const T*, void*); + typedef int (*CompareFunction)(const T*, const T*); + typedef int (*CompareFunctionWithState)(const T*, const T*, void* state); BObjectList(int32 itemsPerBlock = 20, bool owning = false); - BObjectList(const BObjectList &list); + BObjectList(const BObjectList& list); // clones list; if list is owning, makes copies of all // the items virtual ~BObjectList(); - BObjectList &operator=(const BObjectList &list); + BObjectList& operator=(const BObjectList& list); // clones list; if list is owning, makes copies of all // the items // adding and removing // ToDo: // change Add calls to return const item - bool AddItem(T *); - bool AddItem(T *, int32); - bool AddList(BObjectList *); - bool AddList(BObjectList *, int32); + bool AddItem(T*); + bool AddItem(T*, int32); + bool AddList(BObjectList*); + bool AddList(BObjectList*, int32); - bool RemoveItem(T *, bool deleteIfOwning = true); + bool RemoveItem(T*, bool deleteIfOwning = true); // if owning, deletes the removed item - T *RemoveItemAt(int32); + T* RemoveItemAt(int32); // returns the removed item void MakeEmpty(); // item access - T *ItemAt(int32) const; + T* ItemAt(int32) const; - bool ReplaceItem(int32 index, T *); + bool ReplaceItem(int32 index, T*); // if list is owning, deletes the item at first - T *SwapWithItem(int32 index, T *newItem); + T* SwapWithItem(int32 index, T* newItem); // same as ReplaceItem, except does not delete old item at , // returns it instead - T *FirstItem() const; - T *LastItem() const; + T* FirstItem() const; + T* LastItem() const; // misc. getters - int32 IndexOf(const T *) const; - bool HasItem(const T *) const; + int32 IndexOf(const T*) const; + bool HasItem(const T*) const; bool IsEmpty() const; int32 CountItems() const; - T *EachElement(EachFunction, void *); - const T *EachElement(ConstEachFunction, void *) const; + T* EachElement(EachFunction, void*); + const T* EachElement(ConstEachFunction, void*) const; void SortItems(CompareFunction); - void SortItems(CompareFunctionWithState, void *state); + void SortItems(CompareFunctionWithState, void* state); void HSortItems(CompareFunction); - void HSortItems(CompareFunctionWithState, void *state); + void HSortItems(CompareFunctionWithState, void* state); // linear search, returns first item that matches predicate - const T *FindIf(const UnaryPredicate &) const; - T *FindIf(const UnaryPredicate &); + const T* FindIf(const UnaryPredicate&) const; + T* FindIf(const UnaryPredicate&); // list must be sorted with CompareFunction for these to work - T *BinarySearch(const T &, CompareFunction) const; - T *BinarySearch(const T &, CompareFunctionWithState, void *state) const; + T* BinarySearch(const T&, CompareFunction) const; + T* BinarySearch(const T&, CompareFunctionWithState, void* state) const; template - T *BinarySearchByKey(const Key &key, int (*compare)(const Key *, const T *)) const; + T* BinarySearchByKey(const Key& key, int (*compare)(const Key*, const T*)) const; template - T *BinarySearchByKey( - const Key &key, int (*compare)(const Key *, const T *, void *), void *state - ) const; + T* BinarySearchByKey(const Key& key, int (*compare)(const Key*, const T*, void*), void* state) + const; // Binary insertion - list must be sorted with CompareFunction for // these to work // simple insert - bool BinaryInsert(T *, CompareFunction); - bool BinaryInsert(T *, CompareFunctionWithState, void *state); - bool BinaryInsert(T *, const UnaryPredicate &); + bool BinaryInsert(T*, CompareFunction); + bool BinaryInsert(T*, CompareFunctionWithState, void* state); + bool BinaryInsert(T*, const UnaryPredicate&); // unique insert, returns false if item already in list - bool BinaryInsertUnique(T *, CompareFunction); - bool BinaryInsertUnique(T *, CompareFunctionWithState, void *state); - bool BinaryInsertUnique(T *, const UnaryPredicate &); + bool BinaryInsertUnique(T*, CompareFunction); + bool BinaryInsertUnique(T*, CompareFunctionWithState, void* state); + bool BinaryInsertUnique(T*, const UnaryPredicate&); // insert a copy of the item, returns new inserted item - T *BinaryInsertCopy(const T ©This, CompareFunction); - T *BinaryInsertCopy(const T ©This, CompareFunctionWithState, void *state); + T* BinaryInsertCopy(const T& copyThis, CompareFunction); + T* BinaryInsertCopy(const T& copyThis, CompareFunctionWithState, void* state); // insert a copy of the item if not in list already // returns new inserted item or existing item in case of a conflict - T *BinaryInsertCopyUnique(const T ©This, CompareFunction); - T *BinaryInsertCopyUnique(const T ©This, CompareFunctionWithState, void *state); + T* BinaryInsertCopyUnique(const T& copyThis, CompareFunction); + T* BinaryInsertCopyUnique(const T& copyThis, CompareFunctionWithState, void* state); - int32 FindBinaryInsertionIndex(const UnaryPredicate &, bool *alreadyInList = 0) const; + int32 FindBinaryInsertionIndex(const UnaryPredicate&, bool* alreadyInList = 0) const; // returns either the index into which a new item should be inserted // or index of an existing item that matches the predicate // deprecated API, will go away - BList *AsBList() { return this; } + BList* AsBList() { return this; } - const BList *AsBList() const { return this; } + const BList* AsBList() const { return this; } private: - void SetItem(int32, T *); + void SetItem(int32, T*); }; template Result -WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1), Param1 p1) { +WhileEachListItem(BObjectList* list, Result (Item::*func)(Param1), Param1 p1) +{ Result result = 0; int32 count = list->CountItems(); @@ -249,7 +250,8 @@ WhileEachListItem(BObjectList *list, Result (Item::*func)(Param1), Param1 template Result -WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1), Param1 p1) { +WhileEachListItem(BObjectList* list, Result (*func)(Item*, Param1), Param1 p1) +{ Result result = 0; int32 count = list->CountItems(); @@ -263,8 +265,9 @@ WhileEachListItem(BObjectList *list, Result (*func)(Item *, Param1), Param template Result WhileEachListItem( - BObjectList *list, Result (Item::*func)(Param1, Param2), Param1 p1, Param2 p2 -) { + BObjectList* list, Result (Item::*func)(Param1, Param2), Param1 p1, Param2 p2 +) +{ Result result = 0; int32 count = list->CountItems(); @@ -278,8 +281,9 @@ WhileEachListItem( template Result WhileEachListItem( - BObjectList *list, Result (*func)(Item *, Param1, Param2), Param1 p1, Param2 p2 -) { + BObjectList* list, Result (*func)(Item*, Param1, Param2), Param1 p1, Param2 p2 +) +{ Result result = 0; int32 count = list->CountItems(); @@ -293,9 +297,10 @@ WhileEachListItem( template Result WhileEachListItem( - BObjectList *list, Result (*func)(Item *, Param1, Param2, Param3, Param4), Param1 p1, + BObjectList* list, Result (*func)(Item*, Param1, Param2, Param3, Param4), Param1 p1, Param2 p2, Param3 p3, Param4 p4 -) { +) +{ Result result = 0; int32 count = list->CountItems(); @@ -308,7 +313,8 @@ WhileEachListItem( template void -EachListItemIgnoreResult(BObjectList *list, Result (Item::*func)()) { +EachListItemIgnoreResult(BObjectList* list, Result (Item::*func)()) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (list->ItemAt(index)->*func)(); @@ -316,7 +322,8 @@ EachListItemIgnoreResult(BObjectList *list, Result (Item::*func)()) { template void -EachListItem(BObjectList *list, void (*func)(Item *, Param1), Param1 p1) { +EachListItem(BObjectList* list, void (*func)(Item*, Param1), Param1 p1) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1); @@ -324,7 +331,8 @@ EachListItem(BObjectList *list, void (*func)(Item *, Param1), Param1 p1) { template void -EachListItem(BObjectList *list, void (Item::*func)(Param1, Param2), Param1 p1, Param2 p2) { +EachListItem(BObjectList* list, void (Item::*func)(Param1, Param2), Param1 p1, Param2 p2) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (list->ItemAt(index)->*func)(p1, p2); @@ -332,7 +340,8 @@ EachListItem(BObjectList *list, void (Item::*func)(Param1, Param2), Param1 template void -EachListItem(BObjectList *list, void (*func)(Item *, Param1, Param2), Param1 p1, Param2 p2) { +EachListItem(BObjectList* list, void (*func)(Item*, Param1, Param2), Param1 p1, Param2 p2) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2); @@ -341,9 +350,10 @@ EachListItem(BObjectList *list, void (*func)(Item *, Param1, Param2), Para template void EachListItem( - BObjectList *list, void (*func)(Item *, Param1, Param2, Param3), Param1 p1, Param2 p2, + BObjectList* list, void (*func)(Item*, Param1, Param2, Param3), Param1 p1, Param2 p2, Param3 p3 -) { +) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2, p3); @@ -352,9 +362,10 @@ EachListItem( template void EachListItem( - BObjectList *list, void (*func)(Item *, Param1, Param2, Param3, Param4), Param1 p1, + BObjectList* list, void (*func)(Item*, Param1, Param2, Param3, Param4), Param1 p1, Param2 p2, Param3 p3, Param4 p4 -) { +) +{ int32 count = list->CountItems(); for (int32 index = 0; index < count; index++) (func)(list->ItemAt(index), p1, p2, p3, p4); @@ -363,21 +374,24 @@ EachListItem( // inline code inline bool -_PointerList_::Owning() const { +_PointerList_::Owning() const +{ return owning; } template -BObjectList::BObjectList(int32 itemsPerBlock, bool owning) - : _PointerList_(itemsPerBlock, owning) {} +BObjectList::BObjectList(int32 itemsPerBlock, bool owning) : _PointerList_(itemsPerBlock, owning) +{ +} -template BObjectList::BObjectList(const BObjectList &list) : _PointerList_(list) { +template BObjectList::BObjectList(const BObjectList& list) : _PointerList_(list) +{ owning = list.owning; if (owning) { // make our own copies in an owning list int32 count = list.CountItems(); for (int32 index = 0; index < count; index++) { - T *item = list.ItemAt(index); + T* item = list.ItemAt(index); if (item) item = new T(*item); SetItem(index, item); @@ -385,22 +399,24 @@ template BObjectList::BObjectList(const BObjectList &list) : _Po } } -template BObjectList::~BObjectList() { +template BObjectList::~BObjectList() +{ if (Owning()) // have to nuke elements first MakeEmpty(); } template -BObjectList & -BObjectList::operator=(const BObjectList &list) { +BObjectList& +BObjectList::operator=(const BObjectList& list) +{ owning = list.owning; - BObjectList &result = (BObjectList &)_PointerList_::operator=(list); + BObjectList& result = (BObjectList&)_PointerList_::operator=(list); if (owning) { // make our own copies in an owning list int32 count = list.CountItems(); for (int32 index = 0; index < count; index++) { - T *item = list.ItemAt(index); + T* item = list.ItemAt(index); if (item) item = new T(*item); SetItem(index, item); @@ -411,33 +427,38 @@ BObjectList::operator=(const BObjectList &list) { template bool -BObjectList::AddItem(T *item) { +BObjectList::AddItem(T* item) +{ // need to cast to void * to make T work for const pointers - return _PointerList_::AddItem((void *)item); + return _PointerList_::AddItem((void*)item); } template bool -BObjectList::AddItem(T *item, int32 atIndex) { - return _PointerList_::AddItem((void *)item, atIndex); +BObjectList::AddItem(T* item, int32 atIndex) +{ + return _PointerList_::AddItem((void*)item, atIndex); } template bool -BObjectList::AddList(BObjectList *newItems) { +BObjectList::AddList(BObjectList* newItems) +{ return _PointerList_::AddList(newItems); } template bool -BObjectList::AddList(BObjectList *newItems, int32 atIndex) { +BObjectList::AddList(BObjectList* newItems, int32 atIndex) +{ return _PointerList_::AddList(newItems, atIndex); } template bool -BObjectList::RemoveItem(T *item, bool deleteIfOwning) { - bool result = _PointerList_::RemoveItem((void *)item); +BObjectList::RemoveItem(T* item, bool deleteIfOwning) +{ + bool result = _PointerList_::RemoveItem((void*)item); if (result && Owning() && deleteIfOwning) delete item; @@ -446,78 +467,90 @@ BObjectList::RemoveItem(T *item, bool deleteIfOwning) { } template -T * -BObjectList::RemoveItemAt(int32 index) { - return (T *)_PointerList_::RemoveItem(index); +T* +BObjectList::RemoveItemAt(int32 index) +{ + return (T*)_PointerList_::RemoveItem(index); } template -inline T * -BObjectList::ItemAt(int32 index) const { - return (T *)_PointerList_::ItemAt(index); +inline T* +BObjectList::ItemAt(int32 index) const +{ + return (T*)_PointerList_::ItemAt(index); } template bool -BObjectList::ReplaceItem(int32 index, T *item) { +BObjectList::ReplaceItem(int32 index, T* item) +{ if (owning) delete ItemAt(index); - return _PointerList_::ReplaceItem(index, (void *)item); + return _PointerList_::ReplaceItem(index, (void*)item); } template -T * -BObjectList::SwapWithItem(int32 index, T *newItem) { - T *result = ItemAt(index); - _PointerList_::ReplaceItem(index, (void *)newItem); +T* +BObjectList::SwapWithItem(int32 index, T* newItem) +{ + T* result = ItemAt(index); + _PointerList_::ReplaceItem(index, (void*)newItem); return result; } template void -BObjectList::SetItem(int32 index, T *newItem) { - _PointerList_::ReplaceItem(index, (void *)newItem); +BObjectList::SetItem(int32 index, T* newItem) +{ + _PointerList_::ReplaceItem(index, (void*)newItem); } template int32 -BObjectList::IndexOf(const T *item) const { - return _PointerList_::IndexOf((void *)item); +BObjectList::IndexOf(const T* item) const +{ + return _PointerList_::IndexOf((void*)item); } template -T * -BObjectList::FirstItem() const { - return (T *)_PointerList_::FirstItem(); +T* +BObjectList::FirstItem() const +{ + return (T*)_PointerList_::FirstItem(); } template -T * -BObjectList::LastItem() const { - return (T *)_PointerList_::LastItem(); +T* +BObjectList::LastItem() const +{ + return (T*)_PointerList_::LastItem(); } template bool -BObjectList::HasItem(const T *item) const { - return _PointerList_::HasItem((void *)item); +BObjectList::HasItem(const T* item) const +{ + return _PointerList_::HasItem((void*)item); } template bool -BObjectList::IsEmpty() const { +BObjectList::IsEmpty() const +{ return _PointerList_::IsEmpty(); } template int32 -BObjectList::CountItems() const { +BObjectList::CountItems() const +{ return _PointerList_::CountItems(); } template void -BObjectList::MakeEmpty() { +BObjectList::MakeEmpty() +{ if (owning) { int32 count = CountItems(); for (int32 index = 0; index < count; index++) @@ -527,22 +560,25 @@ BObjectList::MakeEmpty() { } template -T * -BObjectList::EachElement(EachFunction func, void *params) { - return (T *)_PointerList_::EachElement((GenericEachFunction)func, params); +T* +BObjectList::EachElement(EachFunction func, void* params) +{ + return (T*)_PointerList_::EachElement((GenericEachFunction)func, params); } template -const T * -BObjectList::EachElement(ConstEachFunction func, void *params) const { - return (const T *)const_cast *>(this)->_PointerList_::EachElement( +const T* +BObjectList::EachElement(ConstEachFunction func, void* params) const +{ + return (const T*)const_cast*>(this)->_PointerList_::EachElement( (GenericEachFunction)func, params ); } template -const T * -BObjectList::FindIf(const UnaryPredicate &predicate) const { +const T* +BObjectList::FindIf(const UnaryPredicate& predicate) const +{ int32 count = CountItems(); for (int32 index = 0; index < count; index++) if (predicate.operator()(ItemAt(index)) == 0) @@ -551,8 +587,9 @@ BObjectList::FindIf(const UnaryPredicate &predicate) const { } template -T * -BObjectList::FindIf(const UnaryPredicate &predicate) { +T* +BObjectList::FindIf(const UnaryPredicate& predicate) +{ int32 count = CountItems(); for (int32 index = 0; index < count; index++) if (predicate.operator()(ItemAt(index)) == 0) @@ -562,59 +599,68 @@ BObjectList::FindIf(const UnaryPredicate &predicate) { template void -BObjectList::SortItems(CompareFunction function) { +BObjectList::SortItems(CompareFunction function) +{ _PointerList_::SortItems((GenericCompareFunction)function); } template void -BObjectList::SortItems(CompareFunctionWithState function, void *state) { +BObjectList::SortItems(CompareFunctionWithState function, void* state) +{ _PointerList_::SortItems((GenericCompareFunctionWithState)function, state); } template void -BObjectList::HSortItems(CompareFunction function) { +BObjectList::HSortItems(CompareFunction function) +{ _PointerList_::HSortItems((GenericCompareFunction)function); } template void -BObjectList::HSortItems(CompareFunctionWithState function, void *state) { +BObjectList::HSortItems(CompareFunctionWithState function, void* state) +{ _PointerList_::HSortItems((GenericCompareFunctionWithState)function, state); } template -T * -BObjectList::BinarySearch(const T &key, CompareFunction func) const { - return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunction)func); +T* +BObjectList::BinarySearch(const T& key, CompareFunction func) const +{ + return (T*)_PointerList_::BinarySearch(&key, (GenericCompareFunction)func); } template -T * -BObjectList::BinarySearch(const T &key, CompareFunctionWithState func, void *state) const { - return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)func, state); +T* +BObjectList::BinarySearch(const T& key, CompareFunctionWithState func, void* state) const +{ + return (T*)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)func, state); } template template -T * -BObjectList::BinarySearchByKey(const Key &key, int (*compare)(const Key *, const T *)) const { - return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunction)compare); +T* +BObjectList::BinarySearchByKey(const Key& key, int (*compare)(const Key*, const T*)) const +{ + return (T*)_PointerList_::BinarySearch(&key, (GenericCompareFunction)compare); } template template -T * +T* BObjectList::BinarySearchByKey( - const Key &key, int (*compare)(const Key *, const T *, void *), void *state -) const { - return (T *)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)compare, state); + const Key& key, int (*compare)(const Key*, const T*, void*), void* state +) const +{ + return (T*)_PointerList_::BinarySearch(&key, (GenericCompareFunctionWithState)compare, state); } template bool -BObjectList::BinaryInsert(T *item, CompareFunction func) { +BObjectList::BinaryInsert(T* item, CompareFunction func) +{ int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunction)func); if (index >= 0) { // already in list, add after existing @@ -626,7 +672,8 @@ BObjectList::BinaryInsert(T *item, CompareFunction func) { template bool -BObjectList::BinaryInsert(T *item, CompareFunctionWithState func, void *state) { +BObjectList::BinaryInsert(T* item, CompareFunctionWithState func, void* state) +{ int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunctionWithState)func, state); if (index >= 0) { @@ -639,7 +686,8 @@ BObjectList::BinaryInsert(T *item, CompareFunctionWithState func, void *state template bool -BObjectList::BinaryInsertUnique(T *item, CompareFunction func) { +BObjectList::BinaryInsertUnique(T* item, CompareFunction func) +{ int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunction)func); if (index >= 0) return false; @@ -649,7 +697,8 @@ BObjectList::BinaryInsertUnique(T *item, CompareFunction func) { template bool -BObjectList::BinaryInsertUnique(T *item, CompareFunctionWithState func, void *state) { +BObjectList::BinaryInsertUnique(T* item, CompareFunctionWithState func, void* state) +{ int32 index = _PointerList_::BinarySearchIndex(item, (GenericCompareFunctionWithState)func, state); if (index >= 0) @@ -659,8 +708,9 @@ BObjectList::BinaryInsertUnique(T *item, CompareFunctionWithState func, void } template -T * -BObjectList::BinaryInsertCopy(const T ©This, CompareFunction func) { +T* +BObjectList::BinaryInsertCopy(const T& copyThis, CompareFunction func) +{ int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunction)func); if (index >= 0) @@ -668,14 +718,15 @@ BObjectList::BinaryInsertCopy(const T ©This, CompareFunction func) { else index = -index - 1; - T *newItem = new T(copyThis); + T* newItem = new T(copyThis); AddItem(newItem, index); return newItem; } template -T * -BObjectList::BinaryInsertCopy(const T ©This, CompareFunctionWithState func, void *state) { +T* +BObjectList::BinaryInsertCopy(const T& copyThis, CompareFunctionWithState func, void* state) +{ int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunctionWithState)func, state); @@ -684,43 +735,46 @@ BObjectList::BinaryInsertCopy(const T ©This, CompareFunctionWithState fun else index = -index - 1; - T *newItem = new T(copyThis); + T* newItem = new T(copyThis); AddItem(newItem, index); return newItem; } template -T * -BObjectList::BinaryInsertCopyUnique(const T ©This, CompareFunction func) { +T* +BObjectList::BinaryInsertCopyUnique(const T& copyThis, CompareFunction func) +{ int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunction)func); if (index >= 0) return ItemAt(index); index = -index - 1; - T *newItem = new T(copyThis); + T* newItem = new T(copyThis); AddItem(newItem, index); return newItem; } template -T * +T* BObjectList::BinaryInsertCopyUnique( - const T ©This, CompareFunctionWithState func, void *state -) { + const T& copyThis, CompareFunctionWithState func, void* state +) +{ int32 index = _PointerList_::BinarySearchIndex(©This, (GenericCompareFunctionWithState)func, state); if (index >= 0) return ItemAt(index); index = -index - 1; - T *newItem = new T(copyThis); + T* newItem = new T(copyThis); AddItem(newItem, index); return newItem; } template int32 -BObjectList::FindBinaryInsertionIndex(const UnaryPredicate &pred, bool *alreadyInList) const { +BObjectList::FindBinaryInsertionIndex(const UnaryPredicate& pred, bool* alreadyInList) const +{ int32 index = _PointerList_::BinarySearchIndexByPredicate( &pred, (UnaryPredicateGlue)&UnaryPredicate::_unary_predicate_glue ); @@ -736,13 +790,15 @@ BObjectList::FindBinaryInsertionIndex(const UnaryPredicate &pred, bool *al template bool -BObjectList::BinaryInsert(T *item, const UnaryPredicate &pred) { +BObjectList::BinaryInsert(T* item, const UnaryPredicate& pred) +{ return AddItem(item, FindBinaryInsertionIndex(pred)); } template bool -BObjectList::BinaryInsertUnique(T *item, const UnaryPredicate &pred) { +BObjectList::BinaryInsertUnique(T* item, const UnaryPredicate& pred) +{ bool alreadyInList; int32 index = FindBinaryInsertionIndex(pred, &alreadyInList); if (alreadyInList) diff --git a/src/PayeeBox.cpp b/src/PayeeBox.cpp index 8759d20..d425764 100644 --- a/src/PayeeBox.cpp +++ b/src/PayeeBox.cpp @@ -10,11 +10,11 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "PayeeBox" - -PayeeBoxFilter::PayeeBoxFilter(PayeeBox *box) : AutoTextControlFilter(box) {} +PayeeBoxFilter::PayeeBoxFilter(PayeeBox* box) : AutoTextControlFilter(box) {} filter_result -PayeeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { +PayeeBoxFilter::KeyFilter(const int32& key, const int32& mod) +{ // Here is where all the *real* work for a date box is done. if (key == B_TAB) { if (mod & B_SHIFT_KEY) @@ -38,7 +38,7 @@ PayeeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { !(mod & B_CONTROL_KEY))) return B_DISPATCH_MESSAGE; - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (!acc) return B_DISPATCH_MESSAGE; @@ -66,15 +66,17 @@ PayeeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { } PayeeBox::PayeeBox( - const char *name, const char *label, const char *text, BMessage *msg, uint32 flags + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags ) - : AutoTextControl(name, label, text, msg, flags) { + : AutoTextControl(name, label, text, msg, flags) +{ SetFilter(new PayeeBoxFilter(this)); SetCharacterLimit(32); } bool -PayeeBox::Validate(const bool &showalert) { +PayeeBox::Validate(const bool& showalert) +{ if (showalert && (Text() == NULL || strlen(Text()) < 1)) { ShowAlert(B_TRANSLATE("Payee is missing."), B_TRANSLATE("You need to enter a payee.")); MakeFocus(true); diff --git a/src/PayeeBox.h b/src/PayeeBox.h index d8a05e9..b380adb 100644 --- a/src/PayeeBox.h +++ b/src/PayeeBox.h @@ -9,18 +9,18 @@ class PayeeBox; class PayeeBoxFilter : public AutoTextControlFilter { public: - PayeeBoxFilter(PayeeBox *box); - filter_result KeyFilter(const int32 &key, const int32 &mod); + PayeeBoxFilter(PayeeBox* box); + filter_result KeyFilter(const int32& key, const int32& mod); }; class PayeeBox : public AutoTextControl { public: PayeeBox( - const char *name, const char *label, const char *text, BMessage *msg, + const char* name, const char* label, const char* text, BMessage* msg, uint32 flags = B_WILL_DRAW | B_NAVIGABLE ); - bool Validate(const bool &showalert = true); + bool Validate(const bool& showalert = true); private: friend PayeeBoxFilter; diff --git a/src/PrefWindow.cpp b/src/PrefWindow.cpp index db30af5..6323f7c 100644 --- a/src/PrefWindow.cpp +++ b/src/PrefWindow.cpp @@ -29,17 +29,18 @@ enum { M_TOGGLE_PREFIX }; -PrefWindow::PrefWindow(const BRect &frame) +PrefWindow::PrefWindow(const BRect& frame) : BWindow( frame, B_TRANSLATE("Options"), B_FLOATING_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS - ) { + ) +{ BString temp; AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddCommonFilter(new EscapeCancelFilter()); - BView *back = new BView(NULL, B_WILL_DRAW); + BView* back = new BView(NULL, B_WILL_DRAW); back->SetViewColor(240, 240, 240); temp = B_TRANSLATE("Default account settings:"); @@ -72,7 +73,8 @@ PrefWindow::PrefWindow(const BRect &frame) } void -PrefWindow::MessageReceived(BMessage *msg) { +PrefWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_EDIT_OPTIONS: { Locale temp = gDefaultLocale; @@ -93,8 +95,9 @@ PrefWindow::MessageReceived(BMessage *msg) { } } -DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) - : BView(name, flags) { +DatePrefView::DatePrefView(const char* name, Locale* locale, const int32& flags) + : BView(name, flags) +{ BString temp; SetViewColor(240, 240, 240); @@ -103,7 +106,7 @@ DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) else fLocale = gDefaultLocale; - BBox *fDateBox = new BBox("DateBox"); + BBox* fDateBox = new BBox("DateBox"); fDateBox->SetLabel(B_TRANSLATE("Date")); BString datestr; @@ -143,14 +146,16 @@ DatePrefView::DatePrefView(const char *name, Locale *locale, const int32 &flags) } void -DatePrefView::AttachedToWindow(void) { +DatePrefView::AttachedToWindow(void) +{ fDateMDY->SetTarget(this); fDateDMY->SetTarget(this); fDateSeparatorBox->SetTarget(this); } void -DatePrefView::MessageReceived(BMessage *msg) { +DatePrefView::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_DMY_FORMAT: { fLocale.SetDateFormat(DATE_DMY); @@ -177,7 +182,8 @@ DatePrefView::MessageReceived(BMessage *msg) { } void -DatePrefView::UpdateDateLabel(void) { +DatePrefView::UpdateDateLabel(void) +{ BString temp, label; fLocale.DateToString(0, temp); label.SetToFormat(B_TRANSLATE("Date format: %s"), temp); @@ -185,14 +191,16 @@ DatePrefView::UpdateDateLabel(void) { } void -DatePrefView::GetSettings(Locale &locale) { +DatePrefView::GetSettings(Locale& locale) +{ if (strlen(fDateSeparatorBox->Text()) > 0) locale.SetDateSeparator(fDateSeparatorBox->Text()); locale.SetDateFormat((fDateDMY->Value() == B_CONTROL_ON) ? DATE_DMY : DATE_MDY); } -CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 &flags) - : BView(name, flags), fSampleAmount((long)12345678, true) { +CurrencyPrefView::CurrencyPrefView(const char* name, Locale* locale, const int32& flags) + : BView(name, flags), fSampleAmount((long)12345678, true) +{ BString temp; SetViewColor(240, 240, 240); @@ -201,7 +209,7 @@ CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 else fLocale = gDefaultLocale; - BBox *fCurrencyBox = new BBox("CurrencyBox"); + BBox* fCurrencyBox = new BBox("CurrencyBox"); fCurrencyBox->SetLabel(B_TRANSLATE("Currency")); BString curstr; @@ -254,7 +262,8 @@ CurrencyPrefView::CurrencyPrefView(const char *name, Locale *locale, const int32 } void -CurrencyPrefView::AttachedToWindow(void) { +CurrencyPrefView::AttachedToWindow(void) +{ fCurrencySymbolBox->SetTarget(this); fCurrencyDecimalBox->SetTarget(this); fCurrencySeparatorBox->SetTarget(this); @@ -262,7 +271,8 @@ CurrencyPrefView::AttachedToWindow(void) { } void -CurrencyPrefView::MessageReceived(BMessage *msg) { +CurrencyPrefView::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_NEW_CURRENCY_SYMBOL: { if (strlen(fCurrencySymbolBox->Text()) < 1) @@ -300,7 +310,8 @@ CurrencyPrefView::MessageReceived(BMessage *msg) { } void -CurrencyPrefView::UpdateCurrencyLabel(void) { +CurrencyPrefView::UpdateCurrencyLabel(void) +{ BString temp, label; fLocale.CurrencyToString(fSampleAmount, temp); label.SetToFormat(B_TRANSLATE("Currency format: %s"), temp); @@ -308,7 +319,8 @@ CurrencyPrefView::UpdateCurrencyLabel(void) { } void -CurrencyPrefView::GetSettings(Locale &locale) { +CurrencyPrefView::GetSettings(Locale& locale) +{ if (strlen(fCurrencySeparatorBox->Text()) > 0) locale.SetCurrencySeparator(fCurrencySeparatorBox->Text()); if (strlen(fCurrencyDecimalBox->Text()) > 0) diff --git a/src/PrefWindow.h b/src/PrefWindow.h index a1e332a..4f5d502 100644 --- a/src/PrefWindow.h +++ b/src/PrefWindow.h @@ -20,48 +20,48 @@ class CurrencyPrefView; class PrefWindow : public BWindow { public: - PrefWindow(const BRect &frame); - void MessageReceived(BMessage *msg); + PrefWindow(const BRect& frame); + void MessageReceived(BMessage* msg); private: - DatePrefView *fDatePrefView; - CurrencyPrefView *fCurrencyPrefView; + DatePrefView* fDatePrefView; + CurrencyPrefView* fCurrencyPrefView; BButton *fOK, *fCancel; - BStringView *fLabel; + BStringView* fLabel; }; class DatePrefView : public BView { public: - DatePrefView(const char *name, Locale *locale = NULL, const int32 &flags = B_WILL_DRAW); + DatePrefView(const char* name, Locale* locale = NULL, const int32& flags = B_WILL_DRAW); void AttachedToWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); - void GetSettings(Locale &locale); + void GetSettings(Locale& locale); private: void UpdateDateLabel(void); - BStringView *fDateLabel; + BStringView* fDateLabel; BRadioButton *fDateMDY, *fDateDMY; - AutoTextControl *fDateSeparatorBox; + AutoTextControl* fDateSeparatorBox; Locale fLocale; }; class CurrencyPrefView : public BView { public: - CurrencyPrefView(const char *name, Locale *locale = NULL, const int32 &flags = B_WILL_DRAW); + CurrencyPrefView(const char* name, Locale* locale = NULL, const int32& flags = B_WILL_DRAW); void AttachedToWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); - void GetSettings(Locale &locale); + void GetSettings(Locale& locale); private: void UpdateCurrencyLabel(void); - BStringView *fCurrencyLabel; + BStringView* fCurrencyLabel; AutoTextControl *fCurrencySymbolBox, *fCurrencyDecimalBox, *fCurrencySeparatorBox; - BCheckBox *fCurrencySymbolPrefix; + BCheckBox* fCurrencySymbolPrefix; Locale fLocale; Fixed fSampleAmount; diff --git a/src/Preferences.cpp b/src/Preferences.cpp index 08fbab3..75d2087 100644 --- a/src/Preferences.cpp +++ b/src/Preferences.cpp @@ -18,7 +18,8 @@ static rgb_color sSelectionNoFocusColor = {205, 205, 230, 255}; static rgb_color sGridHeaderColor = {225, 225, 255, 255}; void -ConstrainWindowFrameToScreen(BRect *rect) { +ConstrainWindowFrameToScreen(BRect* rect) +{ if (!rect) return; @@ -55,7 +56,8 @@ ConstrainWindowFrameToScreen(BRect *rect) { } status_t -SavePreferences(const char *path) { +SavePreferences(const char* path) +{ if (!path) return B_ERROR; @@ -75,7 +77,8 @@ SavePreferences(const char *path) { } status_t -LoadPreferences(const char *path) { +LoadPreferences(const char* path) +{ if (!path) return B_ERROR; @@ -113,7 +116,8 @@ LoadPreferences(const char *path) { } rgb_color -GetColor(const CapitalBeColor &color) { +GetColor(const CapitalBeColor& color) +{ rgb_color returncolor = {0, 0, 0, 0}; switch (color) { diff --git a/src/Preferences.h b/src/Preferences.h index 899f560..bb13c1d 100644 --- a/src/Preferences.h +++ b/src/Preferences.h @@ -15,16 +15,16 @@ extern BString gAppPath; #define PREFERENCES_PATH "/boot/home/config/settings/CapitalBe" status_t -SavePreferences(const char *path); +SavePreferences(const char* path); status_t -LoadPreferences(const char *path); +LoadPreferences(const char* path); void -ConstrainWindowFrameToScreen(BRect *rect); +ConstrainWindowFrameToScreen(BRect* rect); typedef enum { BC_SELECTION_FOCUS = 0, BC_SELECTION_NOFOCUS, BC_GRID_HEADER } CapitalBeColor; rgb_color -GetColor(const CapitalBeColor &color); +GetColor(const CapitalBeColor& color); #endif diff --git a/src/QuickTrackerItem.cpp b/src/QuickTrackerItem.cpp index c07635b..51d6427 100644 --- a/src/QuickTrackerItem.cpp +++ b/src/QuickTrackerItem.cpp @@ -11,31 +11,34 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "QuickTrackerItem" - // Calculates the user's net worth by adding up the balances of all accounts -QTNetWorthItem::QTNetWorthItem(const char *name, uint32 flags) - : QuickTrackerItem(name, flags), fIgnore(false) { +QTNetWorthItem::QTNetWorthItem(const char* name, uint32 flags) + : QuickTrackerItem(name, flags), fIgnore(false) +{ for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); account->AddObserver(this); } } -QTNetWorthItem::~QTNetWorthItem(void) { +QTNetWorthItem::~QTNetWorthItem(void) +{ for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); account->RemoveObserver(this); } } void -QTNetWorthItem::AttachedToWindow(void) { +QTNetWorthItem::AttachedToWindow(void) +{ QuickTrackerItem::AttachedToWindow(); Calculate(); } void -QTNetWorthItem::SetObserving(const bool &value) { +QTNetWorthItem::SetObserving(const bool& value) +{ if (IsObserving() != value) { Observer::SetObserving(value); Calculate(); @@ -43,7 +46,8 @@ QTNetWorthItem::SetObserving(const bool &value) { } void -QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) { +QTNetWorthItem::HandleNotify(const uint64& value, const BMessage* msg) +{ /* TODO: Make QTNetWorthItem ignore mass edits if(value & WATCH_MASS_EDIT) @@ -59,13 +63,14 @@ QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) { return; */ if (value & WATCH_ACCOUNT) { - Account *acc = NULL; - if (msg->FindPointer("item", (void **)&acc) != B_OK) + Account* acc = NULL; + if (msg->FindPointer("item", (void**)&acc) != B_OK) return; if (value & WATCH_CREATE) { acc->AddObserver(this); - } else if (value & WATCH_DELETE) { + } + else if (value & WATCH_DELETE) { acc->RemoveObserver(this); if (gDatabase.CountAccounts() == 1) { if (Window()) @@ -88,7 +93,8 @@ QTNetWorthItem::HandleNotify(const uint64 &value, const BMessage *msg) { } void -QTNetWorthItem::Calculate(void) { +QTNetWorthItem::Calculate(void) +{ BString label, temp; Fixed balance; @@ -109,7 +115,7 @@ QTNetWorthItem::Calculate(void) { } for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); if (!account->IsClosed()) balance += account->Balance(); } @@ -127,31 +133,35 @@ QTNetWorthItem::Calculate(void) { } // Calculates the budget variance for one category -QTBudgetCategoryItem::QTBudgetCategoryItem(const char *category, const char *name, uint32 flags) - : QuickTrackerItem(name, flags), fIgnore(false) { +QTBudgetCategoryItem::QTBudgetCategoryItem(const char* category, const char* name, uint32 flags) + : QuickTrackerItem(name, flags), fIgnore(false) +{ for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); account->AddObserver(this); } gDatabase.GetBudgetEntry(category, fEntry); } -QTBudgetCategoryItem::~QTBudgetCategoryItem(void) { +QTBudgetCategoryItem::~QTBudgetCategoryItem(void) +{ for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); account->RemoveObserver(this); } } void -QTBudgetCategoryItem::AttachedToWindow(void) { +QTBudgetCategoryItem::AttachedToWindow(void) +{ QuickTrackerItem::AttachedToWindow(); Calculate(); } void -QTBudgetCategoryItem::SetObserving(const bool &value) { +QTBudgetCategoryItem::SetObserving(const bool& value) +{ if (IsObserving() != value) { Observer::SetObserving(value); Calculate(); @@ -159,7 +169,8 @@ QTBudgetCategoryItem::SetObserving(const bool &value) { } void -QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) { +QTBudgetCategoryItem::HandleNotify(const uint64& value, const BMessage* msg) +{ /* TODO: Make QTBudgetCategoryItem ignore mass edits if(value & WATCH_MASS_EDIT) @@ -175,13 +186,14 @@ QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) { return; */ if (value & WATCH_ACCOUNT) { - Account *acc = NULL; - if (msg->FindPointer("item", (void **)&acc) != B_OK) + Account* acc = NULL; + if (msg->FindPointer("item", (void**)&acc) != B_OK) return; if (value & WATCH_CREATE) { acc->AddObserver(this); - } else if (value & WATCH_DELETE) { + } + else if (value & WATCH_DELETE) { acc->RemoveObserver(this); if (gDatabase.CountAccounts() == 1) { if (Window()) @@ -204,7 +216,8 @@ QTBudgetCategoryItem::HandleNotify(const uint64 &value, const BMessage *msg) { } void -QTBudgetCategoryItem::Calculate(void) { +QTBudgetCategoryItem::Calculate(void) +{ BString label, temp; Fixed variance; @@ -222,7 +235,8 @@ QTBudgetCategoryItem::Calculate(void) { } } -QuickTrackerItem::QuickTrackerItem(const char *name, uint32 flags) : BTextView(name, flags) { +QuickTrackerItem::QuickTrackerItem(const char* name, uint32 flags) : BTextView(name, flags) +{ MakeEditable(false); MakeSelectable(false); gDatabase.AddObserver(this); @@ -231,16 +245,19 @@ QuickTrackerItem::QuickTrackerItem(const char *name, uint32 flags) : BTextView(n QuickTrackerItem::~QuickTrackerItem(void) { gDatabase.RemoveObserver(this); } void -QuickTrackerItem::AttachedToWindow(void) { +QuickTrackerItem::AttachedToWindow(void) +{ SetViewColor(Parent()->ViewColor()); } void -QuickTrackerItem::HandleNotify(const uint64 &value, const BMessage *msg) { +QuickTrackerItem::HandleNotify(const uint64& value, const BMessage* msg) +{ // Does nothing by default - hook function for child classes } void -QuickTrackerItem::Configure(void) { +QuickTrackerItem::Configure(void) +{ // Does nothing by default - hook function for child classes } diff --git a/src/QuickTrackerItem.h b/src/QuickTrackerItem.h index c09f108..a4ddabe 100644 --- a/src/QuickTrackerItem.h +++ b/src/QuickTrackerItem.h @@ -7,22 +7,22 @@ class QuickTrackerItem : public BTextView, public Observer { public: - QuickTrackerItem(const char *name, uint32 flags = B_WILL_DRAW); + QuickTrackerItem(const char* name, uint32 flags = B_WILL_DRAW); virtual ~QuickTrackerItem(void); - virtual void HandleNotify(const uint64 &value, const BMessage *msg); + virtual void HandleNotify(const uint64& value, const BMessage* msg); virtual void Configure(void); virtual void AttachedToWindow(void); }; class QTNetWorthItem : public QuickTrackerItem { public: - QTNetWorthItem(const char *name, uint32 flags = B_WILL_DRAW); + QTNetWorthItem(const char* name, uint32 flags = B_WILL_DRAW); ~QTNetWorthItem(void); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); void AttachedToWindow(void); - void SetObserving(const bool &value); + void SetObserving(const bool& value); protected: void Calculate(void); @@ -31,11 +31,11 @@ class QTNetWorthItem : public QuickTrackerItem { class QTBudgetCategoryItem : public QuickTrackerItem { public: - QTBudgetCategoryItem(const char *category, const char *name, uint32 flags = B_WILL_DRAW); + QTBudgetCategoryItem(const char* category, const char* name, uint32 flags = B_WILL_DRAW); ~QTBudgetCategoryItem(void); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); void AttachedToWindow(void); - void SetObserving(const bool &value); + void SetObserving(const bool& value); protected: void Calculate(void); diff --git a/src/ReconcileItem.cpp b/src/ReconcileItem.cpp index dd03a59..2c3bfe8 100644 --- a/src/ReconcileItem.cpp +++ b/src/ReconcileItem.cpp @@ -13,18 +13,21 @@ #include #include -ReconcileItem::ReconcileItem(const TransactionData &trans) : BStringItem(""), fTransaction(trans) { +ReconcileItem::ReconcileItem(const TransactionData& trans) : BStringItem(""), fTransaction(trans) +{ fValue = fTransaction.Status(); } ReconcileItem::~ReconcileItem(void) {} void -ReconcileItem::DrawItem(BView *owner, BRect frame, bool complete) { +ReconcileItem::DrawItem(BView* owner, BRect frame, bool complete) +{ if (IsSelected()) { owner->SetHighColor(GetColor(BC_SELECTION_FOCUS)); owner->SetLowColor(GetColor(BC_SELECTION_FOCUS)); - } else { + } + else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); } @@ -63,17 +66,20 @@ ReconcileItem::DrawItem(BView *owner, BRect frame, bool complete) { } void -ReconcileItem::SetReconciled(bool value) { +ReconcileItem::SetReconciled(bool value) +{ fTransaction.SetStatus(value ? TRANS_RECONCILED : TRANS_OPEN); } bool -ReconcileItem::IsReconciled(void) const { +ReconcileItem::IsReconciled(void) const +{ return (fTransaction.Status() == TRANS_RECONCILED); } void -ReconcileItem::SyncToTransaction(void) { +ReconcileItem::SyncToTransaction(void) +{ if (fTransaction.Status() == TRANS_RECONCILED) gDatabase.SetTransactionStatus(fTransaction.GetID(), TRANS_RECONCILED); else diff --git a/src/ReconcileItem.h b/src/ReconcileItem.h index 7b61f78..664d8a4 100644 --- a/src/ReconcileItem.h +++ b/src/ReconcileItem.h @@ -5,14 +5,13 @@ #include - class ReconcileItem : public BStringItem { public: - ReconcileItem(const TransactionData &trans); + ReconcileItem(const TransactionData& trans); ~ReconcileItem(void); - void DrawItem(BView *owner, BRect frame, bool complete = false); + void DrawItem(BView* owner, BRect frame, bool complete = false); - TransactionData *GetTransaction(void) { return &fTransaction; } + TransactionData* GetTransaction(void) { return &fTransaction; } void SetReconciled(bool value); bool IsReconciled(void) const; diff --git a/src/ReconcileWindow.cpp b/src/ReconcileWindow.cpp index ced9361..b0e7716 100644 --- a/src/ReconcileWindow.cpp +++ b/src/ReconcileWindow.cpp @@ -21,7 +21,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ReconcileWindow" - enum { M_TOGGLE_DEPOSIT = 'tgdp', M_TOGGLE_CHECK, @@ -45,11 +44,12 @@ class ReconcileFilter : public BMessageFilter }; */ -ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) +ReconcileWindow::ReconcileWindow(const BRect frame, Account* account) : BWindow( frame, "", B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS - ) { + ) +{ BString temp; fCurrentDate = GetCurrentDate(); // AddCommonFilter(new ReconcileFilter(this)); @@ -66,7 +66,7 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *back = new BView("backview", B_WILL_DRAW); + BView* back = new BView("backview", B_WILL_DRAW); back->SetViewColor(240, 240, 240); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); @@ -198,7 +198,8 @@ ReconcileWindow::ReconcileWindow(const BRect frame, Account *account) .End(); } -ReconcileWindow::~ReconcileWindow(void) { +ReconcileWindow::~ReconcileWindow(void) +{ prefsLock.Lock(); gPreferences.RemoveData("reconcileframe"); gPreferences.AddRect("reconcileframe", Frame()); @@ -206,7 +207,8 @@ ReconcileWindow::~ReconcileWindow(void) { } void -ReconcileWindow::FrameResized(float w, float h) { +ReconcileWindow::FrameResized(float w, float h) +{ // We implement our own resizing routines because all the controls need to be resized in a // proportional manner of the window being resized, such as the 3 listviews each taking up just // a little less than 1/3 of the window's width @@ -244,9 +246,10 @@ ReconcileWindow::FrameResized(float w, float h) { } void -ReconcileWindow::MessageReceived(BMessage *msg) { +ReconcileWindow::MessageReceived(BMessage* msg) +{ int32 index; - ReconcileItem *selection; + ReconcileItem* selection; BString label, temp; switch (msg->what) { @@ -281,21 +284,21 @@ ReconcileWindow::MessageReceived(BMessage *msg) { ApplyChargesAndInterest(); int32 i; - ReconcileItem *item; + ReconcileItem* item; for (i = 0; i < fDepositList->CountItems(); i++) { - item = (ReconcileItem *)fDepositList->ItemAt(i); + item = (ReconcileItem*)fDepositList->ItemAt(i); if (item->IsReconciled()) item->SyncToTransaction(); } for (i = 0; i < fCheckList->CountItems(); i++) { - item = (ReconcileItem *)fCheckList->ItemAt(i); + item = (ReconcileItem*)fCheckList->ItemAt(i); if (item->IsReconciled()) item->SyncToTransaction(); } for (i = 0; i < fChargeList->CountItems(); i++) { - item = (ReconcileItem *)fChargeList->ItemAt(i); + item = (ReconcileItem*)fChargeList->ItemAt(i); if (item->IsReconciled()) item->SyncToTransaction(); } @@ -307,9 +310,9 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } case M_RESET: { int32 i; - ReconcileItem *item; + ReconcileItem* item; for (i = 0; i < fDepositList->CountItems(); i++) { - item = (ReconcileItem *)fDepositList->ItemAt(i); + item = (ReconcileItem*)fDepositList->ItemAt(i); if (item->IsReconciled()) { item->RevertTransaction(); fDepositList->InvalidateItem(i); @@ -317,7 +320,7 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } for (i = 0; i < fCheckList->CountItems(); i++) { - item = (ReconcileItem *)fCheckList->ItemAt(i); + item = (ReconcileItem*)fCheckList->ItemAt(i); if (item->IsReconciled()) { item->RevertTransaction(); fCheckList->InvalidateItem(i); @@ -325,7 +328,7 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } for (i = 0; i < fChargeList->CountItems(); i++) { - item = (ReconcileItem *)fChargeList->ItemAt(i); + item = (ReconcileItem*)fChargeList->ItemAt(i); if (item->IsReconciled()) { item->RevertTransaction(); fChargeList->InvalidateItem(i); @@ -335,13 +338,14 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } case M_TOGGLE_DEPOSIT: { index = fDepositList->CurrentSelection(); - selection = (ReconcileItem *)fDepositList->ItemAt(index); + selection = (ReconcileItem*)fDepositList->ItemAt(index); if (selection) { if (selection->IsReconciled()) { selection->SetReconciled(false); fDepositTotal -= selection->GetTransaction()->Amount(); fTotal -= selection->GetTransaction()->Amount(); - } else { + } + else { selection->SetReconciled(true); fDepositTotal += selection->GetTransaction()->Amount(); fTotal += selection->GetTransaction()->Amount(); @@ -366,13 +370,14 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } case M_TOGGLE_CHECK: { index = fCheckList->CurrentSelection(); - selection = (ReconcileItem *)fCheckList->ItemAt(index); + selection = (ReconcileItem*)fCheckList->ItemAt(index); if (selection) { if (selection->IsReconciled()) { selection->SetReconciled(false); fCheckTotal += selection->GetTransaction()->Amount(); fTotal -= selection->GetTransaction()->Amount(); - } else { + } + else { selection->SetReconciled(true); fCheckTotal -= selection->GetTransaction()->Amount(); fTotal += selection->GetTransaction()->Amount(); @@ -397,13 +402,14 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } case M_TOGGLE_CHARGE: { index = fChargeList->CurrentSelection(); - selection = (ReconcileItem *)fChargeList->ItemAt(index); + selection = (ReconcileItem*)fChargeList->ItemAt(index); if (selection) { if (selection->IsReconciled()) { selection->SetReconciled(false); fChargeTotal += selection->GetTransaction()->Amount(); fTotal -= selection->GetTransaction()->Amount(); - } else { + } + else { selection->SetReconciled(true); fChargeTotal -= selection->GetTransaction()->Amount(); fTotal += selection->GetTransaction()->Amount(); @@ -458,7 +464,8 @@ ReconcileWindow::MessageReceived(BMessage *msg) { } void -ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { +ReconcileWindow::HandleNotify(const uint64& value, const BMessage* msg) +{ bool unlock = false; if (!IsLocked()) { unlock = true; @@ -471,7 +478,8 @@ ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { if (IsWatching(WATCH_TRANSACTION)) { RemoveWatch(WATCH_ALL); AddWatch(WATCH_MASS_EDIT); - } else { + } + else { AddWatch(WATCH_ALL); } @@ -480,16 +488,17 @@ ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { return; } - Account *acc = NULL; + Account* acc = NULL; if ((value & WATCH_ACCOUNT) && (value & WATCH_DELETE)) { - if ((msg->FindPointer("item", (void **)&acc) == B_OK) && (acc == fAccount)) + if ((msg->FindPointer("item", (void**)&acc) == B_OK) && (acc == fAccount)) PostMessage(B_QUIT_REQUESTED); - } else if ((value & WATCH_TRANSACTION)) { + } + else if ((value & WATCH_TRANSACTION)) { if (value & WATCH_DELETE) { uint32 id; - if (msg->FindInt32("id", (int32 *)&id) == B_OK) { - ReconcileItem *deleteditem; - BListView *itemlist; + if (msg->FindInt32("id", (int32*)&id) == B_OK) { + ReconcileItem* deleteditem; + BListView* itemlist; deleteditem = FindItemForID(fDepositList, id); if (deleteditem) @@ -514,18 +523,19 @@ ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { itemlist->RemoveItem(deleteditem); delete deleteditem; } - } else if (value & WATCH_CREATE) { + } + else if (value & WATCH_CREATE) { uint32 accountid; - if (msg->FindInt32("accountid", (int32 *)&accountid) != B_OK || + if (msg->FindInt32("accountid", (int32*)&accountid) != B_OK || accountid != fAccount->GetID()) { if (unlock) Unlock(); return; } - TransactionData *data; - if (msg->FindPointer("item", (void **)&data) == B_OK) { - ReconcileItem *newitem = new ReconcileItem(*data); + TransactionData* data; + if (msg->FindPointer("item", (void**)&data) == B_OK) { + ReconcileItem* newitem = new ReconcileItem(*data); if (data->Type().TypeCode() == TRANS_DEP) InsertTransactionItem(fDepositList, newitem); @@ -541,13 +551,15 @@ ReconcileWindow::HandleNotify(const uint64 &value, const BMessage *msg) { } bool -ReconcileWindow::QuitRequested(void) { +ReconcileWindow::QuitRequested(void) +{ gDatabase.RemoveObserver(this); return true; } void -ReconcileWindow::ApplyChargesAndInterest(void) { +ReconcileWindow::ApplyChargesAndInterest(void) +{ Fixed charge; if (strlen(fCharges->Text()) > 0 && gCurrentLocale.StringToCurrency(fCharges->Text(), charge) == B_OK) { @@ -570,7 +582,8 @@ ReconcileWindow::ApplyChargesAndInterest(void) { } bool -ReconcileWindow::AutoReconcile(void) { +ReconcileWindow::AutoReconcile(void) +{ // We are going to attempt to automatically reconcile the account. We will do // this by adding up the values of all transactions unreconciled before the // statement date. If they balance, we can notify the user that we were successful @@ -578,7 +591,7 @@ ReconcileWindow::AutoReconcile(void) { // we can tell the user that it failed and the conditions under which it works. time_t statdate; int32 i; - ReconcileItem *item; + ReconcileItem* item; if (gDefaultLocale.StringToDate(fDate->Text(), statdate) != B_OK) { // Do we have an empty date box? @@ -601,7 +614,7 @@ ReconcileWindow::AutoReconcile(void) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the amount for Bank Charges."), B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.") + "for this account.") ); return false; } @@ -612,14 +625,14 @@ ReconcileWindow::AutoReconcile(void) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the amount for Interest Earned."), B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.") + "for this account.") ); return false; } } for (i = 0; i < fDepositList->CountItems(); i++) { - item = (ReconcileItem *)fDepositList->ItemAt(i); + item = (ReconcileItem*)fDepositList->ItemAt(i); if (item->GetTransaction()->Date() >= statdate) break; @@ -630,7 +643,7 @@ ReconcileWindow::AutoReconcile(void) { } for (i = 0; i < fCheckList->CountItems(); i++) { - item = (ReconcileItem *)fCheckList->ItemAt(i); + item = (ReconcileItem*)fCheckList->ItemAt(i); if (item->GetTransaction()->Date() >= statdate) break; @@ -641,7 +654,7 @@ ReconcileWindow::AutoReconcile(void) { } for (i = 0; i < fChargeList->CountItems(); i++) { - item = (ReconcileItem *)fChargeList->ItemAt(i); + item = (ReconcileItem*)fChargeList->ItemAt(i); if (item->GetTransaction()->Date() >= statdate) break; @@ -653,7 +666,7 @@ ReconcileWindow::AutoReconcile(void) { if (dep + chk + chrg + bankchrg + interest + fDifference == 0) { for (i = 0; i < list.CountItems(); i++) { - item = (ReconcileItem *)list.ItemAt(i); + item = (ReconcileItem*)list.ItemAt(i); item->SetReconciled(true); } ApplyChargesAndInterest(); @@ -665,16 +678,17 @@ ReconcileWindow::AutoReconcile(void) { ShowAlert( B_TRANSLATE("Couldn't quick balance."), B_TRANSLATE("Quick Balance failed. This doesn't mean " - "that you did something wrong - it's just that Quick Balance works on " - "simpler cases in balancing an account than this one. Sorry.") + "that you did something wrong - it's just that Quick Balance works on " + "simpler cases in balancing an account than this one. Sorry.") ); return false; } -ReconcileItem * -ReconcileWindow::FindItemForID(BListView *target, const uint32 &id) { +ReconcileItem* +ReconcileWindow::FindItemForID(BListView* target, const uint32& id) +{ for (int32 i = 0; i < target->CountItems(); i++) { - ReconcileItem *temp = (ReconcileItem *)target->ItemAt(i); + ReconcileItem* temp = (ReconcileItem*)target->ItemAt(i); if (temp->GetTransaction()->GetID() == id) return temp; } @@ -682,12 +696,13 @@ ReconcileWindow::FindItemForID(BListView *target, const uint32 &id) { } void -ReconcileWindow::InsertTransactionItem(BListView *target, ReconcileItem *item) { - TransactionData *itemdata = item->GetTransaction(); +ReconcileWindow::InsertTransactionItem(BListView* target, ReconcileItem* item) +{ + TransactionData* itemdata = item->GetTransaction(); for (int32 i = 0; i < target->CountItems(); i++) { - ReconcileItem *temp = (ReconcileItem *)target->ItemAt(i); - TransactionData *tempdata = temp->GetTransaction(); + ReconcileItem* temp = (ReconcileItem*)target->ItemAt(i); + TransactionData* tempdata = temp->GetTransaction(); if (itemdata->Date() < tempdata->Date() || (itemdata->Date() == tempdata->Date() && @@ -701,11 +716,12 @@ ReconcileWindow::InsertTransactionItem(BListView *target, ReconcileItem *item) { } void -AddReconcileItems(const TransactionData &data, void *ptr) { +AddReconcileItems(const TransactionData& data, void* ptr) +{ if (data.Status() == TRANS_RECONCILED) return; - ReconcileWindow *win = (ReconcileWindow *)ptr; + ReconcileWindow* win = (ReconcileWindow*)ptr; switch (data.Type().TypeCode()) { case TRANS_NUMERIC: { diff --git a/src/ReconcileWindow.h b/src/ReconcileWindow.h index e69ff7d..c723b65 100644 --- a/src/ReconcileWindow.h +++ b/src/ReconcileWindow.h @@ -18,31 +18,31 @@ class CurrencyBox; class ReconcileItem; void -AddReconcileItems(const TransactionData &data, void *recwin); +AddReconcileItems(const TransactionData& data, void* recwin); class ReconcileWindow : public BWindow, public Observer { public: - ReconcileWindow(const BRect frame, Account *account); + ReconcileWindow(const BRect frame, Account* account); ~ReconcileWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); void FrameResized(float w, float h); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); bool QuitRequested(void); private: friend class ReconcileFilter; - friend void AddReconcileItems(const TransactionData &data, void *ptr); + friend void AddReconcileItems(const TransactionData& data, void* ptr); void ApplyChargesAndInterest(void); - ReconcileItem *FindItemForID(BListView *target, const uint32 &id); - void InsertTransactionItem(BListView *target, ReconcileItem *item); + ReconcileItem* FindItemForID(BListView* target, const uint32& id); + void InsertTransactionItem(BListView* target, ReconcileItem* item); bool AutoReconcile(void); - Account *fAccount; + Account* fAccount; BListView *fDepositList, *fCheckList, *fChargeList; CurrencyBox *fOpening, *fClosing, *fCharges, *fInterest; - DateBox *fDate; + DateBox* fDate; BButton *fReset, *fReconcile, *fCancel, *fAutoReconcile; // fTotal is the sum of all of the deposits, checks, and charges @@ -51,7 +51,7 @@ class ReconcileWindow : public BWindow, public Observer { BStringView *fDepLabel, *fCheckLabel, *fChargeLabel, *fTotalLabel; BScrollView *fDepScroll, *fCheckScroll, *fChargeScroll; - HelpButton *fHelpButton; + HelpButton* fHelpButton; float fDateMultiplier, fOpeningMultiplier, fClosingMultiplier; time_t fCurrentDate; diff --git a/src/RegisterView.cpp b/src/RegisterView.cpp index 71e0902..53b101c 100644 --- a/src/RegisterView.cpp +++ b/src/RegisterView.cpp @@ -17,13 +17,13 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "RegisterView" - enum { M_SELECT_ACCOUNT = 'slac', M_SELECT_CURRENT }; -RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) { +RegisterView::RegisterView(const char* name, int32 flags) : BView(name, flags | B_FRAME_EVENTS) +{ SetViewColor(240, 240, 240); - BStringView *accountlabel = new BStringView("accountlabel", B_TRANSLATE("Accounts")); + BStringView* accountlabel = new BStringView("accountlabel", B_TRANSLATE("Accounts")); // fAccountView = new DragListView(r,"accountview"); fAccountView = new BListView("accountview", B_SINGLE_SELECTION_LIST); @@ -36,7 +36,7 @@ RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | gDatabase.AddObserver(fCheckView); for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *acc = gDatabase.AccountAt(i); + Account* acc = gDatabase.AccountAt(i); fAccountView->AddItem(new AccountListItem(acc)); acc->AddObserver(this); } @@ -48,7 +48,7 @@ RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | fTrackBox = new BBox("qtbox"); fTrackBox->SetLabel(B_TRANSLATE("QuickTracker")); - QTNetWorthItem *item; + QTNetWorthItem* item; item = new QTNetWorthItem("networth"); BFont font; @@ -76,14 +76,15 @@ RegisterView::RegisterView(const char *name, int32 flags) : BView(name, flags | RegisterView::~RegisterView(void) {} void -RegisterView::AttachedToWindow(void) { +RegisterView::AttachedToWindow(void) +{ fAccountView->SetTarget(this); // If the selection done is before being attached to the window, the message is // never received. bool selected = false; for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *acc = gDatabase.AccountAt(i); + Account* acc = gDatabase.AccountAt(i); if (acc && !acc->IsClosed()) { fAccountView->Select(i); selected = true; @@ -96,7 +97,8 @@ RegisterView::AttachedToWindow(void) { } void -RegisterView::MessageReceived(BMessage *msg) { +RegisterView::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_SELECT_ACCOUNT: { if (fAccountView->CurrentSelection() < 0) @@ -117,7 +119,8 @@ RegisterView::MessageReceived(BMessage *msg) { } void -RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { +RegisterView::HandleNotify(const uint64& value, const BMessage* msg) +{ bool lockwin = false; if (!Window()->IsLocked()) { Window()->Lock(); @@ -125,8 +128,8 @@ RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { } if (value & WATCH_ACCOUNT) { - Account *acc; - if (msg->FindPointer("item", (void **)&acc) != B_OK) { + Account* acc; + if (msg->FindPointer("item", (void**)&acc) != B_OK) { if (lockwin) Window()->Unlock(); return; @@ -137,14 +140,16 @@ RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { if (fAccountView->CountItems() == 1) fAccountView->Select(0); acc->AddObserver(this); - } else if (value & WATCH_DELETE) { - AccountListItem *item = - (AccountListItem *)fAccountView->RemoveItem(gDatabase.IndexOf(acc)); + } + else if (value & WATCH_DELETE) { + AccountListItem* item = + (AccountListItem*)fAccountView->RemoveItem(gDatabase.IndexOf(acc)); delete item; fAccountView->Select(0); - } else if (value & WATCH_CHANGE) { + } + else if (value & WATCH_CHANGE) { for (int32 i = 0; i < fAccountView->CountItems(); i++) { - AccountListItem *listitem = (AccountListItem *)fAccountView->ItemAt(i); + AccountListItem* listitem = (AccountListItem*)fAccountView->ItemAt(i); if (listitem && listitem->GetAccount() == acc) { fAccountView->InvalidateItem(i); break; @@ -166,15 +171,16 @@ RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { if (range < 0) range = 0; - BScrollBar *bar = fAccountScroller->ScrollBar(B_HORIZONTAL); + BScrollBar* bar = fAccountScroller->ScrollBar(B_HORIZONTAL); bar->SetRange(0, range); - - } else if (value & WATCH_TRANSACTION) { + } + else if (value & WATCH_TRANSACTION) { if (value & WATCH_CREATE || value & WATCH_DELETE || value & WATCH_CHANGE) fAccountView->Invalidate(); - } else if (value & WATCH_LOCALE) { + } + else if (value & WATCH_LOCALE) { for (int32 i = 0; i < fAccountView->CountItems(); i++) { - AccountListItem *listitem = (AccountListItem *)fAccountView->ItemAt(i); + AccountListItem* listitem = (AccountListItem*)fAccountView->ItemAt(i); if (listitem) fAccountView->InvalidateItem(i); } @@ -184,7 +190,8 @@ RegisterView::HandleNotify(const uint64 &value, const BMessage *msg) { } void -RegisterView::SelectAccount(const int32 &index) { +RegisterView::SelectAccount(const int32& index) +{ if (index < 0 || index > fAccountView->CountItems() - 1) return; diff --git a/src/RegisterView.h b/src/RegisterView.h index baec343..6894f82 100644 --- a/src/RegisterView.h +++ b/src/RegisterView.h @@ -13,12 +13,12 @@ class CheckView; class RegisterView : public BView, public Observer { public: - RegisterView(const char *name, int32 flags); + RegisterView(const char* name, int32 flags); ~RegisterView(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); void AttachedToWindow(void); - void HandleNotify(const uint64 &value, const BMessage *msg); - void SelectAccount(const int32 &index); + void HandleNotify(const uint64& value, const BMessage* msg); + void SelectAccount(const int32& index); bool SelectNextTransaction(void) { return fTransactionView->SelectNext(); } @@ -29,11 +29,11 @@ class RegisterView : public BView, public Observer { bool SelectLastTransaction(void) { return fTransactionView->SelectLast(); } private: - CheckView *fCheckView; - BListView *fAccountView; - BScrollView *fAccountScroller; - TransactionView *fTransactionView; - BBox *fTrackBox; + CheckView* fCheckView; + BListView* fAccountView; + BScrollView* fAccountScroller; + TransactionView* fTransactionView; + BBox* fTrackBox; }; #endif diff --git a/src/ReportGrid.cpp b/src/ReportGrid.cpp index 9c32b25..668a57b 100644 --- a/src/ReportGrid.cpp +++ b/src/ReportGrid.cpp @@ -1,35 +1,39 @@ #include "ReportGrid.h" #include -ReportGrid::ReportGrid(const uint32 &width, const uint32 &height) : fList(20, true), fWidth(width) { +ReportGrid::ReportGrid(const uint32& width, const uint32& height) : fList(20, true), fWidth(width) +{ for (uint32 i = 0; i < height; i++) AddItem(); } ReportGrid::~ReportGrid(void) {} -const char * -ReportGrid::RowTitle(const int32 &index) { - ReportGrid::GridRecord *record = fList.ItemAt(index); +const char* +ReportGrid::RowTitle(const int32& index) +{ + ReportGrid::GridRecord* record = fList.ItemAt(index); return (record) ? record->Title() : NULL; } void -ReportGrid::SetRowTitle(const int32 &index, const char *title) { - ReportGrid::GridRecord *record = (ReportGrid::GridRecord *)fList.ItemAt(index); +ReportGrid::SetRowTitle(const int32& index, const char* title) +{ + ReportGrid::GridRecord* record = (ReportGrid::GridRecord*)fList.ItemAt(index); if (record) record->SetTitle(title); } int32 -ReportGrid::FindTitle(const char *title) { +ReportGrid::FindTitle(const char* title) +{ if (!title || fList.CountItems() == 0) return -1; for (int32 i = 0; i < fList.CountItems(); i++) { - ReportGrid::GridRecord *record = fList.ItemAt(i); + ReportGrid::GridRecord* record = fList.ItemAt(i); if (strcmp(record->Title(), title) == 0) return i; } @@ -37,11 +41,12 @@ ReportGrid::FindTitle(const char *title) { } status_t -ReportGrid::ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed) { +ReportGrid::ValueAt(const uint32& x, const uint32& y, Fixed& fixed) +{ if (y >= (uint32)fList.CountItems() || x >= fWidth) return B_ERROR; - ReportGrid::GridRecord *record = fList.ItemAt(y); + ReportGrid::GridRecord* record = fList.ItemAt(y); if (!record) return B_ERROR; @@ -50,11 +55,12 @@ ReportGrid::ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed) { } status_t -ReportGrid::SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed) { +ReportGrid::SetValue(const uint32& x, const uint32& y, const Fixed& fixed) +{ if (y >= (uint32)fList.CountItems() || x >= fWidth) return B_ERROR; - ReportGrid::GridRecord *record = (ReportGrid::GridRecord *)fList.ItemAt(y); + ReportGrid::GridRecord* record = (ReportGrid::GridRecord*)fList.ItemAt(y); if (!record) return B_ERROR; @@ -64,8 +70,9 @@ ReportGrid::SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed) { int ReportGrid::CompareGridrecord( - const ReportGrid::GridRecord *item1, const ReportGrid::GridRecord *item2 -) { + const ReportGrid::GridRecord* item1, const ReportGrid::GridRecord* item2 +) +{ // ReportGrid::GridRecord *listitem1 = *((ReportGrid::GridRecord**)item1); // ReportGrid::GridRecord *listitem2 = *((ReportGrid::GridRecord**)item2); @@ -74,7 +81,8 @@ ReportGrid::CompareGridrecord( } void -ReportGrid::AddItem(const int32 &index) { +ReportGrid::AddItem(const int32& index) +{ if (index < 0) fList.AddItem(new ReportGrid::GridRecord(fWidth)); else @@ -82,29 +90,34 @@ ReportGrid::AddItem(const int32 &index) { } void -ReportGrid::RemoveItem(const int32 &index) { - ReportGrid::GridRecord *item = fList.RemoveItemAt(index); +ReportGrid::RemoveItem(const int32& index) +{ + ReportGrid::GridRecord* item = fList.RemoveItemAt(index); if (item) delete item; } void -ReportGrid::MakeEmpty(void) { +ReportGrid::MakeEmpty(void) +{ fList.MakeEmpty(); } void -ReportGrid::Sort(void) { +ReportGrid::Sort(void) +{ fList.SortItems(CompareGridrecord); } void -ReportGrid::PrintToStream(void) { +ReportGrid::PrintToStream(void) +{ if (CountItems() == 0) { printf("Grid is empty\n"); - } else + } + else for (int32 i = 0; i < CountItems(); i++) { - ReportGrid::GridRecord *item = fList.ItemAt(i); + ReportGrid::GridRecord* item = fList.ItemAt(i); printf("Row %ld: %s ", i, item->Title()); for (uint32 j = 0; j < fWidth; j++) { @@ -120,22 +133,25 @@ ReportGrid::PrintToStream(void) { //--------------------------------------------------------------------------------- -ReportGrid::GridRecord::GridRecord(const uint32 &size, const char *title) - : fList(size), fTitle(title) { +ReportGrid::GridRecord::GridRecord(const uint32& size, const char* title) + : fList(size), fTitle(title) +{ for (uint32 i = 0; i < size; i++) fList.AddItem(new Fixed()); } -ReportGrid::GridRecord::~GridRecord(void) { +ReportGrid::GridRecord::~GridRecord(void) +{ for (int32 i = 0; i < fList.CountItems(); i++) { - Fixed *item = (Fixed *)fList.ItemAt(i); + Fixed* item = (Fixed*)fList.ItemAt(i); delete item; } } status_t -ReportGrid::GridRecord::ValueAt(const uint32 &index, Fixed &fixed) { - Fixed *item = (Fixed *)fList.ItemAt(index); +ReportGrid::GridRecord::ValueAt(const uint32& index, Fixed& fixed) +{ + Fixed* item = (Fixed*)fList.ItemAt(index); if (!item) return B_ERROR; @@ -145,8 +161,9 @@ ReportGrid::GridRecord::ValueAt(const uint32 &index, Fixed &fixed) { } status_t -ReportGrid::GridRecord::SetValue(const uint32 &index, const Fixed &fixed) { - Fixed *item = (Fixed *)fList.ItemAt(index); +ReportGrid::GridRecord::SetValue(const uint32& index, const Fixed& fixed) +{ + Fixed* item = (Fixed*)fList.ItemAt(index); if (!item) return B_ERROR; diff --git a/src/ReportGrid.h b/src/ReportGrid.h index 13c8cc0..36676fc 100644 --- a/src/ReportGrid.h +++ b/src/ReportGrid.h @@ -8,18 +8,18 @@ class ReportGrid { public: - ReportGrid(const uint32 &width, const uint32 &height); + ReportGrid(const uint32& width, const uint32& height); ~ReportGrid(void); - const char *RowTitle(const int32 &index); - void SetRowTitle(const int32 &index, const char *title); - int32 FindTitle(const char *title); + const char* RowTitle(const int32& index); + void SetRowTitle(const int32& index, const char* title); + int32 FindTitle(const char* title); - status_t ValueAt(const uint32 &x, const uint32 &y, Fixed &fixed); - status_t SetValue(const uint32 &x, const uint32 &y, const Fixed &fixed); + status_t ValueAt(const uint32& x, const uint32& y, Fixed& fixed); + status_t SetValue(const uint32& x, const uint32& y, const Fixed& fixed); - void AddItem(const int32 &index = -1); - void RemoveItem(const int32 &index); + void AddItem(const int32& index = -1); + void RemoveItem(const int32& index); int32 CountItems(void) const { return fList.CountItems(); } @@ -36,22 +36,22 @@ class ReportGrid { private: class GridRecord { public: - GridRecord(const uint32 &size, const char *title = NULL); + GridRecord(const uint32& size, const char* title = NULL); ~GridRecord(void); - const char *Title(void) const { return fTitle.String(); } + const char* Title(void) const { return fTitle.String(); } - void SetTitle(const char *title) { fTitle = title; } + void SetTitle(const char* title) { fTitle = title; } - status_t ValueAt(const uint32 &index, Fixed &fixed); - status_t SetValue(const uint32 &index, const Fixed &fixed); + status_t ValueAt(const uint32& index, Fixed& fixed); + status_t SetValue(const uint32& index, const Fixed& fixed); private: BObjectList fList; BString fTitle; }; - static int CompareGridrecord(const GridRecord *item1, const GridRecord *item2); + static int CompareGridrecord(const GridRecord* item1, const GridRecord* item2); BObjectList fList; uint32 fWidth; diff --git a/src/ReportWindow.cpp b/src/ReportWindow.cpp index a5106d9..467751a 100644 --- a/src/ReportWindow.cpp +++ b/src/ReportWindow.cpp @@ -26,7 +26,7 @@ int -compare_stringitem(const void *item1, const void *item2); +compare_stringitem(const void* item1, const void* item2); enum { M_REPORT_CASH_FLOW = 'csfl', @@ -53,21 +53,22 @@ ReportWindow::ReportWindow(BRect frame) B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS ), fSubtotalMode(SUBTOTAL_NONE), fReportMode(REPORT_CASH_FLOW), fStartDate(GetCurrentYear()), - fEndDate(GetCurrentDate()), fTitleFont(be_bold_font), fHeaderFont(be_plain_font) { + fEndDate(GetCurrentDate()), fTitleFont(be_bold_font), fHeaderFont(be_plain_font) +{ BString temp; fHeaderFont.SetFace(B_ITALIC_FACE); - BView *view = new BView("back", B_WILL_DRAW); + BView* view = new BView("back", B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f).SetInsets(0).Add(view).End(); view->SetViewColor(240, 240, 240); - BGroupLayout *reportsLayout = new BGroupLayout(B_VERTICAL, 0); - BGroupLayout *accountsLayout = new BGroupLayout(B_VERTICAL, 0); - BGroupLayout *subtotalLayout = new BGroupLayout(B_VERTICAL, 0); - BGroupLayout *categoriesLayout = new BGroupLayout(B_VERTICAL, 0); + BGroupLayout* reportsLayout = new BGroupLayout(B_VERTICAL, 0); + BGroupLayout* accountsLayout = new BGroupLayout(B_VERTICAL, 0); + BGroupLayout* subtotalLayout = new BGroupLayout(B_VERTICAL, 0); + BGroupLayout* categoriesLayout = new BGroupLayout(B_VERTICAL, 0); - BGroupLayout *layout_ = new BGroupLayout(B_VERTICAL, 1.0f); + BGroupLayout* layout_ = new BGroupLayout(B_VERTICAL, 1.0f); BLayoutBuilder::Group<>(view, B_HORIZONTAL) .SetInsets(10) .AddGroup(B_VERTICAL, 1.0f) @@ -79,14 +80,15 @@ ReportWindow::ReportWindow(BRect frame) .Add(layout_) .End(); - BMenu *reportmenu = new BMenu(B_TRANSLATE("Reports")); + BMenu* reportmenu = new BMenu(B_TRANSLATE("Reports")); reportmenu->SetLabelFromMarked(true); // TODO: Re-enable the Budget report // reportmenu->AddItem(new BMenuItem(B_TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET))); temp << B_TRANSLATE("Income") << " / " << B_TRANSLATE("Spending"); reportmenu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_CASH_FLOW))); - reportmenu->AddItem(new BMenuItem(B_TRANSLATE("Total worth"), new BMessage(M_REPORT_NET_WORTH))); + reportmenu->AddItem(new BMenuItem(B_TRANSLATE("Total worth"), new BMessage(M_REPORT_NET_WORTH)) + ); reportmenu->AddItem( new BMenuItem(B_TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS)) ); @@ -99,7 +101,7 @@ ReportWindow::ReportWindow(BRect frame) temp = B_TRANSLATE("Reports:"); temp += " "; - BStringView *sv = new BStringView("reportsv", temp.String()); + BStringView* sv = new BStringView("reportsv", temp.String()); reportsLayout->AddView(sv); fReportField = new BMenuField("reportfield", "", reportmenu); @@ -111,7 +113,7 @@ ReportWindow::ReportWindow(BRect frame) accountsLayout->AddView(sv); fAccountList = new BListView("reportaccountlist", B_MULTIPLE_SELECTION_LIST); - BScrollView *scrollview = new BScrollView("accountscroller", fAccountList, 0, false, true); + BScrollView* scrollview = new BScrollView("accountscroller", fAccountList, 0, false, true); accountsLayout->AddView(scrollview); // This is disabled because otherwise the report is rendered once for each @@ -123,7 +125,7 @@ ReportWindow::ReportWindow(BRect frame) sv = new BStringView("subtotalsv", temp.String()); subtotalLayout->AddView(sv); - BMenu *subtotalmenu = new BMenu(B_TRANSLATE("Subtotal")); + BMenu* subtotalmenu = new BMenu(B_TRANSLATE("Subtotal")); subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("None"), new BMessage(M_SUBTOTAL_NONE))); subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("Month"), new BMessage(M_SUBTOTAL_MONTH))); subtotalmenu->AddItem(new BMenuItem(B_TRANSLATE("Quarter"), new BMessage(M_SUBTOTAL_QUARTER))); @@ -139,7 +141,7 @@ ReportWindow::ReportWindow(BRect frame) BString reporthelp = gAppPath; prefsLock.Unlock(); reporthelp << "helpfiles/" << gCurrentLanguage->Name() << "/Report Window Help"; - HelpButton *help = new HelpButton("reporthelp", reporthelp.String()); + HelpButton* help = new HelpButton("reporthelp", reporthelp.String()); temp = B_TRANSLATE("Categories"); temp += ": "; @@ -224,7 +226,7 @@ ReportWindow::ReportWindow(BRect frame) gDatabase.AddObserver(this); for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *acc = gDatabase.AccountAt(i); + Account* acc = gDatabase.AccountAt(i); if (!acc) continue; @@ -235,11 +237,11 @@ ReportWindow::ReportWindow(BRect frame) fCategoryList->SortItems(compare_stringitem); for (int32 i = 0; i < fAccountList->CountItems(); i++) { - BStringItem *item = (BStringItem *)fAccountList->ItemAt(i); + BStringItem* item = (BStringItem*)fAccountList->ItemAt(i); if (!item) continue; - Account *itemaccount = gDatabase.AccountByName(item->Text()); + Account* itemaccount = gDatabase.AccountByName(item->Text()); if (itemaccount && (!itemaccount->IsClosed())) fAccountList->Select(i, true); } @@ -255,30 +257,36 @@ ReportWindow::ReportWindow(BRect frame) } void -ReportWindow::HandleNotify(const uint64 &value, const BMessage *msg) { +ReportWindow::HandleNotify(const uint64& value, const BMessage* msg) +{ Lock(); if (value & WATCH_ACCOUNT) { - Account *acc; - if (msg->FindPointer("item", (void **)&acc) != B_OK) { + Account* acc; + if (msg->FindPointer("item", (void**)&acc) != B_OK) { Unlock(); return; } if (value & WATCH_CREATE) { AddAccount(acc); - } else if (value & WATCH_DELETE) { - } else if (value & WATCH_RENAME) { - } else if (value & WATCH_CHANGE) { } - } else if (value & WATCH_TRANSACTION) { + else if (value & WATCH_DELETE) { + } + else if (value & WATCH_RENAME) { + } + else if (value & WATCH_CHANGE) { + } + } + else if (value & WATCH_TRANSACTION) { } RenderReport(); Unlock(); } void -ReportWindow::MessageReceived(BMessage *msg) { +ReportWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_PREVIOUS_FIELD: { if (fStartDateBox->ChildAt(0)->IsFocus()) @@ -344,12 +352,13 @@ ReportWindow::MessageReceived(BMessage *msg) { if (fStartDate > fEndDate) fStartDate = fEndDate; RenderReport(); - } else { + } + else { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the date you entered."), B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.") + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") ); fStartDateBox->MakeFocus(true); break; @@ -368,12 +377,13 @@ ReportWindow::MessageReceived(BMessage *msg) { if (fStartDate > fEndDate) fStartDate = fEndDate; RenderReport(); - } else { + } + else { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the date you entered."), B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.") + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") ); fEndDateBox->MakeFocus(true); break; @@ -397,7 +407,8 @@ ReportWindow::MessageReceived(BMessage *msg) { if (fGridView->IsHidden()) { fGridView->Show(); fGraphView->Hide(); - } else { + } + else { fGridView->Hide(); fGraphView->Show(); } @@ -409,8 +420,9 @@ ReportWindow::MessageReceived(BMessage *msg) { } void -ReportWindow::FrameResized(float w, float h) { - BScrollBar *bar = fCategoryScroller->ScrollBar(B_VERTICAL); +ReportWindow::FrameResized(float w, float h) +{ + BScrollBar* bar = fCategoryScroller->ScrollBar(B_VERTICAL); if (fCategoryList->CountItems()) { float itemheight = fCategoryList->ItemAt(0)->Height(); @@ -424,20 +436,22 @@ ReportWindow::FrameResized(float w, float h) { bar->GetSteps(&small, &big); big = (int32)(fCategoryScroller->Frame().Height() * .9); bar->SetSteps(small, big); - } else + } + else bar->SetRange(0, 0); FixGridScrollbar(); } void -ReportWindow::AddAccount(Account *acc) { +ReportWindow::AddAccount(Account* acc) +{ if (!acc) return; acc->AddObserver(this); - AccountItem *accountitem = new AccountItem(acc); + AccountItem* accountitem = new AccountItem(acc); fAccountList->AddItem(accountitem); BString command = "select category from account_"; @@ -452,9 +466,9 @@ ReportWindow::AddAccount(Account *acc) { } // Make sure that the category is not already in the list. - BStringItem *existing = NULL; + BStringItem* existing = NULL; for (int32 k = 0; k < fCategoryList->CountItems(); k++) { - BStringItem *item = (BStringItem *)fCategoryList->ItemAt(k); + BStringItem* item = (BStringItem*)fCategoryList->ItemAt(k); if (!item) continue; @@ -476,11 +490,12 @@ ReportWindow::AddAccount(Account *acc) { } void -ReportWindow::FixGridScrollbar(void) { - BScrollBar *bar = fGridView->ScrollBar(B_VERTICAL); +ReportWindow::FixGridScrollbar(void) +{ + BScrollBar* bar = fGridView->ScrollBar(B_VERTICAL); if (!bar) return; - BRow *row = fGridView->RowAt(0); + BRow* row = fGridView->RowAt(0); if (!row) return; float itemrange = (fGridView->CountRows() + 3) * row->Height(); @@ -515,11 +530,12 @@ void ReportWindow::CalcAccountString(void) } */ void -ReportWindow::CalcCategoryString(void) { +ReportWindow::CalcCategoryString(void) +{ // Compile list of selected categories fCategoryString = ""; for (int32 i = 0; i < fCategoryList->CountItems(); i++) { - BStringItem *catitem = (BStringItem *)fCategoryList->ItemAt(i); + BStringItem* catitem = (BStringItem*)fCategoryList->ItemAt(i); if (catitem && catitem->IsSelected()) { if (fCategoryString.CountChars() > 0) fCategoryString << ",'" << EscapeIllegalCharacters(catitem->Text()) << "'"; @@ -530,9 +546,10 @@ ReportWindow::CalcCategoryString(void) { } void -ReportWindow::RenderReport(void) { +ReportWindow::RenderReport(void) +{ fGridView->Clear(); - BColumn *column = fGridView->ColumnAt(0); + BColumn* column = fGridView->ColumnAt(0); while (column) { fGridView->RemoveColumn(column); delete column; @@ -566,12 +583,13 @@ ReportWindow::RenderReport(void) { } bool -ReportWindow::QuitRequested(void) { +ReportWindow::QuitRequested(void) +{ // We need to remove this window's observer object from each account's notifier, or else // we will crash the app after closing the window and selecting an account for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *acc = gDatabase.AccountAt(i); + Account* acc = gDatabase.AccountAt(i); if (!acc) continue; @@ -582,19 +600,21 @@ ReportWindow::QuitRequested(void) { } int -compare_stringitem(const void *item1, const void *item2) { - BListItem *listitem1 = *((BListItem **)item1); - BListItem *listitem2 = *((BListItem **)item2); +compare_stringitem(const void* item1, const void* item2) +{ + BListItem* listitem1 = *((BListItem**)item1); + BListItem* listitem2 = *((BListItem**)item2); - BStringItem *stritem1 = (BStringItem *)listitem1; - BStringItem *stritem2 = (BStringItem *)listitem2; + BStringItem* stritem1 = (BStringItem*)listitem1; + BStringItem* stritem2 = (BStringItem*)listitem2; int len1 = (stritem1 && stritem1->Text()) ? strlen(stritem1->Text()) : 0; int len2 = (stritem2 && stritem2->Text()) ? strlen(stritem2->Text()) : 0; if (len1 < 1) { return (len2 < 1) ? 0 : 1; - } else if (len2 < 1) { + } + else if (len2 < 1) { return (len1 < 1) ? 0 : -1; } diff --git a/src/ReportWindow.h b/src/ReportWindow.h index d180782..3976fb8 100644 --- a/src/ReportWindow.h +++ b/src/ReportWindow.h @@ -31,13 +31,13 @@ enum { REPORT_CASH_FLOW = 0, REPORT_NET_WORTH, REPORT_TRANSACTIONS, REPORT_BUDGE class ReportWindow : public BWindow, public Observer { public: ReportWindow(BRect frame); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); void FrameResized(float w, float h); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); bool QuitRequested(void); private: - void AddAccount(Account *acc); + void AddAccount(Account* acc); void FixGridScrollbar(void); void RenderReport(void); @@ -48,15 +48,15 @@ class ReportWindow : public BWindow, public Observer { void CalcCategoryString(void); - BMenuField *fReportField; - BMenuField *fSubtotalField; - BListView *fAccountList; - BListView *fCategoryList; - BColumnListView *fGridView; - BView *fGraphView; - BScrollView *fCategoryScroller; + BMenuField* fReportField; + BMenuField* fSubtotalField; + BListView* fAccountList; + BListView* fCategoryList; + BColumnListView* fGridView; + BView* fGraphView; + BScrollView* fCategoryScroller; DateBox *fStartDateBox, *fEndDateBox; - StickyDrawButton *fGraphButton; + StickyDrawButton* fGraphButton; uint8 fSubtotalMode; uint8 fReportMode; @@ -68,13 +68,14 @@ class ReportWindow : public BWindow, public Observer { class AccountItem : public BStringItem { public: - AccountItem(Account *acc) : BStringItem("") { + AccountItem(Account* acc) : BStringItem("") + { if (acc) SetText(acc->Name()); account = acc; } - Account *account; + Account* account; }; diff --git a/src/ScheduleAddWindow.cpp b/src/ScheduleAddWindow.cpp index 55f95f7..699a8d8 100644 --- a/src/ScheduleAddWindow.cpp +++ b/src/ScheduleAddWindow.cpp @@ -22,7 +22,6 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ScheduleAddWindow" - enum { M_SCHEDULED_MONTHLY = 'schm', M_SCHEDULED_WEEKLY, @@ -35,30 +34,31 @@ enum { M_SCHEDULE_TRANSACTION }; -ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData &data) +ScheduleAddWindow::ScheduleAddWindow(const BRect& frame, const TransactionData& data) : BWindow( frame, B_TRANSLATE("Schedule transaction"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fTransData(data) { + fTransData(data) +{ AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *back = new BView("backview", B_WILL_DRAW); + BView* back = new BView("backview", B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); back->SetViewColor(240, 240, 240); BString label; label.SetToFormat(B_TRANSLATE("Type: %s"), data.Type().Type()); - BStringView *typelabel = new BStringView("typelabel", label.String()); + BStringView* typelabel = new BStringView("typelabel", label.String()); label.SetToFormat(B_TRANSLATE("Payee: %s"), data.Payee()); - BStringView *payeelabel = new BStringView("payeelabel", label.String()); + BStringView* payeelabel = new BStringView("payeelabel", label.String()); BString temp; gCurrentLocale.CurrencyToString(data.Amount().AbsoluteValue(), temp); label.SetToFormat(B_TRANSLATE("Amount: %s"), temp); - BStringView *amountlabel = new BStringView("amountlabel", label.String()); + BStringView* amountlabel = new BStringView("amountlabel", label.String()); label = B_TRANSLATE("Category:"); label += " "; @@ -67,29 +67,31 @@ ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData & else label << data.NameAt(0); - BStringView *categorylabel = new BStringView("categorylabel", label.String()); + BStringView* categorylabel = new BStringView("categorylabel", label.String()); label = B_TRANSLATE("Memo:"); label << " " << data.Memo(); - BStringView *memolabel = new BStringView("memolabel", label.String()); + BStringView* memolabel = new BStringView("memolabel", label.String()); // Since layout-api, we need other way to make divider // BBox *divider = new BBox(r); // AddChild(divider); fIntervalMenu = new BMenu(B_TRANSLATE("Frequency")); - fIntervalMenu->AddItem(new BMenuItem(B_TRANSLATE("Monthly"), new BMessage(M_SCHEDULED_MONTHLY))); + fIntervalMenu->AddItem(new BMenuItem(B_TRANSLATE("Monthly"), new BMessage(M_SCHEDULED_MONTHLY)) + ); fIntervalMenu->AddItem( new BMenuItem(B_TRANSLATE("Quarterly"), new BMessage(M_SCHEDULED_QUARTERLY)) ); - fIntervalMenu->AddItem(new BMenuItem(B_TRANSLATE("Annually"), new BMessage(M_SCHEDULED_ANNUALLY)) + fIntervalMenu->AddItem( + new BMenuItem(B_TRANSLATE("Annually"), new BMessage(M_SCHEDULED_ANNUALLY)) ); fIntervalMenu->ItemAt(0)->SetMarked(true); fIntervalMenu->SetLabelFromMarked(true); temp = B_TRANSLATE("Frequency:"); temp += " "; - BMenuField *intervalfield = new BMenuField("intervalfield", temp.String(), fIntervalMenu); + BMenuField* intervalfield = new BMenuField("intervalfield", temp.String(), fIntervalMenu); temp = B_TRANSLATE("Starting date:"); temp += " "; @@ -107,18 +109,18 @@ ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData & fRepeatCount->UseTabFiltering(false); fRepeatCount->SetEnabled(false); - BStringView *timeslabel = new BStringView("timeslabel", B_TRANSLATE("times")); + BStringView* timeslabel = new BStringView("timeslabel", B_TRANSLATE("times")); fRepeatAlways->SetValue(B_CONTROL_ON); intervalfield->MakeFocus(true); - BButton *okbutton = + BButton* okbutton = new BButton("okbutton", B_TRANSLATE("Cancel"), new BMessage(M_SCHEDULE_TRANSACTION)); okbutton->MakeDefault(true); okbutton->SetLabel(B_TRANSLATE("OK")); - BButton *cancelbutton = + BButton* cancelbutton = new BButton("cancelbutton", B_TRANSLATE("Cancel"), new BMessage(B_QUIT_REQUESTED)); cancelbutton->MakeDefault(true); @@ -149,7 +151,8 @@ ScheduleAddWindow::ScheduleAddWindow(const BRect &frame, const TransactionData & } void -ScheduleAddWindow::MessageReceived(BMessage *msg) { +ScheduleAddWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_REPEAT_ALWAYS: { fRepeatCount->SetEnabled(false); @@ -172,7 +175,7 @@ ScheduleAddWindow::MessageReceived(BMessage *msg) { case M_SCHEDULE_TRANSACTION: { ScheduledTransData stdata(fTransData); - BMenuItem *intervalitem = fIntervalMenu->FindMarked(); + BMenuItem* intervalitem = fIntervalMenu->FindMarked(); if (!intervalitem) { ShowBug("NULL menu item in ScheduleAddWindow"); break; @@ -207,8 +210,8 @@ ScheduleAddWindow::MessageReceived(BMessage *msg) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the date you entered."), B_TRANSLATE("CapitalBe understands lots of different ways of entering dates. " - "Apparently, this wasn't one of them. You'll need to change how you " - "entered this date. Sorry.") + "Apparently, this wasn't one of them. You'll need to change how you " + "entered this date. Sorry.") ); break; } diff --git a/src/ScheduleAddWindow.h b/src/ScheduleAddWindow.h index 5d604ea..d46b1c1 100644 --- a/src/ScheduleAddWindow.h +++ b/src/ScheduleAddWindow.h @@ -14,14 +14,14 @@ class NumBox; class ScheduleAddWindow : public BWindow { public: - ScheduleAddWindow(const BRect &frame, const TransactionData &data); - void MessageReceived(BMessage *msg); + ScheduleAddWindow(const BRect& frame, const TransactionData& data); + void MessageReceived(BMessage* msg); private: - DateBox *fStartDate; + DateBox* fStartDate; BRadioButton *fRepeatAlways, *fRepeatLimited; - BMenu *fIntervalMenu; - NumBox *fRepeatCount; + BMenu* fIntervalMenu; + NumBox* fRepeatCount; TransactionData fTransData; }; diff --git a/src/ScheduleListWindow.cpp b/src/ScheduleListWindow.cpp index 9a0485a..68a426f 100644 --- a/src/ScheduleListWindow.cpp +++ b/src/ScheduleListWindow.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -19,8 +18,8 @@ #include "ColumnTypes.h" #include "Database.h" #include "EscapeCancelFilter.h" -#include "LanguageRoster.h" #include "HelpButton.h" +#include "LanguageRoster.h" #include "Preferences.h" #include "ScheduledTransData.h" #include "ScheduledTransItem.h" @@ -30,29 +29,29 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ScheduleListWindow" - enum { M_REMOVE_ITEM = 'rmit' }; class ScheduleListView : public BView { public: - ScheduleListView(const char *name, const int32 &flags); + ScheduleListView(const char* name, const int32& flags); void AttachedToWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); private: // This is a float so we can get the maximum string width for payees. float RefreshScheduleList(void); - BColumnListView *fListView; + BColumnListView* fListView; - BButton *fRemoveButton; + BButton* fRemoveButton; BList fTransList; - HelpButton *fHelpButton; + HelpButton* fHelpButton; float fBestWidth; }; -ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView(name, flags) { +ScheduleListView::ScheduleListView(const char* name, const int32& flags) : BView(name, flags) +{ BString temp; SetViewColor(240, 240, 240); @@ -82,13 +81,15 @@ ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView ); fListView->AddColumn( new BStringColumn( - B_TRANSLATE("Payments"), StringWidth(B_TRANSLATE("Payments")) + 20, 25, 300, B_ALIGN_LEFT + B_TRANSLATE("Payments"), StringWidth(B_TRANSLATE("Payments")) + 20, 25, 300, + B_ALIGN_LEFT ), 2 ); fListView->AddColumn( new BStringColumn( - B_TRANSLATE("Frequency"), StringWidth(B_TRANSLATE("Frequency")) + 20, 25, 300, B_ALIGN_LEFT + B_TRANSLATE("Frequency"), StringWidth(B_TRANSLATE("Frequency")) + 20, 25, 300, + B_ALIGN_LEFT ), 3 ); @@ -126,7 +127,8 @@ ScheduleListView::ScheduleListView(const char *name, const int32 &flags) : BView } void -ScheduleListView::AttachedToWindow(void) { +ScheduleListView::AttachedToWindow(void) +{ fListView->SetTarget(this); fRemoveButton->SetTarget(this); @@ -135,14 +137,15 @@ ScheduleListView::AttachedToWindow(void) { } void -ScheduleListView::MessageReceived(BMessage *msg) { +ScheduleListView::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_REMOVE_ITEM: { int32 selection = fListView->IndexOf(fListView->CurrentSelection()); if (selection < 0) break; - ScheduledTransData *data = (ScheduledTransData *)fTransList.ItemAt(selection); + ScheduledTransData* data = (ScheduledTransData*)fTransList.ItemAt(selection); gDatabase.RemoveScheduledTransaction(data->GetID()); fTransList.RemoveItem(data); @@ -160,9 +163,10 @@ ScheduleListView::MessageReceived(BMessage *msg) { } float -ScheduleListView::RefreshScheduleList(void) { +ScheduleListView::RefreshScheduleList(void) +{ for (int32 i = 0; i < fTransList.CountItems(); i++) { - ScheduledTransData *data = (ScheduledTransData *)fTransList.ItemAt(i); + ScheduledTransData* data = (ScheduledTransData*)fTransList.ItemAt(i); delete data; } fTransList.MakeEmpty(); @@ -208,7 +212,7 @@ ScheduleListView::RefreshScheduleList(void) { float maxwidth = 0; for (uint32 i = 0; i <= count; i++) { - ScheduledTransData *sdata = new ScheduledTransData(); + ScheduledTransData* sdata = new ScheduledTransData(); if (!gDatabase.GetScheduledTransaction(idlist[i], *sdata)) { delete sdata; continue; @@ -221,10 +225,10 @@ ScheduleListView::RefreshScheduleList(void) { } for (int32 i = 0; i < fTransList.CountItems(); i++) { - BRow *row = new BRow(); + BRow* row = new BRow(); fListView->AddRow(row); - ScheduledTransData *sdata = (ScheduledTransData *)fTransList.ItemAt(i); + ScheduledTransData* sdata = (ScheduledTransData*)fTransList.ItemAt(i); row->SetField(new BStringField(sdata->Payee()), 0); @@ -238,7 +242,8 @@ ScheduleListView::RefreshScheduleList(void) { if (sdata->GetCount() > 0) { string = ""; string << sdata->GetCount(); - } else + } + else string = B_TRANSLATE("Unlimited"); row->SetField(new BStringField(string.String()), 2); @@ -277,14 +282,15 @@ ScheduleListView::RefreshScheduleList(void) { return maxwidth; } -ScheduleListWindow::ScheduleListWindow(const BRect &frame) +ScheduleListWindow::ScheduleListWindow(const BRect& frame) : BWindow( - frame, B_TRANSLATE("Scheduled transactions"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, - B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS - ) { + frame, B_TRANSLATE("Scheduled transactions"), B_DOCUMENT_WINDOW_LOOK, + B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS + ) +{ AddCommonFilter(new EscapeCancelFilter); - ScheduleListView *view = new ScheduleListView("schedview", B_WILL_DRAW); + ScheduleListView* view = new ScheduleListView("schedview", B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL).SetInsets(0).Add(view).End(); // AddShortcut('A',B_COMMAND_KEY, new BMessage(M_SHOW_ADD_WINDOW),view); diff --git a/src/ScheduleListWindow.h b/src/ScheduleListWindow.h index 410da89..0cb86d8 100644 --- a/src/ScheduleListWindow.h +++ b/src/ScheduleListWindow.h @@ -5,7 +5,7 @@ class ScheduleListWindow : public BWindow { public: - ScheduleListWindow(const BRect &frame); + ScheduleListWindow(const BRect& frame); }; #endif diff --git a/src/ScheduledExecutor.cpp b/src/ScheduledExecutor.cpp index 4c9a2de..3cf5d13 100644 --- a/src/ScheduledExecutor.cpp +++ b/src/ScheduledExecutor.cpp @@ -3,7 +3,8 @@ #include "TimeSupport.h" void -HandleScheduledTransactions(void) { +HandleScheduledTransactions(void) +{ // This function does one thing: enter any transactions which are // scheduled for entry diff --git a/src/ScheduledTransData.cpp b/src/ScheduledTransData.cpp index 7ab8fe5..8d8f0ae 100644 --- a/src/ScheduledTransData.cpp +++ b/src/ScheduledTransData.cpp @@ -2,27 +2,33 @@ #include "CBLocale.h" #include "TimeSupport.h" -ScheduledTransData::ScheduledTransData(void) - : fInterval(SCHEDULED_UNKNOWN), fCount(0), fNextDate(0) {} +ScheduledTransData::ScheduledTransData(void) : fInterval(SCHEDULED_UNKNOWN), fCount(0), fNextDate(0) +{ +} ScheduledTransData::ScheduledTransData( - Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, const TransactionInterval &interval, const int32 &count + Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, const TransactionInterval& interval, const int32& count ) : TransactionData(account, date, type, payee, amount, category, memo, TRANS_OPEN), - fInterval(interval), fCount(count), fNextDate(0) {} + fInterval(interval), fCount(count), fNextDate(0) +{ +} -ScheduledTransData::ScheduledTransData(const ScheduledTransData &trans) { *this = trans; } +ScheduledTransData::ScheduledTransData(const ScheduledTransData& trans) { *this = trans; } ScheduledTransData::ScheduledTransData( - const TransactionData &data, const TransactionInterval &interval, const int32 &count + const TransactionData& data, const TransactionInterval& interval, const int32& count ) - : TransactionData(data), fInterval(interval), fCount(count), fNextDate(0) {} + : TransactionData(data), fInterval(interval), fCount(count), fNextDate(0) +{ +} ScheduledTransData::~ScheduledTransData(void) {} -ScheduledTransData & -ScheduledTransData::operator=(const ScheduledTransData &from) { +ScheduledTransData& +ScheduledTransData::operator=(const ScheduledTransData& from) +{ TransactionData::operator=(from); fInterval = from.GetInterval(); fCount = from.GetCount(); @@ -30,7 +36,8 @@ ScheduledTransData::operator=(const ScheduledTransData &from) { } void -ScheduledTransData::CalculateNextDueDate(void) { +ScheduledTransData::CalculateNextDueDate(void) +{ switch (GetInterval()) { case SCHEDULED_MONTHLY: { fNextDate = IncrementDateByMonth(Date()); @@ -60,7 +67,8 @@ ScheduledTransData::CalculateNextDueDate(void) { } bool -ScheduledTransData::IsValid(void) const { +ScheduledTransData::IsValid(void) const +{ if (!TransactionData::IsValid()) return false; @@ -71,7 +79,8 @@ ScheduledTransData::IsValid(void) const { } void -ScheduledTransData::MakeEmpty(void) { +ScheduledTransData::MakeEmpty(void) +{ TransactionData::MakeEmpty(); fInterval = SCHEDULED_UNKNOWN; fCount = 0; diff --git a/src/ScheduledTransData.h b/src/ScheduledTransData.h index 07b9a99..54ffc84 100644 --- a/src/ScheduledTransData.h +++ b/src/ScheduledTransData.h @@ -7,28 +7,28 @@ class ScheduledTransData : public TransactionData { public: ScheduledTransData(void); ScheduledTransData( - Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, const TransactionInterval &interval, - const int32 &count = 0 + Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, const TransactionInterval& interval, + const int32& count = 0 ); - ScheduledTransData(const ScheduledTransData &trans); + ScheduledTransData(const ScheduledTransData& trans); ScheduledTransData( - const TransactionData &data, const TransactionInterval &interval = SCHEDULED_MONTHLY, - const int32 &count = 0 + const TransactionData& data, const TransactionInterval& interval = SCHEDULED_MONTHLY, + const int32& count = 0 ); virtual ~ScheduledTransData(void); - ScheduledTransData &operator=(const ScheduledTransData &from); + ScheduledTransData& operator=(const ScheduledTransData& from); TransactionInterval GetInterval(void) const { return fInterval; } - void SetInterval(const TransactionInterval &interval) { fInterval = interval; } + void SetInterval(const TransactionInterval& interval) { fInterval = interval; } int32 GetCount(void) const { return fCount; } // count < 0 means repeat indefinitely void SetCount(const int32 count) { fCount = count; } - void SetNextDueDate(const time_t &date) { fNextDate = date; } + void SetNextDueDate(const time_t& date) { fNextDate = date; } void CalculateNextDueDate(void); diff --git a/src/ScheduledTransItem.cpp b/src/ScheduledTransItem.cpp index 3e8ac09..d37d6ec 100644 --- a/src/ScheduledTransItem.cpp +++ b/src/ScheduledTransItem.cpp @@ -20,10 +20,10 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ScheduledTransItem" - -ScheduledTransItem::ScheduledTransItem(const ScheduledTransData &data) +ScheduledTransItem::ScheduledTransItem(const ScheduledTransData& data) : BListItem(), fAccount(data.GetAccount()), fType(data.Type().Type()), fPayee(data.Payee()), - fAmount(""), fCategory(""), fMemo(data.Memo()), fDate(""), fID(data.GetID()) { + fAmount(""), fCategory(""), fMemo(data.Memo()), fDate(""), fID(data.GetID()) +{ Locale locale = data.GetAccount()->GetLocale(); locale.CurrencyToString(data.Amount().AbsoluteValue(), fAmount); gDefaultLocale.DateToString(data.Date(), fDate); @@ -35,7 +35,8 @@ ScheduledTransItem::ScheduledTransItem(const ScheduledTransData &data) } void -ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) { +ScheduledTransItem::DrawItem(BView* owner, BRect frame, bool complete) +{ BString string; Locale locale = fAccount->GetLocale(); @@ -54,7 +55,8 @@ ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->SetHighColor(linecolor); owner->StrokeRect(frame); owner->SetHighColor(255, 255, 255); - } else { + } + else { linecolor.red = 200; linecolor.green = 200; linecolor.blue = 200; @@ -182,7 +184,8 @@ ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) { if (fMemo.CountChars() > 0) { owner->SetHighColor(0, 0, 0); owner->DrawString(fMemo.String(), BPoint(xpos + 5, ypos - 3)); - } else { + } + else { owner->SetHighColor(linecolor); owner->DrawString("No Memo", BPoint(xpos + 5, ypos - 3)); } @@ -190,13 +193,15 @@ ScheduledTransItem::DrawItem(BView *owner, BRect frame, bool complete) { } void -ScheduledTransItem::Update(BView *owner, const BFont *finfo) { +ScheduledTransItem::Update(BView* owner, const BFont* finfo) +{ BListItem::Update(owner, finfo); SetHeight(TRowHeight() * 2); } void -ScheduledTransItem::SetData(const TransactionData &trans) { +ScheduledTransItem::SetData(const TransactionData& trans) +{ fAccount = trans.GetAccount(); Locale locale = fAccount->GetLocale(); diff --git a/src/ScheduledTransItem.h b/src/ScheduledTransItem.h index c16db67..cab005d 100644 --- a/src/ScheduledTransItem.h +++ b/src/ScheduledTransItem.h @@ -11,21 +11,21 @@ class Account; class ScheduledTransItem : public BListItem { public: - ScheduledTransItem(const ScheduledTransData &data); + ScheduledTransItem(const ScheduledTransData& data); - void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView *owner, const BFont *finfo); + void DrawItem(BView* owner, BRect frame, bool complete = false); + void Update(BView* owner, const BFont* finfo); uint32 GetID(void) const { return fID; } - const char *GetDate(void) const { return fDate.String(); } + const char* GetDate(void) const { return fDate.String(); } - const char *GetPayee(void) const { return fPayee.String(); } + const char* GetPayee(void) const { return fPayee.String(); } - void SetData(const TransactionData &trans); + void SetData(const TransactionData& trans); private: - Account *fAccount; + Account* fAccount; BString fType; BString fPayee; BString fAmount; diff --git a/src/Settings.cpp b/src/Settings.cpp new file mode 100644 index 0000000..ad52c17 --- /dev/null +++ b/src/Settings.cpp @@ -0,0 +1,90 @@ +/* + * Copyright 2024, Emir SARI . + * All rights reserved. Distributed under the terms of the MIT license. + */ + + +#include "Settings.h" + +#include +#include + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "Settings" + +std::shared_ptr +Settings::_OpenFile(const char* filename, uint32 openMode) +{ + if (openMode == B_WRITE_ONLY) + openMode |= B_CREATE_FILE | B_ERASE_FILE; + const int index = (openMode == B_READ_ONLY) ? 1 : 2; + auto file = std::make_shared(filename, openMode); + status_t result = file->InitCheck(); + if (result != B_OK) { + BString error = B_TRANSLATE("Unknown error."); + switch (result) { + case B_BAD_VALUE: + error = B_TRANSLATE("Encountered an error while opening the configuration file."); + break; + case B_PERMISSION_DENIED: + error = B_TRANSLATE("Could not open the configuration file. " + "Please check the file permissions."); + break; + case B_NO_MEMORY: + error = B_TRANSLATE("Could not allocate enough memory. " + "Free some memory and try again."); + break; + default: + // If opened for reading and not found, don't throw "Unknown error." + if (index == 1) + return std::shared_ptr(); + } + BAlert* alert = new BAlert( + B_TRANSLATE("Error"), error, B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, + B_EVEN_SPACING, B_WARNING_ALERT + ); + alert->SetShortcut(0, B_ESCAPE); + return std::shared_ptr(); + } + return file; +} + +void +Settings::Load(const char* filename) +{ + auto file = _OpenFile(filename, B_READ_ONLY); + BMessage storage; + + if (file) + storage.Unflatten(file.get()); + + fWindowRect = storage.GetRect("windowRect", BRect(50, 50, 500, 500)); + fUseSystemDefaults = storage.GetBool("useSystemDefaults", true); + + if (storage.FindMessage("findWindowState", &fFindWindowState) != B_OK) + fFindWindowState = BMessage(); +} + +void +Settings::Save(const char* filename) +{ + auto file = _OpenFile(filename, B_WRITE_ONLY); + BMessage storage; + + storage.AddRect("windowRect", fWindowRect); + storage.AddBool("useSystemDefaults", fUseSystemDefaults); + + if (file) { + storage.Flatten(file.get()); + } +} + +Settings& +Settings::operator=(Settings& settings) +{ + fWindowRect = settings.fWindowRect; + fUseSystemDefaults = settings.fUseSystemDefaults; + + return *this; +} diff --git a/src/Settings.h b/src/Settings.h new file mode 100644 index 0000000..13d960b --- /dev/null +++ b/src/Settings.h @@ -0,0 +1,34 @@ +/* + * Copyright 2024, Emir SARI . + * All rights reserved. Distributed under the terms of the MIT license. + */ + + +#ifndef SETTINGS_H +#define SETTINGS_H + + +#include +#include +#include + +#include + +class Settings { + public: + BRect fWindowRect; + BMessage fFindWindowState; + BPath fSettingsPath; + + Settings& operator=(Settings& settings); + + bool fUseSystemDefaults; + void Load(const char* filename); + void Save(const char* filename); + + private: + std::shared_ptr _OpenFile(const char* filename, uint32 openMode); +}; + + +#endif // SETTINGS_H diff --git a/src/SettingsWindow.cpp b/src/SettingsWindow.cpp new file mode 100644 index 0000000..4eb6328 --- /dev/null +++ b/src/SettingsWindow.cpp @@ -0,0 +1,58 @@ +/* + * Copyright 2024, Emir SARI . + * All rights reserved. Distributed under the terms of the MIT license. + */ + + +#include "SettingsWindow.h" + +#include +#include +#include + +#include "Database.h" +#include "EscapeCancelFilter.h" + +#include "Settings.h" + + +#undef B_TRANSLATION_CONTEXT +#define B_TRANSLATION_CONTEXT "SettingsWindow" + +SettingsWindow::SettingsWindow(Settings* settings) + : BWindow( + BRect(0, 0, 300, 300), B_TRANSLATE("CapitalBe settings"), B_TITLED_WINDOW, B_NOT_ZOOMABLE, + B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS | + B_SUPPORTS_LAYOUT + ) +{ + fSettings = settings; + fStartSettings = new Settings(); + *fStartSettings = *fSettings; +} + +SettingsWindow::~SettingsWindow() +{ + if (fStartSettings) + delete fStartSettings; +} + +void +SettingsWindow::MessageReceived(BMessage* message) +{ + switch (message->what) { + case Actions::USE_SYSTEM_DEFAULTS: { + } break; + default: { + BWindow::MessageReceived(message); + } break; + } +} + +void +SettingsWindow::Quit() +{ + be_app->PostMessage(APP_SETTINGS_QUITTING); + + BWindow::Quit(); +} diff --git a/src/SettingsWindow.h b/src/SettingsWindow.h new file mode 100644 index 0000000..e26f4c4 --- /dev/null +++ b/src/SettingsWindow.h @@ -0,0 +1,37 @@ +/* + * Copyright 2024, Emir SARI . + * All rights reserved. Distributed under the terms of the MIT license. + */ + + +#ifndef SETTINGS_WINDOW_H +#define SETTINGS_WINDOW_H + + +#include + +#include "Settings.h" + + +const uint32 APP_SETTINGS_CHANGED = 'apch'; +const uint32 APP_SETTINGS_QUITTING = 'APQU'; + +class SettingsWindow : public BWindow { + public: + SettingsWindow(Settings* settings); + ~SettingsWindow(); + + void MessageReceived(BMessage* message); + void Quit(); + + private: + enum Actions { + USE_SYSTEM_DEFAULTS = 'usdf', + }; + + Settings* fSettings; + Settings* fStartSettings; +}; + + +#endif // SETTINGS_WINDOW_H diff --git a/src/SplitItem.cpp b/src/SplitItem.cpp index 56e531b..ae83959 100644 --- a/src/SplitItem.cpp +++ b/src/SplitItem.cpp @@ -6,40 +6,47 @@ SplitItem::SplitItem(void) : BStringItem(""), fName(""), fAmount(0L), fMemo("") SplitItem::~SplitItem(void) {} void -SplitItem::SetCategory(const char *value) { +SplitItem::SetCategory(const char* value) +{ fName = value; UpdateLabel(); } -const char * -SplitItem::GetCategory(void) const { +const char* +SplitItem::GetCategory(void) const +{ return fName.String(); } void -SplitItem::SetAmount(const Fixed &fixed) { +SplitItem::SetAmount(const Fixed& fixed) +{ fAmount = fixed; UpdateLabel(); } Fixed -SplitItem::GetAmount(void) const { +SplitItem::GetAmount(void) const +{ return fAmount; } void -SplitItem::SetMemo(const char *value) { +SplitItem::SetMemo(const char* value) +{ fMemo = value; UpdateLabel(); } -const char * -SplitItem::GetMemo(void) const { +const char* +SplitItem::GetMemo(void) const +{ return fMemo.String(); } void -SplitItem::UpdateLabel(void) { +SplitItem::UpdateLabel(void) +{ BString text = fName; BString amount; gCurrentLocale.CurrencyToString(fAmount.AbsoluteValue(), amount); diff --git a/src/SplitItem.h b/src/SplitItem.h index 13f46aa..a44f48f 100644 --- a/src/SplitItem.h +++ b/src/SplitItem.h @@ -11,14 +11,14 @@ class SplitItem : public BStringItem { ~SplitItem(void); // void DrawItem(BView *owner, BRect frame, bool complete = false); - void SetCategory(const char *value); - const char *GetCategory(void) const; + void SetCategory(const char* value); + const char* GetCategory(void) const; - void SetAmount(const Fixed &fixed); + void SetAmount(const Fixed& fixed); Fixed GetAmount(void) const; - void SetMemo(const char *value); - const char *GetMemo(void) const; + void SetMemo(const char* value); + const char* GetMemo(void) const; private: void UpdateLabel(void); diff --git a/src/SplitView.cpp b/src/SplitView.cpp index e621704..7d4ae98 100644 --- a/src/SplitView.cpp +++ b/src/SplitView.cpp @@ -31,10 +31,10 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "SplitView" - -SplitView::SplitView(const char *name, const TransactionData &trans, const int32 &flags) +SplitView::SplitView(const char* name, const TransactionData& trans, const int32& flags) : BView(name, flags | B_FRAME_EVENTS), - Observer(WATCH_SELECT | WATCH_TRANSACTION | WATCH_ACCOUNT) { + Observer(WATCH_SELECT | WATCH_TRANSACTION | WATCH_ACCOUNT) +{ fTransaction = trans; fStartExpanded = false; @@ -128,7 +128,7 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 int32 count = fTransaction.CountCategories(); for (int32 i = 0; i < count; i++) { - SplitItem *item = new SplitItem(); + SplitItem* item = new SplitItem(); item->SetCategory(fTransaction.NameAt(i)); item->SetAmount(fTransaction.AmountAt(i)); item->SetMemo(fTransaction.MemoAt(i)); @@ -187,7 +187,8 @@ SplitView::SplitView(const char *name, const TransactionData &trans, const int32 SplitView::~SplitView(void) { delete fMessenger; } void -SplitView::AttachedToWindow(void) { +SplitView::AttachedToWindow(void) +{ SetViewColor(240, 240, 240); Window()->AddCommonFilter(fKeyFilter); fMessenger = new BMessenger(this); @@ -216,12 +217,14 @@ SplitView::AttachedToWindow(void) { } void -SplitView::DetachedFromWindow(void) { +SplitView::DetachedFromWindow(void) +{ Window()->RemoveCommonFilter(fKeyFilter); } void -SplitView::MessageReceived(BMessage *msg) { +SplitView::MessageReceived(BMessage* msg) +{ int32 start; BString string; switch (msg->what) { @@ -250,7 +253,8 @@ SplitView::MessageReceived(BMessage *msg) { if (fSplitContainer->IsHidden()) { fCategory->SetText(string.String()); fCategory->TextView()->Select(start, string.CountChars()); - } else { + } + else { fSplitCategory->SetText(string.String()); fSplitCategory->TextView()->Select(start, string.CountChars()); } @@ -278,11 +282,11 @@ SplitView::MessageReceived(BMessage *msg) { if (!ValidateSplitItems()) break; - Account *account = fTransaction.GetAccount(); + Account* account = fTransaction.GetAccount(); if (!account) ShowBug("NULL transaction account in SplitView::M_ENTER_TRANSACTION"); - Category *cat = MakeCategory(); + Category* cat = MakeCategory(); fTransaction.Set( account, fDate->Text(), fType->Text(), fPayee->Text(), fAmount->Text(), NULL, fMemo->Text(), fTransaction.Status() @@ -295,7 +299,8 @@ SplitView::MessageReceived(BMessage *msg) { // This adds the transaction data without generating a new transaction id gDatabase.AddTransaction(fTransaction, false); - } catch (CppSQLite3Exception &e) { + } + catch (CppSQLite3Exception& e) { debugger(e.errorMessage()); } Window()->PostMessage(B_QUIT_REQUESTED); @@ -305,23 +310,28 @@ SplitView::MessageReceived(BMessage *msg) { if (fDate->ChildAt(0)->IsFocus()) { if (fDate->Validate()) fEnter->MakeFocus(true); - } else if (fType->ChildAt(0)->IsFocus()) + } + else if (fType->ChildAt(0)->IsFocus()) fDate->MakeFocus(true); else if (fPayee->ChildAt(0)->IsFocus()) { if (fPayee->Validate()) fType->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { if (fAmount->Validate()) fPayee->MakeFocus(true); - } else if (fCategory->ChildAt(0)->IsFocus()) { + } + else if (fCategory->ChildAt(0)->IsFocus()) { if (fCategory->Validate()) fAmount->MakeFocus(true); - } else if (fMemo->ChildAt(0)->IsFocus()) { + } + else if (fMemo->ChildAt(0)->IsFocus()) { if (fSplitContainer->IsHidden()) fCategory->MakeFocus(true); else fAmount->MakeFocus(true); - } else if (fSplit->IsFocus()) + } + else if (fSplit->IsFocus()) fMemo->MakeFocus(true); else if (fAddSplit->IsFocus()) fSplit->MakeFocus(true); @@ -332,7 +342,8 @@ SplitView::MessageReceived(BMessage *msg) { else if (fSplitAmount->ChildAt(0)->IsFocus()) { if (ValidateSplitAmountField()) fSplitCategory->MakeFocus(true); - } else if (fSplitMemo->ChildAt(0)->IsFocus()) + } + else if (fSplitMemo->ChildAt(0)->IsFocus()) fSplitAmount->MakeFocus(true); else if (fSplitScroller->IsFocus()) fSplitMemo->MakeFocus(); @@ -341,7 +352,8 @@ SplitView::MessageReceived(BMessage *msg) { fSplit->MakeFocus(true); else fSplitItems->MakeFocus(true); - } else { + } + else { // We should *never* be here ShowBug("M_PREVIOUS_FIELD received for unrecognized view"); } @@ -353,29 +365,34 @@ SplitView::MessageReceived(BMessage *msg) { if (fDate->ChildAt(0)->IsFocus()) { if (fDate->Validate()) fType->MakeFocus(true); - } else if (fType->ChildAt(0)->IsFocus()) + } + else if (fType->ChildAt(0)->IsFocus()) fPayee->MakeFocus(true); else if (fPayee->ChildAt(0)->IsFocus()) { if (fPayee->Validate()) fAmount->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { if (fAmount->Validate()) { if (fSplitContainer->IsHidden()) fCategory->MakeFocus(true); else fMemo->MakeFocus(true); } - } else if (fCategory->ChildAt(0)->IsFocus()) { + } + else if (fCategory->ChildAt(0)->IsFocus()) { if (fCategory->Validate()) fMemo->MakeFocus(true); - } else if (fMemo->ChildAt(0)->IsFocus()) + } + else if (fMemo->ChildAt(0)->IsFocus()) fSplit->MakeFocus(true); else if (fSplit->IsFocus()) { if (fSplitContainer->IsHidden()) fEnter->MakeFocus(true); else fAddSplit->MakeFocus(true); - } else if (fAddSplit->IsFocus()) + } + else if (fAddSplit->IsFocus()) fRemoveSplit->MakeFocus(true); else if (fRemoveSplit->IsFocus()) fSplitCategory->MakeFocus(true); @@ -384,7 +401,8 @@ SplitView::MessageReceived(BMessage *msg) { else if (fSplitAmount->ChildAt(0)->IsFocus()) { if (ValidateSplitAmountField()) fSplitMemo->MakeFocus(true); - } else if (fSplitMemo->ChildAt(0)->IsFocus()) + } + else if (fSplitMemo->ChildAt(0)->IsFocus()) fSplitItems->MakeFocus(true); else if (fSplitItems->IsFocus()) fEnter->MakeFocus(true); @@ -400,7 +418,7 @@ SplitView::MessageReceived(BMessage *msg) { if (fSplitContainer->IsHidden()) ToggleSplit(); - SplitItem *item = new SplitItem(); + SplitItem* item = new SplitItem(); item->SetCategory(B_TRANSLATE("Uncategorized")); item->SetAmount(fTransaction.Amount().AbsoluteValue() - CalculateTotal().AbsoluteValue()); fSplitItems->AddItem(item); @@ -423,7 +441,7 @@ SplitView::MessageReceived(BMessage *msg) { else newselection = (selection == 0) ? 0 : selection - 1; - SplitItem *item = (SplitItem *)fSplitItems->ItemAt(selection); + SplitItem* item = (SplitItem*)fSplitItems->ItemAt(selection); fSplitItems->RemoveItem(item); fSplitItems->Select(newselection); fSplitCategory->TextView()->SelectAll(); @@ -434,7 +452,7 @@ SplitView::MessageReceived(BMessage *msg) { if (selection < 0) break; - SplitItem *item = (SplitItem *)fSplitItems->ItemAt(selection); + SplitItem* item = (SplitItem*)fSplitItems->ItemAt(selection); fSplitCategory->SetText(item->GetCategory()); BString amount; @@ -460,7 +478,7 @@ SplitView::MessageReceived(BMessage *msg) { // which, unfortunately, is what we want. case M_SPLIT_CATEGORY_CHANGED: { int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + SplitItem* splititem = (SplitItem*)fSplitItems->ItemAt(selection); if (!splititem) break; @@ -475,7 +493,7 @@ SplitView::MessageReceived(BMessage *msg) { } case M_SPLIT_AMOUNT_CHANGED: { int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + SplitItem* splititem = (SplitItem*)fSplitItems->ItemAt(selection); if (!splititem) break; @@ -495,7 +513,7 @@ SplitView::MessageReceived(BMessage *msg) { } case M_SPLIT_MEMO_CHANGED: { int32 selection = fSplitItems->CurrentSelection(); - SplitItem *splititem = (SplitItem *)fSplitItems->ItemAt(selection); + SplitItem* splititem = (SplitItem*)fSplitItems->ItemAt(selection); if (!splititem) break; @@ -535,9 +553,10 @@ SplitView::MessageReceived(BMessage *msg) { void SplitView::SetFields( - const char *date, const char *type, const char *payee, const char *amount, const char *category, - const char *memo -) { + const char* date, const char* type, const char* payee, const char* amount, const char* category, + const char* memo +) +{ fDate->SetText(date); fType->SetText(type); fPayee->SetText(payee); @@ -547,20 +566,22 @@ SplitView::SetFields( } void -SplitView::HandleNotify(const uint64 &value, const BMessage *msg) { +SplitView::HandleNotify(const uint64& value, const BMessage* msg) +{ if (value & WATCH_SELECT) { if (value & WATCH_ACCOUNT) MakeEmpty(); else if (value & WATCH_TRANSACTION) { - TransactionData *trans; - if (msg->FindPointer("item", (void **)&trans) == B_OK) + TransactionData* trans; + if (msg->FindPointer("item", (void**)&trans) == B_OK) fCurrentDate = trans->Date(); } } } void -SplitView::MakeEmpty(void) { +SplitView::MakeEmpty(void) +{ fDate->SetText(""); fType->SetText(""); fPayee->SetText(""); @@ -570,15 +591,19 @@ SplitView::MakeEmpty(void) { } void -SplitView::MakeFocus(bool value) { +SplitView::MakeFocus(bool value) +{ fDate->MakeFocus(value); } void -SplitView::FrameResized(float width, float height) {} +SplitView::FrameResized(float width, float height) +{ +} bool -SplitView::ValidateSplitAmountField(void) { +SplitView::ValidateSplitAmountField(void) +{ if (strlen(fSplitAmount->Text()) < 1) fSplitAmount->SetText("0"); @@ -587,11 +612,12 @@ SplitView::ValidateSplitAmountField(void) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the amount."), B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.") + "for this account.") ); fSplitAmount->MakeFocus(true); return false; - } else { + } + else { BString string; gCurrentLocale.CurrencyToString(amount, string); fSplitAmount->SetText(string.String()); @@ -601,10 +627,11 @@ SplitView::ValidateSplitAmountField(void) { } bool -SplitView::ValidateSplitItems(void) { +SplitView::ValidateSplitItems(void) +{ Fixed total; for (int32 i = 0; i < fSplitItems->CountItems(); i++) { - SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); + SplitItem* item = (SplitItem*)fSplitItems->ItemAt(i); total += item->GetAmount().AbsoluteValue(); } @@ -614,7 +641,7 @@ SplitView::ValidateSplitItems(void) { ShowAlert( B_TRANSLATE("CapitalBe didn't understand the amount."), B_TRANSLATE("There may be a typo or the wrong kind of currency symbol " - "for this account.") + "for this account.") ); return false; } @@ -625,7 +652,7 @@ SplitView::ValidateSplitItems(void) { gCurrentLocale.CurrencyToString(total, totalstr); errormsg = B_TRANSLATE("When the split items are added together, they need to add up " - "to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%%"); + "to %%ENTERED_AMOUNT%%. Currently, they add up to %%TOTAL_AMOUNT%%"); errormsg.ReplaceFirst("%%ENTERED_AMOUNT%%", fAmount->Text()); errormsg.ReplaceFirst("%%TOTAL_AMOUNT%%", totalstr.String()); @@ -637,12 +664,14 @@ SplitView::ValidateSplitItems(void) { } bool -SplitView::ValidateAllFields(void) { +SplitView::ValidateAllFields(void) +{ BString date; if (strlen(fDate->Text()) < 1) { gDefaultLocale.DateToString(fCurrentDate, date); fDate->SetText(date.String()); - } else if (!fDate->Validate()) + } + else if (!fDate->Validate()) return false; if (!fPayee->Validate()) @@ -661,7 +690,8 @@ SplitView::ValidateAllFields(void) { } void -SplitView::ToggleSplit(void) { +SplitView::ToggleSplit(void) +{ if (fSplitContainer->IsHidden()) { fSplit->SetLabel(B_TRANSLATE("Hide Split")); @@ -673,7 +703,8 @@ SplitView::ToggleSplit(void) { // These calls are needed because of some stupid resize-related bugs in Zeta. :/ Invalidate(); fEnter->Invalidate(); - } else { + } + else { fSplit->SetLabel(B_TRANSLATE("Show Split")); fSplitContainer->Hide(); @@ -681,10 +712,11 @@ SplitView::ToggleSplit(void) { } } -Category * -SplitView::MakeCategory(void) { +Category* +SplitView::MakeCategory(void) +{ // This makes a category object from the existing data - Category *cat = new Category(); + Category* cat = new Category(); Locale locale = fTransaction.GetAccount()->GetLocale(); if (fSplitContainer->IsHidden() && fSplitItems->CountItems() <= 1) { if (strlen(fCategory->Text()) > 0 && strlen(fAmount->Text()) > 0) { @@ -701,7 +733,7 @@ SplitView::MakeCategory(void) { } for (int32 i = 0; i < fSplitItems->CountItems(); i++) { - SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); + SplitItem* item = (SplitItem*)fSplitItems->ItemAt(i); if (!item || strlen(item->GetCategory()) < 1 || item->GetAmount().IsZero()) continue; @@ -718,11 +750,12 @@ SplitView::MakeCategory(void) { } Fixed -SplitView::CalculateTotal(void) { +SplitView::CalculateTotal(void) +{ Fixed total; for (int32 i = 0; i < fSplitItems->CountItems(); i++) { - SplitItem *item = (SplitItem *)fSplitItems->ItemAt(i); + SplitItem* item = (SplitItem*)fSplitItems->ItemAt(i); total += item->GetAmount().AbsoluteValue(); } diff --git a/src/SplitView.h b/src/SplitView.h index 2536d9b..b2bbd8e 100644 --- a/src/SplitView.h +++ b/src/SplitView.h @@ -39,17 +39,17 @@ class HelpButton; class SplitView : public BView, public Observer { public: - SplitView(const char *name, const TransactionData &trans, const int32 &flags); + SplitView(const char* name, const TransactionData& trans, const int32& flags); ~SplitView(void); void AttachedToWindow(void); void DetachedFromWindow(void); - void MessageReceived(BMessage *msg); + void MessageReceived(BMessage* msg); void SetFields( - const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo + const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo ); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); void MakeEmpty(void); void MakeFocus(bool value = true); void FrameResized(float width, float height); @@ -67,28 +67,28 @@ class SplitView : public BView, public Observer { // bool ValidateCategoryField(void); bool ValidateSplitItems(void); Fixed CalculateTotal(void); - Category *MakeCategory(void); + Category* MakeCategory(void); // BTextControl *fType,*fPayee,*fAmount,*fCategory,*fMemo; - DateBox *fDate; - CheckNumBox *fType; - PayeeBox *fPayee; - CurrencyBox *fAmount; - CategoryBox *fCategory; - NavTextBox *fMemo; + DateBox* fDate; + CheckNumBox* fType; + PayeeBox* fPayee; + CurrencyBox* fAmount; + CategoryBox* fCategory; + NavTextBox* fMemo; BStringView *fDateLabel, *fTypeLabel, *fPayeeLabel, *fAmountLabel, *fCategoryLabel, *fMemoLabel; - SplitViewFilter *fKeyFilter; - BMessenger *fMessenger; + SplitViewFilter* fKeyFilter; + BMessenger* fMessenger; BButton *fEnter, *fTransfer, *fSplit; - BView *fSplitContainer; + BView* fSplitContainer; BTextControl *fSplitCategory, *fSplitAmount, *fSplitMemo; - BListView *fSplitItems; - BScrollView *fSplitScroller; + BListView* fSplitItems; + BScrollView* fSplitScroller; BButton *fAddSplit, *fRemoveSplit; - BStringView *fSplitTotal; - BCheckBox *fReconciled; - HelpButton *fHelpButton; + BStringView* fSplitTotal; + BCheckBox* fReconciled; + HelpButton* fHelpButton; time_t fCurrentDate; bool fStartExpanded; diff --git a/src/SplitViewFilter.cpp b/src/SplitViewFilter.cpp index 3209535..3f8ed50 100644 --- a/src/SplitViewFilter.cpp +++ b/src/SplitViewFilter.cpp @@ -6,34 +6,36 @@ #include "MsgDefs.h" #include "TimeSupport.h" -#include #include +#include #include #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "SplitFilterView" - -SplitViewFilter::SplitViewFilter(SplitView *checkview) - : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fView(checkview) {} +SplitViewFilter::SplitViewFilter(SplitView* checkview) + : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, B_KEY_DOWN), fView(checkview) +{ +} SplitViewFilter::~SplitViewFilter(void) {} filter_result -SplitViewFilter::Filter(BMessage *msg, BHandler **target) { +SplitViewFilter::Filter(BMessage* msg, BHandler** target) +{ int32 mod; if (msg->FindInt32("modifiers", &mod) == B_OK) { if ((mod & B_COMMAND_KEY) || (mod & B_COMMAND_KEY) || (mod & B_OPTION_KEY)) return B_DISPATCH_MESSAGE; } - BView *v = dynamic_cast(*target); + BView* v = dynamic_cast(*target); if (!v) return B_DISPATCH_MESSAGE; - BTextControl *text = dynamic_cast(v->Parent()); - BButton *button = dynamic_cast(v); + BTextControl* text = dynamic_cast(v->Parent()); + BButton* button = dynamic_cast(v); if (!text && !button) return B_DISPATCH_MESSAGE; @@ -70,7 +72,8 @@ SplitViewFilter::Filter(BMessage *msg, BHandler **target) { fView->ToggleSplit(); fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; - } else { + } + else { fView->fMessenger->SendMessage(new BMessage(M_NEXT_FIELD)); return B_SKIP_MESSAGE; } @@ -126,7 +129,7 @@ SplitViewFilter::Filter(BMessage *msg, BHandler **target) { int32 start, end; text->TextView()->GetSelection(&start, &end); - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (text == fView->fSplitCategory || text == fView->fSplitAmount || text == fView->fSplitMemo) { switch (rawchar) { @@ -144,9 +147,11 @@ SplitViewFilter::Filter(BMessage *msg, BHandler **target) { if (text == fView->fSplitCategory) { editmsg.AddInt32("command", M_SPLIT_CATEGORY_CHANGED); - } else if (text == fView->fSplitAmount) { + } + else if (text == fView->fSplitAmount) { editmsg.AddInt32("command", M_SPLIT_AMOUNT_CHANGED); - } else if (text == fView->fSplitMemo) { + } + else if (text == fView->fSplitMemo) { editmsg.AddInt32("command", M_SPLIT_MEMO_CHANGED); } @@ -164,9 +169,11 @@ SplitViewFilter::Filter(BMessage *msg, BHandler **target) { BMessage keymsg(M_EDIT_KEY); if (text == fView->fSplitCategory) { keymsg.AddInt32("command", M_SPLIT_CATEGORY_CHANGED); - } else if (text == fView->fSplitAmount) { + } + else if (text == fView->fSplitAmount) { keymsg.AddInt32("command", M_SPLIT_AMOUNT_CHANGED); - } else if (text == fView->fSplitMemo) { + } + else if (text == fView->fSplitMemo) { keymsg.AddInt32("command", M_SPLIT_MEMO_CHANGED); } diff --git a/src/SplitViewFilter.h b/src/SplitViewFilter.h index 3b76803..64fcd3c 100644 --- a/src/SplitViewFilter.h +++ b/src/SplitViewFilter.h @@ -7,12 +7,12 @@ class SplitViewFilter : public BMessageFilter { public: - SplitViewFilter(SplitView *checkview); + SplitViewFilter(SplitView* checkview); ~SplitViewFilter(void); - virtual filter_result Filter(BMessage *msg, BHandler **target); + virtual filter_result Filter(BMessage* msg, BHandler** target); private: - SplitView *fView; + SplitView* fView; BString fPayeeText; }; diff --git a/src/StickyDrawButton.cpp b/src/StickyDrawButton.cpp index 80e006b..b43e76e 100644 --- a/src/StickyDrawButton.cpp +++ b/src/StickyDrawButton.cpp @@ -1,13 +1,16 @@ #include "StickyDrawButton.h" StickyDrawButton::StickyDrawButton( - BRect frame, const char *name, BBitmap *up, BBitmap *down, BMessage *msg, const int32 &resize, - const int32 &flags + BRect frame, const char* name, BBitmap* up, BBitmap* down, BMessage* msg, const int32& resize, + const int32& flags ) : BButton(frame, name, "", msg, resize, flags), fUp(up), fDown(down), fDisabledUp(NULL), - fDisabledDown(NULL), fButtonState(B_CONTROL_OFF) {} + fDisabledDown(NULL), fButtonState(B_CONTROL_OFF) +{ +} -StickyDrawButton::~StickyDrawButton(void) { +StickyDrawButton::~StickyDrawButton(void) +{ delete fUp; delete fDown; delete fDisabledUp; @@ -15,7 +18,8 @@ StickyDrawButton::~StickyDrawButton(void) { } void -StickyDrawButton::ResizeToPreferred(void) { +StickyDrawButton::ResizeToPreferred(void) +{ if (fUp) ResizeTo(fUp->Bounds().Width(), fUp->Bounds().Height()); else if (fDown) @@ -27,7 +31,8 @@ StickyDrawButton::ResizeToPreferred(void) { } void -StickyDrawButton::SetBitmaps(BBitmap *up, BBitmap *down) { +StickyDrawButton::SetBitmaps(BBitmap* up, BBitmap* down) +{ delete fUp; delete fDown; @@ -36,7 +41,8 @@ StickyDrawButton::SetBitmaps(BBitmap *up, BBitmap *down) { } void -StickyDrawButton::SetDisabled(BBitmap *disabledup, BBitmap *disableddown) { +StickyDrawButton::SetDisabled(BBitmap* disabledup, BBitmap* disableddown) +{ delete fDisabledUp; delete fDisabledDown; @@ -45,14 +51,16 @@ StickyDrawButton::SetDisabled(BBitmap *disabledup, BBitmap *disableddown) { } void -StickyDrawButton::MouseUp(BPoint pt) { +StickyDrawButton::MouseUp(BPoint pt) +{ BButton::MouseUp(pt); fButtonState = (fButtonState == B_CONTROL_ON) ? B_CONTROL_OFF : B_CONTROL_ON; Invalidate(); } void -StickyDrawButton::SetState(int32 value) { +StickyDrawButton::SetState(int32 value) +{ if (fButtonState != value) { if (value == B_CONTROL_ON) fButtonState = B_CONTROL_OFF; @@ -63,7 +71,8 @@ StickyDrawButton::SetState(int32 value) { } void -StickyDrawButton::Draw(BRect update) { +StickyDrawButton::Draw(BRect update) +{ // if down if (fButtonState == B_CONTROL_ON) { if (!IsEnabled()) { @@ -72,21 +81,24 @@ StickyDrawButton::Draw(BRect update) { else StrokeRect(Bounds()); return; - } else { + } + else { if (fDown) DrawBitmap(fDown, BPoint(0, 0)); else StrokeRect(Bounds()); return; } - } else { + } + else { if (!IsEnabled()) { if (fDisabledUp) DrawBitmap(fDisabledUp, BPoint(0, 0)); else StrokeRect(Bounds()); return; - } else { + } + else { if (fUp) DrawBitmap(fUp, BPoint(0, 0)); else diff --git a/src/StickyDrawButton.h b/src/StickyDrawButton.h index 5f9c3d4..6a7a27a 100644 --- a/src/StickyDrawButton.h +++ b/src/StickyDrawButton.h @@ -9,16 +9,16 @@ class StickyDrawButton : public BButton { public: StickyDrawButton( - BRect frame, const char *name, BBitmap *up, BBitmap *down, BMessage *msg, - const int32 &resize, const int32 &flags + BRect frame, const char* name, BBitmap* up, BBitmap* down, BMessage* msg, + const int32& resize, const int32& flags ); ~StickyDrawButton(void); void Draw(BRect update); - void SetBitmaps(BBitmap *up, BBitmap *down); + void SetBitmaps(BBitmap* up, BBitmap* down); void ResizeToPreferred(void); - void SetDisabled(BBitmap *disabledup, BBitmap *disableddown); + void SetDisabled(BBitmap* disabledup, BBitmap* disableddown); void MouseUp(BPoint pt); // void MessageReceived(BMessage *msg); diff --git a/src/TextFile.cpp b/src/TextFile.cpp index ce13867..28380ba 100644 --- a/src/TextFile.cpp +++ b/src/TextFile.cpp @@ -8,21 +8,25 @@ #include #include -TextFile::TextFile(const char *path, const uint32 &openmode) : BFile(path, openmode) { +TextFile::TextFile(const char* path, const uint32& openmode) : BFile(path, openmode) +{ InitObject(); } -TextFile::TextFile(const entry_ref &ref, const uint32 &openmode) : BFile(&ref, openmode) { +TextFile::TextFile(const entry_ref& ref, const uint32& openmode) : BFile(&ref, openmode) +{ InitObject(); } -TextFile::~TextFile(void) { +TextFile::~TextFile(void) +{ delete[] fBuffer; delete[] fReadBuffer; } void -TextFile::InitObject(void) { +TextFile::InitObject(void) +{ fReadBuffer = new char[4096]; fReadBufferSize = 4096; @@ -34,20 +38,22 @@ TextFile::InitObject(void) { Seek(0, SEEK_SET); fBuffer[fBufferSize] = 0; - } else { + } + else { fBuffer = NULL; fBufferSize = 0; } } -const char * -TextFile::ReadLine(void) { +const char* +TextFile::ReadLine(void) +{ off_t pos = Position(); - char *c = fBuffer; + char* c = fBuffer; c += sizeof(char) * pos; - char *eol = strchr(c, '\n'); + char* eol = strchr(c, '\n'); if (!eol) { // This means that there are no more linefeeds before the the @@ -75,6 +81,7 @@ TextFile::ReadLine(void) { } bool -TextFile::IsEOF(void) { +TextFile::IsEOF(void) +{ return (Position() > fBufferSize); } diff --git a/src/TextFile.h b/src/TextFile.h index 7c31b43..1c897b3 100644 --- a/src/TextFile.h +++ b/src/TextFile.h @@ -10,18 +10,18 @@ class TextFile : public BFile { public: - TextFile(const char *path, const uint32 &openmode); - TextFile(const entry_ref &ref, const uint32 &openmode); + TextFile(const char* path, const uint32& openmode); + TextFile(const entry_ref& ref, const uint32& openmode); ~TextFile(void); - const char *ReadLine(void); + const char* ReadLine(void); bool IsEOF(void); private: void InitObject(void); - char *fBuffer; + char* fBuffer; off_t fBufferSize; - char *fReadBuffer; + char* fReadBuffer; int32 fReadBufferSize; }; diff --git a/src/TimeSupport.cpp b/src/TimeSupport.cpp index 784a5e1..d9df91f 100644 --- a/src/TimeSupport.cpp +++ b/src/TimeSupport.cpp @@ -2,35 +2,40 @@ #include time_t -IncrementDateByDay(const time_t &t) { +IncrementDateByDay(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_mday++; return mktime(×truct); } time_t -DecrementDateByDay(const time_t &t) { +DecrementDateByDay(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_mday--; return mktime(×truct); } time_t -IncrementDateByMonth(const time_t &t) { +IncrementDateByMonth(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_mon++; return mktime(×truct); } time_t -DecrementDateByMonth(const time_t &t) { +DecrementDateByMonth(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_mon--; return mktime(×truct); } time_t -IncrementDateByQuarter(const time_t &t) { +IncrementDateByQuarter(const time_t& t) +{ struct tm timestruct = *localtime(&t); int quarter = (timestruct.tm_mon + 1) / 3; if ((timestruct.tm_mon + 1) % 3 > 0) @@ -39,7 +44,8 @@ IncrementDateByQuarter(const time_t &t) { if (quarter == 4) { quarter = 1; timestruct.tm_year++; - } else + } + else quarter++; // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we @@ -49,21 +55,24 @@ IncrementDateByQuarter(const time_t &t) { } time_t -IncrementDateByYear(const time_t &t) { +IncrementDateByYear(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_year++; return mktime(×truct); } time_t -DecrementDateByYear(const time_t &t) { +DecrementDateByYear(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_year--; return mktime(×truct); } time_t -GetCurrentDate(void) { +GetCurrentDate(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -75,7 +84,8 @@ GetCurrentDate(void) { // Returns the value for the first day of the month. time_t -GetCurrentMonth(void) { +GetCurrentMonth(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -88,7 +98,8 @@ GetCurrentMonth(void) { // Returns the value for the first day of the quarter time_t -GetCurrentQuarter(void) { +GetCurrentQuarter(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -110,7 +121,8 @@ GetCurrentQuarter(void) { // Returns the value for the first day of the year time_t -GetCurrentYear(void) { +GetCurrentYear(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -124,7 +136,8 @@ GetCurrentYear(void) { } time_t -GetLastMonth(void) { +GetLastMonth(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -138,7 +151,8 @@ GetLastMonth(void) { } time_t -GetLastQuarter(void) { +GetLastQuarter(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -155,7 +169,8 @@ GetLastQuarter(void) { if (quarter == 1) { quarter = 4; timestruct.tm_year--; - } else + } + else quarter--; // We subtract 3 becuase the actual month is (quarter * 3) - 2, but we @@ -165,7 +180,8 @@ GetLastQuarter(void) { } time_t -GetLastYear(void) { +GetLastYear(void) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -180,7 +196,8 @@ GetLastYear(void) { } BString -GetShortMonthName(const uint8 &number) { +GetShortMonthName(const uint8& number) +{ time_t rawtime; time(&rawtime); struct tm timestruct = *localtime(&rawtime); @@ -192,7 +209,8 @@ GetShortMonthName(const uint8 &number) { } int -DayOfWeek(int day, int month, int year) { +DayOfWeek(int day, int month, int year) +{ // adjust months so February is the last one month -= 2; if (month < 1) { @@ -207,7 +225,8 @@ DayOfWeek(int day, int month, int year) { } int -DaysInMonth(int month, int year) { +DaysInMonth(int month, int year) +{ if (month > 11 || month < 0 || year < 0) { debugger("Bad value in DaysInMonth"); return 0; @@ -238,7 +257,8 @@ DaysInMonth(int month, int year) { } bool -IsLeapYear(int year) { +IsLeapYear(int year) +{ if (year < 0) { debugger("Bad value in IsLeapYear"); return false; @@ -251,7 +271,8 @@ IsLeapYear(int year) { } int -DayOfYear(int day, int month, int year) { +DayOfYear(int day, int month, int year) +{ if (month > 11 || month < 0 || year < 0 || day < 0 || day > 31) { debugger("Bad value in DayOfYear"); return 0; @@ -275,7 +296,8 @@ DayOfYear(int day, int month, int year) { } int -GetQuarterForDate(const time_t &t) { +GetQuarterForDate(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_sec = 0; timestruct.tm_min = 0; @@ -290,7 +312,8 @@ GetQuarterForDate(const time_t &t) { } int -GetQuarterMonthForDate(const time_t &t) { +GetQuarterMonthForDate(const time_t& t) +{ struct tm timestruct = *localtime(&t); timestruct.tm_sec = 0; timestruct.tm_min = 0; diff --git a/src/TimeSupport.h b/src/TimeSupport.h index aef8681..cd9ab38 100644 --- a/src/TimeSupport.h +++ b/src/TimeSupport.h @@ -9,20 +9,20 @@ #define SECONDS_PER_YEAR 31557600 time_t -IncrementDateByDay(const time_t &t); +IncrementDateByDay(const time_t& t); time_t -DecrementDateByDay(const time_t &t); +DecrementDateByDay(const time_t& t); time_t -IncrementDateByMonth(const time_t &t); +IncrementDateByMonth(const time_t& t); time_t -DecrementDateByMonth(const time_t &t); +DecrementDateByMonth(const time_t& t); time_t -IncrementDateByQuarter(const time_t &t); +IncrementDateByQuarter(const time_t& t); time_t -IncrementDateByYear(const time_t &t); +IncrementDateByYear(const time_t& t); time_t -DecrementDateByYear(const time_t &t); +DecrementDateByYear(const time_t& t); time_t @@ -42,12 +42,12 @@ time_t GetLastYear(void); BString -GetShortMonthName(const uint8 &number); +GetShortMonthName(const uint8& number); int -GetQuarterForDate(const time_t &t); +GetQuarterForDate(const time_t& t); int -GetQuarterMonthForDate(const time_t &t); +GetQuarterMonthForDate(const time_t& t); bool IsLeapYear(int year); diff --git a/src/Transaction.cpp b/src/Transaction.cpp index 2235b4f..26ec39f 100644 --- a/src/Transaction.cpp +++ b/src/Transaction.cpp @@ -16,7 +16,8 @@ Transaction::Transaction(void) : fID(0) {} void -TransactionType::SetType(const char *data) { +TransactionType::SetType(const char* data) +{ if (!data) { fTypeCode = TRANS_INIT; fTypeData = ""; diff --git a/src/Transaction.h b/src/Transaction.h index d95290d..8542ede 100644 --- a/src/Transaction.h +++ b/src/Transaction.h @@ -23,11 +23,11 @@ typedef enum { class TransactionType { public: - TransactionType(const char *data) { SetType(data); } + TransactionType(const char* data) { SetType(data); } - void SetType(const char *data); + void SetType(const char* data); - const char *Type(void) const { return fTypeData.String(); } + const char* Type(void) const { return fTypeData.String(); } uint8 TypeCode(void) const { return fTypeCode; } @@ -40,7 +40,7 @@ class Transaction { public: Transaction(void); - void SetID(const time_t &id) { fID = id; }; + void SetID(const time_t& id) { fID = id; }; time_t GetID(void) const { return fID; } diff --git a/src/TransactionData.cpp b/src/TransactionData.cpp index b1c846c..3cc909b 100644 --- a/src/TransactionData.cpp +++ b/src/TransactionData.cpp @@ -14,27 +14,32 @@ #endif TransactionData::TransactionData(void) - : fDate(0), fType(""), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) {} + : fDate(0), fType(""), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) +{ +} TransactionData::TransactionData( - Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, uint8 status + Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, uint8 status ) - : fDate(0), fType(type), fAccount(NULL), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) { + : fDate(0), fType(type), fAccount(NULL), fStatus(TRANS_OPEN), fID(0), fTimeStamp(0) +{ fCategory.MakeEmpty(); Set(account, date, type, payee, amount, category, memo, status); } -TransactionData::TransactionData(const TransactionData &trans) - : fDate(0), fType(""), fStatus(TRANS_OPEN), fTimeStamp(0) { +TransactionData::TransactionData(const TransactionData& trans) + : fDate(0), fType(""), fStatus(TRANS_OPEN), fTimeStamp(0) +{ fCategory.MakeEmpty(); *this = trans; } TransactionData::~TransactionData() {} -TransactionData & -TransactionData::operator=(const TransactionData &from) { +TransactionData& +TransactionData::operator=(const TransactionData& from) +{ fDate = from.fDate; fType = from.fType; @@ -53,9 +58,10 @@ TransactionData::operator=(const TransactionData &from) { status_t TransactionData::Set( - Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, uint8 status -) { + Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, uint8 status +) +{ STRACE( ("TransactionData(%s,%s,%s,%s,%s,%s,%s\n", date, type, payee, amount, category, memo, status ? "reconciled" : "not reconciled") @@ -73,7 +79,8 @@ TransactionData::Set( if (fType.TypeCode() == TRANS_DEP) { if (fAmount.IsNegative()) fAmount.Invert(); - } else { + } + else { if (fAmount.IsPositive()) fAmount.Invert(); } @@ -86,19 +93,22 @@ TransactionData::Set( } uint8 -TransactionData::Month() { - tm *t = localtime(&fDate); +TransactionData::Month() +{ + tm* t = localtime(&fDate); return (t->tm_mon); } uint8 -TransactionData::Year() { - tm *t = localtime(&fDate); +TransactionData::Year() +{ + tm* t = localtime(&fDate); return (t->tm_year); } void -TransactionData::PrintToStream(void) { +TransactionData::PrintToStream(void) +{ BString str, temp; gDefaultLocale.DateToString(fDate, str); @@ -124,17 +134,20 @@ TransactionData::PrintToStream(void) { } void -TransactionData::SetType(const TransactionType &type) { +TransactionData::SetType(const TransactionType& type) +{ fType = type; } void -TransactionData::SetType(const char *type) { +TransactionData::SetType(const char* type) +{ fType.SetType(type); } void -TransactionData::SetCategory(const char *cat) { +TransactionData::SetCategory(const char* cat) +{ if (!cat) { fCategory.MakeEmpty(); return; @@ -147,12 +160,14 @@ TransactionData::SetCategory(const char *cat) { } void -TransactionData::SetCategory(const Category &cat) { +TransactionData::SetCategory(const Category& cat) +{ fCategory = cat; } void -TransactionData::AddCategory(const char *name, const Fixed &amount, const bool &recalculate) { +TransactionData::AddCategory(const char* name, const Fixed& amount, const bool& recalculate) +{ if (!name) return; @@ -166,7 +181,8 @@ TransactionData::AddCategory(const char *name, const Fixed &amount, const bool & } void -TransactionData::MakeEmpty(void) { +TransactionData::MakeEmpty(void) +{ SetAccount(NULL); SetDate(0); SetType(TransactionType(NULL)); @@ -178,7 +194,8 @@ TransactionData::MakeEmpty(void) { } bool -TransactionData::IsValid(void) const { +TransactionData::IsValid(void) const +{ if (fType.TypeCode() == TRANS_INIT) return false; diff --git a/src/TransactionData.h b/src/TransactionData.h index bb89476..5fa6a96 100644 --- a/src/TransactionData.h +++ b/src/TransactionData.h @@ -9,74 +9,74 @@ #include - class TransactionData { public: TransactionData(void); TransactionData( - Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, uint8 status = TRANS_OPEN + Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, uint8 status = TRANS_OPEN ); - TransactionData(const TransactionData &trans); + TransactionData(const TransactionData& trans); virtual ~TransactionData(void); - TransactionData &operator=(const TransactionData &from); + TransactionData& operator=(const TransactionData& from); status_t - Set(Account *account, const char *date, const char *type, const char *payee, const char *amount, - const char *category, const char *memo, uint8 status = TRANS_OPEN); + Set(Account* account, const char* date, const char* type, const char* payee, const char* amount, + const char* category, const char* memo, uint8 status = TRANS_OPEN); uint8 Month(void); uint8 Year(void); time_t Date(void) const { return fDate; } - void SetDate(const time_t &t) { fDate = t; }; + void SetDate(const time_t& t) { fDate = t; }; TransactionType Type(void) const { return fType; } - void SetType(const TransactionType &type); - void SetType(const char *type); + void SetType(const TransactionType& type); + void SetType(const char* type); - const char *Payee(void) const { return fPayee.String(); } + const char* Payee(void) const { return fPayee.String(); } - void SetPayee(const char *payee) { fPayee = payee; }; + void SetPayee(const char* payee) { fPayee = payee; }; Fixed Amount(void) const { return fAmount; } - void SetAmount(const Fixed &fixed) { fAmount = fixed; } + void SetAmount(const Fixed& fixed) { fAmount = fixed; } void PrintToStream(void); - void SetCategory(const char *cat); - void SetCategory(const Category &cat); - void AddCategory(const char *name, const Fixed &amount = 0, const bool &recalculate = true); + void SetCategory(const char* cat); + void SetCategory(const Category& cat); + void AddCategory(const char* name, const Fixed& amount = 0, const bool& recalculate = true); - void RemoveCategory(const int32 &index) { fCategory.RemoveItem(index); } + void RemoveCategory(const int32& index) { fCategory.RemoveItem(index); } - void SetNameAt(const int32 &index, const char *name) { fCategory.SetNameAt(index, name); } + void SetNameAt(const int32& index, const char* name) { fCategory.SetNameAt(index, name); } - const char *NameAt(const int32 &index) const { return fCategory.NameAt(index); } + const char* NameAt(const int32& index) const { return fCategory.NameAt(index); } - void SetAmountAt(const int32 &index, const Fixed &amount) { + void SetAmountAt(const int32& index, const Fixed& amount) + { fCategory.SetAmountAt(index, amount); } - Fixed AmountAt(const int32 &index) const { return fCategory.AmountAt(index); } + Fixed AmountAt(const int32& index) const { return fCategory.AmountAt(index); } - void SetMemoAt(const int32 &index, const char *memo) { fCategory.SetMemoAt(index, memo); } + void SetMemoAt(const int32& index, const char* memo) { fCategory.SetMemoAt(index, memo); } - const char *MemoAt(const int32 &index) const { return fCategory.MemoAt(index); } + const char* MemoAt(const int32& index) const { return fCategory.MemoAt(index); } int32 CountCategories(void) const { return fCategory.CountItems(); } Category GetCategory(void) { return fCategory; } - const char *Memo(void) const { return fMemo.String(); } + const char* Memo(void) const { return fMemo.String(); } - void SetMemo(const char *memo) { fMemo = memo; } + void SetMemo(const char* memo) { fMemo = memo; } - Account *GetAccount(void) const { return fAccount; } + Account* GetAccount(void) const { return fAccount; } - void SetAccount(Account *acc) { fAccount = acc; } + void SetAccount(Account* acc) { fAccount = acc; } uint32 GetID(void) const { return fID; } @@ -87,7 +87,7 @@ class TransactionData { void SetStatus(uint8 value) { fStatus = value; } - void SetTimeStamp(const bigtime_t &time) { fTimeStamp = time; } + void SetTimeStamp(const bigtime_t& time) { fTimeStamp = time; } bigtime_t GetTimeStamp(void) const { return fTimeStamp; } @@ -101,7 +101,7 @@ class TransactionData { time_t fDate; TransactionType fType; - Account *fAccount; + Account* fAccount; BString fPayee; Fixed fAmount; Category fCategory; diff --git a/src/TransactionEditWindow.cpp b/src/TransactionEditWindow.cpp index 2b7eacf..89f25af 100644 --- a/src/TransactionEditWindow.cpp +++ b/src/TransactionEditWindow.cpp @@ -10,11 +10,12 @@ #define M_TOGGLE_SPLIT 'tspl' -TransactionEditWindow::TransactionEditWindow(const BRect &frame, const TransactionData &trans) +TransactionEditWindow::TransactionEditWindow(const BRect& frame, const TransactionData& trans) : BWindow( - frame, B_TRANSLATE("Edit transaction"), B_DOCUMENT_WINDOW_LOOK, B_FLOATING_APP_WINDOW_FEEL, - B_AUTO_UPDATE_SIZE_LIMITS - ) { + frame, B_TRANSLATE("Edit transaction"), B_DOCUMENT_WINDOW_LOOK, + B_FLOATING_APP_WINDOW_FEEL, B_AUTO_UPDATE_SIZE_LIMITS + ) +{ fSplitView = new SplitView("splitview", trans, B_WILL_DRAW); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(fSplitView).End(); @@ -28,7 +29,8 @@ TransactionEditWindow::TransactionEditWindow(const BRect &frame, const Transacti } void -TransactionEditWindow::MessageReceived(BMessage *msg) { +TransactionEditWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_TOGGLE_SPLIT: { fSplitView->ToggleSplit(); diff --git a/src/TransactionEditWindow.h b/src/TransactionEditWindow.h index 20babb2..1d46f06 100644 --- a/src/TransactionEditWindow.h +++ b/src/TransactionEditWindow.h @@ -9,11 +9,11 @@ class TransactionData; class TransactionEditWindow : public BWindow { public: - TransactionEditWindow(const BRect &frame, const TransactionData &trans); - void MessageReceived(BMessage *msg); + TransactionEditWindow(const BRect& frame, const TransactionData& trans); + void MessageReceived(BMessage* msg); private: - SplitView *fSplitView; + SplitView* fSplitView; }; #endif diff --git a/src/TransactionItem.cpp b/src/TransactionItem.cpp index a8d5a6e..6ea2436 100644 --- a/src/TransactionItem.cpp +++ b/src/TransactionItem.cpp @@ -20,11 +20,11 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "TransactionItem" - -TransactionItem::TransactionItem(const TransactionData &trans) +TransactionItem::TransactionItem(const TransactionData& trans) : BListItem(), fDate(trans.Date()), fAccount(trans.GetAccount()), fType(trans.Type().Type()), fPayee(trans.Payee()), fAmount(trans.Amount()), fCategory(""), fMemo(trans.Memo()), - fStatus(trans.Status()), fID(trans.GetID()), fTimeStamp(trans.GetTimeStamp()) { + fStatus(trans.Status()), fID(trans.GetID()), fTimeStamp(trans.GetTimeStamp()) +{ if (trans.CountCategories() > 1) fCategory = B_TRANSLATE("Split"); else @@ -32,7 +32,8 @@ TransactionItem::TransactionItem(const TransactionData &trans) } void -TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { +TransactionItem::DrawItem(BView* owner, BRect frame, bool complete) +{ BString string; Locale locale = fAccount->GetLocale(); @@ -51,7 +52,8 @@ TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->SetHighColor(linecolor); owner->StrokeRect(frame); owner->SetHighColor(255, 255, 255); - } else { + } + else { linecolor.red = 200; linecolor.green = 200; linecolor.blue = 200; @@ -63,7 +65,8 @@ TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { owner->SetHighColor(linecolor); owner->StrokeLine(r.LeftBottom(), r.RightBottom()); owner->SetHighColor(255, 255, 255); - } else { + } + else { owner->SetHighColor(255, 255, 255); owner->SetLowColor(255, 255, 255); owner->FillRect(frame); @@ -190,7 +193,8 @@ TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { if (fMemo.CountChars() > 0) { owner->SetHighColor(0, 0, 0); owner->DrawString(fMemo.String(), BPoint(xpos + 5, ypos - 3)); - } else { + } + else { owner->SetHighColor(linecolor); owner->DrawString(B_TRANSLATE("No Memo"), BPoint(xpos + 5, ypos - 3)); } @@ -198,13 +202,15 @@ TransactionItem::DrawItem(BView *owner, BRect frame, bool complete) { } void -TransactionItem::Update(BView *owner, const BFont *finfo) { +TransactionItem::Update(BView* owner, const BFont* finfo) +{ BListItem::Update(owner, finfo); SetHeight(TRowHeight() * 2); } void -TransactionItem::SetData(const TransactionData &trans) { +TransactionItem::SetData(const TransactionData& trans) +{ fDate = trans.Date(); fAccount = trans.GetAccount(); fType = trans.Type().Type(); diff --git a/src/TransactionItem.h b/src/TransactionItem.h index 19ca712..fa9ce2d 100644 --- a/src/TransactionItem.h +++ b/src/TransactionItem.h @@ -9,24 +9,24 @@ void -InitTransactionItemLayout(BView *owner); +InitTransactionItemLayout(BView* owner); class TransactionItem : public BListItem { public: - TransactionItem(const TransactionData &trans); - void DrawItem(BView *owner, BRect frame, bool complete = false); - void Update(BView *owner, const BFont *finfo); + TransactionItem(const TransactionData& trans); + void DrawItem(BView* owner, BRect frame, bool complete = false); + void Update(BView* owner, const BFont* finfo); uint32 GetID(void) const { return fID; } time_t GetDate(void) const { return fDate; } - const char *GetPayee(void) const { return fPayee.String(); } + const char* GetPayee(void) const { return fPayee.String(); } - void SetData(const TransactionData &trans); + void SetData(const TransactionData& trans); private: - Account *fAccount; + Account* fAccount; BString fCategory; BString fMemo; BString fPayee; diff --git a/src/TransactionLayout.cpp b/src/TransactionLayout.cpp index fae5d03..5092425 100644 --- a/src/TransactionLayout.cpp +++ b/src/TransactionLayout.cpp @@ -8,7 +8,8 @@ static uint8 sDateWidth = 0; static uint8 sAmountWidth = 0; void -InitTransactionItemLayout(BView *owner) { +InitTransactionItemLayout(BView* owner) +{ font_height fh; owner->GetFontHeight(&fh); float fontheight = fh.ascent + fh.descent + fh.leading; @@ -20,26 +21,31 @@ InitTransactionItemLayout(BView *owner) { } uint8 -TLeftPadding(void) { +TLeftPadding(void) +{ return sLeftPadding; } uint8 -TRowHeight(void) { +TRowHeight(void) +{ return sRowHeight; } uint8 -TNumWidth(void) { +TNumWidth(void) +{ return sNumWidth; } uint8 -TDateWidth(void) { +TDateWidth(void) +{ return sDateWidth; } uint8 -TAmountWidth(void) { +TAmountWidth(void) +{ return sAmountWidth; } diff --git a/src/TransactionLayout.h b/src/TransactionLayout.h index c536276..b498a76 100644 --- a/src/TransactionLayout.h +++ b/src/TransactionLayout.h @@ -15,6 +15,6 @@ uint8 TAmountWidth(void); void -InitTransactionItemLayout(BView *owner); +InitTransactionItemLayout(BView* owner); #endif diff --git a/src/TransactionReport.cpp b/src/TransactionReport.cpp index b5aac8c..aa2d131 100644 --- a/src/TransactionReport.cpp +++ b/src/TransactionReport.cpp @@ -16,9 +16,9 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "TransactionReport" - void -ReportWindow::ComputeTransactions(void) { +ReportWindow::ComputeTransactions(void) +{ // Total of all accounts // Calculate the number of columns and the starting date for each one BObjectList timelist(20, true); @@ -26,9 +26,10 @@ ReportWindow::ComputeTransactions(void) { if (fSubtotalMode == SUBTOTAL_NONE) { timelist.AddItem(new time_t(fStartDate)); timelist.AddItem(new time_t(fEndDate)); - } else { + } + else { for (time_t t = fStartDate; t < fEndDate;) { - time_t *item = new time_t(t); + time_t* item = new time_t(t); timelist.AddItem(item); switch (fSubtotalMode) { @@ -56,7 +57,7 @@ ReportWindow::ComputeTransactions(void) { BString longestname(B_TRANSLATE("Transactions")); // int longestnamelength = 12; - BColumn *col = new BStringColumn( + BColumn* col = new BStringColumn( "", fGridView->StringWidth(B_TRANSLATE("Transactions")) + 20, 10, 300, B_TRUNCATE_END, B_ALIGN_RIGHT ); @@ -66,7 +67,8 @@ ReportWindow::ComputeTransactions(void) { ); fGridView->AddColumn(col, 1); col = new BStringColumn( - B_TRANSLATE("Type"), fGridView->StringWidth(B_TRANSLATE("Type")) + 20, 10, 300, B_TRUNCATE_END + B_TRANSLATE("Type"), fGridView->StringWidth(B_TRANSLATE("Type")) + 20, 10, 300, + B_TRUNCATE_END ); fGridView->AddColumn(col, 2); col = new BStringColumn(B_TRANSLATE("Payee"), 75, 10, 300, B_TRUNCATE_END); @@ -85,7 +87,7 @@ ReportWindow::ComputeTransactions(void) { fGridView->AddColumn(col, 6); fGridView->AddRow(new BRow()); - BRow *titlerow = new BRow(); + BRow* titlerow = new BRow(); fGridView->AddRow(titlerow); titlerow->SetField(new BStringField(B_TRANSLATE("Transactions")), 0); fGridView->AddRow(new BRow()); @@ -99,10 +101,10 @@ ReportWindow::ComputeTransactions(void) { int32 count = timelist.CountItems() - 1; for (int32 subtotal_index = 0; subtotal_index < count; subtotal_index++) { - time_t subtotal_start = *((time_t *)timelist.ItemAt(subtotal_index)); - time_t subtotal_end = *((time_t *)timelist.ItemAt(subtotal_index + 1)); + time_t subtotal_start = *((time_t*)timelist.ItemAt(subtotal_index)); + time_t subtotal_end = *((time_t*)timelist.ItemAt(subtotal_index + 1)); - BRow *row = new BRow(); + BRow* row = new BRow(); fGridView->AddRow(row); BString datestring, tempstr; @@ -120,7 +122,7 @@ ReportWindow::ComputeTransactions(void) { int32 accountcount = 0; for (int32 i = 0; i < fAccountList->CountItems(); i++) { - AccountItem *item = (AccountItem *)fAccountList->ItemAt(i); + AccountItem* item = (AccountItem*)fAccountList->ItemAt(i); if (!item || !item->IsSelected()) continue; @@ -144,7 +146,8 @@ ReportWindow::ComputeTransactions(void) { fGridView->ColumnAt(0)->SetWidth( fGridView->StringWidth(B_TRANSLATE("No transactions")) + 15 ); - } else + } + else while (!query.eof()) { row = new BRow(); fGridView->AddRow(row); diff --git a/src/TransactionView.cpp b/src/TransactionView.cpp index 489412d..d5ff301 100644 --- a/src/TransactionView.cpp +++ b/src/TransactionView.cpp @@ -13,7 +13,8 @@ #include TransactionView::TransactionView() - : BView("transactionview", B_WILL_DRAW | B_SUBPIXEL_PRECISE | B_FRAME_EVENTS), fCurrent(NULL) { + : BView("transactionview", B_WILL_DRAW | B_SUBPIXEL_PRECISE | B_FRAME_EVENTS), fCurrent(NULL) +{ InitTransactionItemLayout(this); fListView = new BListView( @@ -28,18 +29,20 @@ TransactionView::TransactionView() BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(fScrollView).End(); } -TransactionView::~TransactionView(void) { +TransactionView::~TransactionView(void) +{ fListView->MakeEmpty(); delete fItemList; } void -TransactionView::AttachedToWindow(void) { +TransactionView::AttachedToWindow(void) +{ SetViewColor(Parent()->ViewColor()); fListView->SetTarget(this); // So the scrollbar initially starts with the proper steps - BScrollBar *bar = fScrollView->ScrollBar(B_VERTICAL); + BScrollBar* bar = fScrollView->ScrollBar(B_VERTICAL); float big, small; bar->GetSteps(&small, &big); @@ -47,13 +50,14 @@ TransactionView::AttachedToWindow(void) { bar->SetSteps(small, big); for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *account = gDatabase.AccountAt(i); + Account* account = gDatabase.AccountAt(i); account->AddObserver(this); } } void -TransactionView::SetAccount(Account *acc) { +TransactionView::SetAccount(Account* acc) +{ // We accept NULL pointers because sometimes we're given them // According to the BeBook, calling BListView::MakeEmpty() doesn't free @@ -149,34 +153,37 @@ TransactionView::SetAccount(Account *acc) { } } -TransactionItem * -TransactionView::AddTransaction(const TransactionData &trans, const int32 &index) { +TransactionItem* +TransactionView::AddTransaction(const TransactionData& trans, const int32& index) +{ int32 itemindex = 0; if (index < 0) itemindex = FindIndexForDate(trans.Date(), trans.Payee()); else itemindex = index; - TransactionItem *transitem = new TransactionItem(trans); + TransactionItem* transitem = new TransactionItem(trans); fListView->AddItem(transitem, itemindex); fItemList->AddItem(transitem, itemindex); - return (TransactionItem *)transitem; + return (TransactionItem*)transitem; } void -TransactionView::DeleteTransaction(const int32 &index) { +TransactionView::DeleteTransaction(const int32& index) +{ // This is totally bizarre. If we remove the first TransactionItem from the // actual fListView, it removes *all* of the items. Does commenting out the line // create a memory leak? BDB doesn't report any leaks FWIW. That won't work as // a fix, though, because whenever a transaction is deleted anywhere else, it // causes a segfault. Grrr.... - TransactionItem *item = (TransactionItem *)fListView->RemoveItem(index); + TransactionItem* item = (TransactionItem*)fListView->RemoveItem(index); delete item; fItemList->RemoveItemAt(index); } void -TransactionView::Draw(BRect updateRect) { +TransactionView::Draw(BRect updateRect) +{ BRect frame = Frame(); frame.OffsetTo(0, 0); frame.bottom = frame.top + 46; @@ -185,19 +192,21 @@ TransactionView::Draw(BRect updateRect) { } void -TransactionView::EditTransaction(void) { +TransactionView::EditTransaction(void) +{ int32 cs = fListView->CurrentSelection(); fListView->InvalidateItem(cs); } void -TransactionView::MessageReceived(BMessage *message) { +TransactionView::MessageReceived(BMessage* message) +{ switch (message->what) { case M_TRANSACTION_SELECTED: { - Account *acc = gDatabase.CurrentAccount(); + Account* acc = gDatabase.CurrentAccount(); if (acc) { - TransactionItem *titem = - (TransactionItem *)fListView->ItemAt(fListView->CurrentSelection()); + TransactionItem* titem = + (TransactionItem*)fListView->ItemAt(fListView->CurrentSelection()); if (titem) acc->SetCurrentTransaction(titem->GetID()); } @@ -215,7 +224,8 @@ TransactionView::MessageReceived(BMessage *message) { } void -TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { +TransactionView::HandleNotify(const uint64& value, const BMessage* msg) +{ bool lockwin = false; if (!Window()->IsLocked()) { lockwin = true; @@ -226,7 +236,8 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { if (IsWatching(WATCH_TRANSACTION)) { RemoveWatch(WATCH_ALL); AddWatch(WATCH_MASS_EDIT); - } else { + } + else { AddWatch(WATCH_ALL); // need to reset all transactions for the current account @@ -236,7 +247,7 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { if (value & WATCH_TRANSACTION) { uint32 accountid = 0; - if (msg->FindInt32("accountid", (int32 *)&accountid) != B_OK) { + if (msg->FindInt32("accountid", (int32*)&accountid) != B_OK) { if (lockwin) Window()->Unlock(); return; @@ -244,19 +255,20 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { if (accountid == gDatabase.CurrentAccount()->GetID()) { if (value & WATCH_CREATE) { - TransactionData *trans = NULL; - if (msg->FindPointer("item", (void **)&trans) != B_OK) { + TransactionData* trans = NULL; + if (msg->FindPointer("item", (void**)&trans) != B_OK) { if (lockwin) Window()->Unlock(); return; } - TransactionItem *item = AddTransaction(*trans); + TransactionItem* item = AddTransaction(*trans); fListView->Select(fListView->IndexOf(item)); fListView->ScrollToSelection(); - } else if (value & WATCH_DELETE) { + } + else if (value & WATCH_DELETE) { uint32 id = 0; - if (msg->FindInt32("id", (int32 *)&id) != B_OK) { + if (msg->FindInt32("id", (int32*)&id) != B_OK) { if (lockwin) Window()->Unlock(); return; @@ -270,11 +282,12 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { } DeleteTransaction(index); - } else if (value & WATCH_CHANGE) { - TransactionData *data; - if (msg->FindPointer("item", (void **)&data) == B_OK) { + } + else if (value & WATCH_CHANGE) { + TransactionData* data; + if (msg->FindPointer("item", (void**)&data) == B_OK) { int32 index = FindItemForID(data->GetID()); - TransactionItem *item = (TransactionItem *)fListView->ItemAt(index); + TransactionItem* item = (TransactionItem*)fListView->ItemAt(index); if (item) { item->SetData(*data); fListView->InvalidateItem(index); @@ -288,13 +301,14 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { fListView->ScrollToSelection(); } */ } - } else if (value & WATCH_ACCOUNT) { + } + else if (value & WATCH_ACCOUNT) { if (value & WATCH_REDRAW) { fListView->Invalidate(); } - Account *acc; - if (msg->FindPointer("item", (void **)&acc) != B_OK) { + Account* acc; + if (msg->FindPointer("item", (void**)&acc) != B_OK) { if (lockwin) Window()->Unlock(); return; @@ -302,17 +316,20 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { if (value & WATCH_SELECT) { SetAccount(gDatabase.CurrentAccount()); - } else if (value & WATCH_CREATE) { + } + else if (value & WATCH_CREATE) { acc->AddObserver(this); - } else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { + } + else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { if (acc == gDatabase.CurrentAccount()) fListView->Invalidate(); } - } else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { + } + else if (value & (WATCH_CHANGE | WATCH_LOCALE)) { // this case handles updates to the default locale // when the default locale is updated - Locale *locale; - if (msg->FindPointer("locale", (void **)&locale) == B_OK) { + Locale* locale; + if (msg->FindPointer("locale", (void**)&locale) == B_OK) { if (locale == &gDefaultLocale) fListView->Invalidate(); } @@ -323,8 +340,9 @@ TransactionView::HandleNotify(const uint64 &value, const BMessage *msg) { } void -TransactionView::FrameResized(float width, float height) { - BScrollBar *bar = fScrollView->ScrollBar(B_VERTICAL); +TransactionView::FrameResized(float width, float height) +{ + BScrollBar* bar = fScrollView->ScrollBar(B_VERTICAL); float big, small; bar->GetSteps(&small, &big); @@ -333,7 +351,8 @@ TransactionView::FrameResized(float width, float height) { } bool -TransactionView::SelectNext(void) { +TransactionView::SelectNext(void) +{ int32 index = fListView->CurrentSelection(); if (index < 0 || index >= fListView->CountItems() - 1) return false; @@ -343,7 +362,8 @@ TransactionView::SelectNext(void) { } bool -TransactionView::SelectPrevious(void) { +TransactionView::SelectPrevious(void) +{ int32 index = fListView->CurrentSelection(); if (index <= 0) return false; @@ -353,7 +373,8 @@ TransactionView::SelectPrevious(void) { } bool -TransactionView::SelectFirst(void) { +TransactionView::SelectFirst(void) +{ if (fListView->CountItems() <= 0) return false; fListView->Select(0L); @@ -362,7 +383,8 @@ TransactionView::SelectFirst(void) { } bool -TransactionView::SelectLast(void) { +TransactionView::SelectLast(void) +{ if (fListView->CountItems() <= 0) return false; fListView->Select(fListView->CountItems() - 1); @@ -371,9 +393,10 @@ TransactionView::SelectLast(void) { } int32 -TransactionView::FindItemForID(const uint32 &id) { +TransactionView::FindItemForID(const uint32& id) +{ for (int32 i = 0; i < fListView->CountItems(); i++) { - TransactionItem *item = (TransactionItem *)fListView->ItemAt(i); + TransactionItem* item = (TransactionItem*)fListView->ItemAt(i); if (item->GetID() == id) return i; } @@ -381,7 +404,8 @@ TransactionView::FindItemForID(const uint32 &id) { } int32 -TransactionView::FindIndexForDate(const time_t &time, const char *payee) { +TransactionView::FindIndexForDate(const time_t& time, const char* payee) +{ // We need to find the appropriate index based on the date of // the transaction and insert it there int32 count = fListView->CountItems(); @@ -391,7 +415,7 @@ TransactionView::FindIndexForDate(const time_t &time, const char *payee) { int32 i = 0; while (i < count) { - TransactionItem *item = (TransactionItem *)fListView->ItemAt(i); + TransactionItem* item = (TransactionItem*)fListView->ItemAt(i); if (time < item->GetDate() || (time == item->GetDate() && strcmp(payee, item->GetPayee()) < 1)) diff --git a/src/TransactionView.h b/src/TransactionView.h index ea0665d..5453682 100644 --- a/src/TransactionView.h +++ b/src/TransactionView.h @@ -22,15 +22,15 @@ class TransactionView : public BView, public Observer { void AttachedToWindow(void); - void SetAccount(Account *acc); - TransactionItem *AddTransaction(const TransactionData &trans, const int32 &index = -1); - void DeleteTransaction(const int32 &index); + void SetAccount(Account* acc); + TransactionItem* AddTransaction(const TransactionData& trans, const int32& index = -1); + void DeleteTransaction(const int32& index); void EditTransaction(); void Draw(BRect updateRect); - void MessageReceived(BMessage *message); + void MessageReceived(BMessage* message); - void HandleNotify(const uint64 &value, const BMessage *msg); + void HandleNotify(const uint64& value, const BMessage* msg); void FrameResized(float width, float height); bool SelectNext(void); @@ -39,14 +39,14 @@ class TransactionView : public BView, public Observer { bool SelectLast(void); private: - int32 FindItemForID(const uint32 &id); - int32 FindIndexForDate(const time_t &time, const char *payee); + int32 FindItemForID(const uint32& id); + int32 FindIndexForDate(const time_t& time, const char* payee); - BListView *fListView; - BObjectList *fItemList; - Transaction *fCurrent; + BListView* fListView; + BObjectList* fItemList; + Transaction* fCurrent; BStringView *fCategoryLabel, *fMemoLabel; - BScrollView *fScrollView; + BScrollView* fScrollView; }; #endif diff --git a/src/TransferWindow.cpp b/src/TransferWindow.cpp index 5737718..cbd11d3 100644 --- a/src/TransferWindow.cpp +++ b/src/TransferWindow.cpp @@ -26,33 +26,36 @@ #define M_DATE_CHANGED 'dtch' #define M_AMOUNT_CHANGED 'amch' -TransferWindow::TransferWindow(BHandler *target) +TransferWindow::TransferWindow(BHandler* target) : BWindow( BRect(100, 100, 500, 350), B_TRANSLATE("Add account transfer"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fMessenger(target), fMessage(M_CREATE_TRANSFER) { + fMessenger(target), fMessage(M_CREATE_TRANSFER) +{ InitObject(NULL, NULL, Fixed(0)); } -TransferWindow::TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount) +TransferWindow::TransferWindow(BHandler* target, Account* src, Account* dest, const Fixed& amount) : BWindow( BRect(100, 100, 300, 300), B_TRANSLATE("Edit transfer"), B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS ), - fMessenger(target) { + fMessenger(target) +{ InitObject(src, dest, amount); } void -TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { +TransferWindow::InitObject(Account* src, Account* dest, const Fixed& amount) +{ BString temp; AddShortcut('W', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('Q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); - BView *back = new BView("back", B_WILL_DRAW); + BView* back = new BView("back", B_WILL_DRAW); back->SetViewColor(240, 240, 240); BLayoutBuilder::Group<>(this, B_VERTICAL, 0).SetInsets(0).Add(back).End(); @@ -93,25 +96,26 @@ TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { BString datestr; gDefaultLocale.DateToString(fDate->GetDate(), datestr); fDate->SetText(datestr.String()); - } else { + } + else { BString datestr; gDefaultLocale.DateToString(fDate->GetDate(), datestr); fDate->SetText(datestr.String()); } fSourceList = new BListView("sourcelist"); - BScrollView *scrollsrc = new BScrollView("sourcescroll", fSourceList, 0, false, true); + BScrollView* scrollsrc = new BScrollView("sourcescroll", fSourceList, 0, false, true); fSourceList->SetSelectionMessage(new BMessage(M_SOURCE_SELECTED)); scrollsrc->SetViewColor(back->ViewColor()); fDestList = new BListView("destlist"); - BScrollView *scrolldest = new BScrollView("destscroll", fDestList, 0, false, true); + BScrollView* scrolldest = new BScrollView("destscroll", fDestList, 0, false, true); fDestList->SetSelectionMessage(new BMessage(M_DEST_SELECTED)); scrolldest->SetViewColor(back->ViewColor()); int32 current = -1; for (int32 i = 0; i < gDatabase.CountAccounts(); i++) { - Account *acc = gDatabase.AccountAt(i); + Account* acc = gDatabase.AccountAt(i); if (acc) { fSourceList->AddItem(new AccountListItem(acc)); fDestList->AddItem(new AccountListItem(acc)); @@ -133,7 +137,8 @@ TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { else fDestList->Select(0L); fAmount->MakeFocus(true); - } else + } + else fDestList->MakeFocus(true); BLayoutBuilder::Group<>(back, B_VERTICAL, 0) @@ -156,16 +161,18 @@ TransferWindow::InitObject(Account *src, Account *dest, const Fixed &amount) { } void -TransferWindow::SetMessage(BMessage msg) { +TransferWindow::SetMessage(BMessage msg) +{ fMessage = msg; } void -TransferWindow::MessageReceived(BMessage *msg) { +TransferWindow::MessageReceived(BMessage* msg) +{ switch (msg->what) { case M_SOURCE_SELECTED: { for (int32 i = 0; i < fDestList->CountItems(); i++) { - AccountListItem *item = (AccountListItem *)fDestList->ItemAt(i); + AccountListItem* item = (AccountListItem*)fDestList->ItemAt(i); if (item && !item->IsEnabled()) { item->SetEnabled(true); fDestList->InvalidateItem(i); @@ -188,7 +195,8 @@ TransferWindow::MessageReceived(BMessage *msg) { if (fDate->ChildAt(0)->IsFocus()) { fDate->Validate(false); fOK->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { fAmount->Validate(false); fDate->MakeFocus(true); } @@ -201,7 +209,8 @@ TransferWindow::MessageReceived(BMessage *msg) { if (fDate->ChildAt(0)->IsFocus()) { fDate->Validate(false); fAmount->MakeFocus(true); - } else if (fAmount->ChildAt(0)->IsFocus()) { + } + else if (fAmount->ChildAt(0)->IsFocus()) { fAmount->Validate(false); fMemo->MakeFocus(true); } @@ -215,13 +224,12 @@ TransferWindow::MessageReceived(BMessage *msg) { if (!fAmount->Validate()) break; - AccountListItem *sitem = - (AccountListItem *)fSourceList->ItemAt(fSourceList->CurrentSelection()); + AccountListItem* sitem = + (AccountListItem*)fSourceList->ItemAt(fSourceList->CurrentSelection()); if (!sitem) break; - AccountListItem *ditem = - (AccountListItem *)fDestList->ItemAt(fDestList->CurrentSelection()); + AccountListItem* ditem = (AccountListItem*)fDestList->ItemAt(fDestList->CurrentSelection()); if (!ditem) break; @@ -231,7 +239,7 @@ TransferWindow::MessageReceived(BMessage *msg) { ShowAlert( B_TRANSLATE("Not transferring any money"), B_TRANSLATE("If you intend to transfer money, it will need to " - "be an amount that is not zero.") + "be an amount that is not zero.") ); break; } @@ -255,9 +263,10 @@ TransferWindow::MessageReceived(BMessage *msg) { } void -TransferWindow::HandleOKButton(void) { +TransferWindow::HandleOKButton(void) +{ if (fSourceList->CurrentSelection() >= 0) { - AccountListItem *item = (AccountListItem *)fDestList->ItemAt(fDestList->CurrentSelection()); + AccountListItem* item = (AccountListItem*)fDestList->ItemAt(fDestList->CurrentSelection()); if (item && item->IsEnabled()) { fOK->SetEnabled(true); return; diff --git a/src/TransferWindow.h b/src/TransferWindow.h index 7fc9948..22a73c3 100644 --- a/src/TransferWindow.h +++ b/src/TransferWindow.h @@ -20,20 +20,20 @@ class CurrencyBox; class TransferWindow : public BWindow { public: - TransferWindow(BHandler *target); - TransferWindow(BHandler *target, Account *src, Account *dest, const Fixed &amount); - void MessageReceived(BMessage *msg); + TransferWindow(BHandler* target); + TransferWindow(BHandler* target, Account* src, Account* dest, const Fixed& amount); + void MessageReceived(BMessage* msg); void SetMessage(BMessage msg); private: friend class TransferFilter; - void InitObject(Account *src, Account *dest, const Fixed &amount); + void InitObject(Account* src, Account* dest, const Fixed& amount); void HandleOKButton(void); - BTextControl *fMemo; - DateBox *fDate; - CurrencyBox *fAmount; + BTextControl* fMemo; + DateBox* fDate; + CurrencyBox* fAmount; BButton *fCancel, *fOK; BStringView *fFromLabel, *fToLabel;