# The NCReport C++ API

This file explains how to use the API; [api-index.md](api-index.md) lists every exported class and member with its
exact signature. Names and signatures below are from the NCReport 2.36 headers (`src/ncreport/ncreport.h` and neighbors). When the
user's headers are available, they win over this file.

Guide: [Using the NCReport API](https://docs.ncreport.org/ncreport/2.36/api/api.html),
[Report outputs](https://docs.ncreport.org/ncreport/2.36/advanced/outputs.html),
[Data sources](https://docs.ncreport.org/ncreport/2.36/advanced/datasources.html).

## The run cycle

```cpp
#include "ncreport.h"

NCReport report;                                   // QObject; a stack object or a parent keeps it tidy
report.setReportFile("reports/invoice.ncr");       // or setReportDefXml(xmlString)
report.addParameter("invoiceId", 1042);            // QVariant; $P{invoiceId} in the template
report.runReportToPdfWriter("invoice.pdf");        // run methods return void...
if (report.hasError())                             // ...so always check afterwards
    qWarning() << report.lastErrorMsg();
```

- A `QApplication` must exist, even for PDF output without a window (the engine uses QtWidgets). Not
  `QGuiApplication` or `QCoreApplication`.
- Add parameters, models, string lists and custom data sources **before** running: the template is read at the
  start of each run and resolves them then.
- One `NCReport` object can run many times; `reset()` / `reset(true)` clears what was added (see below).

## Report source

| Call | Use |
| --- | --- |
| `void setReportFile(const QString& file, bool saveToApp = true)` | Template file path, or a Qt resource path (`":/reports/x.ncr"`) |
| `void setReportDefXml(const QString& xml)` | Template XML as a string. `setReportDef(xml)` is the obsolete name |
| `void setReportSourceType(NCReportSource::ReportSourceType)` | `File`, `Database`, `Http`, `Ftp`, `Custom`, `String` |
| `NCReportSource* reportSource() const` | For a database source: `setConnectionID`, `setTableName`, `setColumnName`, `setKeyColumnName`, `setKeyValue` |
| `void setReportSourceFactory(NCReportSourceFactory*)` | Your own source; set it before any other source call |

## Output methods

All are slots on `NCReport` that run the report and return `void`, except `runReport()`.

```cpp
void runReportToPdfWriter(const QString& filename, int dpi = 600, bool overwrite = true, PdfVersion version = Pdf1_4,
                          const QString& creator = QString(), const QString& title = QString(),
                          const QByteArray& xmpMetaData = QByteArray());
void runReportToPdfWriter(QIODevice* device, int dpi = 600, PdfVersion version = Pdf1_4,
                          const QString& creator = QString(), const QString& title = QString(),
                          const QByteArray& xmpMetaData = QByteArray());
void runReportToPdf(const QString& filename, bool overwrite = true, PdfVersion version = Pdf1_4,
                    const QString& creator = QString());                       // QPrinter based
void runReportToPrinter(int copies = 1, bool showdialog = true, QWidget* parent = nullptr,
                        const QString& printerName = QString(), const QString& docName = QString());
void runReportToPrinterNoDialog(int copies, const QString& printerName, const QString& docName = QString());
void runReportToSVG(const QString& filename);                 // one file per page: name_p1.svg, ...
void runReportToImage(const QString& filename);               // one file per page; format from the extension
void runReportToHtml(const QString& filename, int strategy = 0, const QString& cssFile = QString());
void runReportToExcelHtml(const QString& filename);
void runReportToText(const QString& filename, const QString& templateFileName);
bool runReport();                                             // with an output set by setOutput()
void cancel();
// Only when the engine has the preview module (NCR_PREVIEW_MODULE, the default):
void runReportToModernPreview(int dpi, const QString& outputFileName, QWidget* parent);   // no defaults
void runReportToPreview();                                    // classic preview: renders, shows nothing
QWidget* runReportToShowPreview(QWidget* parent = nullptr, bool maximized = false);
void runReportToQtPreview(QWidget* parent);                   // QPrintPreviewDialog
```

`PdfVersion` is `NCReport::Pdf1_4`, `NCReport::PdfA1b` or `NCReport::Pdf1_6`.

Choosing:

- **PDF:** prefer `runReportToPdfWriter()`. It uses `QPdfWriter`, needs no QPrinter (works on Android and without
  print support), writes to a file or any `QIODevice` (e.g. a `QBuffer` for an HTTP response) and sets the PDF title
  and XMP metadata. The title defaults to the report name; there are no author, subject or keyword setters.
- **Preview:** `runReportToModernPreview(0, QString(), parentWidget)` shows the modern preview dialog (since 2.32),
  modal, rendering exactly like the PDF and printer output. `dpi` 0 uses the report's resolution;
  `outputFileName` is the suggested name for saving.
- The classic preview window (`runReportToPreview()` + `NCReportPreviewWindow`, or `runReportToShowPreview()`) is
  still supported; use it when the user's code already does, or when they need its window features.

These names do **not** exist; don't write them: `runReportToPDF`, `runReportToXls`, `runReportToExcel`,
`runReportToPreviewDialog`, `NCReportPreviewWidget`, `setReportSource(NCReportSource::File)`.

### Classic preview window

```cpp
#include "ncreportpreviewoutput.h"
#include "ncreportpreviewwindow.h"

report->runReportToPreview();
if (report->hasError()) {
    QMessageBox::warning(this, tr("Report error"), report->lastErrorMsg());
} else {
    auto *pv = new NCReportPreviewWindow();
    pv->setOutput(static_cast<NCReportPreviewOutput*>(report->output()));  // the window owns the output now
    pv->setReport(report);              // print/PDF from the window re-runs the report: keep `report` alive
    pv->setWindowModality(Qt::ApplicationModal);
    pv->setAttribute(Qt::WA_DeleteOnClose);
    pv->exec();
}
```

The preview output is not deleted by `NCReport`. Hand it to the window (which deletes it) or delete it yourself.
`runReportToShowPreview()` does all of this in one call and returns the window, which deletes itself on close.

### Your own output object

```cpp
#include "ncreportpdfwriteroutput.h"

auto *out = new NCReportPdfWriterOutput("report.pdf");
out->setPdfVersion(NCReport::Pdf1_4);   // always set it when constructing the output yourself
out->setDpi(600);
report.setOutput(out);                  // auto-delete by default: NCReport deletes it
report.runReport();
```

Output classes: `NCReportPdfWriterOutput`, `NCReportPdfOutput`, `NCReportPrinterOutput`, `NCReportSvgOutput`,
`NCReportImageOutput`, `NCReportHtmlOutput`, `NCReportExcelHtmlOutput`, `NCReportTextOutput`,
`NCReportPreviewOutput`. Each has a header named after it in lower case (`ncreportsvgoutput.h`).

## Errors and progress

- `bool hasError()`, `QString lastErrorMsg()`: check after every run.
- `bool reportDone() const`, `int runTimeElapsed() const` (ms). `int pageCount() const` (like `$V{pagecount}`)
  is only filled in double pass mode, and only when the template has a `<pagefooter>`; otherwise it is 0.
- Signals: `reportStarts()`, `reportEnds()`, `dataRowProgress(int row)` and `dataRowProgress(const QString& dsID, int row)`
  (overloaded: connect with `QOverload<int>::of(&NCReport::dataRowProgress)`), `dataRowCount(int)`,
  `pageProgress(int)`, `sectionProgress(const QString&)`, `batchReportRunning(int)`, `customizePrinter(QPrinter*)`,
  `reportDefChange(NCReportDef*)`.
- `cancel()` stops a run; call `setProcessEvents(true)` first so a UI button can be clicked during the run.
  A cancelled run still finishes the output (partial file).

## Data from the application

```cpp
// SQL: open the connection first; the template's connID names it (empty or "default" = the default connection)
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", "shop");
db.setHostName("localhost"); db.setDatabaseName("shop"); /* … */ db.open();
report.setConnectionName("shop");                  // optional: forces this connection on every SQL data source

// Qt item model:  <datasource id="items" type="model" modelID="itemsModel"/>
report.addItemModel(model, "itemsModel");          // matched by modelID, not by the data source id

// String list:   <datasource id="lines" type="list" listID="lines" columnDelimiter="tab"/>
report.addStringList(QStringList{"Apple\t3", "Pear\t5"}, "lines");   // columns col0, col1, …

// Parameter:     $P{customer} in queries, fields (ftype="par") and scripts
report.addParameter("customer", QStringLiteral("ACME Ltd"));
```

- Item model columns are matched by the horizontal header text (`Qt::EditRole`), or `col0`, `col1`, …. The data role
  defaults to EditRole; column suffixes pick others: `name:d` DisplayRole, `:u` UserRole, `:c` decoration, `:h…`
  header roles.
- Models, views and string lists are **not** owned by `NCReport`; keep them alive for the whole run.

### Custom data source

Subclass `NCReportDataSource` (`ncreportdatasource.h`) when the data comes from your own objects:

```cpp
class OrderDataSource : public NCReportDataSource
{
public:
    explicit OrderDataSource(const QList<Order>& orders, QObject* parent = nullptr)
        : NCReportDataSource(parent), m_orders(orders)
    {
        setID("orders");                           // must equal <datasource id="orders" type="custom">
        setDataSourceType(Custom);
        setLocationType(Static);
    }
    bool open() override { recno() = 0; setOpened(true); return true; }
    bool close() override { setOpened(false); return true; }
    bool first() override { recno() = 0; return !m_orders.isEmpty(); }
    bool last() override { recno() = m_orders.size() - 1; return !m_orders.isEmpty(); }
    bool next() override
    {
        if (recno() + 1 >= m_orders.size()) { flagEnd() = true; return false; }
        ++recno(); flagBegin() = false; return true;
    }
    bool previous() override { if (recno() <= 0) return false; --recno(); return true; }
    bool hasNext() override { return recno() < m_orders.size() - 1; }
    bool seek(int index) override
    {
        if (index == -1) return true;                  // -1: stay on the current row
        if (index < 0 || index >= m_orders.size()) return false;
        recno() = index; return true;
    }
    int size() const override { return m_orders.size(); }
    bool isValid() const override { return recno() >= 0 && recno() < m_orders.size(); }

    // Required in practice: the engine finds a column with columnIndexByName(), which the base class implements
    // with columnCount() and columnName(). Without these two every field stays empty, with no error.
    int columnCount() const override { return columns().size(); }
    QString columnName(int column) const override { return columns().value(column); }

    QVariant value(int column, bool* ok = nullptr, int = -1) const override
    {
        if (ok) *ok = isValid();
        if (!isValid()) return {};
        const Order& o = m_orders.at(recno());
        switch (column) {
        case 0: return o.id;
        case 1: return o.customer;
        case 2: return o.amount;
        }
        if (ok) *ok = false;
        return {};
    }
    QVariant value(const QString& column, bool* ok = nullptr, int role = -1) const override
    {
        return value(columns().indexOf(column), ok, role);
    }
private:
    static const QStringList& columns() { static const QStringList c{"id", "customer", "amount"}; return c; }
    QList<Order> m_orders;
};

auto *ds = new OrderDataSource(orders, &report);   // the application owns custom data sources
report.addCustomDataSource(ds);
```

Fields read the value with `value(int column, …)` after looking the column up with `columnIndexByName()`;
`value(const QString&, …)` is only used when `columnIndexByName()` returns -2. So implement `columnCount()` and
`columnName()` (or override `columnIndexByName()`), or every field of the data source prints empty.
`recno()` returns `int&` and is protected; there are also `flagBegin()`, `flagEnd()` and `setOpened()`. Compare with
`src/runner/testdatasource.cpp` in the source package. For data sources created on demand use
`setCustomDataSourceFactory(NCReportDataSourceFactory*)`, whose `createCustomDataSource(const QString& dsID)` returns
a new data source.

## Report options from code

Options and page settings are read from the template on every run, so changing `reportDef()->option()` before the
run is overwritten. Change them after the template is loaded: connect to `reportDefChange(NCReportDef*)`, or
override the protected `virtual void customizeReportDef(NCReportDef*)` in a subclass.

```cpp
connect(&report, &NCReport::reportDefChange, [](NCReportDef* def) {
    def->option().setDoublePassMode(true);              // $V{pagecount} (the template needs a <pagefooter>)
    def->option().setOutputFileBaseName("invoice-1042");
});
```

Other settings: `setCurrentLanguage("de")` (translated labels), `setCountry(QLocale::Country)`,
`setPageRanges("1-3,5")`, `setForceCopies(int)`, `setShowWaitCursor(bool)`, `setRootDir(path)` (the `{ROOT}`
placeholder in paths).

## Custom formatting, items and functions

- **Format callback (2.33):** `report.reportDef()->setFormatCallback(...)` (include `ncreportdef.h`), with a
  `std::function<bool(NCReportData::DataType, const QVariant& value, QString& result)>`. Return true when you set
  `result`; false falls back to the built-in formatting. Applies to fields, not cross-table cells. It stays set
  across runs.
- **Custom painted item:** subclass `NCReportGraphRenderer` (`ncreportgraphrenderer.h`) and implement
  `void paintItem(QPainter* painter, NCReportOutput* output, const QRectF& rect, const QString& itemdata)`.
  Call `setID("chart1")` **before** `report.addGraphItemRenderer(renderer)`; the template's
  `<graph classID="chart1">` item uses it. Not owned by `NCReport`. (`NCReportAbstractItemRendering` and
  `addItemRenderingClass` are obsolete.)
- **User function:** subclass `NCReportUserFunction`, implement
  `void updateValue(NCReportItem* item, NCReportOutput* output, NCReportEvaluator* evaluator)`, register it with
  `report.addUserFunction("fn1", fn)` and set `funcID="fn1"` on the item.
- **Printing a `QTableView`/`QTreeView`:** `report.addItemView("view1", ui->tableView)` (id first) and
  `report.addItemModel(ui->tableView->model(), "model1")`; the template's `<table>` item names them in `tableView`
  and `model`.

## Batch: several reports in one output

```cpp
report.addReportToBatch("reports/cover.ncr");                       // a string ending in .ncr/.xml is a file
report.addReportToBatch("reports/detail.ncr", {{"year", 2026}});   // with its own parameters
report.runReportToPdfWriter("all.pdf");
report.clearBatch();
```

## Resetting between runs

`reset()` clears the run state; `reset(true)` also clears parameters, string lists, user functions, renderers and
the batch. The detailed overload is
`reset(bool clearRenderers, bool clearParameters, bool clearUserFunctions, bool clearStringLists, bool clearBatchReports, bool keepCustomDataSources = true)`.
Item models, item views and the format callback are not cleared.
