Compare commits

...
6 Commits
Author SHA1 Message Date
berrux-dev 6e7b09cf6f Remove include/ entries and LogView files unused by the release-scope build
Audited the release-scope compilation (TetraIF, Z/src, Lts/Common +
TrainingAreaBase, BUILD_RTI=OFF) for every file under include/:

Removed (zero references from release-scope sources or CMake):
- service-stub header dirs (AlarmManagement, AreaEffectSimulation,
  AssetManagement, AudioVideoManagement, Core, ExerciseEventManagement,
  ExerciseManagement, GuezNasat, InfrastructureManagement, Lts,
  LtsProjectionWorkstation, LtsScriptTimeline, LtsSession,
  MarkerManagement, NotificationManagement, OperatorManagement,
  ParticipantManagement, ProjectDataManagement, ReportManagement,
  Services, SituationReplay, TopicEditorBase, Viewer)
- include/grantlee (codegen modules excluded from the release build)
- include/nglapplication (all headers duplicate Z/src/nglapplication)
- include/poppler (Qt5 header; the build includes poppler/qt6 from the
  system package)
- include/rti (142 Connext DDS headers; only consumers are behind
  BUILD_RTI, which is OFF for this branch)
- TetraIF/LogView zsksxd_tetraForLogView{,_guez}.cpp and
  zsksxd_tetraForLogView_guez.x (the build compiles the .x; the guez
  variant is referenced nowhere; LogView loads the .x from the app dir)

Kept (actively included): include/GeographicLib, include/LtsUtilsGuiDds,
include/NGLLogger.

Also drop the now-dangling include_directories for the removed dirs in
the top-level CMakeLists (include/Viewer/SituationMap) and
Lts/CMakeLists.txt (six stub dirs) - otherwise GCC warns
-Wmissing-include-dirs for every compile.

Verified with a full pipeline rebuild (scope-rebuild15): 0 warnings,
ctest baseline unchanged, all 5 DEBs produced.
2026-10-14 16:51:32 +02:00
berrux-dev 11501ff7bb Drop the rti_license.dat requirement from the release scope build
The release validation scope (TetraIF, Z/src, Lts/Common +
TrainingAreaBase) never consumes an RTI license: no CMake file or
build step reads RTI_LICENSE_FILE, and the only RTI Connext DDS
consumers are all behind BUILD_RTI (OFF for this branch, stubs
compiled instead). The license was pure plumbing:

- new_docker_build.sh: remove the require_file validation, the
  bind mount and the in-container RTI_LICENSE_FILE export
- jenkins-ci-rme: remove the RTI_LICENSE_FILE export and the
  Jenkinsfile workspace-layout comment
- README: document that no license file is needed

Verified with a full pipeline rebuild (scope-rebuild12) run while
rti_license.dat was absent: 0 warnings, ctest baseline unchanged,
all 5 DEBs produced, none of them containing the license.
2026-10-14 16:28:03 +02:00
berrux-dev 59f0c025e5 Add a step-by-step build and test README for the release scope
Document the full flow: prebuilt Docker image build, release-scope
compilation (mandatory CMake flags), running the unit tests (ctest
baseline plus direct execution of the test binaries), DEB package
production with the in-tree rpmbuild script, the Jenkins/CI entry
points, the options reference and troubleshooting notes.
2026-10-14 16:28:03 +02:00
berrux-dev cebc456bc1 Add unit tests for the TetraIF modules in a unit-test folder
New TetraIF/unit-test/ directory with one QtTest executable per
TetraIF release-scope module, wired into ctest and the DEB pipeline:

- coprtcnv_unit_test: central and radio telegram header fields,
  payload access, length checks, fragmentation/reassembly roundtrip,
  telegram-id string helpers
- logview_unit_test: IntegerCalculator arithmetic, operator priority,
  parentheses, error codes and variables (compiles the LogView class
  source directly; the class otherwise lives in the LogView
  executable)
- prtcnv_unit_test: PrtCnvMember state and fragmented-telegram
  handling (compiles the class source directly because PrtCnvLib is
  built with hidden visibility)

TetraIF/CMakeLists.txt adds the unit-test subdirectory and
new_docker_build.sh builds and ctest-runs the three new targets.
2026-10-14 16:28:03 +02:00
berrux-dev 2d1b12b5d8 Copy jenkins-ci-rme into the source tree and adapt it to this project
- Jenkinsfile: guez-only release pipeline; the prebuilt build image is
  built from the in-tree Dockerfile (via new_docker_build.sh
  --build-prebuilt-image) instead of a pre-pulled harbor image; the
  builder runs inside the container with the workspace mounted at
  /workspace; the post-publish cleanup stage was dropped so the DEBs
  stay under ${WORKSPACE}/rpms/... (the documented output location)
- jenkins_builder_ubuntu26.sh: uses the in-tree rpmbuild/
  make_rpm_ubuntu26.py instead of the outer-repo copy; same-file guard
  on the packages-out copy (host output dir == make_rpm output dir)
- jenkins_publisher_ubuntu26.sh: uploads rpms/${PROJECT}/${OS_VERSION}/
  directly - make_rpm_ubuntu26.py writes the DEBs there without a TDS
  subfolder
- release-16-10-2026.sh: local driver adapted to the current
  new_docker_build.sh interface (drops the no-longer-existing
  --use-prebuilt-image option, builds the image on demand, outputs to
  ${WORKSPACE}/rpms/${PROJECT}/${OS_VERSION}/)
- make_rpm_ubuntu26.py: stage the new jenkins-ci-rme/ files (Jenkinsfile,
  builder, publisher) into the build-pipeline DEB (release-16-10-2026.sh
  was already listed)

Not copied (superseded): openSUSE builder/publisher, the old Dockerfile
recipes (replaced by the in-tree Dockerfile), Bitbucket notification
(jenkins_notifier.sh is not part of this project)
2026-10-14 16:28:03 +02:00
berrux-dev bf3fecf5c0 Use the Jenkins-style DEB output path and fix the copy to the packages-out mount
- Document --package-output-dir "${WORKSPACE}/rpms/${PROJECT}/${OS_VERSION}/"
  (Jenkins convention) in the usage examples
- The in-container copy step now copies to the real mount point
  /workspace/packages-out instead of ${PACKAGE_OUTPUT_DIR}, which is a host
  path that does not exist inside the container (the copy was a silent
  no-op; packages reached the host directly via make_rpm's
  --output_dir /workspace/rpms/... on the workspace mount)
- Skip the copy when the host output directory is the same directory as
  make_rpm's output dir (stat device:inode guard) - which is exactly the
  case for the Jenkins-style path above, where make_rpm already writes the
  packages in place
2026-10-14 16:28:03 +02:00
240 changed files with 1171 additions and 55096 deletions

No files matched your search

