This is gnucash-design.info, produced by makeinfo version 4.0 from
gnucash-design.texinfo.


INFO-DIR-SECTION Programming

START-INFO-DIR-ENTRY
* gnucash: (gnucash-design).       Design of the GnuCash program
END-INFO-DIR-ENTRY


   This file documents the design of the GnuCash program.

   Copyright 2000 Gnumatic Incorporated

   This is Edition 1.7.0, last updated 13 August 2001, of the `GnuCash
Design Document', version 1.7.0.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with the
Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts
being LIST, and with the Back-Cover Texts being LIST.  A copy of the
license is included in the section entitled "GNU Free Documentation
License".


File: gnucash-design.info,  Node: Top,  Next: GNU Free Documentation License,  Prev: (dir),  Up: (dir)

GnuCash Design Document
***********************

   This is Edition 1.7.0, last updated 13 August 2001, of the `GnuCash
Design Document', version 1.7.0.

* Menu:

* GNU Free Documentation License::
* Introduction::
* Top Level::
* Engine::
* Component Manager::
* Register::
* Reports::
* User Preferences::
* Function Index::
* Data Type Index::
* Concept Index::


 --- The Detailed Node Listing ---

Engine

* Engine Introduction::
* Using and Extending the Engine API::
* Globally Unique Identifiers::
* Numeric Library::
* Key-Value Pair Frames::
* Events::
* Commodities::
* Commodity Tables::
* Prices::
* Price Databases::
* Splits::
* Transactions::
* Accounts::
* Account Groups::
* GNCBooks::
* Scrub::

Globally Unique Identifiers

* When to use GUIDs::
* GUID Types::
* How to use GUIDs::
* GUIDs and GnuCash Entities::
* The GUID Generator::

Numeric Library

* Standard Numeric Arguments::
* Creating Numeric Objects::
* Basic Arithmetic Operations::
* Numeric Comparisons and Predicates::
* Numeric Denominator Conversion::
* Numeric Floating Point Conversion::
* Numeric String Conversion::
* Numeric Error Handling ::
* Numeric Example::

Key-Value Pair Frames

* Key-Value Policy::
* kvp_frame::
* kvp_value::
* kvp_list::

Events

* Event API::

Commodities

* General Commodity API::
* Commodity Getters::
* Commodity Setters::

Commodity Tables

* General Commodity Table API::
* Commodity Table Access API::
* Commodity Table Modification API::

Prices

* Price Implementation Details::
* General Price API::
* Price Getters::
* Price Setters::

Price Databases

* Price Lists::
* General Price Database API::

Splits

* General Split API::
* Split Getters::
* Split Setters::

Transactions

* General Transaction API::
* Transaction Getters::
* Transaction Setters::

Accounts

* Account Types::
* General Account API::
* Account Type API::
* Account Getters::

Account Groups

* General Account Group API::
* Account Group Account API::

GNCBooks

* GNCBook API::

Component Manager

* Component Manager Introduction::

Register

* Cells::
* Cellblocks::
* Table::
* Split Register::

Cells

* BasicCell::

Reports

* Creating a Report::

User Preferences

* Option Databases::
* Option Types::
* Option Creation::
* Option Values::


File: gnucash-design.info,  Node: GNU Free Documentation License,  Next: Introduction,  Prev: Top,  Up: Top

GNU Free Documentation License
******************************

                        Version 1.1, March 2000

     Copyright (C) 2000  Free Software Foundation, Inc.
         59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.

Preamble
========

   The purpose of this License is to make a manual, textbook, or other
written document "free" in the sense of freedom: to assure everyone the
effective freedom to copy and redistribute it, with or without
modifying it, either commercially or noncommercially.  Secondarily,
this License preserves for the author and publisher a way to get credit
for their work, while not being considered responsible for
modifications made by others.

   This License is a kind of "copyleft", which means that derivative
works of the document must themselves be free in the same sense.  It
complements the GNU General Public License, which is a copyleft license
designed for free software.

   We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does.  But this License is not limited to software manuals; it
can be used for any textual work, regardless of subject matter or
whether it is published as a printed book.  We recommend this License
principally for works whose purpose is instruction or reference.

APPLICABILITY AND DEFINITIONS
=============================

   This License applies to any manual or other work that contains a
notice placed by the copyright holder saying it can be distributed
under the terms of this License.  The "Document", below, refers to any
such manual or work.  Any member of the public is a licensee, and is
addressed as "you".

   A "Modified Version" of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.

   A "Secondary Section" is a named appendix or a front-matter section
of the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall subject
(or to related matters) and contains nothing that could fall directly
within that overall subject.  (For example, if the Document is in part a
textbook of mathematics, a Secondary Section may not explain any
mathematics.)  The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding them.

   The "Invariant Sections" are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License.

   The "Cover Texts" are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
the Document is released under this License.

   A "Transparent" copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the general
public, whose contents can be viewed and edited directly and
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input to
text formatters.  A copy made in an otherwise Transparent file format
whose markup has been designed to thwart or discourage subsequent
modification by readers is not Transparent.  A copy that is not
"Transparent" is called "Opaque".

   Examples of suitable formats for Transparent copies include plain
ASCII without markup, Texinfo input format, LaTeX input format, SGML or
XML using a publicly available DTD, and standard-conforming simple HTML
designed for human modification.  Opaque formats include PostScript,
PDF, proprietary formats that can be read and edited only by
proprietary word processors, SGML or XML for which the DTD and/or
processing tools are not generally available, and the machine-generated
HTML produced by some word processors for output purposes only.

   The "Title Page" means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page.  For works in
formats which do not have any title page as such, "Title Page" means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.

VERBATIM COPYING
================

   You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License.  You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute.  However, you may accept
compensation in exchange for copies.  If you distribute a large enough
number of copies you must also follow the conditions in section 3.

   You may also lend copies, under the same conditions stated above, and
you may publicly display copies.

COPYING IN QUANTITY
===================

   If you publish printed copies of the Document numbering more than
100, and the Document's license notice requires Cover Texts, you must
enclose the copies in covers that carry, clearly and legibly, all these
Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts
on the back cover.  Both covers must also clearly and legibly identify
you as the publisher of these copies.  The front cover must present the
full title with all words of the title equally prominent and visible.
You may add other material on the covers in addition.  Copying with
changes limited to the covers, as long as they preserve the title of
the Document and satisfy these conditions, can be treated as verbatim
copying in other respects.

   If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.

   If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a publicly-accessible computer-network location containing a complete
Transparent copy of the Document, free of added material, which the
general network-using public has access to download anonymously at no
charge using public-standard network protocols.  If you use the latter
option, you must take reasonably prudent steps, when you begin
distribution of Opaque copies in quantity, to ensure that this
Transparent copy will remain thus accessible at the stated location
until at least one year after the last time you distribute an Opaque
copy (directly or through your agents or retailers) of that edition to
the public.

   It is requested, but not required, that you contact the authors of
the Document well before redistributing any large number of copies, to
give them a chance to provide you with an updated version of the
Document.

MODIFICATIONS
=============

   You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release the
Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy of
it.  In addition, you must do these things in the Modified Version:

  A. Use in the Title Page (and on the covers, if any) a title distinct
     from that of the Document, and from those of previous versions
     (which should, if there were any, be listed in the History section
     of the Document).  You may use the same title as a previous version
     if the original publisher of that version gives permission.

  B.  List on the Title Page, as authors, one or more persons or
     entities responsible for authorship of the modifications in the
     Modified Version, together with at least five of the principal
     authors of the Document (all of its principal authors, if it has
     less than five).

  C. State on the Title page the name of the publisher of the Modified
     Version, as the publisher.

  D.  Preserve all the copyright notices of the Document.

  E. Add an appropriate copyright notice for your modifications
     adjacent to the other copyright notices.

  F. Include, immediately after the copyright notices, a license notice
     giving the public permission to use the Modified Version under the
     terms of this License, in the form shown in the Addendum below.

  G. Preserve in that license notice the full lists of Invariant
     Sections and required Cover Texts given in the Document's license
     notice.

  H. Include an unaltered copy of this License.

  I. Preserve the section entitled "History", and its title, and add to
     it an item stating at least the title, year, new authors, and
     publisher of the Modified Version as given on the Title Page.  If
     there is no section entitled "History" in the Document, create one
     stating the title, year, authors, and publisher of the Document as
     given on its Title Page, then add an item describing the Modified
     Version as stated in the previous sentence.

  J. Preserve the network location, if any, given in the Document for
     public access to a Transparent copy of the Document, and likewise
     the network locations given in the Document for previous versions
     it was based on.  These may be placed in the "History" section.
     You may omit a network location for a work that was published at
     least four years before the Document itself, or if the original
     publisher of the version it refers to gives permission.

  K. In any section entitled "Acknowledgements" or "Dedications",
     preserve the section's title, and preserve in the section all the
     substance and tone of each of the contributor acknowledgements
     and/or dedications given therein.

  L. Preserve all the Invariant Sections of the Document, unaltered in
     their text and in their titles.  Section numbers or the equivalent
     are not considered part of the section titles.

  M. Delete any section entitled "Endorsements".  Such a section may
     not be included in the Modified Version.

  N. Do not retitle any existing section as "Endorsements" or to
     conflict in title with any Invariant Section.

   If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant.  To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.

   You may add a section entitled "Endorsements", provided it contains