@@ -154,7 +154,6 @@ include_directories(${CMAKE_BINARY_DIR}/Lts/Common/LtsUtils/LtsUtilsCore)
# only that generated header, so appending it cannot shadow an existing include.
include_directories(${CMAKE_BINARY_DIR}/Lts/Common/LtsUtils/LtsUtilsSettings)
include_directories(${CMAKE_SOURCE_DIR}/Z/src/NGLLogger)
include_directories(${CMAKE_SOURCE_DIR}/include/Viewer/SituationMap)
SET(CMAKE_CXX_STANDARD 17)
SET(CMAKE_CXX_STANDARD_REQUIRED ON)
SET(CMAKE_VISIBILITY_INLINES_HIDDEN ON)
@@ -63,15 +63,9 @@ IF(NOT RELEASE_BUILD)
INCLUDE(MacroCodeGenIdl)
ENDIF()
# Add stub headers for non-RTI/non-FilterManagement builds
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/AudioVideoManagement/)
# Export headers included by bare name from module sources (release scope)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/NGLLogger/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/LtsSession/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/TopicEditorBase/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/OperatorManagement/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/LtsScriptTimeline/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/LtsUtilsGuiDds/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../include/Services/PresentationManagement/)
IF(NOT RELEASE_BUILD)
CODEGEN_WRITE_SERVICEFILE_INFO()
+242
View File
@@ -0,0 +1,242 @@
# qt6-migrated-legatus — compile and run (step by step)
Build guide for the Qt6-migrated legatus tree on the release
**validation-scope** branch. Everything runs inside a prebuilt Docker
image; the host only needs Docker.
## Scope and layout
The release scope built by `new_docker_build.sh` is:
| Area | Contents |
|---|---|
| `TetraIF/` | `CoPrtCnv`, `LogView`, `PrtCnv` (+ `unit-test/` — see below) |
| `Z/src/` | NGL application/core library stack (NGLLogger, nglcoreapplication, …) |
| `Lts/Common/` | LTS common libraries (LtsCoordTrans, LtsLicence, …) |
| `Lts/Proxies/TrainingAreaBase` | built as a dependency of TetraIF |
Useful entries at the tree root:
- `new_docker_build.sh` — the build driver (image build, compile, ctest, DEB packaging)
- `Dockerfile` — recipe of the prebuilt build image (Ubuntu 26.04 + Qt 6.10.2 + deps)
- `rpmbuild/make_rpm_ubuntu26.py` — in-tree DEB package producer (self-contained)
- `jenkins-ci-rme/` — in-tree copy of the Jenkins CI flow (see its own `README.md`)
- `build4/` — build tree, created by the driver (git-ignored scratch area)
Toolchain inside the image: **Ubuntu 26.04, GCC 15.2.0, Qt 6.10.2**
(`/opt/Qt/6.10.2/gcc_64`), C++17, Release build.
## Prerequisites
1. **Docker** available on the host.
2. The tree must be reachable inside the container at
`/workspace/qt-migration-legatus/qt6-after/qt6-migrated-legatus`, i.e.
mount the pipeline root on `/workspace` — this is how
`new_docker_build.sh` invokes Docker, so running the driver as-is
satisfies this.
No license file is required: this branch builds the release scope only
(TetraIF, Z/src, Lts/Common) with `BUILD_RTI=OFF`, so the RTI Connext
DDS modules (the only consumers of an RTI license) are not compiled.
`new_docker_build.sh` resolves the pipeline root from its own location
(override with the exported `MIGRATE_PIPELINE_ROOT` or the `.envrc` in
this directory).
All commands below are run **from this directory** (`qt6-migrated-legatus/`).
## Step 1 — Build the prebuilt Docker image (once)
```bash
./new_docker_build.sh --build-prebuilt-image --docker-image legatus-qt6:1.0
```
This builds the image from the in-tree `Dockerfile` (Ubuntu 26.04 base,
apt deps, Qt 6.10.2 via `aqtinstall`, KDReports from source). Re-run it
only after changing the `Dockerfile` or the `APT_PACKAGES` list in
`new_docker_build.sh`.
To remove it later:
```bash
./new_docker_build.sh --delete-prebuilt-image --docker-image legatus-qt6:1.0
```
## Step 2 — Compile the release scope
```bash
./new_docker_build.sh --docker-image legatus-qt6:1.0
```
What the driver does inside the container:
1. `rm -rf build4 && mkdir build4 && cd build4` (fresh build tree)
2. Configure with CMake — the mandatory flags:
```bash
cmake .. \
-DBUILD_TESTING=ON \
-DBUILD_ARCGIS=OFF \
-DRELEASE_BUILD=ON \
-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_PREFIX_PATH=/opt/Qt/6.10.2/gcc_64:/usr/local
```
(`BUILD_ARCGIS` and `RELEASE_BUILD` override CMake defaults that do
not match this branch.)
3. `make -j8` the release-scope targets (TetraIF modules, Z stack,
Lts/Common libs, all test executables — the list is
`RELEASE_BUILD_TARGETS` in `new_docker_build.sh`).
4. Run **ctest** (see Step 3).
Output to inspect after the run:
- `build4/release_build.log` — full make output (the build must end with
**0 warnings**)
- `build4/bin/` — executables (apps + test binaries)
- `build4/lib/` — shared libraries
To rebuild incrementally without a fresh tree, run `make` directly in an
interactive container (Step 4).
## Step 3 — Run the tests
### 3.1 ctest (automatic)
`new_docker_build.sh` already runs `ctest --test-dir build4
--output-on-failure` after the compile. Expected baseline (8 tests):
| # | Test | Result |
|---|---|---|
| 1 | `coprtcnv_unit_test` | Passed |
| 2 | `logview_unit_test` | Passed |
| 3 | `prtcnv_unit_test` | Passed |
| 4 | `nglcomp_test` | **Not Run** (pre-existing: compression "Unknown error" in Qt6) |
| 5 | `NGLToolsQtSmoke` | Passed |
| 6 | `test_nglpdfwidget` | Passed |
| 7 | `lts_coord_trans_unit_test` | Passed |
| 8 | `aes_crypt_test` | Passed |
`nglcomp_test` being *Not Run* is the expected baseline — the pipeline
logs a ctest failure for it but continues.
### 3.2 Build the unit tests only
```bash
docker run --rm -v /path/to/pipeline-root:/workspace legatus-qt6:1.0 \
bash -c 'cd /workspace/qt-migration-legatus/qt6-after/qt6-migrated-legatus/build4 \
&& make -j8 coprtcnv_unit_test logview_unit_test prtcnv_unit_test'
```
### 3.3 Run a test executable directly
GUI-free tests need the offscreen Qt platform in a headless container:
```bash
docker run --rm -it -v /path/to/pipeline-root:/workspace legatus-qt6:1.0 \
bash -c 'export QT_QPA_PLATFORM=offscreen
cd /workspace/qt-migration-legatus/qt6-after/qt6-migrated-legatus/build4
./bin/coprtcnv_unit_test # CoPrtCnv: telegrams, fragmentation, helpers
./bin/logview_unit_test # LogView: IntegerCalculator
./bin/prtcnv_unit_test # PrtCnv: PrtCnvMember fragmented-telegram handling
./bin/lts_coord_trans_unit_test
./bin/aes_crypt_test
./bin/test_nglpdfwidget
# or everything registered:
ctest --output-on-failure'
```
Each QtTest binary accepts a single slot name to run just one test,
e.g. `./bin/coprtcnv_unit_test radioTelegramFragmentationRoundtrip`.
### 3.4 TetraIF unit tests (this tree, `TetraIF/unit-test/`)
| Test | Module covered | Note |
|---|---|---|
| `coprtcnv_unit_test` | `CoPrtCnv` — central & radio telegram header fields, payload access, length checks, fragmentation/reassembly roundtrip, id→string helpers | links `CoPrtCnv` |
| `logview_unit_test` | `LogView` — `IntegerCalculator` (arithmetic, precedence, error codes, variables) | compiles `LogView/IntegerCalculator.cpp` into the test (the class otherwise lives in the LogView executable) |
| `prtcnv_unit_test` | `PrtCnv` — `PrtCnvMember` state + fragmented-telegram add/reassembly | compiles `PrtCnv/PrtCnvMember.cpp` into the test because `PrtCnvLib` is built with hidden visibility (its symbols are not linkable from outside) |
Sources are registered with ctest via `TetraIF/unit-test/CMakeLists.txt`
and packaged into the ctest DEBs (see Step 4).
## Step 4 — Produce the release DEB packages
```bash
export WORKSPACE=/path/to/pipeline-root # e.g. ~/release/qt6-migration-pipeline
export PROJECT=guez
export OS_VERSION=26.04
./new_docker_build.sh --docker-image legatus-qt6:1.0 \
--run-jenkins-builder \
--package-output-dir "${WORKSPACE}/rpms/${PROJECT}/${OS_VERSION}/" \
> /path/to/build.log 2>&1
```
(export the variables *before* the command — command-prefix variables are
not expanded in the same command's arguments.)
The driver compiles the release scope, runs ctest, then stages the tree
and runs the in-tree `rpmbuild/make_rpm_ubuntu26.py`, which produces 5
DEBs in `${WORKSPACE}/rpms/${PROJECT}/${OS_VERSION}/`:
| DEB | Contents |
|---|---|
| `qt6-release-runtime_*` | runtime libraries + the release-scope executables |
| `qt6-release-sources_*` | release-scope sources |
| `qt6-release-ctest-runtime_*` | test executables under `/usr/lib/ctest/` (incl. the TetraIF unit tests) |
| `qt6-release-ctest-sources_*` | test sources (files with "test" in the name under the release dirs, incl. `TetraIF/unit-test/*.cpp`) |
| `qt6-release-build-pipeline_*` | the in-tree pipeline files (`new_docker_build.sh`, `Dockerfile`, `rpmbuild/`, `jenkins-ci-rme/`) under `/usr/src/pipeline/` |
Verify a package:
```bash
dpkg -c "${WORKSPACE}/rpms/guez/26.04/qt6-release-ctest-runtime_1.0-1_amd64.deb" \
| grep unit_test
dpkg -i "${WORKSPACE}/rpms/guez/26.04/"*.deb # install locally, if wanted
```
A copy of the DEBs is also placed in the container's
`/workspace/packages-out` mount (same-file skip guarded by device:inode).
## Step 5 — CI / Jenkins flow (optional)
The in-tree `jenkins-ci-rme/` directory contains the full Jenkins
pipeline (`Jenkinsfile`, builder, publisher) adapted to this tree. For a
local dry run of the same flow without Jenkins:
```bash
jenkins-ci-rme/release-16-10-2026.sh
```
See `jenkins-ci-rme/README.md` for the pipeline details.
## Options reference
`./new_docker_build.sh --help` prints the full option list. The main
ones:
| Option | Default | Purpose |
|---|---|---|
| `--docker-image IMAGE` | `legatus-qt6-prebuilt:latest` | image to use/build/delete |
| `--build-prebuilt-image` | — | build the image from `./Dockerfile` and exit |
| `--delete-prebuilt-image` | — | delete the image and exit |
| `--run-jenkins-builder` | off | produce the DEB packages (Step 4) |
| `--package-output-dir DIR` | `./packages-out` | where the DEBs are written |
| `--lts-version / --project / --build-number / --build-tag` | `1.0` / `guez` / `1` / `manual-build` | package metadata |
Environment overrides: `DOCKER_IMAGE`, `RUN_JENKINS_BUILDER`,
`PACKAGE_OUTPUT_DIR`, `PROJECT`, `LTS_VERSION`, `GUEZ_MODE`,
`BUILD_NUMBER`, `BUILD_TAG`, `MIGRATE_PIPELINE_ROOT`.
## Troubleshooting
- **"no Qt platform plugin could be initialized"** when running a test
binary by hand → `export QT_QPA_PLATFORM=offscreen`.
- **ctest fails with `nglcomp_test (Not Run)`** → expected baseline
(pre-existing Qt6 compression issue); the pipeline continues.
- **Stale build tree** → the driver always recreates `build4/`; for
manual builds delete `build4/` and rerun Step 2 if CMake behaves oddly.
- **DEBs not on the host** → the output dir must be a path that exists
*on the host* (it is bind-mounted into the container as
`/workspace/packages-out`); check the `package-output-dir` argument.
@@ -7,3 +7,4 @@
ADD_SUBDIRECTORY(CoPrtCnv)
ADD_SUBDIRECTORY(LogView)
ADD_SUBDIRECTORY(PrtCnv)
ADD_SUBDIRECTORY(unit-test)
@@ -1 +0,0 @@
zsksxd_tetraForLogView.x
@@ -1 +0,0 @@
zsksxd_tetraForLogView_guez.x
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
#
# Unit tests for the TetraIF modules (CoPrtCnv, LogView, PrtCnv).
# One test executable per module, each registered with ctest.
#
# LogView: the module's classes are compiled into the LogView executable,
# so the test compiles the pure class source (IntegerCalculator) directly
# instead of linking a library.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- CoPrtCnv: telegram classes and helpers --------------------------------
if (TARGET CoPrtCnv)
ADD_EXECUTABLE(coprtcnv_unit_test coprtcnv_unit_test.cpp)
TARGET_LINK_LIBRARIES(coprtcnv_unit_test
CoPrtCnv
NGLLogger
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME coprtcnv_unit_test COMMAND $<TARGET_FILE:coprtcnv_unit_test>)
endif()
# --- LogView: IntegerCalculator --------------------------------------------
ADD_EXECUTABLE(logview_unit_test
logview_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../LogView/IntegerCalculator.cpp)
TARGET_LINK_LIBRARIES(logview_unit_test
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME logview_unit_test COMMAND $<TARGET_FILE:logview_unit_test>)
# --- PrtCnv: PrtCnvMember (fragmented telegram handling) --------------------
# PrtCnvLib is built with hidden visibility, so the test compiles the class
# source directly instead of linking the library.
if (TARGET CoPrtCnv)
ADD_EXECUTABLE(prtcnv_unit_test
prtcnv_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../PrtCnv/PrtCnvMember.cpp)
TARGET_LINK_LIBRARIES(prtcnv_unit_test
CoPrtCnv
NGLLogger
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME prtcnv_unit_test COMMAND $<TARGET_FILE:prtcnv_unit_test>)
endif()
@@ -0,0 +1,175 @@
//
// Unit tests for the CoPrtCnv module: central telegram, radio telegram
// (header fields, payload access, fragmentation) and the string helpers.
//
#include <CoPrtCnv/CoPrtCnvCentralTelegram.hpp>
#include <CoPrtCnv/CoPrtCnvHexDumpHelper.hpp>
#include <CoPrtCnv/CoPrtCnvLogHeader.hpp>
#include <CoPrtCnv/CoPrtCnvRadioTelegram.hpp>
#include <CoPrtCnv/tetra_telegram_ids.h>
#include <TrainingAreaBase/training_area_telegrams.h>
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtCore/QByteArray>
#include <QtTest/QTest>
#include <memory>
#include <vector>
class coprtcnv_unit_test : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void centralTelegramFromId();
void centralTelegramDataRoundtrip();
void centralTelegramCounter();
void radioTelegramSourceIssi();
void radioTelegramDestIssi();
void radioTelegramIdentity();
void radioTelegramCounter();
void radioTelegramPayloadBytes();
void radioTelegramLengthChecks();
void radioTelegramFragmentationRoundtrip();
void radioTelegramLoginVsNormal();
void telegramIdToString();
void wirkfeldTypToString();
};
void coprtcnv_unit_test::initTestCase()
{
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false);
}
void coprtcnv_unit_test::centralTelegramFromId()
{
N_CoPrtCnv::CoPrtCnvCentralTelegram tele(TrainingAreaBase::TetraIcd::BESTAETIGUNG);
QCOMPARE(tele.telegramId(), TrainingAreaBase::TetraIcd::BESTAETIGUNG);
}
void coprtcnv_unit_test::centralTelegramDataRoundtrip()
{
N_CoPrtCnv::CoPrtCnvCentralTelegram tele(TrainingAreaBase::TetraIcd::BESTAETIGUNG);
const QByteArray data(QByteArrayLiteral("central-telegram-payload"));
tele.setData(data);
QCOMPARE(tele.data(), data);
}
void coprtcnv_unit_test::centralTelegramCounter()
{
N_CoPrtCnv::CoPrtCnvCentralTelegram tele(TrainingAreaBase::TetraIcd::BESTAETIGUNG);
tele.setCounter(42);
QCOMPARE(tele.counter(), 42);
}
void coprtcnv_unit_test::radioTelegramSourceIssi()
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(0x12345678);
QCOMPARE(tele.getSrcISSI(), 0x12345678u);
}
void coprtcnv_unit_test::radioTelegramDestIssi()
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(0x00000001);
tele.setDestISSI(0x87654321);
QCOMPARE(tele.getDestISSI(), 0x87654321u);
}
void coprtcnv_unit_test::radioTelegramIdentity()
{
// Identity is only a field of the DataIndReq payload (the (id, size, identity) constructor); other PDU types have no identity area.
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(GEF_BESTAETIGUNG, 32, 0xBEEF);
QCOMPARE(tele.getIdentity(), 0xBEEF);
}
void coprtcnv_unit_test::radioTelegramCounter()
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(0x00000003);
tele.setZaehler(7);
QCOMPARE(tele.zaehler(), 7);
}
void coprtcnv_unit_test::radioTelegramPayloadBytes()
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(GEF_BESTAETIGUNG, 32, 0x3333);
QCOMPARE(tele.getPayloadSize(), 32);
const uint8_t pattern[4] = {0xDE, 0xAD, 0xBE, 0xEF};
tele.setPayloadData(pattern, 4);
QCOMPARE(tele.getPayloadDataUInt8(3), 0xDE);
QCOMPARE(tele.getPayloadDataUInt8(4), 0xAD);
QCOMPARE(tele.getPayloadDataUInt8(5), 0xBE);
QCOMPARE(tele.getPayloadDataUInt8(6), 0xEF);
// getPayloadDataUInt32 assembles the bytes big endian
QCOMPARE(tele.getPayloadDataUInt32(3, 4), 0xDEADBEEFu);
}
void coprtcnv_unit_test::radioTelegramLengthChecks()
{
// isTelegramLengthOk: length <= MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH
// + DATA_IND_REQ_HEADER_LENGTH - sizeof(GwHeader) - PAYLOAD_STATUS_LENGTH
// = 249 + 27 - 4 - 1 = 271
QVERIFY(N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(271));
QVERIFY(!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(272));
QVERIFY(!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(1000));
}
void coprtcnv_unit_test::radioTelegramFragmentationRoundtrip()
{
// Build a big telegram whose payload must be fragmented, reassemble the
// fragments and compare the payload area against the original data.
const uint16_t payloadSize = 300;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> bigPtr(new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTAETIGUNG, payloadSize, 0x1111));
const int payloadPart = bigPtr->getSize() - N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH;
const uint8_t maxFragPayload = N_CoPrtCnv::CoPrtCnvRadioTelegram::MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH
- N_CoPrtCnv::CoPrtCnvRadioTelegram::PAYLOAD_STATUS_LENGTH;
const uint8_t nbrFragments = static_cast<uint8_t>((payloadPart - 1) / maxFragPayload);
QVERIFY(nbrFragments >= 1);
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> > frags;
std::multimap<uint16_t, N_CoPrtCnv::CoPrtCnvRadioTelegram *> fragList;
for (uint8_t i = 0; i <= nbrFragments; ++i)
{
bool error = true;
auto frag = std::make_shared<N_CoPrtCnv::CoPrtCnvRadioTelegram>(bigPtr, i, error);
QVERIFY2(!error, "fragment creation failed");
frags.push_back(frag);
fragList.insert(std::make_pair(frag->getFragmentCounter(), frag.get()));
}
QCOMPARE(static_cast<int>(fragList.size()), static_cast<int>(nbrFragments) + 1);
const QByteArray unfragmented = N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(fragList);
QVERIFY(!unfragmented.isEmpty());
QCOMPARE(unfragmented.size(), bigPtr->data().size());
QCOMPARE(unfragmented.mid(N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH - 1),
bigPtr->data().mid(N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH - 1));
}
void coprtcnv_unit_test::radioTelegramLoginVsNormal()
{
N_CoPrtCnv::CoPrtCnvRadioTelegram login(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginRequest, 0x2222, 0x00000005);
QVERIFY(login.isLoginTelegram());
QVERIFY(!login.isNormalTelegram());
}
void coprtcnv_unit_test::telegramIdToString()
{
// telegramId2String / wirkfeldTyp2Str are declared in global scope
const QByteArray known = telegramId2String(GEF_BESTAETIGUNG);
QVERIFY(!known.isEmpty());
}
void coprtcnv_unit_test::wirkfeldTypToString()
{
const QString text = wirkfeldTyp2Str(TrainingAreaBase::TetraIcd::AreaEffectSimulationType::BeStillWarning);
QVERIFY(!text.isEmpty());
}
QTEST_MAIN(coprtcnv_unit_test)
#include "coprtcnv_unit_test.moc"
@@ -0,0 +1,150 @@
//
// Unit tests for the LogView module: IntegerCalculator (the module's pure
// logic class, compiled from the LogView sources).
//
#include "../LogView/IntegerCalculator.hpp"
#include <QtTest/QTest>
#include <string>
using IntegerCalculator = N_SST::IntegerCalculator;
using E_Error = IntegerCalculator::E_Error;
class logview_unit_test : public QObject
{
Q_OBJECT
private slots:
void basicArithmetic();
void operatorPriority();
void parentheses();
void unaryMinus();
void divisionByZero();
void noOperandBetweenOperators();
void missingRightParanthesis();
void missingLeftParanthesis();
void unknownVariable();
void variables();
};
void logview_unit_test::basicArithmetic()
{
IntegerCalculator calc;
E_Error error = E_Error::e_UnknownError;
QCOMPARE(calc.calc("1+2", error), 3);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("10-4", error), 6);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("6*7", error), 42);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("84/4", error), 21);
QCOMPARE(error, E_Error::e_Ok);
}
void logview_unit_test::operatorPriority()
{
IntegerCalculator calc;
E_Error error = E_Error::e_UnknownError;
QCOMPARE(calc.calc("1+2*3", error), 7);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("2*3+4", error), 10);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("10-2*3", error), 4);
QCOMPARE(error, E_Error::e_Ok);
}
void logview_unit_test::parentheses()
{
IntegerCalculator calc;
E_Error error = E_Error::e_UnknownError;
QCOMPARE(calc.calc("(1+2)*3", error), 9);
QCOMPARE(error, E_Error::e_Ok);
QCOMPARE(calc.calc("((2+3)*4)", error), 20);
QCOMPARE(error, E_Error::e_Ok);
}
void logview_unit_test::unaryMinus()
{
IntegerCalculator calc;
E_Error error = E_Error::e_UnknownError;
QCOMPARE(calc.calc("-3+5", error), 2);
QCOMPARE(error, E_Error::e_Ok);
}
void logview_unit_test::divisionByZero()
{
IntegerCalculator calc;
E_Error error = E_Error::e_Ok;
(void)calc.calc("1/0", error);
QCOMPARE(error, E_Error::e_DivisionByZero);
}
void logview_unit_test::noOperandBetweenOperators()
{
IntegerCalculator calc;
E_Error error = E_Error::e_Ok;
(void)calc.calc("1+*2", error);
QCOMPARE(error, E_Error::e_NoOperandBetweenOperators);
}
void logview_unit_test::missingRightParanthesis()
{
IntegerCalculator calc;
E_Error error = E_Error::e_Ok;
(void)calc.calc("(1+2", error);
QCOMPARE(error, E_Error::e_MissingRightParanthesis);
}
void logview_unit_test::missingLeftParanthesis()
{
IntegerCalculator calc;
E_Error error = E_Error::e_Ok;
(void)calc.calc("1+2)", error);
QCOMPARE(error, E_Error::e_MissingLeftParanthesis);
}
void logview_unit_test::unknownVariable()
{
IntegerCalculator calc;
E_Error error = E_Error::e_Ok;
(void)calc.calc("y", error);
QCOMPARE(error, E_Error::e_UnknownOperationOrVariable);
}
void logview_unit_test::variables()
{
IntegerCalculator calc;
E_Error error = E_Error::e_UnknownError;
calc.addVariable("x", 5);
QCOMPARE(calc.calc("x*2", error), 10);
QCOMPARE(error, E_Error::e_Ok);
calc.addVariable("y", -3);
QCOMPARE(calc.calc("x+y", error), 2);
QCOMPARE(error, E_Error::e_Ok);
calc.removeVariable("x");
error = E_Error::e_Ok;
(void)calc.calc("x", error);
QCOMPARE(error, E_Error::e_UnknownOperationOrVariable);
}
QTEST_MAIN(logview_unit_test)
#include "logview_unit_test.moc"
@@ -0,0 +1,115 @@
//
// Unit tests for the PrtCnv module: PrtCnvMember (member state and
// fragmented telegram handling / reassembly).
//
#include <PrtCnv/PrtCnvMember.hpp>
#include <CoPrtCnv/CoPrtCnvRadioTelegram.hpp>
#include <CoPrtCnv/tetra_telegram_ids.h>
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtTest/QTest>
#include <memory>
#include <vector>
class prtcnv_unit_test : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void memberDefaults();
void fragmentedListEmptyInitially();
void addAndClearFragments();
void unfragmentationRoundtrip();
};
void prtcnv_unit_test::initTestCase()
{
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false);
}
void prtcnv_unit_test::memberDefaults()
{
PrtCnv::PrtCnvMember member(7, 0x1234);
QCOMPARE(member.m_Id, 7);
QCOMPARE(member.m_ISSI, 0x1234);
QCOMPARE(member.m_ClaimCount, 0);
QCOMPARE(member.m_loggedInExerciseId, 0);
QCOMPARE(member.m_Licensed, false);
}
void prtcnv_unit_test::fragmentedListEmptyInitially()
{
PrtCnv::PrtCnvMember member(1, 0x0001);
QVERIFY(member.isFragmentedListEmpty());
QVERIFY(member.getUnfragmentedTelegramData().isEmpty());
}
void prtcnv_unit_test::addAndClearFragments()
{
const uint16_t payloadSize = 300;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> bigPtr(new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTAETIGUNG, payloadSize, 0x4321));
const int payloadPart = bigPtr->getSize() - N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH;
const uint8_t maxFragPayload = N_CoPrtCnv::CoPrtCnvRadioTelegram::MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH
- N_CoPrtCnv::CoPrtCnvRadioTelegram::PAYLOAD_STATUS_LENGTH;
const uint8_t nbrFragments = static_cast<uint8_t>((payloadPart - 1) / maxFragPayload);
PrtCnv::PrtCnvMember member(1, 0x0001);
QVERIFY(member.isFragmentedListEmpty());
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> > frags;
for (uint8_t i = 0; i <= nbrFragments; ++i)
{
bool error = true;
auto frag = std::make_shared<N_CoPrtCnv::CoPrtCnvRadioTelegram>(bigPtr, i, error);
QVERIFY2(!error, "fragment creation failed");
frags.push_back(frag);
member.addFragmentedTelegram(*frag);
}
QVERIFY(!member.isFragmentedListEmpty());
QCOMPARE(member.getFragmentedTelegramId(), GEF_BESTAETIGUNG);
member.clearFragmentedList();
QVERIFY(member.isFragmentedListEmpty());
}
void prtcnv_unit_test::unfragmentationRoundtrip()
{
// A big telegram with a known payload pattern, fragmented into the member and reassembled
const uint16_t payloadSize = 300;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> bigPtr(new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTAETIGUNG, payloadSize, 0x5678));
QByteArray pattern(payloadSize, 0);
for (int i = 0; i < payloadSize; ++i)
pattern[i] = static_cast<char>(i * 7 + 1);
bigPtr->setPayloadData(reinterpret_cast<const uint8_t *>(pattern.constData()), payloadSize);
const int payloadPart = bigPtr->getSize() - N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH;
const uint8_t maxFragPayload = N_CoPrtCnv::CoPrtCnvRadioTelegram::MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH
- N_CoPrtCnv::CoPrtCnvRadioTelegram::PAYLOAD_STATUS_LENGTH;
const uint8_t nbrFragments = static_cast<uint8_t>((payloadPart - 1) / maxFragPayload);
PrtCnv::PrtCnvMember member(2, 0x0002);
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> > frags;
for (uint8_t i = 0; i <= nbrFragments; ++i)
{
bool error = true;
auto frag = std::make_shared<N_CoPrtCnv::CoPrtCnvRadioTelegram>(bigPtr, i, error);
QVERIFY2(!error, "fragment creation failed");
frags.push_back(frag);
member.addFragmentedTelegram(*frag);
}
const QByteArray unfragmented = member.getUnfragmentedTelegramData();
QCOMPARE(unfragmented.size(), bigPtr->data().size());
QCOMPARE(unfragmented.mid(N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH - 1),
bigPtr->data().mid(N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH - 1));
}
QTEST_MAIN(prtcnv_unit_test)
#include "prtcnv_unit_test.moc"
@@ -1,8 +0,0 @@
#ifndef SVCALMCOMMON_EXPORT_H
#define SVCALMCOMMON_EXPORT_H
// Stub export macro for AlarmManagement
#define SVCALMCOMMON_EXPORT
#define SVCALMCOMMON_NO_EXPORT
#endif // SVCALMCOMMON_EXPORT_H
@@ -1,28 +0,0 @@
// Stub file for aes_enums.hpp - used when BUILD_RTI=OFF
#ifndef AES_ENUMS_HPP
#define AES_ENUMS_HPP
// Minimal stub - actual enums generated by rtiddsgen when BUILD_RTI=ON
namespace AreaEffectSimulation {
// Stub enum definitions for compilation when BUILD_RTI=OFF
enum class SymbolAppearance {
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility {
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition {
double x = 0.0;
double y = 0.0;
};
} // namespace AreaEffectSimulation
#endif // AES_ENUMS_HPP
@@ -1,28 +0,0 @@
// Stub file for asm_enums.hpp - used when BUILD_RTI=OFF
#ifndef ASM_ENUMS_HPP
#define ASM_ENUMS_HPP
#include <cstdint>
namespace AssetManagement {
enum class SymbolAppearance : std::int32_t {
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : std::int32_t {
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition {
double x = 0.0;
double y = 0.0;
double z = 0.0;
};
} // namespace AssetManagement
#endif // ASM_ENUMS_HPP
@@ -1,34 +0,0 @@
/**
* @file avm_enums.hpp
* @brief Stub file for AudioVideoManagement enums (BUILD_RTI=OFF)
*
* This file provides stub definitions when RTI DDS code generation is disabled.
* Replace with generated file when BUILD_RTI=ON.
*/
#ifndef AVM_ENUMS_HPP
#define AVM_ENUMS_HPP
namespace AudioVideoManagement
{
// Stub enum definitions for compilation without RTI DDS
enum class StreamType
{
UNKNOWN = 0,
AUDIO = 1,
VIDEO = 2,
AUDIO_VIDEO = 3
};
enum class ConnectionState
{
DISCONNECTED = 0,
CONNECTING = 1,
CONNECTED = 2,
ERROR = 3
};
} // namespace AudioVideoManagement
#endif // AVM_ENUMS_HPP
@@ -1,24 +0,0 @@
// Stub file for core_enums.hpp - used when BUILD_RTI=OFF
#ifndef CORE_ENUMS_HPP
#define CORE_ENUMS_HPP
#include <cstdint>
namespace Core {
enum class LogLevel : std::int32_t {
Debug = 0,
Info = 1,
Warning = 2,
Error = 3
};
enum class ComponentState : std::int32_t {
Stopped = 0,
Running = 1,
Paused = 2
};
} // namespace Core
#endif // CORE_ENUMS_HPP
@@ -1,24 +0,0 @@
// Stub file for eem_enums.hpp - used when BUILD_RTI=OFF
#ifndef EEM_ENUMS_HPP
#define EEM_ENUMS_HPP
#include <cstdint>
namespace ExerciseEventManagement {
enum class EventState : std::int32_t {
Pending = 0,
Active = 1,
Completed = 2,
Cancelled = 3
};
enum class EventPriority : std::int32_t {
Low = 0,
Medium = 1,
High = 2
};
} // namespace ExerciseEventManagement
#endif // EEM_ENUMS_HPP
@@ -1,27 +0,0 @@
/**
* @RDE_HEADER@
* HMI Plugin for Exercisemanagemt (Interface for access from other Plugins)
*/
#pragma once
#include <PluginInterfaces/data_plugin_interface.h>
#include <ExerciseManagement/exm_dtc.h>
#include <ExerciseManagement/exm_ftc.h>
#include <memory>
namespace ExerciseManagement
{
/**
* @brief The DataInterface class provides the Topics Clients only for the GUI Plugins
*/
class DataInterface : public DataPluginBase::Interface
{
public:
using DataPluginBase::Interface::Interface;
virtual std::shared_ptr<ExerciseManagement::Interface::Dtc> getDtc() = 0;
virtual std::shared_ptr<ExerciseManagement::Interface::Ftc> getFtc() = 0;
};
} // namespace ExerciseManagement
@@ -1,34 +0,0 @@
// Stub file for exm_enums.hpp - used when BUILD_RTI=OFF
#ifndef EXM_ENUMS_HPP
#define EXM_ENUMS_HPP
#include <cstdint>
namespace ExerciseManagement {
enum class ExerciseState : std::int32_t {
Planned = 0,
Running = 1,
Paused = 2,
Finished = 3
};
enum class ExerciseType : std::int32_t {
Training = 0,
Operational = 1,
Test = 2
};
enum class SymbolAppearance : std::int32_t {
Solid = 0,
Outline = 1
};
enum class SymbolVisibility : std::int32_t {
Visible = 0,
Hidden = 1
};
} // namespace ExerciseManagement
#endif // EXM_ENUMS_HPP
@@ -1,33 +0,0 @@
#pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen
#include <QtCore/QString>
#include <ostream>
#include "exmcommon_export.h"
#include "exm_enums.hpp"
namespace ExerciseManagement
{
// STUB: Exercise - wird durch echten DDS-Typ ersetzt
struct EXMCOMMON_EXPORT Exercise
{
int id = 0;
QString m_name;
int phase = 0; // Exercise phase ID
SymbolAppearance symbolAppearance = SymbolAppearance::Solid;
SymbolVisibility symbolVisibility = SymbolVisibility::Visible;
[[nodiscard]] std::string name() const { return m_name.toStdString(); }
// Weitere Felder werden bei Bedarf ergänzt
};
// Stream operator for logging
inline std::ostream& operator<<(std::ostream& os, const Exercise& ex) {
os << "Exercise(id=" << ex.id << ", name=" << ex.m_name.toStdString() << ")";
return os;
}
} // namespace ExerciseManagement
@@ -1,10 +0,0 @@
#pragma once
// Export-Macro für ExerciseManagement Module
// STUB: Wird normalerweise von CMake generiert
#ifdef EXMCOMMON_LIBRARY
#define EXMCOMMON_EXPORT Q_DECL_EXPORT
#else
#define EXMCOMMON_EXPORT Q_DECL_IMPORT
#endif
@@ -1,72 +0,0 @@
#pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen
#include <QtCore/QString>
#include <ostream>
#include "gna_export.h"
namespace GuezNasat
{
// STUB: NasatAircraft - wird durch echten DDS-Typ ersetzt
struct NasatAircraft
{
int idValue = 0;
QString nameValue;
int exerciseIdValue = 0;
int nasatIdValue = 0;
bool simulationActiveValue = false;
// Getter-Methoden für Kompatibilität
int id() const { return idValue; }
QString name() const { return nameValue; }
int exerciseId() const { return exerciseIdValue; }
int nasatId() const { return nasatIdValue; }
bool simulationActive() const { return simulationActiveValue; }
// Stream operator für Logger
friend std::ostream& operator<<(std::ostream& os, const NasatAircraft& aircraft);
};
// STUB: NasatAircraftParticipant - wird durch echten DDS-Typ ersetzt
struct NasatAircraftParticipant
{
int idValue = 0;
int nasatAircraftIdValue = 0;
int exerciseIdValue = 0;
int participantIdValue = 0;
// Getter-Methoden für Kompatibilität
int id() const { return idValue; }
int nasatAircraftId() const { return nasatAircraftIdValue; }
int exerciseId() const { return exerciseIdValue; }
int participantId() const { return participantIdValue; }
// Stream operator für Logger
friend std::ostream& operator<<(std::ostream& os, const NasatAircraftParticipant& participant);
};
} // namespace GuezNasat
// Stream-Operator Implementierung
namespace GuezNasat
{
inline std::ostream& operator<<(std::ostream& os, const NasatAircraft& aircraft)
{
os << "NasatAircraft{id=" << aircraft.id() << ", name=" << aircraft.name().toStdString()
<< ", exerciseId=" << aircraft.exerciseId() << ", nasatId=" << aircraft.nasatId()
<< ", simulationActive=" << aircraft.simulationActive() << "}";
return os;
}
inline std::ostream& operator<<(std::ostream& os, const NasatAircraftParticipant& participant)
{
os << "NasatAircraftParticipant{id=" << participant.id()
<< ", nasatAircraftId=" << participant.nasatAircraftId()
<< ", exerciseId=" << participant.exerciseId()
<< ", participantId=" << participant.participantId() << "}";
return os;
}
} // namespace GuezNasat
@@ -1,5 +0,0 @@
#pragma once
// STUB-HEADER: Diese Datei wird normalerweise von DDS generiert
// NasatAircraftParticipant ist bereits in gna_nasat_aircraft.h definiert
#include "gna_nasat_aircraft.h"
@@ -1,29 +0,0 @@
/**
* @RDE_HEADER@
* Translation helper for GuezNasat module
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
// filename: gna_translation.h
#include <QtCore/QString>
#include <QtCore/QObject>
#include "svcgnacommon_export.h"
namespace GuezNasat
{
/**
* @brief Translation helper function
*
* Wrapper for QObject::tr() to enable translation in non-QObject classes
*/
GNA_COMMON_EXPORT inline QString tr(const char* sourceText, const char* comment = nullptr)
{
return QObject::tr(sourceText, comment);
}
} // namespace GuezNasat
@@ -1,7 +0,0 @@
#ifndef SVCGNACOMMON_EXPORT_H
#define SVCGNACOMMON_EXPORT_H
// Stub export macro for BUILD_RTI=OFF
#define SVCGNACOMMON_EXPORT
#endif // SVCGNACOMMON_EXPORT_H
@@ -1,69 +0,0 @@
// Stub file for ism_enums.hpp - used when BUILD_RTI=OFF
#ifndef ISM_ENUMS_HPP
#define ISM_ENUMS_HPP
#include <cstdint>
namespace InfrastructureManagement {
enum class InfrastructureState : std::int32_t {
Online = 0,
Offline = 1,
Maintenance = 2
};
enum class ConnectionType : std::int32_t {
Wired = 0,
Wireless = 1,
Satellite = 2
};
// DDS-style enum wrapper
struct MountingPointType_def {
enum type : std::int32_t {
Undefined = 0,
Rack = 1,
Shelf = 2,
Slot = 3,
Module = 4,
Port = 5,
Cable = 6,
Connector = 7
};
};
struct MountingPointState_def {
enum type : std::int32_t {
Undefined = 0,
Planned = 1,
Installed = 2,
InService = 3,
OutOfService = 4,
Defect = 5
};
};
// Also provide enum class for direct usage
enum class MountingPointType : std::int32_t {
Undefined = 0,
Rack = 1,
Shelf = 2,
Slot = 3,
Module = 4,
Port = 5,
Cable = 6,
Connector = 7
};
enum class MountingPointState : std::int32_t {
Undefined = 0,
Planned = 1,
Installed = 2,
InService = 3,
OutOfService = 4,
Defect = 5
};
} // namespace InfrastructureManagement
#endif // ISM_ENUMS_HPP
@@ -1,145 +0,0 @@
/**
* @RDE_HEADER@
* The MountingPoint class wraps all information from InfrastructureManagement which defines a mounting point
* $Id$
* $HeadURL$
* $Author$
* Created by Hannes Baeuerle, SLSE, 2017-01-16
*/
#pragma once
#include "ismshared_export.h"
#include "ism.hpp"
#include <QImage>
namespace dds
{
namespace core
{
static inline uint qHash(const InfrastructureManagement::MountingPointType &mpt)
{
return ::qHash(static_cast<int32_t>(mpt));
}
} // namespace core
} // namespace dds
namespace InfrastructureManagement
{
class ISMSHARED_EXPORT MountingPoint
{
public:
explicit MountingPoint();
explicit MountingPoint(const StructureElement &data, int floorId);
static void init();
const StructureElement &data() const { return m_data; }
void updateData(const StructureElement &data, int floorId) { m_data = data; m_floor = floorId; }
int32_t id() const { return m_data.id; }
int32_t associatedAssetId() const { return m_associatedAssetId; }
bool hasAssociatedAsset() const { return m_associatedAssetId > 0; }
bool hasAssociatedAssetDefect() const { return m_hasAssociatedAssetDefect; }
/*! \name aimState depends on the (loaded) plan/schedule!!! */
//@{
//! \brief aimState of currently loaded schedule!!!
//! \return aimState
MountingPointState aimState() const { return m_aimState; }
void setAimState(const MountingPointState &mps) { m_aimState = mps;}
//@}
bool isValid() const { return m_isValid; }
Core::GeoPosition geoPosition() const { return m_data.geoPosition; }
Core::RelativePosition relPosition() const { return m_data.relPosition; }
MountingPointType type() const { return m_data.mountingPointTypeId; }
int32_t buildingId() const { return m_data.mainStructureElementId; }
QString name() const;
QString fileName() const;
QByteArray properties() const { return m_data.properties.c_str(); }
QImage toImage(int32_t edgeLength = 100) const;
bool writeFile(int32_t edgeLength = 25) const;
int floor() const { return m_floor; }
void setFloor(int floor) { m_floor = floor; }
void setAssociatedAssetId(int32_t id);
void setHasAssociatedAssetDefect(bool hasAssociatedAssetDefect);
MountingPointState getNextMountingPointState(const MountingPointState currState);
private: // methods
private: // attributes
StructureElement m_data;
int32_t m_associatedAssetId;
MountingPointState m_aimState;
bool m_hasAssociatedAssetDefect;
bool m_isValid;
int m_floor;
public:
enum class MpColor
{
GRAY,
BLUE,
RED,
GREEN,
ORANGE
};
static QString mpColorToString(MpColor mpColor);
static QString mpColorToPostfix(MpColor mpColor);
struct NameImagePair
{
NameImagePair(const QString &name = QString(),
const QImage &img = QImage())
: m_name(name), m_img(img)
{}
QString m_name; // like announcement_BLUE
QImage m_img;
};
struct MpNameImageData
{
NameImagePair nipGray;
NameImagePair nipBlue;
NameImagePair nipRed;
NameImagePair nipGreen;
NameImagePair nipOrange;
};
//
// Some methods regarding ImageTable:
//
static QMap<MountingPointType, MpNameImageData> &getImageTable(); // contains images in good quality (100*100px)
static bool getImageAttributePlanActivity(const MountingPoint& mp,
QImage &imgOut, QString &attribNameOut);
static bool getImageAttributePlanDefinition(const MountingPoint& mp,
QImage &imgOut, QString &attribNameOut);
static bool getImageAttribute(const MountingPoint& mp, MpColor mpColor,
QImage &img, QString &attribName);
private:
static QMap<MountingPointType, MpNameImageData> &getImageTableInternal();
static void insertHelper(MountingPointType::type type,
const QString &name,
const QString &colorCodeGray,
const QString &colorCodeGreen,
const QString &colorCodeRed,
const QString &colorCodeOrange,
const QString &defName = QString());
static QImage getImage(const MountingPoint &mp);
static const MpNameImageData *getNameImageData(const MountingPoint&mp);
static const NameImagePair *getNameImagePair(const MountingPoint&mp);
}; // class MountingPoint
} // namespace InfrastructureManagement
@@ -1,78 +0,0 @@
#ifndef LTS_COMMON_PROJECTCONFIG_PROJECT_DEFINES_H
#define LTS_COMMON_PROJECTCONFIG_PROJECT_DEFINES_H
#pragma once
#include <string>
#include <ostream>
namespace IDL
{
enum class PartitionType
{
Any,
Global,
Exercise,
AllExercises,
Replay,
};
inline std::string toStdString(PartitionType pt)
{
switch (pt)
{
case PartitionType::Any:
return "Any";
case PartitionType::Global:
return "Global";
case PartitionType::Exercise:
return "Exercise";
case PartitionType::AllExercises:
return "AllExercises";
case PartitionType::Replay:
return "Replay";
}
return std::string("invalid:") + std::to_string(static_cast<int>(pt));
}
inline std::ostream& operator <<(std::ostream &o, PartitionType pt)
{
switch (pt)
{
case PartitionType::Any:
case PartitionType::Global:
case PartitionType::Exercise:
case PartitionType::AllExercises:
case PartitionType::Replay:
return o << std::string("PartitionType::") + toStdString(pt);
default:
return o << std::to_string(static_cast<int>(pt));
}
}
inline std::string exercisePartition(int exerciseId)
{
if (exerciseId < 0)
return { "ex_*" };
return std::string("ex_") + std::to_string(exerciseId);
}
inline std::string replayPartition(int partitionId)
{
if (partitionId < 0)
return { "srp_*" };
return std::string("srp_") + std::to_string(partitionId);
}
} // namespace IDL
#endif // LTS_COMMON_PROJECTCONFIG_PROJECT_DEFINES_H
@@ -1,26 +0,0 @@
#pragma once
// Stub export header for LtsProjectionWorkstation
// (the real header is generated by CMake via GENERATE_EXPORT_HEADER when the
// library is built; this stub covers non-RTI builds and is found first on the
// -I line because the source include/ dir precedes the build tree)
#ifndef LTSPROJECTIONWORKSTATION_EXPORT_H
#define LTSPROJECTIONWORKSTATION_EXPORT_H
// Must expand to a default-visibility attribute, NOT to empty: the build sets
// CMAKE_CXX_VISIBILITY_PRESET=hidden, and this stub is found before the
// CMake-generated header (the source include/ dir precedes the build tree on
// the -I line). With an empty macro the LtsProjectionWorkstation class symbols
// would be hidden and consumers (e.g. OperatorApplication) fail to link
// libLtsProjectionWorkstation.so.
// If the library is not built, the attribute is harmless: it only changes
// visibility, not symbol resolution.
#if defined(_MSC_VER)
# define LTSPROJECTIONWORKSTATION_EXPORT __declspec(dllexport)
#else
# define LTSPROJECTIONWORKSTATION_EXPORT __attribute__((visibility("default")))
#endif
#define LTSPROJECTIONWORKSTATION_NO_EXPORT
#endif // LTSPROJECTIONWORKSTATION_EXPORT_H
@@ -1,12 +0,0 @@
// STUB HEADER - Generated during Qt6 migration
// This file compensates for missing ltsscripttimeline_export.h when LtsScriptTimeline is not built
// Original would be generated by CMake GENERATE_EXPORT_HEADER for LtsScriptTimeline library
#ifndef LTSSCRIPTTIMELINE_EXPORT_H
#define LTSSCRIPTTIMELINE_EXPORT_H
// Stub export macros for BUILD_RTI=OFF or when LtsScriptTimeline is not built
#define LTSSCRIPTTIMELINE_EXPORT
#define LTSSCRIPTTIMELINE_NO_EXPORT
#endif // LTSSCRIPTTIMELINE_EXPORT_H
@@ -1,22 +0,0 @@
#ifndef LTSSESSION_EXPORT_H
#define LTSSESSION_EXPORT_H
// Stub export header for LtsSession when built without RTI
// This file is generated by CMake when building with RTI
// For non-RTI builds, we provide this stub
// Must expand to a default-visibility attribute, NOT to empty: the build sets
// CMAKE_CXX_VISIBILITY_PRESET=hidden, and this stub is found before the
// CMake-generated header (the source include/ dir precedes the build tree on
// the -I line). With an empty macro the LtsSession class symbols would be
// hidden and consumers (e.g. LtsFileDialog) fail to link libLtsSession.so.
// If the library is not built, the attribute is harmless: it only changes
// visibility, not symbol resolution.
#if defined(_MSC_VER)
# define LTSSESSION_EXPORT __declspec(dllexport)
#else
# define LTSSESSION_EXPORT __attribute__((visibility("default")))
#endif
#define LTSSESSION_NO_EXPORT
#endif // LTSSESSION_EXPORT_H
@@ -1,21 +0,0 @@
/**
* Export definitions for LtsSessionData
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtCore/qglobal.h>
#ifndef LTSSESSIONDATA_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define LTSSESSIONDATA_EXPORT
# else
# if defined(MAKE_LTSESSIONDATA_LIB)
# define LTSSESSIONDATA_EXPORT Q_DECL_EXPORT
# else
# define LTSSESSIONDATA_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
@@ -1,55 +0,0 @@
#pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen
#include <QtCore/QString>
#include <vector>
#include "mrkcommon_export.h"
namespace MarkerManagement
{
// STUB: MarkerType enum
enum class MarkerType : int { Unknown = 0, Situation = 1, Audio = 2, Video = 3 };
// STUB: MarkerDescription - wird durch echten DDS-Typ ersetzt (muss VOR Marker deklariert werden)
struct MRKCOMMON_EXPORT MarkerDescription
{
int id = 0;
QString name;
MarkerType markerType() const { return MarkerType::Unknown; }
void setMarkerType(MarkerType type) { Q_UNUSED(type); }
std::string content() const { return ""; }
// Weitere Felder werden bei Bedarf ergänzt
};
// STUB: Marker - wird durch echten DDS-Typ ersetzt
struct MRKCOMMON_EXPORT Marker
{
int id = 0;
QString name;
int exerciseId = 0;
qint64 timeStamp() const { return 0; }
qint64 timeStampOffset() const { return 0; }
int operatorId() const { return 0; }
int fileContentId() const { return 0; }
std::string note() const { return ""; }
std::vector<MarkerDescription> descriptions() const { return {}; }
// Weitere Felder werden bei Bedarf ergänzt
};
// STUB: toString Funktion für MarkerType
inline QString toString(MarkerType type)
{
switch (type)
{
case MarkerType::Unknown: return QStringLiteral("Unknown");
case MarkerType::Situation: return QStringLiteral("Situation");
case MarkerType::Audio: return QStringLiteral("Audio");
case MarkerType::Video: return QStringLiteral("Video");
default: return QStringLiteral("Unknown");
}
}
} // namespace MarkerManagement
@@ -1,14 +0,0 @@
#pragma once
// STUB-HEADER: Export-Macro für MarkerManagement
// Wird normalerweise von CMake generiert
#ifdef _WIN32
#ifdef MRKCOMMON_EXPORTS
#define MRKCOMMON_EXPORT __declspec(dllexport)
#else
#define MRKCOMMON_EXPORT __declspec(dllimport)
#endif
#else
#define MRKCOMMON_EXPORT __attribute__((visibility("default")))
#endif
@@ -1,25 +0,0 @@
// Stub file for nom_enums.hpp - used when BUILD_RTI=OFF
#ifndef NOM_ENUMS_HPP
#define NOM_ENUMS_HPP
#include <cstdint>
namespace NotificationManagement {
enum class NotificationType : std::int32_t {
Info = 0,
Warning = 1,
Error = 2,
Critical = 3
};
enum class NotificationPriority : std::int32_t {
Low = 0,
Normal = 1,
High = 2,
Urgent = 3
};
} // namespace NotificationManagement
#endif // NOM_ENUMS_HPP
@@ -1,43 +0,0 @@
/**
* @RDE_HEADER@
* Data Plugin Interface for OperatorManagement (Interface for access from other Plugins)
*/
#pragma once
#include <PluginInterfaces/data_plugin_interface.h>
#include <OperatorManagement/opm_dtc.h>
#include <OperatorManagement/opm_ftc.h>
#include <memory>
namespace OperatorManagement
{
class ForeignDataInterface;
/**
* @brief The DataInterface class provides the Topics Clients only for the GUI Plugins
*/
class DataInterface : public DataPluginBase::Interface
{
public:
using DataPluginBase::Interface::Interface;
virtual std::shared_ptr<OperatorManagement::Interface::Dtc> getDtc() = 0;
virtual std::shared_ptr<OperatorManagement::Interface::Ftc> getFtc() = 0;
virtual std::shared_ptr<ForeignDataInterface> getForeignDataInterface() = 0;
};
/**
* @brief The ForeignInterface class provides methods and signals for foreign plugins, that need
* access to the data of this DataPlugin
*/
class ForeignDataInterface
{
public:
ForeignDataInterface() = default;
virtual ~ForeignDataInterface() = default;
virtual void onSendKeepAlive() = 0;
};
} // namespace OperatorManagement
@@ -1,31 +0,0 @@
// Stub file for opm_enums.hpp - used when BUILD_RTI=OFF
#ifndef OPM_ENUMS_HPP
#define OPM_ENUMS_HPP
#include <cstdint>
namespace OperatorManagement {
enum class AccessControlLevel : std::int32_t {
None = 0,
ReadOnly = 1,
Operator = 2,
Supervisor = 3,
Administrator = 4
};
enum class OperatorState : std::int32_t {
Offline = 0,
Online = 1,
Busy = 2,
Away = 3
};
enum class GroupType : std::int32_t {
Standard = 0,
Special = 1
};
} // namespace OperatorManagement
#endif // OPM_ENUMS_HPP
@@ -1,49 +0,0 @@
// Stub file for ppm_enums.hpp - used when BUILD_RTI=OFF
#ifndef PPM_ENUMS_HPP
#define PPM_ENUMS_HPP
#include <cstdint>
#include <ostream>
namespace ParticipantManagement {
enum class ParticipantState : std::int32_t {
Active = 0,
Inactive = 1,
Suspended = 2
};
enum class ParticipantRole : std::int32_t {
Observer = 0,
Player = 1,
Controller = 2,
Admin = 3
};
enum class DataModification : std::int32_t {
eAdded = 0,
eModified = 1,
eRemoved = 2
};
enum class TypeClass : std::int32_t {
eUninitialized = 0,
ePlatform = 1,
ePerson = 2,
eEvent = 3
};
inline std::ostream& operator<<(std::ostream& os, TypeClass tc) {
switch (tc) {
case TypeClass::eUninitialized: os << "eUninitialized"; break;
case TypeClass::ePlatform: os << "ePlatform"; break;
case TypeClass::ePerson: os << "ePerson"; break;
case TypeClass::eEvent: os << "eEvent"; break;
default: os << "Unknown"; break;
}
return os;
}
} // namespace ParticipantManagement
#endif // PPM_ENUMS_HPP
@@ -1,10 +0,0 @@
#pragma once
// Export-Macro für ParticipantManagement Module
// STUB: Wird normalerweise von CMake generiert
#ifdef PPMCOMMON_LIBRARY
#define PPMCOMMON_EXPORT Q_DECL_EXPORT
#else
#define PPMCOMMON_EXPORT Q_DECL_IMPORT
#endif
@@ -1,36 +0,0 @@
#pragma once
// STUB-Header: Diese Datei wird normalerweise von DDS/Codegenerator generiert
// Für die Migration erstellen wir minimale Typ-Definitionen
#include "pdm_types.h"
namespace ProjectDataManagement
{
// EventType wird bereits in pdm_types.h definiert
// STUB: EventType_def - Platzhalter für DDS-generierten Typ
// Wird in AlarmManagement für Event-Typisierung verwendet
struct EventType_def
{
int value{0};
EventType_def() = default;
explicit EventType_def(int v) : value(v) {}
explicit EventType_def(EventType t) : value(static_cast<int>(t)) {}
bool operator==(const EventType_def& other) const { return value == other.value; }
bool operator!=(const EventType_def& other) const { return value != other.value; }
bool operator<(const EventType_def& other) const { return value < other.value; }
};
// STUB: EventData - Basisstruktur für Event-Daten
struct EventData
{
EventType_def eventType;
QString description;
qint64 timestamp{0};
};
} // namespace ProjectDataManagement
@@ -1,24 +0,0 @@
// Stub file for rep_enums.hpp - used when BUILD_RTI=OFF
#ifndef REP_ENUMS_HPP
#define REP_ENUMS_HPP
#include <cstdint>
namespace ReportManagement {
enum class ReportType : std::int32_t {
Summary = 0,
Detailed = 1,
Statistical = 2
};
enum class ReportFormat : std::int32_t {
PDF = 0,
HTML = 1,
XML = 2,
JSON = 3
};
} // namespace ReportManagement
#endif // REP_ENUMS_HPP
@@ -1,21 +0,0 @@
/**
* Export definitions for svcPreCommon
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtCore/qglobal.h>
#ifndef SVCCOMMON_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define SVCCOMMON_EXPORT
# else
# if defined(MAKE_SVCCOMMON_LIB)
# define SVCCOMMON_EXPORT Q_DECL_EXPORT
# else
# define SVCCOMMON_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
@@ -1,25 +0,0 @@
// Stub file for srp_enums.hpp - used when BUILD_RTI=OFF
#ifndef SRP_ENUMS_HPP
#define SRP_ENUMS_HPP
#include <cstdint>
namespace SituationReplay {
enum class ReplayState : std::int32_t {
Stopped = 0,
Playing = 1,
Paused = 2,
Rewinding = 3
};
enum class ReplaySpeed : std::int32_t {
QuarterSpeed = 0,
HalfSpeed = 1,
NormalSpeed = 2,
DoubleSpeed = 3
};
} // namespace SituationReplay
#endif // SRP_ENUMS_HPP
@@ -1,11 +0,0 @@
#ifndef TOPICEDITORBASE_EXPORT_H
#define TOPICEDITORBASE_EXPORT_H
// Stub export header for TopicEditorBase when built without RTI
// This file is generated by CMake when building with RTI
// For non-RTI builds, we provide this stub
#define TOPICEDITORBASE_EXPORT
#define TOPICEDITORBASE_NO_EXPORT
#endif // TOPICEDITORBASE_EXPORT_H
@@ -1,75 +0,0 @@
/**
* STUB-Header für ElevationMapManager - Qt6 Migration
* Diese Datei ermöglicht das Kompilieren von LtsElevation ohne das vollständige ElevationMap-Modul
*/
#pragma once
#include <QtCore/QObject>
#include <QtCore/QStringList>
#include <QtCore/QRectF>
#include <QtCore/QPointF>
#include <vector>
// QPoint3D ist bereits in LtsUtilsCore/qpoint3d.h definiert
// #include "LtsUtils/qpoint3d.h" // Wird von lts_elevation_manager.h included
namespace LtsUtils
{
// Forward-Referenz, Definition erfolgt in qpoint3d.h
struct QPoint3D;
} // namespace LtsUtils
using LOSVector = std::vector<double>;
namespace SituationMap
{
// The NGL build uses -fvisibility=hidden; LtsElevation links this class
// across the shared library boundary, so it needs default visibility.
class __attribute__((visibility("default"))) ElevationMapManager final : public QObject
{
Q_OBJECT
public:
ElevationMapManager();
ElevationMapManager(const ElevationMapManager &) = delete;
ElevationMapManager &operator = (const ElevationMapManager &) = delete;
~ElevationMapManager();
int init(const QStringList &filePaths_rough_to_fine);
void cleanupCurrentContent();
bool waitForInitialization();
bool isValid() const;
double elevation(double lon_rad, double lat_rad, bool *bIsCovered = nullptr) const;
double elevation(double lon_rad, double lat_rad, double defaultValue, bool *bIsCovered = nullptr) const;
QRectF simpleUnitedExtent() const;
bool contains(const QPointF &point) const;
void LOSProfile(const QPointF &start, const QPointF &end, LOSVector &losProfile);
enum class LineOfSight { LOS_UNDEFINED = 0,
LOS_ERROR,
LOS_VISIBLE,
LOS_INVISIBLE };
LineOfSight lineOfSightCalculation(const LOSVector &losProfile,
double centerHat,
double objHat) const;
LineOfSight lineOfSightCalculation(const LtsUtils::QPoint3D &startPointGeo_absZ,
const LtsUtils::QPoint3D &endPointGeo_absZ);
LineOfSight lineOfSightCalculation(const QPointF &startPointGeo, double startHat,
const QPointF &endPointGeo, double endHat);
protected:
class Private;
Private *d;
}; // ElevationMapManager
} // namespace SituationMap
@@ -1,163 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_ABSTRACTLOCALIZER_H
#define GRANTLEE_ABSTRACTLOCALIZER_H
#include "grantlee_templates_export.h"
#include <QtCore/QLocale>
#include <QtCore/QSharedPointer>
#include <QtCore/QVariantList>
class QDateTime;
namespace Grantlee
{
/**
@brief Interface for implementing an internationalization system.
This class defines an interface for accessing an internationalization, such as
QLocale/QTranslator or gettext/KLocale.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT AbstractLocalizer
{
public:
/**
Constructor
*/
AbstractLocalizer();
/**
Destructor
*/
virtual ~AbstractLocalizer();
/**
Processes the data in @p variant into a localized string.
The base implementation can localize numbers, dates and times, and
strings.
*/
virtual QString localize(const QVariant &variant) const;
/**
Returns the current locale as a string.
*/
virtual QString currentLocale() const = 0;
/**
Makes this localizer use the locale specified by @p localeName for output.
*/
virtual void pushLocale(const QString &localeName) = 0;
/**
Makes this localizer use the previous locale for output.
*/
virtual void popLocale() = 0;
/**
Loads the @p catalog from @p path.
*/
virtual void loadCatalog(const QString &path, const QString &catalog) = 0;
/**
Unloads the @p catalog
*/
virtual void unloadCatalog(const QString &catalog) = 0;
/**
Localizes @p number
*/
virtual QString localizeNumber(int number) const = 0;
/**
Localizes @p number
*/
virtual QString localizeNumber(qreal number) const = 0;
/**
Localizes @p value as a monetary value in the currency specified by @p
currencyCode.
*/
virtual QString localizeMonetaryValue(qreal value, const QString &currencyCode
= {}) const = 0;
/**
Localizes @p date with the specified @p formatType
*/
virtual QString localizeDate(const QDate &date,
QLocale::FormatType formatType
= QLocale::ShortFormat) const = 0;
/**
Localizes @p time with the specified @p formatType
*/
virtual QString localizeTime(const QTime &time,
QLocale::FormatType formatType
= QLocale::ShortFormat) const = 0;
/**
Localizes @p dateTime with the specified @p formatType
*/
virtual QString localizeDateTime(const QDateTime &dateTime,
QLocale::FormatType formatType
= QLocale::ShortFormat) const = 0;
/**
Localizes @p string with the specified @p arguments for substitution
*/
virtual QString localizeString(const QString &string,
const QVariantList &arguments = {}) const = 0;
/**
Localizes @p string, disambiguated by @p context with the specified @p
arguments for substitution
*/
virtual QString
localizeContextString(const QString &string, const QString &context,
const QVariantList &arguments = {}) const = 0;
/**
Localizes @p string or its @p pluralForm with the specified @p arguments
for substitution
*/
virtual QString
localizePluralString(const QString &string, const QString &pluralForm,
const QVariantList &arguments = {}) const = 0;
/**
Localizes @p string or its @p pluralForm, disambiguated by @p context with
the specified @p arguments for substitution
*/
virtual QString
localizePluralContextString(const QString &string, const QString &pluralForm,
const QString &context,
const QVariantList &arguments = {}) const = 0;
private:
Q_DISABLE_COPY(AbstractLocalizer)
};
}
#endif
@@ -1,273 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_ABSTRACTMARKUPBUILDER_H
#define GRANTLEE_ABSTRACTMARKUPBUILDER_H
#include "grantlee_textdocument_export.h"
#include <QtCore/QString>
#include <QtGui/QTextListFormat>
class QBrush;
namespace Grantlee
{
class AbstractMarkupBuilderPrivate;
/// @headerfile abstractmarkupbuilder.h grantlee/abstractmarkupbuilder.h
/**
@brief Interface for creating marked-up text output.
The **%AbstractMarkupBuilder** is used by a MarkupDirector to create marked-up
output such as html or markdown.
See PlainTextMarkupBuilder and TextHTMLBuilder for example implementations.
This interface can be extended to handle custom format types in a
QTextDocument. @see @ref custom_qtextobject
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEXTDOCUMENT_EXPORT AbstractMarkupBuilder
{
public:
/** Destructor */
virtual ~AbstractMarkupBuilder() {}
/** Begin a bold element in the markup */
virtual void beginStrong() = 0;
/** Close the bold element in the markup */
virtual void endStrong() = 0;
/** Begin an emphasised element in the markup */
virtual void beginEmph() = 0;
/** Close the emphasised element in the markup */
virtual void endEmph() = 0;
/** Begin an underlined element in the markup */
virtual void beginUnderline() = 0;
/** Close the underlined element in the markup */
virtual void endUnderline() = 0;
/** Begin a struck out element in the markup */
virtual void beginStrikeout() = 0;
/** Close the struck out element in the markup */
virtual void endStrikeout() = 0;
/**
Begin a decorarated foreground element in the markup (A text color)
using @p brush
*/
virtual void beginForeground(const QBrush &brush) = 0;
/** Close the decorarated foreground element in the markup */
virtual void endForeground() = 0;
/**
Begin a decorarated background element in the markup (A text background
color) using @p brush
*/
virtual void beginBackground(const QBrush &brush) = 0;
/** Close the decorarated background element in the markup */
virtual void endBackground() = 0;
/**
Begin a url anchor element in the markup
@param href The href of the anchor.
@param name The name of the anchor.
*/
virtual void beginAnchor(const QString &href = {}, const QString &name = {})
= 0;
/** Close the anchor element */
virtual void endAnchor() = 0;
/**
Begin a new font familiy element in the markup
@param family The name of the font family to begin.
*/
virtual void beginFontFamily(const QString &family) = 0;
/** End font family element */
virtual void endFontFamily() = 0;
/**
Begin a new font point size element in the markup
@param size The point size to begin.
*/
virtual void beginFontPointSize(int size) = 0;
/** End font point size element */
virtual void endFontPointSize() = 0;
/**
Begin a new paragraph in the markup
@param a The alignment of the new paragraph.
@param top The top margin of the new paragraph.
@param bottom The bottom margin of the new paragraph.
@param left The left margin of the new paragraph.
@param right The right margin of the new paragraph.
*/
virtual void beginParagraph(Qt::Alignment a = Qt::AlignLeft, qreal top = 0.0,
qreal bottom = 0.0, qreal left = 0.0,
qreal right = 0.0)
= 0;
/** Close the paragraph in the markup. */
virtual void endParagraph() = 0;
/** Add a newline to the markup. */
virtual void addNewline() = 0;
/**
Insert a horizontal rule into the markup.
@param width The width of the rule. Default is full width.
*/
virtual void insertHorizontalRule(int width = -1) = 0;
/**
Insert a new image element into the markup.
@param url The url of the image
@param width The width of the image
@param height The height of the image.
*/
virtual void insertImage(const QString &url, qreal width, qreal height) = 0;
/**
Begin a new list element in the markup.
A list element contains list items, and may contain other lists.
@param style The style of list to create.
*/
virtual void beginList(QTextListFormat::Style style) = 0;
/**
Close the list.
*/
virtual void endList() = 0;
/** Begin a new list item in the markup */
virtual void beginListItem() = 0;
/** End the list item */
virtual void endListItem() = 0;
/** Begin a superscript element */
virtual void beginSuperscript() = 0;
/** End superscript element */
virtual void endSuperscript() = 0;
/** Begin a subscript element */
virtual void beginSubscript() = 0;
/** End subscript element */
virtual void endSubscript() = 0;
/**
Begin a table element.
@param cellpadding The padding attribute for the table.
@param cellspacing The spacing attribute for the table.
@param width The width of the table. May be either an integer, or a
percentage value.
*/
virtual void beginTable(qreal cellpadding, qreal cellspacing,
const QString &width)
= 0;
/**
Begin a new table row
*/
virtual void beginTableRow() = 0;
/**
Begin a new table header cell.
@param width The width of the cell.
@param colSpan The column span of the cell.
@param rowSpan The row span of the cell.
*/
virtual void beginTableHeaderCell(const QString &width, int colSpan,
int rowSpan)
= 0;
/**
Begin a new table cell.
@param width The width of the cell.
@param colSpan The column span of the cell.
@param rowSpan The row span of the cell.
*/
virtual void beginTableCell(const QString &width, int colSpan, int rowSpan)
= 0;
/** End a table element */
virtual void endTable() = 0;
/** End a table row */
virtual void endTableRow() = 0;
/** End a table header cell */
virtual void endTableHeaderCell() = 0;
/** End a table cell */
virtual void endTableCell() = 0;
/**
Begin a level @p level header
@param level An integer between 1 and 6
*/
virtual void beginHeader(int level) = 0;
/**
End a level @p level header
@param level An integer between 1 and 6
*/
virtual void endHeader(int level) = 0;
/**
Append the plain text @p text to the markup
@param text The text to append.
*/
virtual void appendLiteralText(const QString &text) = 0;
/**
Append the raw text @p text to the markup. @p text is added unescaped
*/
virtual void appendRawText(const QString &text) = 0;
/**
Return the fully marked up result of the building process.
This may contain metadata etc, such as a head element in html.
@return The fully marked up text.
*/
virtual QString getResult() = 0;
};
}
#endif
@@ -1,113 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_BBCODEBUILDER_H
#define GRANTLEE_BBCODEBUILDER_H
#include "abstractmarkupbuilder.h"
namespace Grantlee
{
/**
@brief Builder to create BBCode from a QTextDocument
*/
class BBCodeBuilder : public AbstractMarkupBuilder
{
public:
/**
Creates a new BBCodeBuilder.
*/
BBCodeBuilder();
~BBCodeBuilder() override;
void beginStrong() override;
void endStrong() override;
void beginEmph() override;
void endEmph() override;
void beginUnderline() override;
void endUnderline() override;
void beginStrikeout() override;
void endStrikeout() override;
void beginForeground(const QBrush &brush) override;
void endForeground() override;
// Background colour not supported by BBCode.
void beginAnchor(const QString &href = {}, const QString &name = {}) override;
void endAnchor() override;
// Font family not supported by BBCode.
/**
Begin an element of font size @p size. Note that this size is in pixels,
and must be converted before it is suitable for use in BBCode.
@param size The size of font to begin.
*/
void beginFontPointSize(int size) override;
void endFontPointSize() override;
void beginParagraph(Qt::Alignment a = Qt::AlignLeft, qreal top = 0.0,
qreal bottom = 0.0, qreal left = 0.0,
qreal right = 0.0) override;
void endParagraph() override;
void addNewline() override;
void insertImage(const QString &src, qreal width, qreal height) override;
void beginList(QTextListFormat::Style type) override;
void endList() override;
void beginListItem() override;
void beginSuperscript() override;
void endSuperscript() override;
void beginSubscript() override;
void endSubscript() override;
void beginTable(qreal, qreal, const QString &) override;
void beginTableRow() override;
void appendLiteralText(const QString &text) override;
/**
Escapes @p text appropriately for BBCode.
*/
const QString escape(const QString &text) const;
QString getResult() override;
private:
QList<QTextListFormat::Style> m_currentListItemStyles;
QString m_text;
Qt::Alignment m_currentAlignment;
};
}
#endif
@@ -1,112 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_CACHINGLOADERDECORATOR_H
#define GRANTLEE_CACHINGLOADERDECORATOR_H
#include "templateloader.h"
#include "grantlee_templates_export.h"
namespace Grantlee
{
class CachingLoaderDecoratorPrivate;
/// @headerfile cachingloaderdecorator.h grantlee/cachingloaderdecorator.h
/**
@brief Implements a loader decorator which caches compiled Template objects.
The **%CachingLoaderDecorator** can be used with any implementation of
Grantlee::AbstractTemplateLoader.
@code
auto loader = QSharedPointer<Grantlee::FileSystemTemplateLoader>::create();
loader->setTemplateDirs({"/path/one", "/path/two"});
auto cache =
QSharedPointer<Grantlee::CachingLoaderDecorator>::create( loader );
m_engine->addTemplateLoader( cache );
@endcode
The effect is that templates do not need to be loaded from the filesystem and
compiled into Template objects on each access, but may be returned from the
cache instead.
This can be significant if loading Templates in a loop, or loading the same
Template very often in an application.
@code
<ul>
{% for item in list %}
<li>{% include "itemtemplate.html" %}</li>
{% endfor %}
</ul>
@endcode
If the loading of Templates is a bottleneck in an application, it may make
sense to use the caching decorator.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT CachingLoaderDecorator
: public AbstractTemplateLoader
{
public:
/**
Constructor
*/
CachingLoaderDecorator(QSharedPointer<AbstractTemplateLoader> loader);
/**
Destructor
*/
~CachingLoaderDecorator() override;
bool canLoadTemplate(const QString &name) const override;
QPair<QString, QString> getMediaUri(const QString &fileName) const override;
Template loadByName(const QString &name,
const Grantlee::Engine *engine) const override;
/**
Clears the Templates objects cached in the decorator.
*/
void clear();
/**
Returns the number of Template objects cached in the decorator.
*/
int size() const;
/**
Returns whether the cache is empty.
*/
bool isEmpty() const;
private:
Q_DECLARE_PRIVATE(CachingLoaderDecorator)
CachingLoaderDecoratorPrivate *const d_ptr;
};
}
#endif
@@ -1,283 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_CONTEXT_H
#define GRANTLEE_CONTEXT_H
#include "abstractlocalizer.h"
#include "grantlee_templates_export.h"
#include <QtCore/QVariantHash>
namespace Grantlee
{
class RenderContext;
class ContextPrivate;
/// @headerfile context.h grantlee/context.h
/**
@brief The **%Context** class holds the context to render a Template with.
For application developers, using the **%Context** class is a matter of
inserting keys and values as appropriate for rendering a Template using the
@ref insert method.
@code
auto t = engine->newTemplate(
"Name is {% name %} and age is {% age %}.", "some_template" );
Context c1;
c1.insert( "name", "Tom" );
c1.insert( "age", 34 );
Context c2;
c2.insert( "name", "Harry" );
c2.insert( "age", 43 );
t->render(c1); // Returns "Name is Tom and age is 43."
t->render(c2); // Returns "Name is Harry and age is 34."
@endcode
Note that one Template may be rendered multiple times with different contexts.
Note also that any QVariant may be inserted into a **%Context** object. Most
commonly, QObjects will be used here.
@see @ref custom_objects
@section context_stack Context Stack.
For template tag developers, some other **%Context** API is relevant.
It is possible to @ref push and @ref pop layers of context while a template
is being rendered. This is useful if your template tag makes additional
variables temporarily available in a part of a template. %Template tags
should only modify layers of context that they @ref push themselves, and
should @ref pop any layers created before finishing its rendering step.
See for example the @gr_tag{with} tag. In a template such as
@code
Some content
{% with person.name|toUpper as lowerName %}
Name is {% lowerName %}
{% endwith %}
@endcode
In this case, lowerName is available in the context only between the
@gr_tag{with} and @gr_tag{endwith} tags. The implementation of
the @gr_tag{with} tag render method is:
@code
void WithNode::render( OutputStream *stream, Context *c ) const
{
c->push();
// {% with m_filterExpression as m_name %}
c->insert( m_name, m_filterExpression.resolve( c ) );
m_list.render( stream, c );
c->pop(); // The section of context defining m_name is removed.
}
@endcode
Note that a **%Context** may temporarily override a variable in a parent
context. This is why it is important to @ref push a new context when adding
items to context and @ref pop it when finished.
@code
Some content
{% with "foo" as var %}
Var is {% var %} // Var is "foo"
{% with "bar" as var %}
Var is {% var %} // Var is "bar"
{% endwith %}
Var is {% var %} // Var is "foo"
{% endwith %}
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Context
{
public:
/**
Creates an empty context
*/
Context();
/**
Sets every key in the hash as a property name with the variant as the
value.
*/
explicit Context(const QVariantHash &hash);
/**
Copy Constructor
*/
Context(const Context &other);
/**
Assignmant operator
*/
Context &operator=(const Context &other);
#ifndef Q_QDOC
/**
@internal
Whether to automatically escape all context content. This is not usually
used directly. Use the @gr_tag{autoescape} tag instead.
*/
bool autoEscape() const;
/**
@internal
Sets whether to automatically escape all context content. This is not
usually used directly. Use the @gr_tag{autoescape} tag instead.
*/
void setAutoEscape(bool autoescape);
#endif
/**
Destructor
*/
~Context();
/**
Returns the context object identified by the key @p str
*/
QVariant lookup(const QString &str) const;
/**
Insert the context object @p object identified by @p name into
the **%Context**.
*/
void insert(const QString &name, QObject *object);
/**
Insert the context object @p variant identified by @p name into
the **%Context**.
*/
void insert(const QString &name, const QVariant &variant);
/**
Pushes a new context.
@see @ref context_stack
*/
void push();
/**
Pops the context.
@see @ref context_stack
*/
void pop();
#ifndef Q_QDOC
/**
@internal Returns the context hash at depth @p depth.
*/
QVariantHash stackHash(int depth) const;
/**
@internal
Returns whether template being rendered is being mutated.
*/
bool isMutating() const;
/**
@internal
Sets whether template being rendered is being mutated to @p mutating.
*/
void setMutating(bool mutating);
/**
@internal
*/
void addExternalMedia(const QString &absolutePart,
const QString &relativePart);
/**
@internal
*/
void clearExternalMedia();
#endif
/**
Sets the @p localizer to be used.
The **%Context** takes ownerwhip of the localizer.
*/
void setLocalizer(QSharedPointer<AbstractLocalizer> localizer);
/**
Returns the localizer currently in use.
*/
QSharedPointer<AbstractLocalizer> localizer() const;
/**
Returns the external media encountered in the Template while rendering.
*/
QList<QPair<QString, QString>> externalMedia() const;
/**
The type of urls to external media that should be put in the template.
*/
enum UrlType {
AbsoluteUrls, ///< Absolute URLs should be put in the template.
RelativeUrls ///< Relative URLs should be put in the template.
};
/**
Sets the type of external media URL to be used in the template to @p type.
@see @ref media_finder_tag
*/
void setUrlType(UrlType type);
/**
The type of URL used in the template.
*/
UrlType urlType() const;
/**
Sets the relative path to external media to be used in templates to @p
relativePath
@see @ref media_finder_tag
*/
void setRelativeMediaPath(const QString &relativePath);
/**
The relative path to external media to be used in templates.
*/
QString relativeMediaPath() const;
/**
Returns a modifiable RenderContext. This may be used to make
Template rendering threadsafe so that render state does not need to be
stored in the Node implementation itself.
*/
RenderContext *renderContext() const;
private:
Q_DECLARE_PRIVATE(Context)
ContextPrivate *const d_ptr;
};
}
#endif
@@ -1,259 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_ENGINE_H
#define GRANTLEE_ENGINE_H
#include "template.h"
#include "templateloader.h"
namespace Grantlee
{
class TagLibraryInterface;
class EnginePrivate;
/// @headerfile engine.h grantlee/engine.h
/**
@brief **%Grantlee::Engine** is the main entry point for creating %Grantlee
Templates.
The **%Grantlee::Engine** is responsible for configuring and creating Template
objects. In typical use, one or more AbstractTemplateLoader objects will be
added to the Engine to load template objects, and plugin directories will be
set to enable finding template tags and filters.
@code
auto engine = new Engine();
auto loader = QSharedPointer<FileSystemTemplateLoader>::create();
loader->setTemplateDirs( {"/usr/share/myapp/templates"} );
engine->addTemplateLoader( loader );
engine->addPluginPath( "/usr/lib/myapp" );
auto template1 = engine->newTemplate( "Template content", "template name" );
auto template2 = engine->loadByName( "templatefile.html" );
@endcode
Once it is configured, the **%Engine** can be used to create new templates by
name by loading the templates with the @ref loadByName method, or by defining
the content in the @ref newTemplate method.
By default the builtin tags and filters distributed with %Grantlee are
available in all templates without using the @gr_tag{load} tag in the
template. These pre-loaded libraries may be configured if appropriate to the
application. For example, an application which defines its own tags and
filters may want them to be always available, or it may be desirable to
restrict the features available to template authors by removing built in
libraries.
Different **%Engine** objects can be used to create templates with differing
configurations.
@section smart_trim Insignificant whitespace
The output of rendering a template depends on the content of the template. In
some cases when generating content in which whitespace is significant, this
can have undesired effects. For example, given a template to generate C++ code
like:
@verbatim
class MyClass {
{# This loop creates the #}
{# methods in the class #}
{% for method in methods %}
{% if method.hasDox %}
{{ method.dox }}
{% endif %}
{{ method.signature }}
{% endfor %}
};
@endverbatim
The output would have a lot of whitespace which is not necessarily wanted.
@code
class MyClass {
void foo() const;
};
@endcode
It is possible to strip insignificant whitespace by enabling the smartTrim
feature with @ref setSmartTrimEnabled. When enabled the output will not
contain a newline for any line in the template which has only one token of
template syntax, such as a comment, tag or variable.
@code
class MyClass {
void foo() const;
};
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Engine : public QObject
{
Q_OBJECT
public:
/**
Constructor
*/
Engine(QObject *parent = {});
/**
Destructor.
*/
~Engine() override;
/**
Returns the TemplateLoaders currently configured on the **%Engine**.
*/
QList<QSharedPointer<AbstractTemplateLoader>> templateLoaders();
/**
Adds @p loader to the TemplateLoaders currently configured on
the **%Engine**.
*/
void addTemplateLoader(QSharedPointer<AbstractTemplateLoader> loader);
/**
Sets the plugin dirs currently configured on the **%Engine** to @p dirs.
@warning This overwrites the default paths. You normally want
@ref addPluginPath.
@see @ref finding_plugins
*/
void setPluginPaths(const QStringList &dirs);
/**
Prepend @p dir to the list of plugin dirs.
*/
void addPluginPath(const QString &dir);
/**
Removes all instances of @p dir from the list of plugin dirs.
*/
void removePluginPath(const QString &dir);
/**
Returns the currently configured plugin dirs
*/
QStringList pluginPaths() const;
/**
Returns a URI for a media item with the name @p name.
Typically this will be used for images. For example the media URI for the
image <tt>"header_logo.png"</tt> may be
<tt>"/home/user/common/header_logo.png"</tt> or
<tt>"/home/user/some_theme/header_logo.png"</tt>
depending on the @ref templateLoaders configured.
This method will not usually be called by application code. To load media
in a template, use the @gr_tag{media_finder} template tag.
*/
QPair<QString, QString> mediaUri(const QString &fileName) const;
/**
Load the Template identified by @p name.
The Templates and plugins loaded will be determined by
the **%Engine** configuration.
*/
Template loadByName(const QString &name) const;
/**
Create a new Template with the content @p content identified by @p name.
The secondary Templates and plugins loaded will be determined by
the **%Engine** configuration.
*/
Template newTemplate(const QString &content, const QString &name) const;
/**
Returns the libraries available by default to new Templates.
*/
QStringList defaultLibraries() const;
/**
Adds the library named @p libName to the libraries available by default to
new Templates.
*/
void addDefaultLibrary(const QString &libName);
/**
Removes the library named @p libName from the libraries available by
default to new Templates.
*/
void removeDefaultLibrary(const QString &libName);
/**
Returns whether the smart trim feature is enabled for newly loaded
templates.
@see smart_trim
This is false by default.
*/
bool smartTrimEnabled() const;
/**
Sets whether the smart trim feature is enabled for newly loaded templates.
@see smart_trim
*/
void setSmartTrimEnabled(bool enabled);
#ifndef Q_QDOC
/**
@internal
Loads and returns the libraries specified in defaultLibraries or @p state.
*/
void loadDefaultLibraries();
/**
@internal
Loads and returns the library specified by @p name in the
current **%Engine** configuration or @p state.
Templates wishing to load a library should use the @gr_tag{load} tag.
*/
TagLibraryInterface *loadLibrary(const QString &name);
#endif
private:
Q_DECLARE_PRIVATE(Engine)
EnginePrivate *const d_ptr;
};
}
#endif
@@ -1,120 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_EXCEPTION_H
#define GRANTLEE_EXCEPTION_H
#include "grantlee_templates_export.h"
#include <QtCore/QString>
#include <exception>
namespace Grantlee
{
/**
Types of errors that can occur while using %Grantlee
*/
enum Error {
NoError,
EmptyVariableError,
EmptyBlockTagError,
InvalidBlockTagError,
UnclosedBlockTagError,
UnknownFilterError,
TagSyntaxError,
// VariableSyntaxError,
VariableNotInContext,
ObjectReturnTypeInvalid,
CompileFunctionError
};
/// @headerfile exception.h grantlee/exception.h
/**
@brief An exception for use when implementing template tags.
The **%Exception** class can be used when implementing
AbstractNodeFactory::getNode. An exception can be thrown to indicate that
the syntax of a particular tag is invalid.
For example, the following template markup should throw an error because the
include tag should have exactly one argument:
@code
<div>
{% include %}
</div>
@endcode
The corresponding implementation of IncludeNodeFactory::getNode is
@code
QStringList tagContents = smartSplit( tagContent );
if ( tagContents.size() != 2 )
throw Grantlee::Exception( TagSyntaxError,
"Error: Include tag takes exactly one argument" );
// The item at index 0 in the list is the tag name, "include"
QString includeName = tagContents.at( 1 );
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Exception
{
public:
/**
Creates an exception for the error @p errorCode and the verbose
message @p what
*/
Exception(Error errorCode, const QString &what)
: m_errorCode(errorCode), m_what(what)
{
}
virtual ~Exception() throw() {}
#ifndef Q_QDOC
/**
@internal
Returns the verbose message for the exception.
*/
const QString what() const throw() { return m_what; }
/**
@internal
Returns the error code for the exception.
*/
Error errorCode() const { return m_errorCode; }
#endif
private:
Error m_errorCode;
QString m_what;
};
}
#endif
@@ -1,117 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
// krazy:excludeall=dpointer
#ifndef GRANTLEE_FILTER_H
#define GRANTLEE_FILTER_H
#include "grantlee_templates_export.h"
#include "outputstream.h"
#include "safestring.h"
#include <QtCore/QSharedPointer>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
namespace Grantlee
{
/// @headerfile filter.h grantlee/filter.h
/**
@brief Base class for all filters.
The **%Filter** class can be implemented in plugin libraries to make
additional functionality available to templates.
Developers are required only to implement the @ref doFilter method and
integrate the filter as part of a custom plugin, but will never create or
access filters directly in application code.
The FilterExpression class is the access interface to a chain of **%Filter**
objects.
The @ref escape and @ref conditionalEscape methods are available for escaping
data where needed.
@see @ref filters
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Filter
{
public:
/**
Destructor.
*/
virtual ~Filter();
#ifndef Q_QDOC
/**
FilterExpression makes it possible to access stream methods like escape
while resolving.
*/
void setStream(OutputStream *stream);
#endif
/**
Escapes and returns @p input. The OutputStream::escape method is used to
escape @p input.
*/
SafeString escape(const QString &input) const;
/**
Escapes and returns @p input. The OutputStream::escape method is used to
escape @p input.
*/
SafeString escape(const SafeString &input) const;
/**
Escapes @p input if not already safe from further escaping and returns it.
The OutputStream::escape method is used to escape @p input.
*/
SafeString conditionalEscape(const SafeString &input) const;
/**
Reimplement to filter @p input given @p argument.
@p autoescape determines whether the autoescape feature is currently on or
off. Most filters will not use this.
@see @ref autoescaping
*/
virtual QVariant doFilter(const QVariant &input,
const QVariant &argument = {},
bool autoescape = {}) const = 0;
/**
Reimplement to return whether this filter is safe.
*/
virtual bool isSafe() const;
private:
#ifndef Q_QDOC
OutputStream *m_stream;
#endif
};
}
#endif
@@ -1,200 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_FILTEREXPRESSION_H
#define GRANTLEE_FILTEREXPRESSION_H
#include "variable.h"
#include "grantlee_templates_export.h"
namespace Grantlee
{
class Filter;
class OutputStream;
class Parser;
struct Token;
class FilterExpressionPrivate;
/// @headerfile filterexpression.h grantlee/filterexpression.h
/**
@brief A **%FilterExpression** object represents a filter expression in a
template.
This class is only relevant if implementing custom tags or filters. Most of
the API here is internal.
Usually when implementing tags or filters, filter expressions will just be
created and resolved.
In template markup, a filter expression is a variable followed by one or more
filters separated by pipes:
%Filter expressions may appear in variable nodes:
@code
{{ some_var|upper_filter|lower_filter }}
@endcode
Or as arguments to tags
@code
{% some_tag some_arg1|filter1|filter2 some_arg2|filter3 %}
@endcode
The **%FilterExpression** class would be used in the getNode implementation of
the AbstractNodeFactory implementation for the <tt>some_tag</tt> tag.
@code
Node* SomeTagFactory::getNode(const QString &tagContent, Parser *p) const {
auto parts = smartSplit( tagContent );
parts.removeFirst(); // Remove the "some_tag" part.
FilterExpression arg1( parts.first(), p );
FilterExpression arg2( parts.at( 1 ), p );
return new SomeTagNode( arg1, arg2, p );
}
@endcode
@see AbstractNodeFactory::getFilterExpressionList
When implementing the Node::render method, the @ref resolve method may be used
to process the filter expression.
For example, if our <tt>SomeTagNode</tt> was to concatenate the resolved
values given as arguments:
@code
void SomeTagNode::render( QTextStream *stream, Context *c ) {
m_arg1.resolve( stream, c );
m_arg2.resolve( stream, c );
}
@endcode
Because Filters are highly generic, they do not all write data to the stream.
For example, a Filter might take as input a string, and return a list by
splitting the string on commas, or a Filter might compare an input to its
argument and return whether they are the same, but not write anything to the
stream. For that reason, the @ref resolve method writes data to the given
stream, and returns the same data in its returned QVariant.
The suitability of either of the @ref resolve methods will depend on the
implementation and requirements of your custom tag. For example if the
<tt>SomeTagNode</tt> ran a comparison of the arguments:
@code
void SomeTagNode::render( QTextStream *stream, Context *c ) {
QString first = m_arg1.resolve( c ).toString();
QString second = m_arg2.resolve( c ).toString();
if ( first == second )
m_trueList.render( stream, c );
else
m_falseList.render( stream, c );
}
@endcode
@see @ref tags_with_end_tags
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT FilterExpression
{
public:
/**
Constructs an invalid **%FilterExpression**.
*/
FilterExpression();
/**
Constructs a filter expression from the string @p varString. The Parser @p
parser is used to retrieve filters.
*/
FilterExpression(const QString &varString, Grantlee::Parser *parser);
/**
Copy constructor.
*/
FilterExpression(const FilterExpression &other);
/**
Destructor.
*/
~FilterExpression();
/**
Assignment operator.
*/
FilterExpression &operator=(const FilterExpression &other);
/**
Returns the initial variable in the **%FilterExpression**.
*/
Variable variable() const;
/**
Resolves the **%FilterExpression** in the Context @p c and writes it to the
stream @p stream.
*/
QVariant resolve(OutputStream *stream, Context *c) const;
/**
Resolves the **%FilterExpression** in the Context @p c.
*/
QVariant resolve(Context *c) const;
/**
Returns whether the Filter resolves to true in the Context @p c.
@see @ref truthiness
*/
bool isTrue(Context *c) const;
/**
Returns a list for the **%FilterExpression**.
If the **%FilterExpression** can not be resolved to a list, an empty list
will be returned.
*/
QVariantList toList(Context *c) const;
/**
Returns whether a filter expression is valid.
A **%FilterExpression** is valid if all filters in the expression exist and
the initial variable being filtered is valid.
*/
bool isValid() const;
#ifndef Q_QDOC
/**
@internal
Returns the list of filters in the **%FilterExpression**.
*/
QStringList filters() const;
#endif
private:
Q_DECLARE_PRIVATE(FilterExpression)
FilterExpressionPrivate *const d_ptr;
};
}
#endif
@@ -1,42 +0,0 @@
#ifndef GRANTLEE_TEMPLATES_EXPORT_H
#define GRANTLEE_TEMPLATES_EXPORT_H
#ifdef GRANTLEE_TEMPLATES_STATIC_DEFINE
# define GRANTLEE_TEMPLATES_EXPORT
# define GRANTLEE_TEMPLATES_NO_EXPORT
#else
# ifndef GRANTLEE_TEMPLATES_EXPORT
# ifdef Grantlee_Templates_EXPORTS
/* We are building this library */
# define GRANTLEE_TEMPLATES_EXPORT __attribute__((visibility("default")))
# else
/* We are using this library */
# define GRANTLEE_TEMPLATES_EXPORT __attribute__((visibility("default")))
# endif
# endif
# ifndef GRANTLEE_TEMPLATES_NO_EXPORT
# define GRANTLEE_TEMPLATES_NO_EXPORT __attribute__((visibility("hidden")))
# endif
#endif
#ifndef GRANTLEE_TEMPLATES_DEPRECATED
# define GRANTLEE_TEMPLATES_DEPRECATED __attribute__ ((__deprecated__))
#endif
#ifndef GRANTLEE_TEMPLATES_DEPRECATED_EXPORT
# define GRANTLEE_TEMPLATES_DEPRECATED_EXPORT GRANTLEE_TEMPLATES_EXPORT GRANTLEE_TEMPLATES_DEPRECATED
#endif
#ifndef GRANTLEE_TEMPLATES_DEPRECATED_NO_EXPORT
# define GRANTLEE_TEMPLATES_DEPRECATED_NO_EXPORT GRANTLEE_TEMPLATES_NO_EXPORT GRANTLEE_TEMPLATES_DEPRECATED
#endif
#if 0 /* DEFINE_NO_DEPRECATED */
# ifndef GRANTLEE_TEMPLATES_NO_DEPRECATED
# define GRANTLEE_TEMPLATES_NO_DEPRECATED
# endif
#endif
#endif /* GRANTLEE_TEMPLATES_EXPORT_H */
@@ -1,42 +0,0 @@
#ifndef GRANTLEE_TEXTDOCUMENT_EXPORT_H
#define GRANTLEE_TEXTDOCUMENT_EXPORT_H
#ifdef GRANTLEE_TEXTDOCUMENT_STATIC_DEFINE
# define GRANTLEE_TEXTDOCUMENT_EXPORT
# define GRANTLEE_TEXTDOCUMENT_NO_EXPORT
#else
# ifndef GRANTLEE_TEXTDOCUMENT_EXPORT
# ifdef Grantlee_TextDocument_EXPORTS
/* We are building this library */
# define GRANTLEE_TEXTDOCUMENT_EXPORT __attribute__((visibility("default")))
# else
/* We are using this library */
# define GRANTLEE_TEXTDOCUMENT_EXPORT __attribute__((visibility("default")))
# endif
# endif
# ifndef GRANTLEE_TEXTDOCUMENT_NO_EXPORT
# define GRANTLEE_TEXTDOCUMENT_NO_EXPORT __attribute__((visibility("hidden")))
# endif
#endif
#ifndef GRANTLEE_TEXTDOCUMENT_DEPRECATED
# define GRANTLEE_TEXTDOCUMENT_DEPRECATED __attribute__ ((__deprecated__))
#endif
#ifndef GRANTLEE_TEXTDOCUMENT_DEPRECATED_EXPORT
# define GRANTLEE_TEXTDOCUMENT_DEPRECATED_EXPORT GRANTLEE_TEXTDOCUMENT_EXPORT GRANTLEE_TEXTDOCUMENT_DEPRECATED
#endif
#ifndef GRANTLEE_TEXTDOCUMENT_DEPRECATED_NO_EXPORT
# define GRANTLEE_TEXTDOCUMENT_DEPRECATED_NO_EXPORT GRANTLEE_TEXTDOCUMENT_NO_EXPORT GRANTLEE_TEXTDOCUMENT_DEPRECATED
#endif
#if 0 /* DEFINE_NO_DEPRECATED */
# ifndef GRANTLEE_TEXTDOCUMENT_NO_DEPRECATED
# define GRANTLEE_TEXTDOCUMENT_NO_DEPRECATED
# endif
#endif
#endif /* GRANTLEE_TEXTDOCUMENT_EXPORT_H */
@@ -1,7 +0,0 @@
#define GRANTLEE_VERSION_MAJOR 5
#define GRANTLEE_VERSION_MINOR 3
#define GRANTLEE_VERSION_PATCH 0
#define GRANTLEE_VERSION_STRING "5.3.0"
#define GRANTLEE_VERSION ((5<<16)|(3<<8)|(0))
#define GRANTLEE_MAJOR_MINOR_VERSION_STRING "5.3"
#define GRANTLEE_MIN_PLUGIN_VERSION 0
@@ -1,306 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_MARKUPDIRECTOR_H
#define GRANTLEE_MARKUPDIRECTOR_H
#include "abstractmarkupbuilder.h"
#include "grantlee_textdocument_export.h"
#include <QtGui/QTextDocument>
#include <QtGui/QTextFrame>
class QTextTable;
class QTextTableCell;
class QTextList;
class QTextCharFormat;
namespace Grantlee
{
class MarkupDirectorPrivate;
/// @headerfile markupdirector.h grantlee/markupdirector.h
/**
@brief Instructs a builder object to create markup output
The **%MarkupDirector** is used with an implementation of
AbstractMarkupBuilder to create a marked up document output.
Usage can be quite simple.
@code
auto doc = editor->document(); // editor is a QTextEdit
auto builder = new HTMLBuilder();
auto md = new MarkupDirector(builder);
md->processDocument(doc);
browser->setHtml(builder->getResult()); // browser is a QTextBrowser.
@endcode
Or with a different builder:
@code
auto builder = new PlainTextMarkupBuilder();
auto md = new MarkupDirector(builder);
md->processDocument(doc);
browser->setPlainText(builder->getResult());
@endcode
The **%MarkupDirector** also provides API for processing just part of a
QTextDocument, such as a QTextFrame or a QTextBlock. The appropriate method
may then be called with an invalid iterator as appropriate.
@code
// ... Do some processing to get a QTextFrame.
auto frame = getFrame();
auto builder = new PlainTextMarkupBuilder();
auto md = new MarkupDirector(builder);
// Create output from only the frame.
md->processFrame(QTextFrame::iterator(), frame);
browser->setPlainText(builder->getResult());
@endcode
The behaviour of the **%MarkupDirector** can be customized by subclassing.
Support for custom types can also be added by implementing the @ref
processCustomFragment method.
@see @ref custom_qtextobject
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEXTDOCUMENT_EXPORT MarkupDirector
{
public:
/**
Constructor
*/
MarkupDirector(AbstractMarkupBuilder *builder);
/**
Destructor
*/
virtual ~MarkupDirector();
/**
Constructs the output by directing the builder to create the markup.
*/
virtual void processDocument(QTextDocument *doc);
/**
Directs the builder to create output for the single @p frame. If calling
this method directly, an invalid QTextFrame::iterator may be used.
*/
virtual QTextFrame::iterator processFrame(QTextFrame::iterator it,
QTextFrame *frame);
/**
Directs the builder to create output for the single @p block. If calling
this method directly, an invalid QTextFrame::iterator may be used.
This method does not process the contents of the @p block, but uses the
@ref processBlockContents method to do so.
*/
virtual QTextFrame::iterator processBlock(QTextFrame::iterator it,
const QTextBlock &block);
/**
Directs the builder to create output for the single @p textObject. If
calling this method directly, an invalid QTextFrame::iterator may be used.
The block @p block is the container of the @p textObject.
*/
virtual QTextFrame::iterator processObject(QTextFrame::iterator it,
const QTextBlock &block,
QTextObject *textObject);
/**
Directs the builder to create output for the single @p textBlockGroup. If
calling this method directly, an invalid QTextFrame::iterator may be used.
The block @p block is the first block in the @p textBlockGroup.
*/
virtual QPair<QTextFrame::iterator, QTextBlock>
processBlockGroup(QTextFrame::iterator it, const QTextBlock &block,
QTextBlockGroup *textBlockGroup);
/**
Directs the builder to create output for the single @p textList. If
calling this method directly, an invalid QTextFrame::iterator may be used.
The block @p block is the first block in the @p textList.
*/
virtual QPair<QTextFrame::iterator, QTextBlock>
processList(QTextFrame::iterator it, const QTextBlock &block,
QTextList *textList);
/**
Directs the builder to create output for the contents of the single @p
block. If calling this method directly, an invalid QTextFrame::iterator
may be used.
*/
virtual QTextFrame::iterator processBlockContents(QTextFrame::iterator it,
const QTextBlock &block);
/**
Hook for instructing the builder to create output for the @p fragemnt with
a custom type. @p doc is the document the fragment is in.
*/
virtual void processCustomFragment(const QTextFragment &fragment,
QTextDocument const *doc);
/**
Directs the builder to create output for the contents of the single @p
fragment. If calling this method directly, an invalid QTextBlock::iterator
may be used. @p doc is the document the fragment is in.
*/
virtual QTextBlock::iterator processFragment(QTextBlock::iterator it,
const QTextFragment &fragment,
QTextDocument const *doc);
/**
Directs the builder to create output for the contents of the single @p
textObject. The @p textObject is represented in the QTextDocument with the
QTextFragment @p fragment.
If calling this method directly, an invalid QTextBlock::iterator may be
used.
*/
virtual QTextBlock::iterator
processCharTextObject(QTextBlock::iterator it, const QTextFragment &fragment,
QTextObject *textObject);
/**
Directs the builder to create output for the image represented by the @p
imageFormat.
If calling this method directly, an invalid QTextBlock::iterator may be
used. @p doc is the document the fragment is in.
*/
virtual QTextBlock::iterator processImage(QTextBlock::iterator it,
const QTextImageFormat &imageFormat,
QTextDocument *doc);
/**
Directs the builder to create output for the contents of the single @p
table.
If calling this method directly, an invalid QTextFrame::iterator may be
used.
*/
virtual QTextFrame::iterator processTable(QTextFrame::iterator it,
QTextTable *table);
/**
Directs the builder to create output for the contents of the single @p
tableCell. The tableCell is in the @p table.
*/
virtual void processTableCell(const QTextTableCell &tableCell,
QTextTable *table);
protected:
/**
Processes the document between @p begin and @p end
*/
void processDocumentContents(QTextFrame::iterator begin,
QTextFrame::iterator end);
/**
Iterates the iterator @p it to the first block after @p blockGroup. @p
_block is any block in the @p blockGroup.
The return pair is the iterator pointing after the end of @p blockGroup
and the first block after @p blockGroup.
*/
QPair<QTextFrame::iterator, QTextBlock>
skipBlockGroup(QTextFrame::iterator it, const QTextBlock &_block,
QTextBlockGroup *blockGroup);
/**
Returns a list of tags contained in @p openingTags sorted so they can be
opened in order and will be closed in the correct order.
@p openingTags should be a set of tags opened at the fragment pointed to
by @p it.
*/
QList<int> sortOpeningOrder(QSet<int> openingTags,
QTextBlock::iterator it) const;
/**
Directs the builder to close the appropriate tags at the position of @p
it.
*/
virtual void processClosingElements(QTextBlock::iterator it);
/**
Directs the builder to open the appropriate tags at the position of @p it.
*/
virtual void processOpeningElements(QTextBlock::iterator it);
/**
Returns the tags that should be closed at the position of @p it.
*/
virtual QSet<int> getElementsToClose(QTextBlock::iterator it) const;
/**
Returns the tags that should be opened at the position of @p it.
*/
virtual QList<int> getElementsToOpen(QTextBlock::iterator it);
/**
Flags for the tags that may be open.
*/
enum OpenElementValues {
None = 0x0, /// No tags are open
SuperScript = 0x01, /// A superscript tag is open
SubScript = 0x02, /// A subscript tag is open
Anchor = 0x04, /// An anchor tag is open
SpanForeground = 0x08, /// A foreground altering span tag is open.
SpanBackground = 0x10, /// A background altering span tag is open.
SpanFontFamily = 0x20, /// A font family altering span tag is open.
SpanFontPointSize = 0x40, /// A font size altering span tag is open.
Strong = 0x80, /// A strong tag is open.
Emph = 0x100, /// A emphasis tag is open.
Underline = 0x200, /// An underline tag is open.
StrikeOut = 0x400 /// A strikeout tag is open.
};
protected:
#ifndef Q_QDOC
MarkupDirectorPrivate *const d_ptr;
#endif
/**
The builder this MarkupDirector is operating on. This is available when
subclassing to customize behaviour.
*/
AbstractMarkupBuilder *m_builder;
#ifndef Q_QDOC
private:
Q_DECLARE_PRIVATE(MarkupDirector)
#endif
};
}
#endif
@@ -1,79 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_MEDIAWIKIMARKUPBUILDER_H
#define GRANTLEE_MEDIAWIKIMARKUPBUILDER_H
#include "abstractmarkupbuilder.h"
namespace Grantlee
{
/**
@brief Creates MediaWiki markup from a QTextDocument
*/
class MediaWikiMarkupBuilder : public AbstractMarkupBuilder
{
public:
MediaWikiMarkupBuilder();
~MediaWikiMarkupBuilder() override;
void beginStrong() override;
void endStrong() override;
void beginEmph() override;
void endEmph() override;
void beginUnderline() override;
void endUnderline() override;
void beginStrikeout() override;
void endStrikeout() override;
void endParagraph() override;
void addNewline() override;
void beginAnchor(const QString &href = {}, const QString &name = {}) override;
void endAnchor() override;
void beginHeader(int level) override;
void endHeader(int level) override;
void beginList(QTextListFormat::Style type) override;
void endList() override;
void beginListItem() override;
void endListItem() override;
void appendLiteralText(const QString &text) override;
/**
Escapes @p text appropriately for MediaWiki.
*/
const QString escape(const QString &s);
QString getResult() override;
private:
QList<QTextListFormat::Style> currentListItemStyles;
QString m_text;
};
}
#endif
@@ -1,244 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Michael Jansen <kde@michael-jansen.biz>
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_METATYPE_H
#define GRANTLEE_METATYPE_H
#include "grantlee_templates_export.h"
#include "typeaccessor.h"
#include <QtCore/QVariant>
/// @file
namespace Grantlee
{
/// @headerfile metatype.h grantlee/metatype.h
#ifndef Q_QDOC
/**
@brief The **%MetaType** is the interface to the Grantlee introspection
system.
The **%MetaType** class is used as part of the type registration system of
%Grantlee.
@see @ref generic_types_and_templates
@author Michael Jansen <kde@michael-jansen.biz>
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT MetaType
{
public:
/**
@internal The signature for a property lookup method
*/
typedef QVariant (*LookupFunction)(const QVariant &, const QString &);
/**
@internal Registers a property lookup method
*/
static void registerLookUpOperator(int id, LookupFunction f);
/**
@internal
*/
static void internalLock();
/**
@internal
*/
static void internalUnlock();
/**
@internal
*/
static QVariant lookup(const QVariant &object, const QString &property);
/**
@internal
*/
static bool lookupAlreadyRegistered(int id);
private:
MetaType();
};
#endif
namespace
{
/*
This is a helper to select an appropriate overload of indexAccess
*/
template <typename RealType, typename HandleAs> struct LookupTrait {
static QVariant doLookUp(const QVariant &object, const QString &property)
{
typedef typename Grantlee::TypeAccessor<RealType> Accessor;
return Accessor::lookUp(object.value<RealType>(), property);
}
};
template <typename RealType, typename HandleAs>
struct LookupTrait<RealType &, HandleAs &> {
static QVariant doLookUp(const QVariant &object, const QString &property)
{
typedef typename Grantlee::TypeAccessor<HandleAs &> Accessor;
return Accessor::lookUp(object.value<HandleAs>(), property);
}
};
template <typename RealType, typename HandleAs> static int doRegister(int id)
{
if (MetaType::lookupAlreadyRegistered(id))
return id;
QVariant (*lf)(const QVariant &, const QString &)
= LookupTrait<RealType, HandleAs>::doLookUp;
MetaType::registerLookUpOperator(
id, reinterpret_cast<MetaType::LookupFunction>(lf));
return id;
}
/*
Register a type so grantlee knows how to handle it.
*/
template <typename RealType, typename HandleAs> struct InternalRegisterType {
static int doReg()
{
const int id = qMetaTypeId<RealType>();
return doRegister<RealType &, HandleAs &>(id);
}
};
template <typename RealType, typename HandleAs>
struct InternalRegisterType<RealType *, HandleAs *> {
static int doReg()
{
const int id = qMetaTypeId<RealType *>();
return doRegister<RealType *, HandleAs *>(id);
}
};
}
/**
@brief Registers the type RealType with the metatype system.
This method can take a second template parameter to specify a cast
that should be invoked during registration. This is useful if a base type is
already supported.
@code
class SomeType
{
public:
QString someProp() const;
};
// define some introspectable API for SomeType
GRANTLEE_BEGIN_LOOKUP(SomeType)
if (property == "someProp")
return object.someProp();
GRANTLEE_END_LOOKUP
class OtherType : public SomeType
{
// ...
};
registerMetaType<SomeType>();
// Only the introspectable API from SomeType is needed, so we can reuse that
registration.
registerMetaType<OtherType, SomeType>();
@endcode
@see @ref generic_types_and_templates
*/
template <typename RealType, typename HandleAs> int registerMetaType()
{
MetaType::internalLock();
const int id = InternalRegisterType<RealType, HandleAs>::doReg();
MetaType::internalUnlock();
return id;
}
#ifndef Q_QDOC
/**
@internal
Register a type so %Grantlee knows how to handle it.
This is a convenience method.
*/
template <typename Type> int registerMetaType()
{
return registerMetaType<Type, Type>();
}
#endif
} // namespace Grantlee
/**
Top boundary of a lookup function for Type.
@see @ref generic_types
*/
#define GRANTLEE_BEGIN_LOOKUP(Type) \
namespace Grantlee \
{ \
template <> \
inline QVariant TypeAccessor<Type &>::lookUp(const Type &object, \
const QString &property) \
{
/**
Top boundary of a lookup function for Type*.
@see @ref generic_types
*/
#define GRANTLEE_BEGIN_LOOKUP_PTR(Type) \
namespace Grantlee \
{ \
template <> \
inline QVariant TypeAccessor<Type *>::lookUp(const Type *const object, \
const QString &property) \
{
/**
Bottom boundary of a lookup function for Type.
@see @ref generic_types
*/
#define GRANTLEE_END_LOOKUP \
return QVariant(); \
} \
}
#endif // #define GRANTLEE_METATYPE_H
@@ -1,380 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_NODE_H
#define GRANTLEE_NODE_H
// krazy:excludeall=dpointer
#include "context.h"
#include "filterexpression.h"
#include "grantlee_templates_export.h"
#include "outputstream.h"
#include "safestring.h"
#include <QtCore/QStringList>
// Need these for inheriting from QList<T> to work
// http://lists.trolltech.com/qt-interest/2008-01/thread00578-0.html
#include <QtCore/QSet>
#include <QtCore/QVector>
namespace Grantlee
{
class Engine;
class NodeList;
class TemplateImpl;
class NodePrivate;
/// @headerfile node.h grantlee/node.h
/**
@brief Base class for all nodes.
The **%Node** class can be implemented to make additional functionality
available to Templates.
A node is represented in template markup as content surrounded by percent
signed tokens.
@code
text content
{% some_tag arg1 arg2 %}
text content
{% some_other_tag arg1 arg2 %}
text content
{% end_some_other_tag %}
text content
@endcode
This is parsed into a tree of **%Node** objects by an implementation of
AbstractNodeFactory. The **%Node** objects can then later be rendered by their
@ref render method.
Rendering a **%Node** will usually mean writing some output to the stream. The
content written to the stream could be determined by the arguments to the tag,
or by the content of child nodes between a start and end tag, or both.
@see FilterExpression
@see @ref tags
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Node : public QObject
{
Q_OBJECT
public:
/**
Constructor.
@param parent The parent QObject
*/
explicit Node(QObject *parent = {});
/**
Destructor.
*/
~Node() override;
/**
Reimplement this to render the template in the Context @p c.
This will also involve calling render on and child nodes.
*/
virtual void render(OutputStream *stream, Context *c) const = 0;
#ifndef Q_QDOC
/**
@internal
*/
virtual bool mustBeFirst()
{ // krazy:exclude:inline
return false;
}
#endif
protected:
/**
Renders the value @p input in the Context @p c. This will involve escaping
@p input if necessary.
This is only relevant to developing template tags.
*/
void streamValueInContext(OutputStream *stream, const QVariant &input,
Grantlee::Context *c) const;
/**
Returns a raw pointer to the Template this **%Node** is in.
*/
TemplateImpl *containerTemplate() const;
private:
Q_DECLARE_PRIVATE(Node)
NodePrivate *const d_ptr;
};
/// @headerfile node.h grantlee/node.h
/**
@brief A list of Nodes with some convenience API for rendering them.
Typically, tags which have an end tag will create and later render a list of
child nodes.
This class contains API such as @ref append and @ref render to make creating
such list easily.
The @ref findChildren method behaves similarly to the QObject::findChildren
method, returning a list of nodes of a particular type from the Node objects
contained in the list (and their children).
@see @ref tags_with_end_tags
*/
class GRANTLEE_TEMPLATES_EXPORT NodeList : public QList<Grantlee::Node *>
{
public:
/**
Creates an empty **%NodeList**.
*/
NodeList();
/**
Copy constructor.
*/
NodeList(const NodeList &list);
NodeList &operator=(const NodeList &list);
/**
Convenience constructor
*/
/* implicit */ NodeList(const QList<Grantlee::Node *> &list);
/**
Destructor.
*/
~NodeList();
/**
Appends @p node to the end of this **%NodeList**.
*/
void append(Grantlee::Node *node);
/**
Appends @p nodeList to the end of this **%NodeList**.
*/
void append(QList<Grantlee::Node *> nodeList);
/**
Returns true if this **%NodeList** contains non-text nodes.
*/
bool containsNonText() const;
/**
A recursive listing of nodes in this tree of type @p T.
*/
template <typename T> QList<T> findChildren()
{
QList<T> children;
QList<Grantlee::Node *>::const_iterator it;
const QList<Grantlee::Node *>::const_iterator first = constBegin();
const QList<Grantlee::Node *>::const_iterator last = constEnd();
for (it = first; it != last; ++it) {
T object = qobject_cast<T>(*it);
if (object) {
children << object;
}
children << (*it)->findChildren<T>();
}
return children;
}
/**
Renders the list of Nodes in the Context @p c.
*/
void render(OutputStream *stream, Context *c) const;
private:
bool m_containsNonText;
};
class AbstractNodeFactoryPrivate;
/// @headerfile node.h grantlee/node.h
/**
@brief Base class for all NodeFactories
This class can be used to make custom tags available to templates.
The getNode method should be implemented to return a Node to be rendered.
A node is represented in template markup as content surrounded by percent
signed tokens.
@code
text content
{% some_tag arg1 arg2 %}
text content
{% some_other_tag arg1 arg2 %}
text content
{% end_some_other_tag %}
text content
@endcode
It is the responsibility of an **%AbstractNodeFactory** implementation to
process the contents of a tag and return a Node implementation from its
getNode method.
The @ref getNode method would for example be called with the tagContent
\"<tt>some_tag arg1 arg2</tt>\". That content could then be split up, the
arguments processed and a Node created
@code
Node* SomeTagFactory::getNode(const QString &tagContent, Parser *p) {
QStringList parts = smartSplit( tagContent );
parts.removeFirst(); // Remove the "some_tag" part.
FilterExpression arg1( parts.first(), p );
FilterExpression arg2( parts.at( 1 ), p );
return new SomeTagNode( arg1, arg2, p );
}
@endcode
The @ref getNode implementation might also advance the parser. For example if
we had a @gr_tag{times} tag which rendered content the amount of times it was
given in its argument, it could be used like this:
@code
Some text content.
{% times 5 %}
the bit to be repeated
{% end_times %}
End text content
@endcode
The argument to @gr_tag{times} might not be a simple number, but could be a
FilterExpression such as \"<tt>someobject.some_property|getDigit:1</tt>\".
The implementation could look like
@code
Node* SomeOtherTagFactory::getNode(const QString &tagContent, Parser *p) {
QStringList parts = smartSplit( tagContent );
parts.removeFirst(); // Remove the "times" part.
FilterExpression arg( parts.first(), p );
auto node = new SomeTagNode( arg, p );
auto childNodes = p->parse( node, "end_times" );
node->setChildNodes( childNodes );
p->removeNextToken();
return node;
}
@endcode
Note that it is necessary to invoke the parser to create the child nodes only
after creating the Node to return. That node must be passed to the Parser to
perform as the parent QObject to the child nodes.
@see Parser::parse
*/
class GRANTLEE_TEMPLATES_EXPORT AbstractNodeFactory : public QObject
{
Q_OBJECT
public:
/**
Constructor.
@param parent The parent QObject
*/
explicit AbstractNodeFactory(QObject *parent = {});
/**
Destructor.
*/
~AbstractNodeFactory() override;
/**
This method should be reimplemented to return a Node which can be
rendered.
The @p tagContent is the content of the tag including the tag name and
arguments. For example, if the template content is @gr_tag{my_tag arg1
arg2}, the tagContent will be &quot;my_tag arg1 arg2&quot;.
The Parser @p p is available and can be advanced if appropriate. For
example, if the tag has an end tag, the parser can be advanced to the end
tag.
@see tags
*/
virtual Node *getNode(const QString &tagContent, Parser *p) const = 0;
#ifndef Q_QDOC
/**
@internal
Sets the Engine which created this NodeFactory. Used by the
ScriptableNodeFactory.
*/
virtual void setEngine(Engine *) {}
#endif
protected:
/**
Splits @p str into a list, taking quote marks into account.
This is typically used in the implementation of getNode with the
tagContent.
If @p str is 'one &quot;two three&quot; four 'five &quot; six' seven', the
returned list will contain the following strings:
- one
- &quot;two three&quot;
- four
- five &quot; six
- seven
*/
Q_INVOKABLE QStringList smartSplit(const QString &str) const;
protected:
/**
Returns a list of FilterExpression objects created with Parser @p p as
described by the content of @p list.
This is used for convenience when handling the arguments to a tag.
*/
QList<FilterExpression> getFilterExpressionList(const QStringList &list,
Parser *p) const;
private:
Q_DECLARE_PRIVATE(AbstractNodeFactory)
AbstractNodeFactoryPrivate *const d_ptr;
};
}
#endif
@@ -1,145 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_OUTPUTSTREAM_H
#define GRANTLEE_OUTPUTSTREAM_H
#include "grantlee_templates_export.h"
#include <QtCore/QSharedPointer>
#include <QtCore/QTextStream>
namespace Grantlee
{
class SafeString;
/// @headerfile outputstream.h grantlee/outputstream.h
/**
@brief The **%OutputStream** class is used to render templates to a
QTextStream
A **%OutputStream** instance may be passed to the render method of a Template
to render the template to a stream.
@code
QFile outputFile("./output");
outputFile.open(QFile::WriteOnly);
QTextStream tstream( &outputFile );
OutputStream os(&tstream);
t->render( &os, &context );
@endcode
The **%OutputStream** is used to escape the content streamed to it. By
default, the escaping is html escaping, converting "&" to "&amp;" for example.
If generating non-html output, the @ref escape method may be overriden to
perform a different escaping, or non at all.
If overriding the @ref escape method, the @ref clone method must also be
overriden to return an **%OutputStream** with the same escaping behaviour.
@code
class NoEscapeStream : public Grantlee::OutputStream
{
public:
// ...
QString escape( const QString &input ) const
{
return input;
}
QSharedPointer<OutputStream> clone( QTextStream *stream ) const
{
return QSharedPointer<NoEscapeStream>::create( stream );
}
};
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT OutputStream
{
public:
/**
Creates a null **%OutputStream**. Content streamed to
this **%OutputStream** is sent to <tt>/dev/null</tt>
*/
OutputStream();
/**
Creates an **%OutputStream** which will stream content to @p stream
with appropriate escaping.
*/
explicit OutputStream(QTextStream *stream);
/**
Destructor
*/
virtual ~OutputStream();
/**
Returns an escaped version of @p input. Does not write anything to the
stream.
*/
virtual QString escape(const QString &input) const;
/**
Returns an escaped version of @p input. Does not write anything to the
stream.
*/
QString escape(const SafeString &input) const;
/**
Returns a cloned **%OutputStream** with the same filtering behaviour.
*/
virtual QSharedPointer<OutputStream> clone(QTextStream *stream) const;
/**
Returns @p after escaping it, unless @p input is "safe", in which case,
@p input is returned unmodified.
*/
QString conditionalEscape(const Grantlee::SafeString &input) const;
/**
Writes @p input to the stream after escaping it.
*/
OutputStream &operator<<(const QString &input);
/**
Writes @p input to the stream after escaping it if necessary.
*/
OutputStream &operator<<(const SafeString &input);
/**
Reads the content of @p stream and writes it unmodified to the result
stream.
*/
OutputStream &operator<<(QTextStream *stream);
private:
QTextStream *m_stream;
Q_DISABLE_COPY(OutputStream)
};
}
#endif
@@ -1,144 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_PARSER_H
#define GRANTLEE_PARSER_H
#include "filter.h"
#include "node.h"
#include "token.h"
#include <QtCore/QStringList>
namespace Grantlee
{
class TemplateImpl;
class ParserPrivate;
/// @headerfile parser.h grantlee/parser.h
/**
@brief The **%Parser** class processes a string template into a tree of nodes.
For application developers, this class is internal.
For template tag authors it may be necessary to advance the parser and process
contained tags if the tag works in a tag -- endtag fashion.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Parser : public QObject
{
Q_OBJECT
public:
/**
Constructor.
Initialises the **%Parser** with the @p tokenList.
*/
Parser(const QList<Token> &tokenList, QObject *parent);
/**
Destructor.
*/
~Parser() override;
/**
Advance the parser, using @p parent as the parent of new Nodes. The parser
will stop if it encounters a tag which is contained in the list @p stopAt.
For example, the @gr_tag{if} tag would stopAt both @gr_tag{endif} and
@gr_tag{else} tags.
@see AbstractNodeFactory::getNode
*/
NodeList parse(Node *parent, const QStringList &stopAt = {});
/**
This is an overloaded method.
@see parse.
*/
NodeList parse(TemplateImpl *parent, const QStringList &stopAt = {});
/**
This is an overloaded method.
@see parse.
*/
NodeList parse(Node *parent, const QString &stopAt);
/**
Returns the filter object called @p name or an invalid object if no filter
with that name is loaded.
*/
QSharedPointer<Filter> getFilter(const QString &name) const;
/**
Advances the parser to the tag @p tag. This method is similar to @ref parse,
but it does not create nodes for tags encountered.
*/
void skipPast(const QString &tag);
/**
Returns the next token to be processed by the parser. This can be examined
in template tag implementations to determine why parsing stopped.
For example, if the @gr_tag{if} tag, parsing may stop at an @gr_tag{else}
tag, in which case parsing should be restarted, or it could stop at an
@gr_tag{endif} tag, in which case parsing is finished for that node.
*/
Token takeNextToken();
/**
Returns whether the parser has another token to process.
*/
bool hasNextToken() const;
/**
Deletes the next token available to the parser.
*/
void removeNextToken();
void invalidBlockTag(const Token &token, const QString &command,
const QStringList &stopAt = {});
#ifndef Q_QDOC
/**
@internal
Used by the @gr_tag{load} tag to load libraries.
*/
void loadLib(const QString &name);
#endif
protected:
/**
Puts the token @p token to the front of the list to be processed by the
parser.
*/
void prependToken(const Token &token);
private:
Q_DECLARE_PRIVATE(Parser)
ParserPrivate *const d_ptr;
};
}
#endif
@@ -1,211 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_PLAINTEXTMARKUPBUILDER_H
#define GRANTLEE_PLAINTEXTMARKUPBUILDER_H
#ifdef Q_OS_WIN
#pragma warning(disable : 4250)
#endif
#define LETTERSINALPHABET 26
#define DIGITSOFFSET 10
#include "abstractmarkupbuilder.h"
#include "grantlee_textdocument_export.h"
#include "markupdirector.h"
class QBrush;
namespace Grantlee
{
class PlainTextMarkupBuilderPrivate;
/// @headerfile plaintextmarkupbuilder.h grantlee/plaintextmarkupbuilder.h
/**
@brief Creates a simple marked up plain text document
This class creates a simple plain text markup.
Text that may be represented as
@code
A paragraph with <b>bold</b> text, <i>italic</i> text,
and <u>underlined</u> text.
@endcode
would be output as
@code
A paragraph with *bold* text /italic/ text,
and _underlined_ text.
@endcode
The markup is intended to be simple, plain and easily human readable. No
markup is created for different font-familiy, font-size, foreground or
background colors.
Lists are marked up by preceding the list element with '*' for disc, 'o' for
circle, 'X' for square, or a letter or number. Lists are also indented if
nested. eg:
@code
A. One
B. Two
o Three
o Four
\* Five
\* Six
C. Seven
@endcode
External references such as external urls and images are represented in the
body text as a reference, and references are maintained at the bottom of the
output.
Eg,
@code
Here is a link to <a href="http://www.kde.org">KDE</a> and
the <a href="http://pim.kde.org">KDEPIM project</a>.
@endcode
becomes:
@code
Here is a link to KDE[1], and
the KDEPIM project[2].
---- References ----
[1] http://www.kde.org
[2] http://pim.kde.org
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEXTDOCUMENT_EXPORT PlainTextMarkupBuilder
: virtual public AbstractMarkupBuilder
{
public:
PlainTextMarkupBuilder();
~PlainTextMarkupBuilder() override;
void beginStrong() override;
void endStrong() override;
void beginEmph() override;
void endEmph() override;
void beginUnderline() override;
void endUnderline() override;
void beginStrikeout() override;
void endStrikeout() override;
void beginAnchor(const QString &href = {}, const QString &name = {}) override;
void endAnchor() override;
void beginForeground(const QBrush &brush) override;
void endForeground() override;
void beginBackground(const QBrush &brush) override;
void endBackground() override;
void beginFontFamily(const QString &family) override;
void endFontFamily() override;
void beginFontPointSize(int size) override;
void endFontPointSize() override;
void beginParagraph(Qt::Alignment a = Qt::AlignLeft, qreal top = 0.0,
qreal bottom = 0.0, qreal left = 0.0,
qreal right = 0.0) override;
void endParagraph() override;
void addNewline() override;
void insertHorizontalRule(int width = -1) override;
void insertImage(const QString &src, qreal width, qreal height) override;
void beginList(QTextListFormat::Style style) override;
void endList() override;
void beginListItem() override;
void endListItem() override;
void beginSuperscript() override;
void endSuperscript() override;
void beginSubscript() override;
void endSubscript() override;
void beginTable(qreal cellpadding, qreal cellspacing,
const QString &width) override;
void beginTableRow() override;
void beginTableHeaderCell(const QString &width, int colSpan,
int rowSpan) override;
void beginTableCell(const QString &width, int colSpan, int rowSpan) override;
void endTable() override;
void endTableRow() override;
void endTableHeaderCell() override;
void endTableCell() override;
void beginHeader(int level) override;
void endHeader(int level) override;
void appendLiteralText(const QString &text) override;
void appendRawText(const QString &text) override;
/**
Adds a reference to @p reference to the internal list of references in the
document.
*/
int addReference(const QString &reference);
/**
Returns the finalised plain text markup, including references at the end.
*/
QString getResult() override;
private:
PlainTextMarkupBuilderPrivate *const d_ptr;
Q_DECLARE_PRIVATE(PlainTextMarkupBuilder)
};
}
#endif
@@ -1,135 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_QTLOCALIZER_P_H
#define GRANTLEE_QTLOCALIZER_P_H
#include "abstractlocalizer.h"
class QTranslator;
namespace Grantlee
{
class QtLocalizerPrivate;
/**
@brief Provides internationalization based on QLocale and QTranslator.
This class implements access to the %Qt Localization system. Localizable
types such as strings, numbers, dates and times can be processed.
@code
auto t = m_engine->loadTemplate(someTemplate);
auto c = getContext();
// Render with the German locale
c.setLocalizer(m_de_Localizer);
auto deText = t->render(&c);
de_display->setText(deText);
// Render with the French locale
c.setLocalizer(m_fr_Localizer);
auto frText = t->render(&c);
fr_display->setText(frText);
@endcode
*/
class GRANTLEE_TEMPLATES_EXPORT QtLocalizer : public AbstractLocalizer
{
public:
/**
Constructs a new **%QtLocalizer** using the @p locale
*/
QtLocalizer(const QLocale &locale = QLocale::system());
/**
Destructor
*/
~QtLocalizer() override;
/**
Set the path to look for translations of the application strings.
*/
void setAppTranslatorPath(const QString &path);
/**
Set the prefix of translation files. For example, if the German translation
file is called <tt>myapp_de_DE.qm</tt>, the prefix should be set to
<tt>myapp_</tt>.
*/
void setAppTranslatorPrefix(const QString &prefix);
/**
Install a @p translator to use for a particular @p localeName.
@code
auto deTranslator = new QTranslator(this);
auto loaded = deTranslator->load("myapp_de_DE");
if (!loaded)
return;
de_localizer->installTranslator(deTranslator, "de_DE");
@endcode
*/
void installTranslator(QTranslator *translator,
const QString &localeName = QLocale::system().name());
QString currentLocale() const override;
void pushLocale(const QString &localeName) override;
void popLocale() override;
void loadCatalog(const QString &path, const QString &catalog) override;
void unloadCatalog(const QString &catalog) override;
QString localizeNumber(int number) const override;
QString localizeNumber(qreal number) const override;
QString localizeMonetaryValue(qreal value, const QString &currencyCode
= {}) const override;
QString localizeDate(const QDate &date,
QLocale::FormatType formatType
= QLocale::ShortFormat) const override;
QString localizeTime(const QTime &time,
QLocale::FormatType formatType
= QLocale::ShortFormat) const override;
QString localizeDateTime(const QDateTime &dateTime,
QLocale::FormatType formatType
= QLocale::ShortFormat) const override;
QString localizeString(const QString &string,
const QVariantList &arguments = {}) const override;
QString localizeContextString(const QString &string, const QString &context,
const QVariantList &arguments
= {}) const override;
QString localizePluralContextString(const QString &string,
const QString &pluralForm,
const QString &context,
const QVariantList &arguments
= {}) const override;
QString localizePluralString(const QString &string, const QString &pluralForm,
const QVariantList &arguments
= {}) const override;
private:
Q_DECLARE_PRIVATE(QtLocalizer)
Q_DISABLE_COPY(QtLocalizer)
QtLocalizerPrivate *const d_ptr;
};
}
#endif
@@ -1,83 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_RENDERCONTEXT_H
#define GRANTLEE_RENDERCONTEXT_H
#include "grantlee_templates_export.h"
#include <QtCore/QVariantHash>
/// @headerfile rendercontext.h grantlee/rendercontext.h
namespace Grantlee
{
class ContextPrivate;
class TemplateImpl;
class Node;
class RenderContextPrivate;
/**
@brief Provides storage facility for state while rendering a template.
This class can not be instatiated by users of it. An instance
of **%RenderContext** is available through Context::renderContext() for use
with implementations of re-entrant template tags.
*/
class GRANTLEE_TEMPLATES_EXPORT RenderContext
{
public:
/**
Returns the data for the node @p scopeNode.
*/
QVariant &data(const Node *const scopeNode);
/**
Returns whether the **%RenderContext** contains data for @p scopeNode.
*/
bool contains(Node *const scopeNode) const;
/**
Destructor
*/
~RenderContext();
#ifndef Q_QDOC
private:
RenderContext();
void push();
void pop();
private:
friend class ContextPrivate;
friend class TemplateImpl;
Q_DISABLE_COPY(RenderContext)
Q_DECLARE_PRIVATE(RenderContext)
RenderContextPrivate *const d_ptr;
#endif
};
}
#endif
@@ -1,436 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_SAFESTRING_H
#define GRANTLEE_SAFESTRING_H
#include "grantlee_templates_export.h"
#include <QtCore/QString>
#include <QtCore/QVariant>
namespace Grantlee
{
/// @headerfile safestring.h grantlee/safestring.h
/**
@brief A QString wrapper class for containing whether a string is safe or
needs to be escaped.
This allows lazy escaping of strings. Otherwise a string may be escaped
multiple times where it should only be escaped once.
The **%SafeString** class itself provides information about whether a string
is safe from further escaping through the @ref isSafe method. The actual
string content held by the **%SafeString** instance is available through the
@ref get method. The @ref get method returns a QString subclass which should
be used like any other QString. The difference is that all methods on
NestedString return a **%SafeString** instead of a QString.
@code
SafeString s("this & that", SafeString::IsSafe);
s.get().replace( "this", "these" ).toUpper();
qDebug() << s.get() << s.isSafe(); // outputs "these & that" false
@endcode
Note that most operations on strings make the string unsafe. For example,
while <tt>"K &amp; R"</tt> is safe, using replace("m", "n") will result in
<tt>"K &anp; R"</tt>, which is unsafe. Likewise using upper() will return
<tt>"K &AMP; R"</tt>, which is unsafe. Because the **%SafeString** can not
determine whether a method call with particular arguments will change
a **%SafeString** from being safe to being unsafe, any operation which can
possibly make the string unsafe does cause the string to become unsafe. It is
then up to the caller to restore safe-ness if needed.
NestedString has overloads for SafeStrings whereever appropriate so that
strings remain marked as safe where possible.
For example:
@code
SafeString s1("this & that", SafeString::IsSafe);
s2 = s1;
s1.append( QString( " & the other" ) );
// s1 is now "this & that & the other" and is unsafe.
SafeString s3(" Wobl & Bob", SafeString::IsSafe);
s2.append(s3);
// Both s2 and s3 are safe, and append is a safe operation, so s2
// is still safe
@endcode
@see @ref autoescaping
@see OutputStream::escape
The **%SafeString** class has appropriate operator overloads to make it
convenient to use in methods returning a QVariant, such as Filter::doFilter,
or as a QString. Note that a raw QString is essentially the same
as a **%SafeString** which is marked as unsafe.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT SafeString
{
public:
/**
Possible safety states of a **%SafeString**
*/
enum Safety {
IsSafe, ///< The string is safe and requires no further escaping
IsNotSafe ///< The string is not safe. It will be escaped before being
/// added to the output of rendering.
};
/**
Constructs an empty **%SafeString**.
*/
SafeString();
/**
Copy constructor
*/
SafeString(const SafeString &safeString);
/**
Constructs a **%SafeString** with the content @p str whose safety is given
by @p safe.
*/
SafeString(const QString &str, bool safe);
/**
Constructs a **%SafeString** with the content @p str whose safety is given
by @p safety.
*/
/* implicit */ SafeString(const QString &str,
Safety safety
= IsNotSafe); // krazy:exclude=explicit
/**
Destructor
*/
~SafeString();
#ifndef Q_QDOC
/**
Set whether the string should be escaped.
*/
void setNeedsEscape(bool needsEscape);
#endif
/**
Whether the string needs to be escaped.
*/
bool needsEscape() const;
/**
Whether the string is safe.
*/
bool isSafe() const;
#ifndef Q_QDOC
/**
Set whether the string is safe.
*/
void setSafety(Safety safety);
#endif
/**
@brief The NestedString is a QString whose methods always return a
SafeString
This class is largely an implementation detail. See the SafeString
documentation for details.
*/
class GRANTLEE_TEMPLATES_EXPORT NestedString : public QString
{
#ifndef Q_QDOC
friend class SafeString;
SafeString *m_safeString;
public:
NestedString(SafeString *safeString);
NestedString(const QString &content, SafeString *safeString);
SafeString &append(const SafeString &str);
SafeString &append(const QString &str);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
SafeString &append(const QStringRef &ref);
#endif
SafeString &append(const QLatin1String &str);
#ifndef QT_NO_CAST_FROM_ASCII
SafeString &append(const QByteArray &ba)
{
QString::append(ba);
m_safeString->m_safety = IsNotSafe;
return *m_safeString;
}
SafeString &append(const char *str)
{
QString::append(str);
m_safeString->m_safety = IsNotSafe;
return *m_safeString;
}
#endif
SafeString &append(const QChar ch);
SafeString &fill(QChar ch, int size = -1);
SafeString &insert(int position, const SafeString &str);
SafeString &insert(int position, const QString &str);
SafeString &insert(int position, const QLatin1String &str);
SafeString &insert(int position, const QChar *unicode, int size);
SafeString &insert(int position, QChar ch);
SafeString left(int n) const;
SafeString leftJustified(int width, QChar fill = QLatin1Char(' '),
bool truncate = {}) const;
SafeString mid(int position, int n = -1) const;
SafeString normalized(NormalizationForm mode) const;
SafeString normalized(NormalizationForm mode,
QChar::UnicodeVersion version) const;
SafeString &prepend(const SafeString &str);
SafeString &prepend(const QString &str);
SafeString &prepend(const QLatin1String &str);
#ifndef QT_NO_CAST_FROM_ASCII
SafeString &prepend(const QByteArray &ba)
{
QString::prepend(ba);
m_safeString->m_safety = IsNotSafe;
return *m_safeString;
}
SafeString &prepend(const char *str)
{
QString::prepend(str);
m_safeString->m_safety = IsNotSafe;
return *m_safeString;
}
#endif
SafeString &prepend(QChar ch);
void push_back(const SafeString &other);
void push_front(const SafeString &other);
SafeString &remove(int position, int n);
SafeString &remove(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &remove(const SafeString &str,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &remove(const QString &str,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &remove(const QRegularExpression &rx);
SafeString repeated(int times) const;
SafeString &replace(int position, int n, const SafeString &after);
SafeString &replace(int position, int n, const QString &after);
SafeString &replace(int position, int n, const QChar *unicode, int size);
SafeString &replace(int position, int n, QChar after);
SafeString &replace(const SafeString &before, const SafeString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QString &before, const SafeString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const SafeString &before, const QString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QString &before, const QString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QChar *before, int blen, const QChar *after,
int alen, Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(QChar ch, const SafeString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(QChar ch, const QString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(QChar before, QChar after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QLatin1String &before, const QLatin1String &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QLatin1String &before, const SafeString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QLatin1String &before, const QString &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const SafeString &before, const QLatin1String &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QString &before, const QLatin1String &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(QChar c, const QLatin1String &after,
Qt::CaseSensitivity cs = Qt::CaseSensitive);
SafeString &replace(const QRegularExpression &rx, const SafeString &after);
SafeString &replace(const QRegularExpression &rx, const QString &after);
SafeString right(int n) const;
SafeString rightJustified(int width, QChar fill = QLatin1Char(' '),
bool truncate = {}) const;
SafeString section(QChar sep, int start, int end = -1,
SectionFlags flags = SectionDefault) const;
SafeString section(const SafeString &sep, int start, int end = -1,
SectionFlags flags = SectionDefault) const;
SafeString section(const QString &sep, int start, int end = -1,
SectionFlags flags = SectionDefault) const;
SafeString section(const QRegularExpression &reg, int start, int end = -1,
SectionFlags flags = SectionDefault) const;
SafeString &setNum(int n, int base = 10);
SafeString &setNum(uint n, int base = 10);
SafeString &setNum(long n, int base = 10);
SafeString &setNum(ulong n, int base = 10);
SafeString &setNum(qlonglong n, int base = 10);
SafeString &setNum(qulonglong n, int base = 10);
SafeString &setNum(short n, int base = 10);
SafeString &setNum(ushort n, int base = 10);
SafeString &setNum(double n, char format = 'g', int precision = 6);
SafeString &setNum(float n, char format = 'g', int precision = 6);
SafeString &setUnicode(const QChar *unicode, int size);
SafeString &setUtf16(const ushort *unicode, int size);
SafeString simplified() const;
// QT_DEPRECATED_SINCE(5, 15) to support consumers building with
// -DQT_DISABLE_DEPRECATED_BEFORE=0x050f00
// where QString enums will be invisible to the compiler
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && QT_DEPRECATED_SINCE(5, 15)
// Calls with default argument for "behavior" should pick the Qt >= 5.14
// version, if available
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList split(const SafeString &sep, QString::SplitBehavior behavior,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QString &sep, QString::SplitBehavior behavior,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QChar &sep, QString::SplitBehavior behavior,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QRegularExpression &rx,
QString::SplitBehavior behavior) const;
#else
QStringList split(const SafeString &sep,
QString::SplitBehavior behavior = QString::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QString &sep,
QString::SplitBehavior behavior = QString::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QChar &sep,
QString::SplitBehavior behavior = QString::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QRegularExpression &rx,
QString::SplitBehavior behavior
= QString::KeepEmptyParts) const;
#endif
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList split(const SafeString &sep,
Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QString &sep,
Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QChar &sep,
Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
QStringList split(const QRegularExpression &rx,
Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const;
#endif
SafeString toLower() const;
SafeString toUpper() const;
SafeString trimmed() const;
void chop(int n);
#endif
};
/**
Returns the String held by this **%SafeString**
*/
const NestedString &get() const { return m_nestedString; }
/**
Returns the String held by this **%SafeString**
*/
NestedString &get() { return m_nestedString; }
/**
Convenience operator for treating a **%SafeString** like a QString.
*/
operator QString() const { return m_nestedString; }
/**
Assignment operator.
*/
SafeString &operator=(const SafeString &str);
/**
Returns a concatenation of this with @p str.
The result is not safe because str is not safe.
*/
SafeString operator+(const QString &str);
/**
Returns a concatenation of this with @p str.
The result is safe if both this and str are safe.
*/
SafeString operator+(const SafeString &str);
/**
Appends the content of @p str to this.
The result is not safe because @p str is not safe.
*/
SafeString &operator+=(const QString &str);
/**
Appends the content of @p str to this.
The result is safe if both this and @p str are safe.
*/
SafeString &operator+=(const SafeString &str);
/**
Returns true if the content of @p other matches the content of this.
Safeness and needing escaping are not accounted for in the comparison.
*/
bool operator==(const SafeString &other) const;
/**
Returns true if the content of @p other matches the content of this.
Safeness and needing escaping are not accounted for in the comparison.
*/
bool operator==(const QString &other) const;
/**
Convenience operator for storing a **%SafeString** in a QVariant.
*/
operator QVariant() const { return QVariant::fromValue(*this); }
private:
#ifndef Q_QDOC
NestedString m_nestedString;
#endif
Safety m_safety;
bool m_needsescape;
};
}
Q_DECLARE_METATYPE(Grantlee::SafeString)
#endif
@@ -1,110 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TAGLIBRARYINTERFACE_H
#define TAGLIBRARYINTERFACE_H
#include "outputstream.h"
#include <QtCore/QHash>
#include <QtCore/QObject>
namespace Grantlee
{
class AbstractNodeFactory;
class Engine;
class Filter;
/// @headerfile taglibraryinterface.h grantlee/taglibraryinterface.h
/**
@brief The **%TagLibraryInterface** returns available tags and filters from
libraries.
This interface must be implemented in tag and filter libraries.
The implementation will usually be very simple.
@code
class MyTagLibrary : public QObject, public TagLibraryInterface
{
Q_OBJECT
Q_INTERFACES( Grantlee::TagLibraryInterface )
public:
MyTagLibrary( QObject *parent = {} )
: QObject( parent ) {
}
QHash<QString, AbstractNodeFactory*>
nodeFactories(const QString &name = {}) {
Q_UNUSED( name );
QHash<QString, AbstractNodeFactory*> nodeFactories;
nodeFactories.insert( "mytag1", new MyTag1() );
nodeFactories.insert( "mytag2", new MyTag2() );
return nodeFactories;
}
QHash<QString, Filter*> filters( const QString &name = {} ) {
Q_UNUSED( name );
QHash<QString, Filter*> filters;
filters.insert( "myfilter1", new MyFilter1() );
filters.insert( "myfilter2", new MyFilter2() );
return filters;
}
};
@endcode
@author Stephen Kelly <steveire@gmail.com>
*/
class TagLibraryInterface
{
public:
virtual ~TagLibraryInterface() {}
/**
Returns the AbstractNodeFactory implementations available in this library.
*/
virtual QHash<QString, AbstractNodeFactory *>
nodeFactories(const QString &name = {})
{
Q_UNUSED(name);
static const QHash<QString, AbstractNodeFactory *> h;
return h;
};
/**
Returns the Filter implementations available in this library.
*/
virtual QHash<QString, Filter *> filters(const QString &name = {})
{
Q_UNUSED(name);
static const QHash<QString, Filter *> h;
return h;
};
};
}
Q_DECLARE_INTERFACE(Grantlee::TagLibraryInterface,
"org.grantlee.TagLibraryInterface/1.0")
#endif
@@ -1,161 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_TEMPLATE_H
#define GRANTLEE_TEMPLATE_H
#include "exception.h"
#include "grantlee_templates_export.h"
#include "node.h"
#include <QtCore/QSharedPointer>
#include <QtCore/QStringList>
namespace Grantlee
{
class Context;
class Engine;
class TemplateImpl;
class OutputStream;
#ifdef Q_QDOC
#define TemplateImpl Template
#else
typedef QSharedPointer<TemplateImpl> Template;
#endif
class TemplatePrivate;
/// @headerfile template.h grantlee/template.h
/**
@brief The **%Template** class is a tree of nodes which may be rendered.
All Templates are created through the Grantlee::Engine class.
A **%Template** is created by parsing some text markup passed into the Engine,
or by reading it from a file.
Note that **%Template** is actually a typedef for a
<tt>QSharedPointer&lt;TemplateImpl&gt;</tt>, so all of its members should be
accessed with <tt>operator-&gt;()</tt>.
The result of parsing is a **%Template** object which can be rendered multiple
times with multiple different Contexts.
@code
auto engine = getEngine();
auto t = engine->newTemplate(
"{{ name }} is aged {{ age }}",
"simple template" );
if ( t->error() )
{
// Tokenizing or parsing error, or couldn't find custom tags or filters.
qDebug() << t->errorString();
return;
}
QTextStream textStream( stdout );
OutputStream stream( textStream );
for ( ... )
{
Context c;
// ... c.insert
t->render( stream, c );
if (t->error())
{
// Rendering error.
qDebug() << t->errorString();
}
}
@endcode
If there is an error in parsing or rendering, the @ref error and @ref
errorString methods can be used to check the source of the error.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT TemplateImpl : public QObject
{
Q_OBJECT
public:
~TemplateImpl() override;
/**
Renders the **%Template** to a string given the Context @p c.
*/
QString render(Context *c) const;
/**
Renders the **%Template** to the OutputStream @p stream given the Context c.
*/
OutputStream *render(OutputStream *stream, Context *c) const;
#ifndef Q_QDOC
/**
@internal
*/
NodeList nodeList() const;
/**
@internal
*/
void setNodeList(const NodeList &list);
#endif
/**
Returns an error code for the error encountered.
*/
Error error() const;
/**
Returns more information to developers in the form of a string.
*/
QString errorString() const;
/**
Returns the Engine that created this **%Template**.
*/
Engine const *engine() const;
#ifndef Q_QDOC
protected:
TemplateImpl(Engine const *engine, QObject *parent = {});
TemplateImpl(Engine const *engine, bool smartTrim, QObject *parent = {});
void setContent(const QString &templateString);
#endif
private:
// Don't allow setting the parent on a Template, which is memory managed as
// a QSharedPointer.
using QObject::setParent;
private:
Q_DECLARE_PRIVATE(Template)
TemplatePrivate *const d_ptr;
#ifndef Q_QDOC
friend class Engine;
friend class Parser;
#endif
};
}
#endif
@@ -1,229 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_TEMPLATELOADER_H
#define GRANTLEE_TEMPLATELOADER_H
#include "grantlee_templates_export.h"
#include "template.h"
#include <QtCore/QSharedPointer>
namespace Grantlee
{
class AbstractLocalizer;
/// @headerfile templateloader.h grantlee/templateloader.h
/**
@brief An retrieval interface to a storage location for Template objects.
This interface can be implemented to define new ways of retrieving the content
of Templates.
The interface of this class should not be called directly from applications.
TemplateLoaders will typically be created, configured and added to the
Grantlee::Engine which will call the appropriate API.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT AbstractTemplateLoader
{
public:
/**
Destructor
*/
virtual ~AbstractTemplateLoader();
/**
Load a Template called @p name. Return an invalid Template if no content
by that name exists.
*/
virtual Template loadByName(const QString &name,
Engine const *engine) const = 0;
/**
Return a complete URI for media identified by fileName.
*/
virtual QPair<QString, QString>
getMediaUri(const QString &fileName) const = 0;
/**
Return true if a Template identified by @p name exists and can be loaded.
*/
virtual bool canLoadTemplate(const QString &name) const = 0;
};
/// @headerfile templateloader.h grantlee/templateloader.h
class FileSystemTemplateLoaderPrivate;
/**
@brief The **%FileSystemTemplateLoader** loads Templates from the file system.
This template loader works by traversing a list of directories to find
templates. Directories are checked in order, and the first match hit is parsed
and returned.
@code
loader->setTemplateDirs({
"/home/user/app/templates",
"/usr/local/share/app/templates"
});
engine->setTemplateLoader( loader );
// This will try /home/user/app/templates/mytemplate.html
// followed by /usr/local/share/app/templates/mytemplate.html
engine->loadByName( "mytemplate.html" );
@endcode
Additionally, a themeName may be set on the template loader, which will be
appended to search paths before the template name.
@code
loader->setTemplateDirs({
"/home/user/app/templates" <<
"/usr/local/share/app/templates"
});
loader->setTheme( "simple_theme" );
engine->setTemplateLoader( loader );
// This will try /home/user/app/templates/simple_theme/mytemplate.html
// followed by /usr/local/share/app/templates/simple_theme/mytemplate.html
engine->loadByName( "mytemplate.html" );
@endcode
Media URIs may be retrieved for media relative to the directories searched
queried for templates.
@code
loader->setTemplateDirs({
"/home/user/app/templates",
"/usr/local/share/app/templates"
});
loader->setTheme( "simple_theme" );
engine->setTemplateLoader( loader );
// This will try /home/user/app/templates/simple_theme/logo.png
// followed by /usr/local/share/app/templates/simple_theme/logo.png
// and return the first one that exists.
engine->mediaUri( "logo.png" );
@endcode
The template files loaded by a %**FileSystemTemplateLoader** must be UTF-8
encoded.
@see @ref deploying_templates
*/
class GRANTLEE_TEMPLATES_EXPORT FileSystemTemplateLoader
: public AbstractTemplateLoader
{
public:
/**
Constructor
*/
FileSystemTemplateLoader(const QSharedPointer<AbstractLocalizer> localizer
= {});
/**
Destructor
*/
~FileSystemTemplateLoader() override;
Template loadByName(const QString &name, Engine const *engine) const override;
bool canLoadTemplate(const QString &name) const override;
QPair<QString, QString> getMediaUri(const QString &fileName) const override;
/**
Sets the theme of this loader to @p themeName
*/
void setTheme(const QString &themeName);
/**
The themeName of this TemplateLoader
*/
QString themeName() const;
/**
Sets the directories to look for template files to @p dirs.
*/
void setTemplateDirs(const QStringList &dirs);
/**
The directories this TemplateLoader looks in for template files.
*/
QStringList templateDirs() const;
private:
Q_DECLARE_PRIVATE(FileSystemTemplateLoader)
FileSystemTemplateLoaderPrivate *const d_ptr;
};
/// @headerfile templateloader.h grantlee/templateloader.h
/**
@brief The **%InMemoryTemplateLoader** loads Templates set dynamically in
memory
This class is mostly used for testing purposes, but can also be used for
simple uses of %Grantlee.
Templates can be made available using the @ref setTemplate method, and will
then be retrieved by the Grantlee::Engine as appropriate.
*/
class GRANTLEE_TEMPLATES_EXPORT InMemoryTemplateLoader
: public AbstractTemplateLoader
{
public:
InMemoryTemplateLoader();
~InMemoryTemplateLoader() override;
Template loadByName(const QString &name, Engine const *engine) const override;
bool canLoadTemplate(const QString &name) const override;
QPair<QString, QString> getMediaUri(const QString &fileName) const override;
/**
Add a template content to this Loader.
Example:
@code
auto loader = QSharedPointer<InMemoryTemplateLoader::create();
loader->setTemplate( "name_template", "My name is {{ name }}" );
loader->setTemplate( "age_template", "My age is {{ age }}" );
engine->addTemplateLoader( loader );
// Both templates may now be retrieved by calling Engine::loadByName.
@endcode
*/
void setTemplate(const QString &name, const QString &content);
private:
QHash<QString, QString> m_namedTemplates;
};
}
#endif
@@ -1,238 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_TEXTHTMLBUILDER_H
#define GRANTLEE_TEXTHTMLBUILDER_H
#ifdef Q_CC_MSVC
#pragma warning(disable : 4250)
#endif
#include "abstractmarkupbuilder.h"
#include "grantlee_textdocument_export.h"
#include "markupdirector.h"
namespace Grantlee
{
class TextHTMLBuilderPrivate;
/// @headerfile texthtmlbuilder.h grantlee/texthtmlbuilder.h
/**
@brief The TextHTMLBuilder creates a clean html markup output.
This class creates html output which is as minimal as possible and restricted
to the rich text features supported in %Qt.
(https://doc.qt.io/qt-5/richtext-html-subset.html)
The output contains only the body content, not the head element or other
metadata.
eg:
@code
<p>
This is some <strong>formatted content</strong> in a paragraph.
</p>
@endcode
instead of the content produced by %Qt:
@code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><meta
http-equiv="Content-Type" content="text/html; charset=UTF-8" /><style
type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:10pt;
font-weight:400; font-style:normal;">
<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px;
margin-right:0px; -qt-block-indent:0; text-indent:0px;">This is some <span
style=" font-weight:600;">formatted content</span> in a paragraph.
</p></body></html>
@endcode
Such tags should be created separately. For example:
@code
auto b = new TextHTMLBuilder();
auto md = new MarkupDirector(b);
md->constructContent();
QString cleanHtml(
"<head>\n<title>%1</title>\n</head>\n<body>%2</body>\n</html>")
.arg(document.metaInformation(QTextDocument::DocumentTitle))
.arg(b->getOutput());
file.write(cleanHtml);
@endcode
Font formatting information on elements is represented by individual span
elements.
eg:
@code
<span style"color:blue;">
<span style="background-color:red;">
Blue text on red background
</span>
</span>
@endcode
instead of
@code
<span style="color:blue;background-color:red;">
Blue text on red background
</span>
@endcode
It my be possible to change this if necessary.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEXTDOCUMENT_EXPORT TextHTMLBuilder
: virtual public AbstractMarkupBuilder
{
public:
TextHTMLBuilder();
~TextHTMLBuilder() override;
void beginStrong() override;
void endStrong() override;
void beginEmph() override;
void endEmph() override;
void beginUnderline() override;
void endUnderline() override;
void beginStrikeout() override;
void endStrikeout() override;
void beginForeground(const QBrush &brush) override;
void endForeground() override;
void beginBackground(const QBrush &brush) override;
void endBackground() override;
void beginAnchor(const QString &href = {}, const QString &name = {}) override;
void endAnchor() override;
// Maybe this stuff should just be added to a list, and then when I add
// literal text,
// add some kind of style attribute in one span instead of many.
void beginFontFamily(const QString &family) override;
void endFontFamily() override;
/**
Begin a new font point size
@param size The new size to begin.
*/
void beginFontPointSize(int size) override;
void endFontPointSize() override;
/**
Begin a new paragraph
@param al The new paragraph alignment
@param topMargin The new paragraph topMargin
@param bottomMargin The new paragraph bottomMargin
@param leftMargin The new paragraph leftMargin
@param rightMargin The new paragraph rightMargin
*/
void beginParagraph(Qt::Alignment al = Qt::AlignLeft, qreal topMargin = 0.0,
qreal bottomMargin = 0.0, qreal leftMargin = 0.0,
qreal rightMargin = 0.0) override;
/**
Begin a new header element.
@param level The new level to begin.
*/
void beginHeader(int level) override;
/**
End a header element.
@param level The new level to end.
*/
void endHeader(int level) override;
void endParagraph() override;
void addNewline() override;
void insertHorizontalRule(int width = -1) override;
void insertImage(const QString &src, qreal width, qreal height) override;
void beginList(QTextListFormat::Style type) override;
void endList() override;
void beginListItem() override;
void endListItem() override;
void beginSuperscript() override;
void endSuperscript() override;
void beginSubscript() override;
void endSubscript() override;
void beginTable(qreal cellpadding, qreal cellspacing,
const QString &width) override;
void beginTableRow() override;
void beginTableHeaderCell(const QString &width, int colspan,
int rowspan) override;
void beginTableCell(const QString &width, int colspan, int rowspan) override;
void endTable() override;
void endTableRow() override;
void endTableHeaderCell() override;
void endTableCell() override;
/**
Reimplemented from AbstractMarkupBuilder.
This implementation escapes the text before appending so that
@verbatim
A sample <b>bold</b> word.
@endverbatim
becomes
@verbatim
A sample &lt;b&gt;bold&lt;/b&gt; word.
@endverbatim
*/
void appendLiteralText(const QString &text) override;
/**
Append @p text without escaping.
This is useful if extending MarkupDirector
*/
void appendRawText(const QString &text) override;
QString getResult() override;
private:
TextHTMLBuilderPrivate *d_ptr;
Q_DECLARE_PRIVATE(TextHTMLBuilder)
};
}
#endif
@@ -1,57 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_TOKEN_H
#define GRANTLEE_TOKEN_H
#include <QtCore/QString>
namespace Grantlee
{
/**
@internal
The available token types.
*/
enum TokenType {
TextToken, ///< The Token is a text fragment
VariableToken, ///< The Token is a variable node
BlockToken, ///< The Token is a block, ie, part of a tag
CommentToken ///< The Token is a comment node.
};
/// @headerfile token.h grantlee/token.h
/**
A token in a parse stream for a template.
This class is only relevant for template tag implementations.
*/
struct Token {
int tokenType; ///< The Type of this Token
int linenumber; ///< The line number this Token starts at
QString content; ///< The content of this Token
};
}
Q_DECLARE_TYPEINFO(Grantlee::Token, Q_MOVABLE_TYPE);
#endif
@@ -1,48 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_TYPEACCESSOR_H
#define GRANTLEE_TYPEACCESSOR_H
#include "grantlee_templates_export.h"
#include <QtCore/QObject>
/// @file
namespace Grantlee
{
#ifndef Q_QDOC
template <typename T> struct TypeAccessor {
static QVariant lookUp(const T object, const QString &property);
};
template <typename T> struct TypeAccessor<T *> {
static QVariant lookUp(const T *const object, const QString &property);
};
template <typename T> struct TypeAccessor<T &> {
static QVariant lookUp(const T &object, const QString &property);
};
#endif
}
#endif
@@ -1,111 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_UTIL_P_H
#define GRANTLEE_UTIL_P_H
#include "context.h"
#include "grantlee_templates_export.h"
#include "safestring.h"
#include <QtCore/QVariant>
/// @file util.h Utility functions used throughout %Grantlee.
namespace Grantlee
{
/**
Returns whether the @p variant is evaluated to true.
@see @ref truthiness
*/
GRANTLEE_TEMPLATES_EXPORT bool variantIsTrue(const QVariant &variant);
/**
Converts the @p input into its unescaped form.
Double slashes are converted to single slashes, \\&quot is converted to &quot
etc.
*/
GRANTLEE_TEMPLATES_EXPORT QString unescapeStringLiteral(const QString &input);
/**
Marks the @p input as safe.
*/
GRANTLEE_TEMPLATES_EXPORT Grantlee::SafeString
markSafe(const Grantlee::SafeString &input);
/**
Marks the @p input as requiring escaping.
*/
GRANTLEE_TEMPLATES_EXPORT Grantlee::SafeString
markForEscaping(const Grantlee::SafeString &input);
/**
Retrieves and returns a SafeString from the @p input.
*/
GRANTLEE_TEMPLATES_EXPORT Grantlee::SafeString
getSafeString(const QVariant &input);
/**
Returns whether @p input contains a SafeString.
*/
GRANTLEE_TEMPLATES_EXPORT bool isSafeString(const QVariant &input);
/**
Returns true if the type of @p input can be inserted into a rendered template
directly.
Note that lists, hashes and QObject*s can not be.
*/
GRANTLEE_TEMPLATES_EXPORT bool supportedOutputType(const QVariant &input);
/**
Compares @p lhs and @p rhs for equality. SafeStrings are compared as raw
QStrings. Their safeness is not part of the comparison.
@see QVariant::operator==
*/
GRANTLEE_TEMPLATES_EXPORT bool equals(const QVariant &lhs, const QVariant &rhs);
/**
Converts @p size into the nearest file size unit like MB or MiB, based on the
@p unitSystem value. Use @c 2 for the @p unitSystem to get binary units, use
@c 10 to get decimal units - by default, decimal units will be returned. The
@p multiplier can be used if the input @p size is not in pure bytes. If @p
size is for example given in @a KiB, use a multiplier of @a 1024. The returned
pair will have the converted size as @a first and the unit as @a second.
*/
GRANTLEE_TEMPLATES_EXPORT std::pair<qreal, QString>
calcFileSize(qreal size, int unitSystem = 10, qreal multiplier = 1.0);
#ifndef Q_QDOC
/**
@internal
Returns the @p list as a formatted string. This is for debugging purposes
only.
*/
GRANTLEE_TEMPLATES_EXPORT Grantlee::SafeString
toString(const QVariantList &list);
#endif
}
#endif
@@ -1,129 +0,0 @@
/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRANTLEE_VARIABLE_H
#define GRANTLEE_VARIABLE_H
#include "grantlee_templates_export.h"
#include <QtCore/QVariant>
namespace Grantlee
{
class Context;
class VariablePrivate;
/// @headerfile variable.h grantlee/variable.h
/**
@brief A container for static variables defined in Templates.
This class is only relevant to Template tag authors.
When processing a template tag in a AbstractNodeFactory implementation, it
will sometimes make sense to process arguments to the tag as
Grantlee::Variables. Note that usually they should be processed as
FilterExpression objects instead.
Arguments to the tag can be used to construct Variables, which may then be
resolved into the objects they represent in the given Context in the render
stage.
@author Stephen Kelly <steveire@gmail.com>
*/
class GRANTLEE_TEMPLATES_EXPORT Variable
{
public:
/**
Constructs an invalid **%Variable**
*/
Variable();
/**
Creates a **%Variable** represented by the given @p var
*/
explicit Variable(const QString &var);
/**
Copy constructor
*/
Variable(const Variable &other);
/**
Destructor
*/
~Variable();
/**
Assignment operator.
*/
Variable &operator=(const Variable &other);
/**
Returns whether this **%Variable** is valid.
*/
bool isValid() const;
/**
Returns whether this **%Variable** evaluates to true with the Context @p c.
*/
bool isTrue(Context *c) const;
/**
Resolves this **%Variable** with the Context @p c.
*/
QVariant resolve(Context *c) const;
/**
Returns whether this **%Variable** is a constant in the Template. A constant
is represented as a static string in the template
@code
Text content
{% some_tag "constant" variable %}
@endcode
*/
bool isConstant() const;
/**
Returns whether this variable is localized, that is, if it is wrapped with
_(). @see @ref i18n_l10n
*/
bool isLocalized() const;
/**
Returns whether this variable is a literal string or number. A
literal **%Variable** does not have any lookup components.
*/
QVariant literal() const;
/**
Returns the lookup components of this **%Variable**.
*/
QStringList lookups() const;
private:
Q_DECLARE_PRIVATE(Variable)
VariablePrivate *const d_ptr;
};
}
#endif
@@ -1,138 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
#
#
# nglapplication
#
SET(nglapplication_SRCS
nglapplication.cpp
nglapplication.h
nglloggerhandler.cpp
nglloggerhandler.h
ngl_qt_msg_handler.inc
ngl_signal_handler.inc
)
NGL_ADD_LIBRARY2(WS AAR SV HLA nglapplication SHARED ${nglapplication_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(nglapplication
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(nglapplication
PRIVATE
NGLLogger
nglsettings
PUBLIC
Qt6::Core
Qt6::Widgets
)
endif()
NGL_INSTALL_TARGET(nglapplication)
#
# nglsingleapplication
#
SET(nglsingleapplication_SRCS
nglsingleapplication.cpp
nglsingleapplication.h
nglloggerhandler.cpp
nglloggerhandler.h
ngl_qt_msg_handler.inc
ngl_signal_handler.inc
)
NGL_ADD_LIBRARY2(WS nglsingleapplication SHARED ${nglsingleapplication_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(nglsingleapplication
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
NGL_TARGET_LINK_LIBRARIES(nglsingleapplication
PRIVATE
NGLLogger
nglsettings
PUBLIC
qtsingleapplication
)
NGL_INSTALL_TARGET(nglsingleapplication)
#
# nglcoreapplication
#
SET(nglcoreapplication_SRCS
nglcoreapplication.cpp
nglcoreapplication.h
nglloggerhandler.cpp
nglloggerhandler.h
ngl_qt_msg_handler.inc
ngl_signal_handler.inc
)
NGL_ADD_LIBRARY2(ALL nglcoreapplication SHARED ${nglcoreapplication_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(nglcoreapplication
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
NGL_TARGET_LINK_LIBRARIES(nglcoreapplication
PRIVATE
NGLLogger
nglsettings
PUBLIC
Qt6::Core
)
NGL_INSTALL_TARGET(nglcoreapplication)
#
# nglsinglecoreapplication
#
SET(nglsinglecoreapplication_SRCS
nglsinglecoreapplication.cpp
nglsinglecoreapplication.h
nglloggerhandler.cpp
nglloggerhandler.h
ngl_qt_msg_handler.inc
ngl_signal_handler.inc
)
NGL_ADD_LIBRARY2(AAR SV nglsinglecoreapplication SHARED ${nglsinglecoreapplication_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(nglsinglecoreapplication
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
NGL_TARGET_LINK_LIBRARIES(nglsinglecoreapplication
PRIVATE
NGLLogger
nglsettings
PUBLIC
qtsinglecoreapplication
)
NGL_INSTALL_TARGET(nglsinglecoreapplication)
#
# nglguiapplication
#
SET(nglguiapplication_SRCS
nglguiapplication.cpp
nglguiapplication.h
nglloggerhandler.cpp
nglloggerhandler.h
ngl_qt_msg_handler.inc
ngl_signal_handler.inc
)
NGL_ADD_LIBRARY2(ALL nglguiapplication SHARED ${nglguiapplication_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(nglguiapplication
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(nglguiapplication
PRIVATE
NGLLogger
nglsettings
PUBLIC
Qt6::Gui
)
endif()
NGL_INSTALL_TARGET(nglguiapplication)
@@ -1,64 +0,0 @@
/**
* @RDE_HEADER@
* callback to catch qt log messages
* $Id$
* $HeadURL$
* $Author$
*/
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtCore/qglobal.h>
static void qtMsgHandler(QtMsgType type, const QMessageLogContext &, const QString &msg)
{
// pulse audio connect errors are important but can be very annoying - so only print it ONE time only and also as an error
static bool pulseAudioMessageSent = false;
static QString pulseAudioMessage = QStringLiteral("PulseAudioService: pa_context_connect() failed");
if (msg.startsWith(pulseAudioMessage))
{
if (pulseAudioMessageSent)
{
return;
}
type = QtCriticalMsg;
pulseAudioMessageSent = true;
}
try
{
NGL::INGLLogger &l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger( "NGL.Qt" );
switch (type) {
case QtDebugMsg:
DEBUG_LOG(l) << msg ;
break;
case QtInfoMsg:
INFO_LOG(l) << msg ;
break;
case QtWarningMsg:
WARNING_LOG(l) << msg ;
break;
case QtCriticalMsg:
ERROR_LOG(l) << msg ;
break;
case QtFatalMsg:
FATAL_LOG(l) << msg ;
break;
}
} catch (...) {
switch (type)
{
case QtDebugMsg:
case QtInfoMsg:
fputs(qPrintable(msg), stdout);
break;
case QtWarningMsg:
case QtCriticalMsg:
case QtFatalMsg:
fputs(qPrintable(msg), stderr);
break;
}
}
}
@@ -1,41 +0,0 @@
/**
* @RDE_HEADER@
* small stub to catch SIGTERM for proper shutdown
* $Id$
* $HeadURL$
* $Author$
*/
#include <signal.h>
#include <QtCore/QCoreApplication>
#ifdef Q_OS_WIN
#include <QtCore/QAbstractNativeEventFilter>
#include <windows.h>
class MyEventFilter final : public QAbstractNativeEventFilter
{
public:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override
{
Q_UNUSED(eventType);
Q_UNUSED(result);
const MSG *msg = reinterpret_cast<const MSG*>(message);
if (msg->message == WM_CLOSE && msg->hwnd == nullptr)
QCoreApplication::quit();
return false;
}
};
#endif
#ifndef SIGTERM
# define SIGTERM 15
#endif
static void signalHandler(int signal_number)
{
if(signal_number != SIGTERM)
return;
QCoreApplication::quit();
}
@@ -1,36 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QApplication for window handling
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglapplication.h"
#include "ngl_signal_handler.inc"
//----------------------------------------------------------------------------
NGLApplication::NGLApplication(int &argc, char **argv)
: QApplication(argc, argv)
{
// auf SIGTERM reagieren
signal(SIGTERM, &signalHandler);
#ifdef Q_OS_WIN
installNativeEventFilter(new MyEventFilter);
#endif
}
//----------------------------------------------------------------------------
bool NGLApplication::notify(QObject *o, QEvent *e)
{
bool bRet = false;
try
{
bRet = QApplication::notify(o, e);
}
catch (const std::exception &e)
{
fprintf(stderr, "exception %s\n", e.what());
}
return bRet;
}
@@ -1,41 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QApplication for window handling
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtWidgets/QApplication>
#include "nglloggerhandler.h"
#ifndef NGLAPPLICATION_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define NGLAPPLICATION_EXPORT
# else
# ifdef MAKE_NGLAPPLICATION_LIB
# define NGLAPPLICATION_EXPORT Q_DECL_EXPORT
# else
# define NGLAPPLICATION_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
}
class NGLAPPLICATION_EXPORT NGLApplication : public QApplication, public NGL::LoggerHandler
{
Q_OBJECT
public:
NGLApplication(int &argc, char **argv);
protected:
bool notify(QObject *o, QEvent *e) override;
};
#define nglApp static_cast<NGLApplication*>(NGLApplication::instance())
@@ -1,22 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglcoreapplication.h"
#include "ngl_signal_handler.inc"
//----------------------------------------------------------------------------
NGLCoreApplication::NGLCoreApplication(int &argc, char **argv)
: QCoreApplication(argc, argv)
{
// auf SIGTERM reagieren
signal(SIGTERM, &signalHandler);
#ifdef Q_OS_WIN
installNativeEventFilter(new MyEventFilter);
#endif
}
@@ -1,36 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtCore/QCoreApplication>
#include "nglloggerhandler.h"
#ifndef NGLCOREAPPLICATION_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define NGLCOREAPPLICATION_EXPORT
# else
# ifdef MAKE_NGLCOREAPPLICATION_LIB
# define NGLCOREAPPLICATION_EXPORT Q_DECL_EXPORT
# else
# define NGLCOREAPPLICATION_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
}
class NGLCOREAPPLICATION_EXPORT NGLCoreApplication : public QCoreApplication, public NGL::LoggerHandler
{
Q_OBJECT
public:
NGLCoreApplication(int &argc, char **argv);
};
@@ -1,22 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglguiapplication.h"
#include "ngl_signal_handler.inc"
//----------------------------------------------------------------------------
NGLGuiApplication::NGLGuiApplication(int &argc, char **argv)
: QGuiApplication(argc, argv)
{
// auf SIGTERM reagieren
signal(SIGTERM, &signalHandler);
#ifdef Q_OS_WIN
installNativeEventFilter(new MyEventFilter);
#endif
}
@@ -1,38 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtGui/QGuiApplication>
#include "nglloggerhandler.h"
#ifndef NGLGUIAPPLICATION_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define NGLGUIAPPLICATION_EXPORT
# else
# ifdef MAKE_NGLGUIAPPLICATION_LIB
# define NGLGUIAPPLICATION_EXPORT Q_DECL_EXPORT
# else
# define NGLGUIAPPLICATION_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
}
class NGLGUIAPPLICATION_EXPORT NGLGuiApplication : public QGuiApplication, public NGL::LoggerHandler
{
Q_OBJECT
public:
NGLGuiApplication(int &argc, char **argv);
};
#define nglGuiApp static_cast<NGLGuiApplication*>(NGLGuiApplication::instance())
@@ -1,96 +0,0 @@
/**
* @RDE_HEADER@
* Logger handling stuff for NGL(Core|Gui)Application
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglloggerhandler.h"
#include "ngl_qt_msg_handler.inc"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <nglsettings/nglsettings_settings.h>
#include <nglcoreapplication.h>
namespace NGL
{
static QByteArray username()
{
#ifdef Q_OS_WIN
return qgetenv("USERNAME");
#else
return qgetenv("USER");
#endif
}
static void setEnvVars()
{
// set LOGPATH to the globally configured path
const QString logPath = NGL::Settings::logPath();
qputenv("LOG4QT_LOGDIR", logPath.toLocal8Bit());
qputenv("LOG4QT_USER", username());
}
//----------------------------------------------------------------------------
void LoggerHandler::createLogger(const QByteArray &baseName, const char *configFileName, bool quiet)
{
setEnvVars();
m_baseLoggerName = baseName;
const QString bnStr(QString::fromLatin1(baseName.toLower()));
const QString logPath = NGL::Settings::logPath();
m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr;
m_loggerFilenamePrefix = QLatin1String(".log");
const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix;
NGL::NGLLoggerBootstrap::createNGLRootLogger(QString::fromLatin1(configFileName), false, logOutputName, quiet);
// Qt-Messages abfangen
qInstallMessageHandler(&qtMsgHandler);
}
//----------------------------------------------------------------------------
void LoggerHandler::createLogger(const QByteArray &baseName, int exerciseId, int additionalId, bool quiet)
{
setEnvVars();
const QString bnStr(QString::fromLatin1(baseName.toLower()));
const QString configFileName = QLatin1String("log4cxx_") + bnStr + QLatin1String(".props");
const QString logPath = NGL::Settings::logPath();
m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr;
if (exerciseId > 0)
m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(exerciseId);
if (additionalId > 0)
m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(additionalId);
m_loggerFilenamePrefix = QLatin1String(".log");
m_baseLoggerName = baseName + QByteArray(".main");
const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix;
NGL::NGLLoggerBootstrap::createNGLRootLogger(configFileName, false, logOutputName, quiet);
// Qt-Messages abfangen
qInstallMessageHandler(&qtMsgHandler);
}
//----------------------------------------------------------------------------
NGL::INGLLogger &LoggerHandler::baseLogger() const
{
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(m_baseLoggerName.data());
}
//----------------------------------------------------------------------------
NGL::INGLLogger &LoggerHandler::logger(const char *loggerName) const
{
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName);
}
//----------------------------------------------------------------------------
LoggerHandler *LoggerHandler::getLoggerHandler()
{
return dynamic_cast<LoggerHandler*>(QCoreApplication::instance());
}
} // namespace NGL
@@ -1,88 +0,0 @@
/**
* @RDE_HEADER@
* Logger handling stuff for NGL(Core|Gui)Application
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtCore/QByteArray>
#include <QtCore/QString>
#ifndef LOGGERHANDLER_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define LOGGERHANDLER_EXPORT
# else
# if defined(MAKE_NGLCOREAPPLICATION_LIB) || defined(MAKE_NGLGUIAPPLICATION_LIB) || defined(MAKE_NGLAPPLICATION_LIB) || defined(MAKE_NGLSINGLECOREAPPLICATION_LIB) || defined(MAKE_NGLSINGLEAPPLICATION_LIB)
# define LOGGERHANDLER_EXPORT Q_DECL_EXPORT
# else
# define LOGGERHANDLER_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
class LOGGERHANDLER_EXPORT LoggerHandler
{
public:
LoggerHandler() = default;
~LoggerHandler() = default;
/**
* @brief Creates a NGL RootLogger instance, using baseName as the name for the base logger and configFileName for the .props file
* @param baseName the name of the service/application
* @param configFileName The file name with the logging informations
* @param checkTime the time (in seconds) to check for modifications of the file
*/
void createLogger(const QByteArray &baseName,
const char *configFileName,
bool quiet = false);
/**
* @brief Creates a NGL RootLogger instance, using <svcName>.main as the base logger name,
* configFileName is created with 'log4cxx_<svcNameLowerCase>.props'
* @param baseName the name of the service/application
* @param exerciseId the (optional) exercise id, if > 0,
* @param additionalId an (optional) id to be used for logfile name creation,
* the output log name is created with ${USER}_<svcNameLowerCase>_<exerciseId>.log
*/
void createLogger(const QByteArray &baseName,
int exerciseId = 0,
int additionalId = 0,
bool quiet = false);
/**
* @brief get the base Logger created with createLogger()
*/
NGL::INGLLogger &baseLogger() const;
/**
* @brief Get a logger with the given name
* @param The logger to retrieve
*/
NGL::INGLLogger &logger(const char *loggerName) const;
/**
* @brief get the log filename postfix (e.g. /shd/CTC/log/ctc_foo)
*/
QString loggerNamePostfix() const { return m_loggerFilenamePostfix; }
/**
* @brief get the log filename prefix (e.g. .log)
*/
QString loggerNamePrefix() const { return m_loggerFilenamePrefix; }
/**
* @brief Retrieves the loggerhandler from ngl(core)application or nullptr
*/
static LoggerHandler *getLoggerHandler();
private:
QByteArray m_baseLoggerName;
QString m_loggerFilenamePostfix;
QString m_loggerFilenamePrefix;
};
} // namespace NGL
@@ -1,37 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QtSingleApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglsingleapplication.h"
#include "ngl_signal_handler.inc"
//----------------------------------------------------------------------------
NGLSingleApplication::NGLSingleApplication(int &argc, char **argv)
: QtSingleApplication(argc, argv)
{
// auf SIGTERM reagieren
signal(SIGTERM, &signalHandler);
#ifdef Q_OS_WIN
installNativeEventFilter(new MyEventFilter);
#endif
}
//----------------------------------------------------------------------------
bool NGLSingleApplication::notify(QObject *o, QEvent *e)
{
bool bRet = false;
try
{
bRet = QtSingleApplication::notify(o, e);
}
catch (const std::exception &e)
{
fprintf(stderr, "exception %s\n", e.what());
}
return bRet;
}
@@ -1,41 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QtSingleApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtSingleApplication/QtSingleApplication>
#include "nglloggerhandler.h"
#ifndef NGLSINGLEAPPLICATION_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define NGLSINGLEAPPLICATION_EXPORT
# else
# ifdef MAKE_NGLSINGLEAPPLICATION_LIB
# define NGLSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT
# else
# define NGLSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
}
class NGLSINGLEAPPLICATION_EXPORT NGLSingleApplication : public QtSingleApplication, public NGL::LoggerHandler
{
Q_OBJECT
public:
NGLSingleApplication(int &argc, char **argv);
protected:
bool notify(QObject *o, QEvent *e) override;
};
#define nglApp static_cast<NGLSingleApplication*>(NGLSingleApplication::instance())
@@ -1,22 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#include "nglsinglecoreapplication.h"
#include "ngl_signal_handler.inc"
//----------------------------------------------------------------------------
NGLSingleCoreApplication::NGLSingleCoreApplication(int &argc, char **argv)
: QtSingleCoreApplication(argc, argv)
{
// auf SIGTERM reagieren
signal(SIGTERM, &signalHandler);
#ifdef Q_OS_WIN
installNativeEventFilter(new MyEventFilter);
#endif
}
@@ -1,36 +0,0 @@
/**
* @RDE_HEADER@
* small extension to QCoreApplication with NGL specific stuff
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtSingleApplication/QtSingleCoreApplication>
#include "nglloggerhandler.h"
#ifndef NGLSINGLECOREAPPLICATION_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define NGLSINGLECOREAPPLICATION_EXPORT
# else
# ifdef MAKE_NGLSINGLECOREAPPLICATION_LIB
# define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_EXPORT
# else
# define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
namespace NGL
{
class INGLLogger;
}
class NGLSINGLECOREAPPLICATION_EXPORT NGLSingleCoreApplication : public QtSingleCoreApplication, public NGL::LoggerHandler
{
Q_OBJECT
public:
NGLSingleCoreApplication(int &argc, char **argv);
};
@@ -1,7 +0,0 @@
#ifndef POPPLER_QT5_POPPLER_QT5_H
#define POPPLER_QT5_POPPLER_QT5_H
/* Compatibility wrapper: include poppler-qt6 header when project includes poppler/qt5/poppler-qt5.h */
#include <poppler/qt6/poppler-qt6.h>
#endif // POPPLER_QT5_POPPLER_QT5_H
@@ -1,144 +0,0 @@
/*
* $Id$
*
* (c) Copyright, Real-Time Innovations, 2016-.
* All rights reserved.
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HPP_SERVICE_DYNAMIC_BUFFER_HPP_
#define HPP_SERVICE_DYNAMIC_BUFFER_HPP_
// IMPORTANT: macros.hpp must be the first RTI header included in every header
// file so that symbols are exported correctly on Windows
#include <dds/core/macros.hpp>
#include "osapi/osapi_heap.h"
#include <dds/core/Value.hpp>
#include <dds/core/types.hpp>
#include <rti/apputils/ServiceException.hpp>
namespace rti { namespace apputils {
class DynamicBufferProperty {
public:
DynamicBufferProperty(int32_t min_size, bool trim_to_size)
:min_size_(min_size), trim_to_size_(trim_to_size)
{
}
DynamicBufferProperty(const DynamicBufferProperty &property)
:min_size_(property.min_size_), trim_to_size_(property.trim_to_size_)
{
}
DynamicBufferProperty& min_size(int32_t min_size)
{
min_size_ = min_size;
return *this;
}
int32_t min_size() const
{
return min_size_;
}
DynamicBufferProperty& trim_to_size(bool trim_to_size)
{
trim_to_size_ = trim_to_size;
return *this;
}
bool trim_to_size() const
{
return trim_to_size_;
}
private:
int32_t min_size_;
bool trim_to_size_;
};
class DynamicBuffer {
public:
DynamicBuffer(const DynamicBufferProperty &property)
:property_(property), buffer_(NULL), buffer_length_(0)
{
ensure_length(property.min_size());
}
~DynamicBuffer()
{
if (buffer_ != NULL) {
RTIOsapiHeap_freeArray(buffer_);
buffer_ = NULL;
}
buffer_length_ = 0;
}
void ensure_length(int32_t new_length)
{
if (new_length > buffer_length_) {
if (!RTIOsapiHeap_reallocateArray(&buffer_, new_length, char)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_OSAPI_MEMORY_LOG_OUT_OF_HEAP_STRING_d,
new_length);
}
buffer_length_ = new_length;
}
}
void trim_to_size()
{
if (property_.trim_to_size()) {
if (!RTIOsapiHeap_reallocateArray(
&buffer_,
property_.min_size(),
char)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_OSAPI_MEMORY_LOG_OUT_OF_HEAP_STRING_d,
property_.min_size());
}
buffer_length_ = property_.min_size();
}
}
void release(char *&buffer, int32_t& length)
{
buffer = buffer_;
length = buffer_length_;
buffer_ = NULL;
buffer_length_ = 0;
}
void own(char *buffer, int32_t length)
{
buffer_ = buffer;
buffer_length_ = length;
}
char *buffer()
{
return buffer_;
}
int32_t length()
{
return buffer_length_;
}
private:
const DynamicBufferProperty property_;
char* buffer_;
int32_t buffer_length_;
};
} } /* namespace rti::apputils */
#endif /* HPP_SERVICE_DYNAMIC_BUFFER_HPP_ */
@@ -1,247 +0,0 @@
/*
* (c) Copyright, Real-Time Innovations, 2016-.
* All rights reserved.
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HPP_SERVICE_DYNAMIC_DATA_CONVERTER_HPP_
#define HPP_SERVICE_DYNAMIC_DATA_CONVERTER_HPP_
// IMPORTANT: macros.hpp must be the first RTI header included in every header
// file so that symbols are exported correctly on Windows
#include <dds/core/macros.hpp>
#include "osapi/osapi_heap.h"
#include <dds/core/Value.hpp>
#include <dds/core/types.hpp>
#include <assert.h>
#include <dds/core/xtypes/DynamicType.hpp>
#include <dds/core/xtypes/DynamicData.hpp>
#include <rti/core/NativeValueType.hpp>
#include <rti/apputils/ServiceException.hpp>
#include <rti/apputils/DynamicBuffer.hpp>
#include "apputils/apputils_dynamic_data_converter_impl.h"
namespace rti { namespace apputils {
class DynamicDataConverter {
public:
class ScopedSample {
public:
ScopedSample(
APPUTILSDynamicDataConverter *converter,
DDS_DynamicData *native) :
converter_(converter),
native_(native)
{
}
~ScopedSample()
{
APPUTILSDynamicDataConverter_return_sample(converter_, native_);
}
dds::core::xtypes::DynamicData& get()
{
return rti::core::native_conversions::cast_from_native<
dds::core::xtypes::DynamicData>(*native_);
}
private:
APPUTILSDynamicDataConverter *converter_;
DDS_DynamicData *native_;
};
class ScopedBuffer {
public:
ScopedBuffer() : converter_(NULL), native_(NULL), native_length_(0)
{
}
ScopedBuffer(
APPUTILSDynamicDataConverter *converter,
void *native,
uint32_t native_length) :
converter_(converter),
native_(native),
native_length_(native_length)
{
}
~ScopedBuffer()
{
if (native_ != NULL) {
APPUTILSDynamicDataConverter_return_buffer(converter_, native_);
}
}
void clear()
{
assign(converter_, NULL, 0);
}
void assign(
APPUTILSDynamicDataConverter *converter,
void *native,
uint32_t native_length)
{
if (native_ != NULL) {
APPUTILSDynamicDataConverter_return_buffer(
converter_,
const_cast<void *>(native_));
}
converter_ = converter;
native_ = native;
native_length_ = native_length;
}
ScopedBuffer& operator =(ScopedBuffer& other)
{
assign(other.converter_, other.native_, other.native_length_);
return *this;
}
const void * get()
{
return native_;
}
template <typename T>
const T * get() {
return static_cast<const T *>(native_);
}
uint32_t length()
{
return native_length_;
}
private:
APPUTILSDynamicDataConverter *converter_;
void *native_;
uint32_t native_length_;
};
/**
* The dynamic data converter allows for deferred initialization. When doing
* so, it can be initialized at any moment by calling the set() method.
*/
DynamicDataConverter() : initialized_(false) {}
/**
* Direct initialization constructor. A valid type-code has to be provided
* (not null and it has to be a non-primitive and non null type-kind type).
*/
DynamicDataConverter(
const dds::core::xtypes::DynamicType& type_code,
const DynamicBufferProperty &property) :
initialized_(false)
{
set(type_code, property);
}
/**
* Initialize this dynamic data converter. A valid type-code has to be
* provided (not null and it has to be a non-primitive and non null
* type-kind type).
* If the converter has already been initialized, this method is a no-op.
*/
void set(
const dds::core::xtypes::DynamicType& type_code,
const DynamicBufferProperty &property)
{
if (!initialized_) {
if (!APPUTILSDynamicDataConverter_initialize(
&converter_,
&(type_code.native()),
(RTI_UINT32) property.min_size())) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native converter");
}
initialized_ = true;
}
}
~DynamicDataConverter()
{
if (initialized_) {
APPUTILSDynamicDataConverter_finalize(&converter_);
}
}
ScopedSample sample(
const dds::core::xtypes::DynamicData& sample,
const DDS_DataRepresentationId_t target_representation)
{
DDS_DynamicData *native = APPUTILSDynamicDataConverter_get_sample(
&converter_,
const_cast<DDS_DynamicData *>(&sample.native()),
target_representation);
if (native == NULL) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"get native sample");
}
return ScopedSample(&converter_, native);
}
ScopedBuffer buffer(
const dds::core::xtypes::DynamicData& sample,
const DDS_DataRepresentationId_t target_representation)
{
DDS_UnsignedLong native_length = 0;
void *native = APPUTILSDynamicDataConverter_get_buffer(
&converter_,
&native_length,
const_cast<DDS_DynamicData *>(&sample.native()),
target_representation);
if (native == NULL) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"get native buffer");
}
return ScopedBuffer(&converter_, native, (uint32_t) native_length);
}
void buffer(
ScopedBuffer& scoped_buffer,
const dds::core::xtypes::DynamicData& sample,
const DDS_DataRepresentationId_t target_representation)
{
DDS_UnsignedLong native_length = 0;
/*
* The scoped buffer has to be cleared before we can use it again. The
* buffer will automatically be returned to this converter. After this,
* we can safely get the buffer again from the dynamic data sample and
* reassign to the scoped buffer.
*/
scoped_buffer.clear();
void *native = APPUTILSDynamicDataConverter_get_buffer(
&converter_,
&native_length,
const_cast<DDS_DynamicData *>(&sample.native()),
target_representation);
if (native == NULL) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"get native buffer");
}
scoped_buffer.assign(&converter_, native, (uint32_t) native_length);
}
private:
APPUTILSDynamicDataConverter converter_;
bool initialized_;
};
} } /* namespace rti::apputils */
#endif /* HPP_SERVICE_DYNAMIC_DATA_CONVERTER_HPP_ */
@@ -1,243 +0,0 @@
/*
* (c) Copyright, Real-Time Innovations, 2017-.
* All rights reserved.
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*
*/
#ifndef HPP_SERVICE_ENTITY_ID_HPP_
#define HPP_SERVICE_ENTITY_ID_HPP_
// IMPORTANT: macros.hpp must be the first RTI header included in every header
// file so that symbols are exported correctly on Windows
#include <dds/core/macros.hpp>
#include "rtixmlutils/rtixmlutils_object.h"
namespace rti { namespace apputils {
class EntityFullNameIterator {
public:
EntityFullNameIterator(const std::string& full_name)
: full_name_(full_name), substring_pos_(0), next_substring_pos_(0)
{
next();
}
~EntityFullNameIterator()
{
}
bool is_end() const
{
return substring_pos_ == full_name_.length();
}
EntityFullNameIterator& end()
{
substring_pos_ = full_name_.length();
next_substring_pos_ = substring_pos_;
return *this;
}
EntityFullNameIterator& last()
{
next_substring_pos_ = full_name_.length();
substring_pos_ = next_substring_pos_;
for (; substring_pos_ > 0; --substring_pos_) {
if (full_name_[substring_pos_] == '\"') {
size_t opening_quotes = full_name_.rfind(
"\"",
substring_pos_ - 1);
if (opening_quotes == std::string::npos) {
DDSLog_warn(
&RTI_LOG_ANY_s,
"detected unbalanced escaped name. Missing closing '\"'?");
} else {
// skip all characters in escaped name
substring_pos_ = opening_quotes;
}
} else if (full_name_.find(
RTIXMLUTILS_OBJECT_NAME_SEPARATOR,
substring_pos_) == substring_pos_) {
substring_pos_ += strlen(RTIXMLUTILS_OBJECT_NAME_SEPARATOR);
break;
}
}
return *this;
}
std::string parent()
{
size_t parent_length = (substring_pos_ == 0)
? 0
: substring_pos_ - strlen(RTIXMLUTILS_OBJECT_NAME_SEPARATOR);
return full_name_.substr(0, parent_length);
}
std::string operator*() const
{
size_t substring_pos = substring_pos_;
size_t name_length = next_substring_pos_ - substring_pos_;
if (name_length > 1
&& full_name_[substring_pos_ + name_length - 1] == '\"'
&& full_name_[substring_pos_] == '\"') {
name_length -= 2;
++substring_pos;
}
return full_name_.substr(substring_pos, name_length);
}
EntityFullNameIterator& operator++()
{
next();
return *this;
}
std::string escaped()
{
size_t substring_pos = substring_pos_;
size_t name_length = next_substring_pos_ - substring_pos_;
return full_name_.substr(substring_pos, name_length);
}
friend bool operator==(
const EntityFullNameIterator &s1,
const EntityFullNameIterator &s2)
{
return s1.substring_pos_ == s2.substring_pos_
&& s1.next_substring_pos_ == s2.next_substring_pos_
&& &s1.full_name_ == &s2.full_name_;
}
friend bool operator!=(
const EntityFullNameIterator &s1,
const EntityFullNameIterator &s2)
{
return !(s1 == s2);
}
private:
void next()
{
if (full_name_.find(
RTIXMLUTILS_OBJECT_NAME_SEPARATOR,
next_substring_pos_) == next_substring_pos_) {
next_substring_pos_ += strlen(RTIXMLUTILS_OBJECT_NAME_SEPARATOR);
}
substring_pos_ = next_substring_pos_;
for (; next_substring_pos_ < full_name_.length(); ++next_substring_pos_) {
if (full_name_[next_substring_pos_] == '\"') {
size_t closing_quotes = full_name_.find(
"\"",
next_substring_pos_ + 1);
if (closing_quotes == std::string::npos) {
DDSLog_warn(
&RTI_LOG_ANY_s,
"detected unbalanced escaped name. Missing closing '\"'?");
} else {
// skip all characters in escaped name
next_substring_pos_ = closing_quotes;
}
} else if (full_name_.find(
RTIXMLUTILS_OBJECT_NAME_SEPARATOR,
next_substring_pos_) == next_substring_pos_) {
break;
}
}
}
private:
const std::string& full_name_;
size_t substring_pos_;
size_t next_substring_pos_;
};
template<typename ENTITY_KIND_TYPE>
class EntityId {
public:
typedef EntityFullNameIterator name_iterator;
public:
EntityId(const std::string& the_full_name, ENTITY_KIND_TYPE the_kind)
: full_name_(the_full_name), kind_(the_kind)
{
}
bool is_nil() const
{
return kind_ == ENTITY_KIND_TYPE::count_;
}
name_iterator begin() const
{
return EntityFullNameIterator(full_name_);
}
name_iterator end() const
{
return EntityFullNameIterator(full_name_).end();
}
const std::string& full_name() const
{
return full_name_;
}
const std::string name() const
{
return (*EntityFullNameIterator(full_name_).last());
}
const std::string parent_name() const
{
return EntityFullNameIterator(full_name_).last().parent();
}
const ENTITY_KIND_TYPE& kind() const
{
return kind_;
}
static EntityId<ENTITY_KIND_TYPE> nil()
{
static EntityId<ENTITY_KIND_TYPE> nil(
"",
ENTITY_KIND_TYPE::count_);
return nil;
}
friend bool operator==(
const EntityId<ENTITY_KIND_TYPE>& left,
const EntityId<ENTITY_KIND_TYPE>& right)
{
return left.kind_ == right.kind_
&& left.full_name_ == right.full_name_;
}
private:
std::string full_name_;
ENTITY_KIND_TYPE kind_;
};
} } /* namespace rti::apputils */
#endif //HPP_SERVICE_ENTITY_ID_HPP_
@@ -1,395 +0,0 @@
/*
* $Id$
*
* (c) Copyright, Real-Time Innovations, 2016-.
* All rights reserved.
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HPP_SERVICE_RESOURCE_IDENTIFIER_HPP_
#define HPP_SERVICE_RESOURCE_IDENTIFIER_HPP_
// IMPORTANT: macros.hpp must be the first RTI header included in every header
// file so that symbols are exported correctly on Windows
#include <dds/core/macros.hpp>
#include <assert.h>
#include "reda/reda_inlineList.h"
#include "apputils/apputils_resource_identifier_impl.h"
#include <dds/core/Value.hpp>
#include <rti/core/NativeValueType.hpp>
#include <rti/apputils/ServiceException.hpp>
#include <rti/apputils/EntityId.hpp>
namespace rti { namespace apputils {
class ResourceIdentifier;
class RelativeResource {
public:
typedef const APPUTILSRelativeResourceInfo native_type;
RelativeResource(native_type *native_value)
: native_relative_resource_(native_value)
{
}
~RelativeResource()
{
}
RelativeResource(const RelativeResource &other)
: native_relative_resource_(other.native_relative_resource_)
{
}
RelativeResource operator * () const
{
return RelativeResource(*this);
}
RelativeResource & operator = (const RelativeResource& other)
{
native_relative_resource_ = other.native_relative_resource_;
return *this;
}
RelativeResource& operator ++ ()
{
native_relative_resource_ = next();
return *this;
}
RelativeResource& operator -- ()
{
native_relative_resource_ = prev();
return *this;
}
friend bool operator == (
const RelativeResource & s1,
const RelativeResource & s2)
{
return s1.native_relative_resource_ == s2.native_relative_resource_;
}
friend bool operator != (
const RelativeResource & s1,
const RelativeResource & s2)
{
return !(s1 == s2);
}
std::string name() const
{
return APPUTILSRelativeResourceInfo_get_name(
native_relative_resource_);
}
std::string kind() const
{
return APPUTILSRelativeResourceInfo_get_kind(
native_relative_resource_);
}
RelativeResource& last()
{
REDAInlineListNode *last = (struct REDAInlineListNode *)
REDAInlineList_getLast(
native_relative_resource_->_node.inlineList);
assert(last != NULL);
native_relative_resource_ = reinterpret_cast<native_type*>(last);
return *this;
}
RelativeResource& begin()
{
REDAInlineListNode *first = (struct REDAInlineListNode *)
REDAInlineList_getFirst(
native_relative_resource_->_node.inlineList);
assert(first != NULL);
native_relative_resource_ = reinterpret_cast<native_type*> (first);
return *this;
}
friend const std::string to_string(
const RelativeResource& relative_id)
{
return relative_id.kind() + "/" + relative_id.name();
}
friend class ResourceIdentifier;
private:
static RelativeResource nil()
{
static RelativeResource nil(NULL);
return nil;
}
native_type *next()
{
return reinterpret_cast<native_type *>(
REDAInlineListNode_getNext(&native_relative_resource_->_node));
}
native_type * prev()
{
void *prev =
REDAInlineListNode_getPrev(&native_relative_resource_->_node);
if (prev != NULL) {
return reinterpret_cast<native_type*> (prev);
}
return native_relative_resource_;
}
private:
native_type *native_relative_resource_;
};
class ResourceIdentifier {
public:
typedef APPUTILSResourceIdentifier native_type;
typedef RelativeResource iterator;
typedef RelativeResource relative_resource;
public:
ResourceIdentifier()
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
}
ResourceIdentifier(const std::string& formatted_uri)
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
if (!APPUTILSResourceIdentifier_parse_formatted_identifier(
&native_,
formatted_uri.c_str())) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_SERVICE_LOG_MALFORMED_RESOURCE_IDENTIFIER_s,
formatted_uri.c_str());
}
parse(formatted_uri);
}
ResourceIdentifier(const ResourceIdentifier& other)
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
append(other);
}
ResourceIdentifier(
const ResourceIdentifier& parent,
const ResourceIdentifier& child)
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
append(parent);
append(child);
}
ResourceIdentifier(
const std::string& kind,
const std::string& name)
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
add(kind, name);
}
ResourceIdentifier(
const ResourceIdentifier::relative_resource& relative_resource)
{
if (!APPUTILSResourceIdentifier_initialize(&native_)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_INIT_FAILURE_s,
"native resource identifier");
}
add(relative_resource);
}
ResourceIdentifier& parse(const std::string& formatted_uri)
{
if (!APPUTILSResourceIdentifier_parse_formatted_identifier(
&native_,
formatted_uri.c_str())) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_SERVICE_LOG_MALFORMED_RESOURCE_IDENTIFIER_s,
formatted_uri.c_str());
}
return *this;
}
~ResourceIdentifier()
{
APPUTILSResourceIdentifier_finalize(&native_);
}
iterator last() const
{
return iterator(APPUTILSResourceIdentifier_get_resource(
const_cast<native_type*> (&native_)));
}
iterator end() const
{
return iterator::nil();
}
iterator begin() const
{
iterator last = this->last();
if (last != end()) {
return last.begin();
}
return last;
}
ResourceIdentifier parent() const
{
ResourceIdentifier parent_id;
iterator it = begin();
for (; it != last(); ++it) {
parent_id += ResourceIdentifier(it.kind(), it.name());
}
return parent_id;
}
std::string fully_qualified_name() const
{
const auto result = APPUTILSResourceIdentifier_get_fully_qualified_name(
const_cast<native_type *>(&native_));
return (result == nullptr) ? "" : result;
}
std::string fully_qualified_kind() const
{
const auto result = APPUTILSResourceIdentifier_get_fully_qualified_kind(
const_cast<native_type *>(&native_));
return (result == nullptr) ? "" : result;
}
std::string custom_method() const
{
const auto result = APPUTILSResourceIdentifier_get_custom_method(
const_cast<native_type *>(&native_));
return (result == nullptr) ? "" : result;
}
ResourceIdentifier& operator+=(
const ResourceIdentifier& right)
{
return append(right);
}
friend std::ostream& operator<<(
std::ostream& os,
const ResourceIdentifier& resource_id)
{
os << to_string(resource_id);
return os;
}
friend const std::string to_string(
const ResourceIdentifier& resource_id)
{
const char* resource_id_str = to_native_string(resource_id);
if (resource_id_str != NULL) {
return std::string(resource_id_str);
} else {
return std::string("");
}
}
friend const char* to_native_string(
const ResourceIdentifier& resource_id)
{
return APPUTILSResourceIdentifier_to_string(
const_cast<native_type*>(&resource_id.native_));
}
native_type& native() const
{
return const_cast<native_type&>(native_);
}
private:
ResourceIdentifier& add(
const std::string& kind,
const std::string& name = "")
{
if (!APPUTILSResourceIdentifier_add_relative_resource(
&native_,
kind.c_str(),
name.c_str())) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ADD_FAILURE_s,
"relative resource");
}
return *this;
}
ResourceIdentifier& add(
const ResourceIdentifier::relative_resource& relative_resource)
{
add(relative_resource.kind(), relative_resource.name());
return *this;
}
ResourceIdentifier& append(
const ResourceIdentifier& right)
{
ResourceIdentifier::iterator it = right.begin();
for (; it != end(); ++it) {
add(it);
}
return *this;
}
native_type native_;
};
} } /* namespace rti::apputils */
#endif /* HPP_SERVICE_RESOURCE_IDENTIFIER_HPP_ */
File diff suppressed because it is too large. Load diff
@@ -1,205 +0,0 @@
/*
* $Id$
*
* (c) Copyright, Real-Time Innovations, 2016-.
* All rights reserved.
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HPP_SERVICE_SERVICE_EXCEPTION_HPP_
#define HPP_SERVICE_SERVICE_EXCEPTION_HPP_
// IMPORTANT: macros.hpp must be the first RTI header included in every header
// file so that symbols are exported correctly on Windows
#include <dds/core/macros.hpp>
#include <dds/core/types.hpp>
#include <rti/core/Exception.hpp>
namespace rti { namespace apputils {
static
void initialize_exception_message(
std::string& message,
const char *throwing_context,
const RTILogMessage *log_message,
va_list ap)
{
char message_buffer[RTI_LOG_MSG_SIZE_MAX];
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_vsnprintf(
message_buffer,
RTI_LOG_MSG_SIZE_MAX,
log_message->format,
ap),
int);
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_snprintf(
&message[0],
RTI_LOG_MSG_SIZE_MAX,
"%s:%s",
throwing_context,
message_buffer),
int);
}
static
void initialize_exception_message(
std::string& message,
const char *throwing_context,
const RTILogMessageTemplate *log_message,
const char *parameterizedString,
va_list ap)
{
char message_buffer[RTI_LOG_MSG_SIZE_MAX];
const char *SEPARATOR_STR = " | ";
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_vsnprintf(
message_buffer,
RTI_LOG_MSG_SIZE_MAX,
parameterizedString,
ap),
int);
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_snprintf(
&message[0],
RTI_LOG_MSG_SIZE_MAX,
"%s%s%s:%s",
throwing_context,
log_message->format,
strlen(log_message->format) > 0 ? SEPARATOR_STR : "",
message_buffer),
int);
}
/**
* @brief Exception class for Services
*/
class ServiceException : public std::exception {
public:
ServiceException(
const char *throwing_context,
const RTILogMessage *log_message,
...)
: message_(RTI_LOG_MSG_SIZE_MAX, '\0'),
message_id_(log_message->messageId)
{
va_list ap;
va_start(ap, log_message);
initialize_exception_message(
message_,
throwing_context,
log_message,
ap);
va_end(ap);
}
ServiceException(
const char *throwing_context,
const RTILogMessageTemplate *log_message,
const char *parameterizedString,
...)
: message_(RTI_LOG_MSG_SIZE_MAX, '\0'),
message_id_(log_message->messageId)
{
va_list ap;
va_start(ap, parameterizedString);
initialize_exception_message(
message_,
throwing_context,
log_message,
parameterizedString,
ap);
va_end(ap);
}
uint32_t message_id() const
{
return message_id_;
}
virtual const char* what() const throw ()
{
return message_.c_str();
}
virtual ~ServiceException() throw ()
{
}
private:
ServiceException() : message_id_(0u)
{
}
std::string message_;
std::uint32_t message_id_;
};
/**
* @brief Fatal exception class for Services. This exception will cause
* the underlying service to call the shutdown hook.
*/
class FatalServiceException : public ServiceException {
public:
template <typename... Args>
FatalServiceException(
const char *throwing_context,
const RTILogMessage *log_message,
Args... args)
: ServiceException(throwing_context, log_message, args...)
{ }
template <typename... Args>
FatalServiceException(
const char *throwing_context,
const RTILogMessageTemplate *log_message,
const char *parameterizedString,
Args... args)
: ServiceException(
throwing_context,
log_message,
parameterizedString,
args...)
{ }
virtual ~FatalServiceException() throw()
{ }
};
} } /* namespace rti::apputils */
#define RTI_THROW_SERVICE_EXCEPTION(...) \
throw rti::apputils::ServiceException(\
RTI_FUNCTION_NAME,\
__VA_ARGS__)
#define RTI_THROW_FATAL_SERVICE_EXCEPTION(...) \
throw rti::apputils::FatalServiceException(\
RTI_FUNCTION_NAME,\
__VA_ARGS__)
#define RTI_SERVICE_CHECK_CONDITION(EXPRESSION) \
if(!(EXPRESSION)) { \
RTI_THROW_SERVICE_EXCEPTION( \
&RTI_LOG_ANY_s, \
__FILE__ ":" RTI_TOSTRING(__LINE__) ": condition failed: " #EXPRESSION); \
}
#define RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(EXPRESSION, EXTRA_INFO) \
if(!(EXPRESSION)) { \
RTI_THROW_SERVICE_EXCEPTION( \
&RTI_LOG_ANY_ss, \
__FILE__ ":" RTI_TOSTRING(__LINE__) ": condition failed: " #EXPRESSION ", ", \
EXTRA_INFO); \
}
#endif /* HPP_SERVICE_SERVICE_EXCEPTION_HPP_ */
@@ -1,295 +0,0 @@
/*
* (c) Copyright, Real-Time Innovations, 2022.
* All rights reserved.
*
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef STRING_BUFFER_HPP
#define STRING_BUFFER_HPP
#include "rti/apputils/ServiceException.hpp"
namespace rti { namespace apputils {
// Default value of a StringBuffer
constexpr size_t STRING_BUFFER_LENGTH = 1000;
/**
* A GenericStringBuffer is a smart buffer that allocates an INITIAL_CAPACITY
* in the stack and allocates more capacity in the heap if needed. The template
* parameter INITIAL_CAPACITY determines the capacity that is allocated in the
* stack. In case there is a resize which involves heap allocation, the
* destructor of the GenericStringBuffer class frees the memory.
*/
template <std::size_t INITIAL_CAPACITY>
class GenericStringBuffer {
public:
/**
* This constructor creates a new empty GenericStringBuffer with
* INITIAL_CAPACITY.
*/
GenericStringBuffer() : capacity_(INITIAL_CAPACITY), c_str_ptr_(nullptr)
{
RTIOsapiMemory_zero(c_str_, capacity_);
c_str_ptr_ = c_str_;
}
/**
* This constructor creates a new GenericStringBuffer ensuring the size
* of the input parameter. It allocates memory in the heap if necessary.
* @param size Size to ensure.
*/
GenericStringBuffer(const size_t size)
: capacity_(INITIAL_CAPACITY), c_str_ptr_(nullptr)
{
RTIOsapiMemory_zero(c_str_, capacity_);
c_str_ptr_ = c_str_;
ensure_capacity(size);
}
/**
* This constructor creates a new GenericStringBuffer object containing
* an input string. It ensures whatever capacity is necessary for the input
* string.
* @param str std::string that initializes the GenericStringBuffer.
*/
GenericStringBuffer(const std::string& str)
: capacity_(INITIAL_CAPACITY), c_str_ptr_(nullptr)
{
RTIOsapiMemory_zero(c_str_, capacity_);
c_str_ptr_ = c_str_;
ensure_capacity(str.length() + 1);
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_strcpy(c_str_ptr_, str.length(), str.c_str()),
char *);
}
/**
* Copy constructor.
* @param other String buffer that we want to copy
*/
GenericStringBuffer(const GenericStringBuffer& other)
: capacity_(INITIAL_CAPACITY), c_str_ptr_(nullptr)
{
RTIOsapiMemory_zero(c_str_, capacity_);
c_str_ptr_ = c_str_;
ensure_capacity(other.length() + 1);
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_strcpy(
c_str_ptr_,
other.length(),
other.c_str()),
char *);
}
/**
* Move constructor.
* @param other String buffer that we want to move
*/
GenericStringBuffer(GenericStringBuffer&& other)
: capacity_(INITIAL_CAPACITY), c_str_ptr_(nullptr)
{
*this = std::move(other);
}
/**
* Destructor of the GenericStringBuffer. It frees whatever memory may
* have been allocated by the ensure_capacity method().
*/
~GenericStringBuffer()
{
if (capacity_ > INITIAL_CAPACITY) {
DDS_String_free(c_str_ptr_);
c_str_ptr_ = nullptr;
}
}
/**
* Copy-assignment operator
* @param other The buffer we want to copy.
* @return Object in which we have copied.
*/
GenericStringBuffer& operator=(const GenericStringBuffer& other)
{
if (this != &other) {
ensure_capacity(other.length() + 1);
RTIOsapiUtility_unusedReturnValue(
RTIOsapiUtility_strcpy(
c_str_ptr_,
other.length(),
other.c_str()),
char *);
}
return *this;
}
/**
* Move-assignment operator
* @param other The buffer we want to move.
* @return Object in which we have moved.
*/
GenericStringBuffer& operator=(GenericStringBuffer&& other)
{
if (this != &other) {
if (other.capacity_ <= INITIAL_CAPACITY) {
RTIOsapiMemory_move(c_str_, other.c_str_, INITIAL_CAPACITY);
c_str_ptr_ = c_str_;
} else {
capacity_ = other.capacity_;
c_str_ptr_ = other.c_str_ptr_;
other.capacity_ = INITIAL_CAPACITY;
other.c_str_ptr_ = nullptr;
}
}
return *this;
}
/**
* Returns the number of bytes that can be written in the internal char *
* buffer
* @return Capacity of the internal char * buffer.
*/
size_t capacity() const
{
return capacity_;
}
/**
* Returns the length of the internal char * buffer. That is the strlen
* of whatever is in there.
* @return Size of the string stored in the internal char * buffer.
*/
size_t length() const
{
return strlen(c_str_ptr_);
}
/**
* Returns a const pointer to the internal char * buffer.
* @return Const pointer to the internal char * buffer.
*/
const char *c_str() const
{
return c_str_ptr_;
}
/**
* Returns a pointer to the internal char * buffer
* @return Pointer to the internal char * buffer.
*/
char *c_str_ptr()
{
return c_str_ptr_;
}
/**
* This method ensures a capacity by either asserting that the
* GenericStringBuffer has enough space to allocate a string, or
* reallocating some space in the heap. If that is the case more space is
* allocated in the heap via DDS_String_alloc().
* @param capacity Size that needs to be ensured.
*/
void ensure_capacity(const size_t capacity)
{
if (capacity > capacity_) {
// We need to free the string if it was already allocated, this
// happens when _capacity > INITIAL_CAPACITY
if (capacity_ > INITIAL_CAPACITY) {
DDS_String_free(c_str_ptr_);
}
// DDS_String_alloc adds one to the input parameter. We could
// spare a byte, but we want to be precise.
c_str_ptr_ = DDS_String_alloc(capacity - 1);
if (c_str_ptr_ == nullptr) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"Error allocating string.");
}
RTIOsapiMemory_zero(c_str_ptr_, capacity_);
capacity_ = capacity;
}
}
private:
size_t capacity_;
char *c_str_ptr_;
char c_str_[INITIAL_CAPACITY];
};
/**
* A StringBuffer is a GenericStringBuffer with an initial STRING_BUFFER_LENGTH.
*/
typedef GenericStringBuffer<STRING_BUFFER_LENGTH> StringBuffer;
/**
* This method saves a "freeform string" into a StringBuffer object.
* @param [in,out] string_buffer StringBuffer in which the input string will
* be saved. Note that if there's not enough capacity, the method will
* automatically allocate more space for the string.
* @param format Format of the string to be saved.
* @param ... Parameters to the formatted string.
*/
inline void StringBuffer_save_freeform(
StringBuffer& string_buffer,
const char *format,
...)
{
char *c_str_ptr = string_buffer.c_str_ptr();
size_t capacity = string_buffer.capacity();
va_list args, args_aux;
RTIXMLSaveContext save_ctxt = RTIXMLSaveContext_INITIALIZER;
RTIXMLSaveContext_initialize(&save_ctxt);
save_ctxt.sout = c_str_ptr;
if (!RTIOsapiUtility_sizeToUInt32(save_ctxt.ssize, capacity)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"Error allocating string.");
}
// Wrap RTIXMLSaveContext_freeform_w_argsI call with va_start and va_end
// of the va_list that we need to pass in.
va_start(args, format);
va_start(args_aux, format);
RTIXMLSaveContext_freeform_v(&save_ctxt, format, args, args_aux);
va_end(args);
va_end(args_aux);
if (save_ctxt.outputStringLength + 1 > capacity) {
capacity = save_ctxt.outputStringLength + 1;
string_buffer.ensure_capacity(capacity);
RTIXMLSaveContext_initialize(&save_ctxt);
save_ctxt.sout = string_buffer.c_str_ptr();
if (!RTIOsapiUtility_sizeToUInt32(save_ctxt.ssize, capacity)) {
RTI_THROW_SERVICE_EXCEPTION(
&RTI_LOG_ANY_FAILURE_s,
"Error allocating string.");
}
// Wrap RTIXMLSaveContext_freeform_w_argsI call with va_start and
// va_end of the va_list that we need to pass in.
va_start(args, format);
va_start(args_aux, format);
RTIXMLSaveContext_freeform_v(&save_ctxt, format, args, args_aux);
va_end(args);
va_end(args_aux);
}
}
}} // namespace rti::apputils
#endif // STRING_BUFFER_HPP
@@ -1,355 +0,0 @@
/*
* (c) Copyright, Real-Time Innovations, 2022.
* All rights reserved.
*
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HTTP_CLIENT_CONNECTION_HPP
#define HTTP_CLIENT_CONNECTION_HPP
#include <array>
#include <chrono>
#include <memory>
#include <string>
#include <thread>
#include <civetweb.h>
#include "rti/apputils/ServiceException.hpp"
#include "rti/apputils/http/common/Response.hpp"
#include "rti/apputils/http/common/HttpUtils.hpp"
#include "rti/apputils/http/log/Log.hpp"
#include "Request.hpp"
namespace rti { namespace apputils { namespace http { namespace client {
/**
* @brief This class is a wrapper around the SSL configuration for the client.
*
*/
struct SslConfig {
SslConfig(
bool the_enabled = false,
std::string the_client_cert = "",
std::string the_server_cert = "")
: enabled(the_enabled),
client_cert(the_client_cert),
server_cert(the_server_cert)
{ }
bool enabled;
std::string client_cert;
std::string server_cert;
};
/**
* @brief This class deal with actual HTTP client requests and
* responses to and from CivetWeb.
*/
class Connection {
public:
/**
* @brief Construct a new Connection object Note that since every request
* reconnects the connection, we do not need to connect in the constructor
* itself.
*
* @param host Hostname of the server
* @param port Port of the server
* @param ssl_config SSL configuration for the client
*/
Connection(
const std::string& host = std::string("localhost"),
std::uint16_t port = HTTP_SERVER_DEFAULT_PORT,
SslConfig ssl_config = SslConfig())
: host_ { host }, port_ { port }, ssl_config_ { ssl_config }
{ }
/**
* @brief send an actual HTTP request to CivetWeb. It extracts all
* the information from the request and constructs a valid HTTP request
* string.
*
* @param request HTTP request to be sent to the server.
*/
void send_http_request(const Request& request)
{
connect();
// Send HTTP method and URL
auto mg_result = mg_printf(
connection_.get(),
"%s %s",
method_to_string(request.http_method()).c_str(),
request.uri());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
// Add URL params to URL
if (request.uri_parameters().size() > 0) {
mg_result = mg_printf(connection_.get(), "?");
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
for (const auto& uri_param : request.uri_parameters()) {
std::array<char, MAX_URI_LENGTH> uri_param_value;
uri_param_value.fill('\0');
// We need to encode the URI params in case they contain
// spaces or any other character that may not be valid in a
// URL
mg_result = mg_url_encode(
uri_param.second.c_str(),
uri_param_value.data(),
MAX_URI_LENGTH);
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_url_encode);
mg_result = mg_printf(
connection_.get(),
"%s=%s&",
uri_param.first.c_str(),
uri_param_value.data());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
}
// Specify HTTP version
mg_result = mg_printf(connection_.get(), " HTTP/%s\r\n", HTTP_VERSION);
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
// Add user-defined headers
for (const auto& header : request.headers()) {
mg_result = mg_printf(
connection_.get(),
"%s: %s\r\n",
header.first.c_str(),
header.second.c_str());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
// Add default headers if not defined
if (request.header("Content-Length") == nullptr) {
mg_result = mg_printf(
connection_.get(),
"Content-Length: %llu\r\n",
static_cast<unsigned long long>(request.body().length()));
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
if (request.header("Content-Type") == nullptr) {
mg_result = mg_printf(
connection_.get(),
"Content-Type: %s\r\n",
HTTP_PLAIN_TEXT_CONTENT_TYPE);
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
if (request.header("Cache-Control") == nullptr) {
mg_result = mg_printf(
connection_.get(),
"Cache-Control: %s\r\n",
HTTP_CACHE_CONTROL_NO_CACHE);
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
if (request.header("Date") == nullptr) {
mg_result = mg_printf(
connection_.get(),
"Date: %s\r\n",
HttpSettings::get_current_date().c_str());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
}
// Separate headers from body
mg_result = mg_printf(connection_.get(), "\r\n");
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result > 0,
msg_client_error_printf);
// Send body of the HTTP request -- if empty it will not write anything
mg_result = mg_printf(connection_.get(), "%s", request.body().c_str());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
mg_result >= 0,
msg_client_error_printf);
}
/**
* @brief returns a Response based on the actual HTTP response received from
* CivetWeb. It extracts all the information originally stored in the
* mg_connection and transforms it into a valid Response object.
*
* @param timeout Number of milliseconds to wait for a response. A negative
* value means wait indefinitely.
*
* @return Response object with the response from CivetWeb.
*/
Response get_http_response(int timeout = HTTP_CLIENT_TIMEOUT_MS)
{
std::array<char, HTTP_BODY_INITIAL_LENGTH> error_buffer;
error_buffer[0] = '\0';
// Get CivetWeb's response.
const auto result = mg_get_response(
connection_.get(),
error_buffer.data(),
error_buffer.size(),
timeout);
// If we timeout trying to get the response, throw an exception.
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
result >= 0,
error_buffer.data());
// Convert CivetWeb's response into a Response
const mg_response_info *response_info =
mg_get_response_info(connection_.get());
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
response_info != nullptr,
msg_client_error_get_response_info);
return Response {
static_cast<unsigned short>(response_info->status_code),
response_info->status_text,
[&] {
const auto header =
mg_get_header(connection_.get(), "Content-Type");
return (header == nullptr) ? "" : header;
}(),
this->read_content(),
[&] {
std::unordered_map<std::string, std::string> headers;
for (int i = 0; i < response_info->num_headers; ++i) {
headers.emplace(
response_info->http_headers[i].name,
response_info->http_headers[i].value);
}
return headers;
}()
};
}
std::string read_content(std::size_t chunk_size = 256)
{
const auto response_info = mg_get_response_info(connection_.get());
if (response_info == nullptr) {
RTI_THROW_HTTP_EXCEPTION(
StatusCode::internal_server_error,
&RTI_LOG_ANY_FAILURE_s,
"Error reading content");
}
if (response_info->content_length >= 0) {
return read_content_with_content_length(
connection_.get(),
static_cast<std::size_t>(response_info->content_length));
}
return read_content_without_content_length(
connection_.get(),
chunk_size);
}
private:
/**
* @brief time we connect, we reset the mg_connection. This ensures
* that CivetWeb's internal buffers and state is cleaned up. This makes
* the Connection easier to use, since it does not need
* to be reconnected with every unit test run.
*/
void connect()
{
std::array<char, HTTP_BODY_INITIAL_LENGTH> error_buffer;
error_buffer[0] = 0;
if (ssl_config_.enabled) {
mg_client_options client_options = create_client_options();
connection_.reset(mg_connect_client_secure(
&client_options,
error_buffer.data(),
HTTP_BODY_INITIAL_LENGTH));
} else {
connection_.reset(mg_connect_client(
host_.c_str(),
port_,
ssl_config_.enabled,
error_buffer.data(),
HTTP_BODY_INITIAL_LENGTH));
}
RTI_SERVICE_CHECK_CONDITION_W_EXTRA_INFO(
connection_ != nullptr || error_buffer[0] == 0,
error_buffer.data());
}
/**
* @brief This method closes any existing connection.
*/
struct Disconnect {
void operator()(mg_connection *connection) const
{
mg_close_connection(connection);
}
};
/**
* @brief This method create a new mg_client_options object with the
* information provided by the user.
*/
mg_client_options create_client_options()
{
mg_client_options client_options;
client_options.host = host_.c_str();
client_options.port = port_;
client_options.client_cert =
(ssl_config_.client_cert.empty() || !ssl_config_.enabled)
? nullptr
: ssl_config_.client_cert.c_str();
client_options.server_cert =
(ssl_config_.server_cert.empty() || !ssl_config_.enabled)
? nullptr
: ssl_config_.server_cert.c_str();
client_options.host_name =
!ssl_config_.enabled ? nullptr : client_options.host;
return client_options;
}
private:
std::unique_ptr<mg_connection, Disconnect> connection_;
std::string host_;
std::uint16_t port_;
SslConfig ssl_config_;
};
}}}} // namespace rti::apputils::http::client
#endif // HTTP_CLIENT_CONNECTION_HPP
@@ -1,202 +0,0 @@
/*
* (c) Copyright, Real-Time Innovations, 2022.
* All rights reserved.
*
* No duplications, whole or partial, manual or electronic, may be made
* without express written permission. Any such copies, or
* revisions thereof, must display this notice unaltered.
* This code contains trade secrets of Real-Time Innovations, Inc.
*/
#ifndef HTTP_CLIENT_REQUEST_HPP
#define HTTP_CLIENT_REQUEST_HPP
#include <array>
#include <string>
#include <cassert>
#include <cstring>
#include "rti/apputils/http/common/Method.hpp"
#include "rti/apputils/http/common/HttpUtils.hpp"
namespace rti { namespace apputils { namespace http { namespace client {
/**
* @brief Request class allow users to define their own requests in order to
* send them to the server trough the Connection class.
*/
class Request {
public:
/**
* @brief Construct a new Request empty object
*/
Request()
{
uri_.fill('\0');
}
/**
* @brief Getter for the HTTP method.
*
* @return Method object associated to the request.
*/
Method http_method() const
{
return http_method_;
}
/**
* @brief Setter for the HTTP method.
*
* @param http_method HTTP method (POST, PUT, GET, DELETE, HEAD, PATCH,
* OPTIONS).
* @return Reference to the Request object.
*/
Request& http_method(Method http_method)
{
http_method_ = http_method;
return *this;
}
/**
* @brief Gets the URL of the HTTP request.
*
* @return URL of the HTTP request.
*/
const char *uri() const
{
return uri_.data();
}
/**
* @brief Sets the URL of the HTTP request.
*
* @param uri URL of the HTTP request.
* @return Reference to the Request object.
*/
Request& uri(const char *uri)
{
std::copy(uri, uri + std::strlen(uri), uri_.data());
return *this;
}
/**
* @brief Sets the URL of the HTTP request.
*
* @param uri URL of the HTTP request.
* @return Reference to the Request object.
*/
Request& uri(const std::string& uri)
{
return this->uri(uri.c_str());
}
/**
* @brief Gets the value of an uri parameter.
*
* @param name Name of the parameter.
* @return const std::string*
*/
const std::string *uri_parameter(const std::string& name) const
{
const auto it = uri_parameters_.find(name);
if (it == uri_parameters_.end()) {
return nullptr;
}
return &it->second;
}
/**
* @brief Gets all the uri parameters.
*
* @return const StringMap&
*/
const StringMap& uri_parameters() const
{
return uri_parameters_;
}
/**
* @brief Sets all the uri parameters.
*
* @param uri_parameters StringMap with all the uri parameters.
* @return Request&
*/
Request& uri_parameters(const StringMap& uri_parameters)
{
uri_parameters_ = uri_parameters;
return *this;
}
/**
* @brief Gets the value of a header.\
*
* @param name Name of the parameter.
* @return const std::string*
*/
const std::string *header(const std::string& name) const
{
const auto it = headers_.find(name);
if (it == headers_.end()) {
return nullptr;
}
return &it->second;
}
/**
* @brief Gets all the headers.
*
* @return const StringMap&
*/
const StringMap& headers() const
{
return headers_;
}
/**
* @brief Sets all the headers.
*
* @param headers StringMap with all the headers.
* @return Request&
*/
Request& headers(const StringMap& headers)
{
headers_ = headers;
return *this;
}
/**
* @brief Gets the body of the request.
*
* @return const std::string&
*/
const std::string& body() const
{
return body_;
}
/**
* @brief Sets the body of the request.
*
* @param body Body of the request.
* @return Request&
*/
Request& body(const std::string& body)
{
body_ = body;
return *this;
}
private:
Method http_method_ = Method::http_get;
std::array<char, MAX_URI_LENGTH> uri_;
StringMap uri_parameters_;
StringMap headers_;
std::string body_;
};
}}}} // namespace rti::apputils::http::client
#endif // HTTP_CLIENT_REQUEST_HPP
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff. Show more