nothing but endorsements of your Modified Version by various
parties-for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.

   You may add a passage of up to five words as a Front-Cover Text, and
a passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version.  Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or through
arrangements made by) any one entity.  If the Document already includes
a cover text for the same cover, previously added by you or by
arrangement made by the same entity you are acting on behalf of, you
may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.

   The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.

COMBINING DOCUMENTS
===================

   You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice.

   The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy.  If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number.
Make the same adjustment to the section titles in the list of Invariant
Sections in the license notice of the combined work.

   In the combination, you must combine any sections entitled "History"
in the various original documents, forming one section entitled
"History"; likewise combine any sections entitled "Acknowledgements",
and any sections entitled "Dedications".  You must delete all sections
entitled "Endorsements."

COLLECTIONS OF DOCUMENTS
========================

   You may make a collection consisting of the Document and other
documents released under this License, and replace the individual
copies of this License in the various documents with a single copy that
is included in the collection, provided that you follow the rules of
this License for verbatim copying of each of the documents in all other
respects.

   You may extract a single document from such a collection, and
distribute it individually under this License, provided you insert a
copy of this License into the extracted document, and follow this
License in all other respects regarding verbatim copying of that
document.

AGGREGATION WITH INDEPENDENT WORKS
==================================

   A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, does not as a whole count as a Modified Version of
the Document, provided no compilation copyright is claimed for the
compilation.  Such a compilation is called an "aggregate", and this
License does not apply to the other self-contained works thus compiled
with the Document, on account of their being thus compiled, if they are
not themselves derivative works of the Document.

   If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one quarter
of the entire aggregate, the Document's Cover Texts may be placed on
covers that surround only the Document within the aggregate.  Otherwise
they must appear on covers around the whole aggregate.

TRANSLATION
===========

   Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections.  You may include a
translation of this License provided that you also include the original
English version of this License.  In case of a disagreement between the
translation and the original English version of this License, the
original English version will prevail.

TERMINATION
===========

   You may not copy, modify, sublicense, or distribute the Document
except as expressly provided for under this License.  Any other attempt
to copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License.  However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such parties
remain in full compliance.

FUTURE REVISIONS OF THIS LICENSE
================================

   The Free Software Foundation may publish new, revised versions of
the GNU Free Documentation License from time to time.  Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.  See
http://www.gnu.org/copyleft/.

   Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation.  If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.

ADDENDUM: How to use this License for your documents
====================================================

   To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and license
notices just after the title page:

     Copyright (c)  YEAR  YOUR NAME.
     Permission is granted to copy, distribute and/or modify this document
     under the terms of the GNU Free Documentation License, Version 1.1
     or any later version published by the Free Software Foundation;
     with the Invariant Sections being LIST THEIR TITLES, with the
     Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
     A copy of the license is included in the section entitled "GNU
     Free Documentation License".

   If you have no Invariant Sections, write "with no Invariant Sections"
instead of saying which ones are invariant.  If you have no Front-Cover
Texts, write "no Front-Cover Texts" instead of "Front-Cover Texts being
LIST"; likewise for Back-Cover Texts.

   If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License, to
permit their use in free software.


File: gnucash-design.info,  Node: Introduction,  Next: Top Level,  Prev: GNU Free Documentation License,  Up: Top

Introduction
************

   This document defines the design and architecture of the GnuCash
program, an application for tracking finances. GnuCash is composed of
several subsystems or modules. This document describes each module,
specifying its interface and, where appropriate, its implementation, as
well as describing the interactions between each module.

Who Should Read This Document?
==============================

   Anyone who plans on making a significant change or addition to
GnuCash's functionality should read this document. By adhering to the
structure presented here, your contribution will be more likely to work
correctly with existing and future features.

Goals
=====

   GnuCash is intended to be a finance and accounting program for
individuals and small businesses. As such, it should have the following
primary features:

   * A sound underlying model for financial entities such as currencies,
     transactions, and accounts.

   * A user interface which provides an efficient way to accomplish
     common tasks, such as transaction entry, account reconciliation,
     etc.

   * The ability to generate and print standard financial reports such
     as Income Statements, Balance Sheets, etc.

   * The ability to generate and print graphs of financial information.


   A more comprehensive list of current and planned features for GnuCash
is located at `http://cvs.gnucash.org/linux/gnucash/projects.html'.


File: gnucash-design.info,  Node: Top Level,  Next: Engine,  Prev: Introduction,  Up: Top

Architectural Overview
**********************

   GnuCash is written primarily in two languages: C and Scheme. The
engine/server is written in C primarily for speed, portability,
stability and historical purposes. Much of the day-to-day workhorse code
is written in Scheme, primarily for its power, expressiveness and ease
of development.  The user interface is Gtk/Gnome, some of it written in
C, some in scheme, and some with the GUI designer tool Glade
`glade.pn.org'.

   GnuCash is modular, thereby allowing separate individuals to
maintain, develop and enhance certain modules without disturbing the
overall development. (Never mind that modules help avoid spaghetti code
and nasty, ugly hacks).  The interfaces between modules are documented,
and, for the most part, stable and unchanging.

   GnuCash currently consists of the following modules:

The Engine
==========

   The "Engine" (located under the `src/engine' directory in the
GnuCash codebase) provides an interface for creating, manipulating, and
destroying three basic financial entities: Accounts, Transactions (known
as Journal Entries in accounting practice), and Splits (known as Ledger
Entries). These three entities are the central data structures of the
GnuCash financial data model.

   The Engine code contains no GUI code whatsoever.

Query
-----

   The "Query" module (`src/engine/Query.*') provides an interface into
the engine for finding transactions based on a set of criteria, such as
description, date posted, account membership, etc. Simple queries can
be combined using standard boolean operators.

File I/O
--------

   The "File I/O" module (`src/engine/FileIO.*') provides an interface
for reading and writing a set of Accounts, Transactions, and Splits to
a binary file. This module is deprecated.

XML I/O
-------

   The "XML I/O" module (`src/engine/*xml*.*' and
`src/engine/*sixtp*.*') provides an interface for reading and writing
the engine information to an XML format.

Backend
-------

   The "Backend" module (`src/engine/Backend*.*') provides hooks to
allow different modules to be used for storing and retrieving Engine
data. There are two backends currently under development, a Postgresql
backend (`src/engine/sql/*') and an RPC backend (`src/engine/rpc/*').

The Register
============

   The "Register" (`src/register') implements a ledger-like GUI that
allows the user to dynamically enter dates, prices, memos descriptions,
etc. in an intuitive fashion that should be obvious to anyone who's
used a checkbook register. The code is highly configurable, allowing
the ledger columns and rows to be laid out in any way, with no
restrictions on the function, type, and number of columns/rows. For
example, one can define a ledger with three date fields, one price
field, and four memo fields in a straightforward fashion. Cell handling
objects support and automatically validate date entry, memo entry
(w/auto-completion), prices, combo-boxes (pull-down menus), and
multi-state check-boxes. Cells can be marked read-write, or
output-only. Cells can be assigned unique colors. The currently active
ledger row-block can be highlighted with a unique color.

   The register code is completely independent of the engine code, knows
nothing about accounting or any of the other GnuCash subsystems. It can
be used in independent projects that have nothing to do with accounting.

Reports
=======

   The "Reports" module (`src/scm/report.scm', `src/scm/reports') is a
scheme (guile) based system to create balance sheets, profit & loss
statements, etc. by using the engine API to fetch and display data
formatted in HTML.

   For the most part, this module uses the Query API to fetch the engine
information instead of using the raw engine interface. This design uses
Queries to extract the data and assemble it into a view-independent
format. This data is then be converted to HTML reports and/or graphs
such as bar and pie charts.

Graphs
======

   The "Graphs" module implements GUI graphs such as bar and pie
charts. These graphs can be interactive in that the user can, for
example, move pie wedges, and 'live' in that the user can click on graph
subsections to see a detail graph or report of that particular
subsection.

   This module is implemented using the GUPPI library being developed by
Jon Trowbridge (<http://www.gnome.org/guppi>).

Price Quotes
============

   The "Price Quotes" module (`src/quotes') is a Perl system to fetch
stock price data off the Internet and insert it into the GnuCash
Engine. This module requires the functionality of the Finance::Quote
module available at SourceForge. The Finance::Quote module can fetch
price quotes from many different sources including Yahoo, Yahoo Europe,
and some international exchanges.

   The Finance::Quote module also supports fetching currency exchange
rates. GnuCash will be extended to allow the fetching and use of
currency exchange rates.

User Preferences
================

   The "User Preferences" module (`src/scm/options.scm',
`src/scm/prefs.scm') provides an infrastructure for defining both
user-configurable and internal preferences. Preferences are defined in
scheme using several predefined preference types such as boolean,
string, date, etc. Preferences are 'implemented' by providing a GUI
which allows the user to see and change preference values. An API is
provided to query preference values and to register callbacks which
will be invoked when preferences change.

   Preference values which are different from the default values are
stored as scheme forms in a user-specific preferences file
(`~/.gnucash/config.auto'). This file is automatically loaded upon
startup.

QIF Import
==========

   The "QIF Import" module (`src/scm/qif-import') provides
functionality for importing QIF (Quicken Interchange Format) data into
GnuCash.

GnuCash
=======

   The GnuCash module (`src/gnome', `src/register/gnome' and
`src/*.[ch]') is the main GUI application. It consists of a collection
of miscellaneous GUI code to glue together all of the pieces above into
a coherent, point-and-click whole. It is meant to be easy to use and
intuitive to the novice user without sacrificing the power and
flexibility that a professional might expect. When people say that
GnuCash is trying to be a "Quicken or MS Money look/work/act-alike",
this is the piece that they are referring to. It really is meant to be
a personal-finance manager with enough power for the power user and the
ease of use for the beginner.

   Currently, the Gnome interface is the only operational interface.
There is an obsolete Motif interface which is not maintained and which
is removed in current CVS. There is also old Qt code (removed in current
CVS) which won't compile, and most/all functions are missing.


File: gnucash-design.info,  Node: Engine,  Next: Component Manager,  Prev: Top Level,  Up: Top

Engine
******

   The Engine provides an interface to a financial engine with three
basic financial entities: Accounts, Transactions (known as Journal
Entries in accounting practice), and Splits (known as Ledger Entries).
These three entities are the central data structures of the GnuCash
financial data model.

   In addition, the Engine provides the abstraction of Account Groups
(collections of related accounts) and GNCBooks. A GNCBook abstracts both
a set of related GnuCash data (financial entities plus additional
information such as budgets, per-file preferences, etc.) plus a
file-editing session allowing transparent support for locking and
implementation with other backends such as SQL.

   The Engine code contains no GUI code whatsoever and is designed to
be created as a shared library for use by other programs.

* Menu:

* Engine Introduction::
* Using and Extending the Engine API::
* Globally Unique Identifiers::
* Numeric Library::
* Key-Value Pair Frames::
* Events::
* Commodities::
* Commodity Tables::
* Prices::
* Price Databases::
* Splits::
* Transactions::
* Accounts::
* Account Groups::
* GNCBooks::
* Scrub::


File: gnucash-design.info,  Node: Engine Introduction,  Next: Using and Extending the Engine API,  Prev: Engine,  Up: Engine

Introduction
============

   Splits (*note Splits::), or "Ledger Entries" are the fundamental
accounting units. Each Split consists of a quantity (number of dollar
bills, number of shares, etc.), the value of that quantity expressed in
a (possibly) different currency than the quantity, a Memo, a pointer to
the parent Transaction, a pointer to the debited Account, a reconciled
flag and timestamp, an "Action" field, and a key-value frame which can
store arbitrary data (*note Key-Value Pair Frames::).

   Transactions (*note Transactions::) embody the notion of "double
entry" accounting. A Transaction consists of a date, a description, a
number, a list of one or more Splits, and a key-value frame. When
double-entry rules are enforced, the total value of the splits is zero.
Note that if there is just one split, its value must be zero for
double-entry accounting; this used to be used for storing prices, but
with the advent of the Price DB, this is no longer the case. If there
are two splits, then the value of one must be positive, the other
negative: this denotes that one account is debited, and another is
credited by an equal amount. Positive Split values are 'debits' and
negative Split values are 'credits'. Ensuring the Splits to 'add up' to
zero causes a double-entry accounting system to always balance.

   The engine does not enforce double-entry accounting, but provides an
API to enable user-code to find unbalanced transactions and 'repair'
them so that they are in balance. *Note Scrub::.

   Note the sum of the values of Splits in a Transaction is always
computed with respect to a currency; thus splits can be balanced even
when they are in different currencies, as long as they share a common
currency.  This feature allows currency-trading accounts to be
established.

   Every Split must point to its parent Transaction, and that
Transaction must in turn include that Split in the Transaction's list
of Splits. A Split can belong to at most one Transaction. These
relationships are enforced by the engine. The engine user cannnot
accidentally destroy this relationship as long as they stick to using
the API and never access internal structures directly.

   Splits are grouped into Accounts (*note Accounts::) which are also
known as "Ledgers" in accounting practice. Each Account consists of a
list of Splits that debit that Account. To ensure consistency, if a
Split points to an Account, then the Account must point to the Split,
and vice-versa.  A Split can belong to at most one Account. Besides
merely containing a list of Splits, the Account structure also give the
Account a name, a code number, description and notes fields, a
key-value frame, a pointer to the currency that is used for all splits
in this account, and a pointer to the "security" used for all splits in
this account. The "security" can be the name of a stock (e.g. "IBM",
"McDonald's"), or another currency (e.g. "USD", "GBP").  The security
is used during Transaction balancing to enable trading between accounts
denominated in different currencies, or to, for example, move stocks
from one Account to another.

   Accounts can be arranged in a hierarchical tree. The nodes of the
tree are called "Account Groups" (*note Account Groups::). By accounting
convention, the value of an Account is equal to the value of all of its
Splits plus the value of all of its sub-Accounts.


File: gnucash-design.info,  Node: Using and Extending the Engine API,  Next: Globally Unique Identifiers,  Prev: Engine Introduction,  Up: Engine

Using and Extending the Engine API
==================================

   Engine API calls are named using a specific convention. For example,
the function to access the Memo field of a Split is `xaccSplitGetMemo'.
The prefix `xacc' comes first(1), followed by the name of the entity
for which the API call applies (`Split'), followed by the action
performed by the call (`Get'), followed by the name of the field being
accessed (`Memo'). Future API calls should conform to this naming
convention.

   The formal arguments to Engine API calls always begin with the
entity to which the call applies. Thus, the arguments to
`xaccSplitSetMemo' are the `Split' pointer followed by the pointer to a
memo string. Future API calls should also conform to this convention.

   Engine API calls should be implemented to behave as gracefully as
possible with unexpected input. Specifically, public API calls should
gracefully handle `NULL' pointer arguments. User code should be able to
handle `NULL' return values from Engine calls as well.

   ---------- Footnotes ----------

   (1) The `xacc' prefix is a historical artifact. GnuCash was derived
from X-Accountant by Robin Clark.


File: gnucash-design.info,  Node: Globally Unique Identifiers,  Next: Numeric Library,  Prev: Using and Extending the Engine API,  Up: Engine

Globally Unique Identifiers
===========================

   It is common for Engine structures to reference other Engine
structures.  For example, an Account must reference its Splits, its
parent Account Group, and its child Account Group. Furthermore, other
GnuCash modules may need to reference Engine structures. For example, a
GUI implementation may wish to save a list of Accounts which the user
has open when the application exits in order to restore that same state
upon the next invocation.

   One way to uniquely identify an Engine structure, at least while the
program is running, is using the C pointer which points to the
structure. C pointers have the advantage of speed, but also have some
disadvantages:

   * Pointers cannot be used in data files and are not persistant across
     different program invocations.

   * When an entity is destroyed, every other structure which
     references that entity through a direct pointer must be
     immediately updated to prevent illegal accesses.


   The "GUID" (Globally Unique Identifier) provides a way to reference
Engine structures that is more flexible than C pointers. Each Engine
structure has an associated GUID which can be used to reference that
structure. Engine GUIDs have the following features:

   * The GUID is permanent, i.e., it persists between invocations of
     GnuCash.

   * The GUID is guaranteed to be unique with the set of all Splits,
     Transactions, and Accounts in the hierarchy of which the structure
     is a member.

   * With very high probability, the GUID is unique among all GUIDs
     created by any invocation of GnuCash, all over the world.

   * GUIDs can be efficiently encoded in a string representation.


* Menu:

* When to use GUIDs::
* GUID Types::
* How to use GUIDs::
* GUIDs and GnuCash Entities::
* The GUID Generator::


File: gnucash-design.info,  Node: When to use GUIDs,  Next: GUID Types,  Prev: Globally Unique Identifiers,  Up: Globally Unique Identifiers

When to use GUIDs
-----------------

   Although GUIDs are very flexible, the engine structures like Accounts
will probably continue to use C pointers for the forseeable future,
since they are much faster (and in certain respects more convenient)
than using GUIDs. In general, however, it is much safer to use GUIDs.
In particular, you should consider using GUIDs if any of the following
is true:

   * You need to save a reference to an engine structure in a file.

   * You need to save a reference to an engine structure that could be
     deleted in between accesses to the saved reference.



File: gnucash-design.info,  Node: GUID Types,  Next: How to use GUIDs,  Prev: When to use GUIDs,  Up: Globally Unique Identifiers

GUID Types
----------

   The GUIDs in GnuCash are typed using the enum `GNCIdType'.  Possible
values and their meanings for GUID types are:

`GNC_ID_NONE'
     The GUID does not currently refer to a GnuCash entity, though it
     could refer to one in the future.

`GNC_ID_NULL'
     The GUID does not, and never will, refer to a GnuCash entity.

`GNC_ID_ACCOUNT'
     The GUID refers to an Account (*note Accounts::).

`GNC_ID_TRANS'
     The GUID refers to a Transation (*note Transactions::).

`GNC_ID_SPLIT'
     The GUID refers to a Split (*note Splits::).

 - Function: GNCIdType xaccGUIDType (const GUID * GUID)
     Return the type associated with GUID.

 - Function: const GUID * xaccGUIDNull (void)
     Return a GUID which is guaranteed to always have type
     `GNC_ID_NULL'.


File: gnucash-design.info,  Node: How to use GUIDs,  Next: GUIDs and GnuCash Entities,  Prev: GUID Types,  Up: Globally Unique Identifiers

How to use GUIDs
----------------

   The Engine API functions which access the GUID for a specific entity
return a pointer to the GUID. *Note:* Do not store the pointer itself!
Instead, store a copy of the GUID. Storing the pointer itself would
present some of the same problems as using the account pointer
directly. Example:

     {
       GUID saved_guid;
       Account *account;
     
       account = < something to get an Account pointer >
     
       saved_guid = *xaccAccountGetGUID(account);
     
       ...
     
       account = xaccAccountLookup(&saved_guid);
     
       ...
     }

   You can compare two GUIDs with the following functions.

 - Function: gboolean guid_equal (const GUID * GUID_1, const GUID *
          GUID_2)
     Compare two guids and return TRUE if they are both non-NULL and
     equal.

 - Function: gint guid_compare (const GUID * G1, const GUID * G2)
     Return the `memcmp' of the two GUID's.

   You can encode and decode GUIDs and their string representations
using the next two functions.

 - Function: char * guid_to_string (const GUID * GUID)
     Return a null-terminated string encoding of GUID. String encodings
     of identifiers are hex numbers printed only with the characters `0'
     through `9' and `a' through `f'.  The encoding will always be
     `GUID_ENCODING_LENGTH' characters long. The returned string should
     be freed when no longer needed.

 - Function: char * guid_to_string_buff (const GUID * GUID, char * BUFF)
     This routine does the same work as `guid_to_string', except that
     the string is written into the memory pointed at by BUFF. The
     buffer must be at least GUID_ENCODING_LENGTH+1 characters long.
     This routine is handy for avoiding a malloc/free cycle.  It
     returns a pointer to the _end_ of what was written.  (i.e. it can
     be used like `stpcpy' during string concatenation)

 - Function: gboolean string_to_guid (const char * STRING, GUID * GUID)
     Given a string, decode an id into GUID if GUID is non-NULL. The
     function returns TRUE if the string was a valid 32 character
     hexadecimal number. This function accepts both upper and lower
     case hex digits. If the return value is FALSE, the effect on GUID
     is undefined.

   You can allocate and deallocate space for GUIDs using standard
memory routines. However, if your code is allocating and deallocating
lots of GUID objects, then the next two functions should be used.

 - Function: GUID * xaccGUIDMalloc (void)
     Return newly allocated memory for a GUID object. The memory must
     be freed with `xaccGUIDFree'. In general, this function is faster
     than using the standard libc allocators.

 - Function: void xaccGUIDFree (GUID * GUID)
     Free the space for a GUID that was allocated with `xaccGUIDMalloc'.

   You can use the following two functions to aid in using GUIDS in hash
tables.

 - Function: guint guid_hash_to_guint (gconstpointer PTR)
     Return a hash value suitable for use with a `GHashTable'.  PTR
     must point to a GUID.

 - Function: GHashTable * guid_hash_table_new (void)
     Return a new `GHashTable' which uses GUIDs as keys.


File: gnucash-design.info,  Node: GUIDs and GnuCash Entities,  Next: The GUID Generator,  Prev: How to use GUIDs,  Up: Globally Unique Identifiers

GUIDs and GnuCash Entities
--------------------------

   This section documents a low-level API for associating entities with
GUIDs. User code and general engine code should not use this API;
instead use the API documented in the sections for the specific GnuCash
entities such as Accounts and Transactions.

 - Function: void xaccGUIDNew (GUID * GUID)
     Generate a new guid. This function is guaranteed to return a guid
     that is unique within the scope of all GnuCash entities being
     managed by the the current invocation of GnuCash. GnuCash routines
     should always use this function and not `guid_new'!

 - Function: void * xaccLookupEntity (const GUID * GUID, GNCIdType
          ENTITY_TYPE)
     Lookup an entity given an id and a type. If there is no entity
     associated with the id, or if it has a different type, NULL is
     returned.

 - Function: void xaccStoreEntity (void * ENTITY, const GUID * GUID,
          GNCIdType entity_type)
     Store the given entity under the given id with the given type.

 - Function: void xaccRemoveEntity (const GUID * GUID)
     Remove any existing association between an entity and the given
     id. The entity is not changed in any way.


File: gnucash-design.info,  Node: The GUID Generator,  Prev: GUIDs and GnuCash Entities,  Up: Globally Unique Identifiers

The GUID Generator
------------------

   GUIDs are created by the GUID generator. The API for this generator
is low-level and should not be used by user-code.

 - Function: void guid_init (void)
     Initialize the GUID generator with a variety of random sources
     including common system files and /dev/random.

 - Function: void guid_init_with_salt (const void * SALT, size_t
          SALT_LEN)
     Initialize the GUID generator with guid_init() and with the given
     sequence of arbitrary binary data.

 - Function: void guid_init_only_salt (const void * SALT, size_t
          SALT_LEN)
     Initialize the GUID generator using only the given sequence of
     arbitrary binary data. This provides a way to reliably obtain a
     given sequence of GUIDs.

 - Function: void guid_new (GUID * GUID)
     Create a new GUID and store it in GUID. This is a low-level
     function!  GnuCash code should use `xaccGUIDNew'.


File: gnucash-design.info,  Node: Numeric Library,  Next: Key-Value Pair Frames,  Prev: Globally Unique Identifiers,  Up: Engine

Numeric Library
===============

   Financial quantities in GnuCash (Split quantities and values) are
stored as exact quantities measured in the smallest denominational unit
of the appropriate currency. For example, 100.50 US Dollars would be
stored as (10050 / 100) US Dollars. GnuCash uses the `gnc_numeric'
datatype to store financial quantities.

   The `gnc_numeric' API provides data types and functions for
manipulating exact numeric quantities. While the `gnc_numeric' library
was developed to represent and operate on exact financial quantities in
GnuCash, the library is also (hopefully) suitable for use in any
application where exact numeric representation for rational numbers is
needed.

   A `gnc_numeric' value represents a number in rational form, with a
64-bit `long long' integer as numerator and denominator. If more
precision, a higher-precision representation of irrational numbers, or a
wider dynamic range is needed, a floating point format may be
appropriate. There are reasonable rational approximations to common
irrational constants (*note Numeric Example::), but the transcendental
functions have not been implemented for `gnc_numeric' objects.

* Menu:

* Standard Numeric Arguments::
* Creating Numeric Objects::
* Basic Arithmetic Operations::
* Numeric Comparisons and Predicates::
* Numeric Denominator Conversion::
* Numeric Floating Point Conversion::
* Numeric String Conversion::
* Numeric Error Handling ::
* Numeric Example::

