Skip to content
vnotexPublic

About

Notebook management core for VNote

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

vxcore

vxcore is a cross-platform C/C++ library providing notebook management functionality for VNote. It offers a stable C ABI for embedding in desktop (Qt), iOS (Swift), and Android (Kotlin) applications.

Features

  • Notebook Management: Create, open, close notebooks (bundled & raw types)
  • Unified Node Operations: Work with files and folders using consistent (notebook_id, path) API
  • Folder Operations: Create, delete, rename, move, copy folders
  • File Operations: Create, delete, rename, move, copy files with metadata
  • Tag System: Create tags at notebook level, apply/remove tags on files
  • Configuration: JSON-based configuration with session persistence
  • Search: Built-in content, file/path and tag search, with JSON and typed C results

API Usage

First-match content search and existing tag assignments

Content search always uses the built-in Simple engine; no external executable or backend selection is required. JSON and typed APIs share the same native results: one-based line numbers, zero-based end-exclusive UTF-16 columns, and UTF-8 line text. Queries may set "firstMatchPerFile": true. Both blob and streaming APIs then return only the first qualifying occurrence in each matched file. Literal, regex, case, whole-word and excluded-line rules still apply. The matchers stop before copying a second matching line, avoiding repeated-line allocation growth. The default remains every occurrence. File count, source size and result transport still need consumer bounds; the streaming API does not enforce maxResults.

vxcore.json retains search.encodings (default ["UTF-8", "GB18030"]) and explicit encoding overrides. Retired search.backends values in older files are ignored, including rg-only, ordered, unknown and empty lists; ordinary config saves omit that key while preserving other recognized settings. Search is never disabled by an old empty list. test_core covers disk load/save/restart and custom configuration retention; test_search covers real Unicode searches, first-match results and restart under legacy configuration. The optional search validator compares the built-in engine with an external ripgrep oracle; it does not select an application backend.

For bundled notes, vxcore_file_update_tags accepts a replacement name when it is a current notebook definition or already assigned to that same file. This preserves legacy/orphan assignments without recreating definitions. Newly introduced undefined names are rejected before replacement; omitting an orphan removes it, and it cannot then be reintroduced unless defined. All other file metadata and content retain their existing update behavior.

Platform-selected mobile extension

The shared C API remains in vxcore/vxcore.h. Default Windows, Linux and macOS builds retain vxcore_context_create(config_json, &context) and its existing platform/portable/test-mode roots. They do not declare, compile or install the mobile context extension.

Android and iOS targets additionally expose vxcore/mobile/vxcore_mobile.h:

#include <vxcore/mobile/vxcore_mobile.h>

VxCoreContextHandle context = NULL;
VxCoreError error = vxcore_context_create_with_paths(
    NULL, absolute_app_data_utf8, absolute_local_data_utf8, &context);

CMake selects src/mobile/context_mobile.cpp and src/mobile/config_manager_mobile.cpp and publishes VXCORE_MOBILE_API=1 to linked consumers. Both factories share manager initialization; the mobile factory copies both UTF-8 paths before configuration loading and never changes global path defaults. config_json remains ignored in both factories. App data holds vxcore.json; local data holds vxsession.json, activity and notebook-local state. The embedding app supplies persistent sandbox locations, not cache directories.

Explicit-root contexts start with no open notebooks, buffers or workspaces. They do not read vxsession.json, including stale or malformed legacy session data; the embedding app owns recovery and explicitly admits each notebook. User vxcore.json configuration still loads normally and is not rewritten by this policy. Later explicit operations/shutdown may persist session state, but a fresh explicit-root context never restores it. Default desktop context creation retains its existing session restoration. This prevents untracked restored buffers and unrequested notebook recovery from crossing app-owned context lifetimes.

Both nonempty absolute roots are validated before creating directories or loading configuration. Existing ancestors are resolved; equal/containing roots and aliases are rejected. Invalid UTF-8, null/empty/relative or overlapping roots return VXCORE_ERR_INVALID_PARAM; inaccessible/non-directory ancestors return VXCORE_ERR_IO. A null output returns VXCORE_ERR_NULL_POINTER; otherwise output is null on failure. Allocation and JSON errors retain their specific codes. Partial resources are released, but created directories are not rolled back. Consumers serialize operations and protect roots from concurrent mutation; this is not an adversarial filesystem sandbox.

For desktop-hosted mobile bridge tests only, -DVXCORE_ENABLE_MOBILE_TEST_API=ON -DVXCORE_INSTALL=OFF compiles the extension, including host path validation. This explicit option never selects mobile save semantics and cannot install a desktop SDK containing the test-only extension.

Prepared WebDAV lifecycle and platform trust

Mobile consumers use vxcore_sync_prepare_lifecycle on their metadata owner, vxcore_sync_execute_lifecycle on a joined network worker, and vxcore_sync_complete_lifecycle back on the owner. Prepare/complete do not issue network requests; execute owns copied roots/configuration, transient credentials and a private backend, never a worker-accessed notebook manager or SQLite store. A handle excludes competing sync registration/phase operations for that notebook until vxcore_sync_free_lifecycle. The embedding host must also retain its notebook/configuration/structural lease and context through free, and join workers and trust callbacks before destroying either. Execute and complete are each single-use; cancellation observed before publication prevents publication.

Commands are closed objects with version: 1, a canonical UUID operationId, and kind:

  • enable: config containing backend: "webdav", HTTPS remoteUrl, and optional boolean autoSyncEnabled.
  • credentials: no configuration override; the registered endpoint is captured.
  • credentialRecovery: the same config plus recoveryOperationId naming a retained candidate validation operation. This proves scratch cleanup only: committed is always false, including successful cleanup.
  • clone: config, an empty transaction-private target, and positive integer limits: maxFileBytes, maxTotalBytes, maxEntries, maxDepth, maxPathBytes. The total bounds clone staging, including private snapshots; callers separately reserve the later prepared copy and filesystem/metadata headroom. Inventory limits are checked before body downloads, and byte/declared-size limits while streaming, before atomic publication. Failed/cancelled incomplete data remains owned by the import transaction, never a successful clone receipt.

Credentials are a separate bounded { "extra": { "username": "...", "password": "..." } } input, never a result or portable configuration. Complete returns version, operationId, kind, nullable notebookId, executed, committed, cleanupRequired, and the actual code; free strings with vxcore_string_free. Prepared enable publishes the runtime backend, not portable routing. The consumer must persist enabled/backend/URL and auto-sync preference through the complete notebook-config API before refresh/reopen; runtime disable likewise does not clear those fields. Never substitute a Dart notebook-schema writer for that owner call. Candidate validation uses its own vx_notebook/vx_sync/webdav/credential-validation/<operation-id> namespace, bound to notebook UUID, canonical endpoint and candidate username hash. It cannot replace the published account, baseline or provider until validation and hash/ETag-proved scratch cleanup succeed and owner completion commits. Retained candidate recovery blocks reconfiguration without masquerading as an incoming encryption-key conflict. Cleanup credentials must match the candidate account.

Prepared clone requires an empty private owner with app/local roots at imports/<id>/runtime/{app,local} and target imports/<id>/unpacked. Only the private context is registered on completion. The core-generated clean WebDAV baseline stays inside unpacked; core does not mint an import permit. The host must close/join the private owner and bind its own sibling clone-complete receipt to the operation, notebook, endpoint/account, baseline hash and completed source tree before allowing that baseline through managed publication. Ordinary imports must reject every nonempty vx_sync, even a schema-valid clean cursor.

On Windows only, prepared clone also admits the unchanged desktop registration host before work starts: the target and its vx_notebook/config.json, plus the private local root's notebooks/<36-character UUID>/metadata.db-journal and vxsession.json, must each have a logical native path length below 260 WCHARs (excluding the terminator). The config bound also covers the vx_transfer and vx_import absence probes. The complete remote inventory must satisfy the same bound for every non-excluded vx_notebook/vx_import path and descendant before any clone file is written. Violations return VXCORE_ERR_UNSUPPORTED, not a clone receipt. This is a Windows registration-host limit, not a mobile path limit or a ceiling on private asset/body or vx_sync descendants; Android/iOS and legacy clone retain their existing behavior. Completion still opens and registers the actual notebook, and the private close/receipt requirements above remain mandatory.

vxcore_sync_set_tls_verifier installs an immutable, runtime-only policy before any backend or prepared work. Its callback receives the actual ASCII host (bare IP literal, not a URL) and leaf-first DER plus intermediates, bounded to 16 certificates and 1 MiB total; only VXCORE_OK trusts. Userdata must survive context, worker and callback drain. The bundled OpenSSL curl target publishes VXCORE_SYNC_TLS_OPENSSL and replaces certificate verification through SSL_CTX_set_cert_verify_callback, retaining curl peer and hostname verification. Unsupported custom-verifier/backend combinations fail explicitly before network; there is no trust-off or default-store fallback. Default desktop trust and legacy sync/clone/credential APIs remain unchanged. URL bindings use the transport's canonical HTTPS spelling; dot segments are rejected, not normalized away.

vxcore_sync_refresh_notebook_result separates the original apply/operation result from the actual metadata refresh result, initializing both on every path. A successful refresh does not erase an apply failure. With no in-memory phase it performs a full owner-thread reload. Neither API publishes a success timestamp.

Provider storage and retained archive recovery

vxcore_sync_inspect_storage(root, expected_id, &facts) is context-free, network-free and read-only. It validates bundled identity, confined no-follow provider storage, supported state/bindings/entries, candidate/probe recovery and retirement namespaces. probe reports unresolved probe recovery; a validated legacy dormant empty probe remains archiveable but is not a clean clone baseline. Facts include hasState, pending, conflicts, probe, credentialValidation, retirement, retired, cleanCloneBaseline and the raw baselineSha256, alongside notebook/provider/endpoint/account-hash binding. State/hash/account/endpoint facts describe the live top-level baseline, never a candidate or archived binding; their absence does not erase retained recovery. cleanCloneBaseline is diagnostic only, never permission to import a sync cursor.

vxcore_sync_provider_transaction derives paths from the selected notebook and accepts only version-1 inspect, begin, commit, restore, recover commands; mutations additionally require a canonical UUID operationId. Begin requires a writable bundled notebook, no runtime/apply lease and clean reconfiguration preflight. It seals a bounded inventory and journals ownership before no-replace moves to retired/<operation-id>. Restore validates the entire exclusive source/archive layout and original identities before moving anything back. Commit requires runtime absent and persisted enabled/backend/URL routing fully cleared; it retires only its proved journal and retains the archive. Ambiguous, replaced, linked or unknown data is never deleted. Legacy version-1 retirement journals remain readable as recovery, but missing ownership seals do not become permission to mutate or delete their data. Such legacy records remain explicit retained recovery for the original desktop/manual resolution path, never a successful recovery or an absent journal. No Git/Jianguoyun migration is added.

On Windows, validated WebDAV private storage uses an explicit native-I/O mode for long candidate, snapshot and archive paths. Every private query, enumeration, read, write, move and cleanup uses the same no-follow component walk and transient extended DOS/UNC OS argument. Logical roots, relative journals and containment inputs remain unprefixed; caller-supplied device/prefixed paths are not authority. Ordinary/body/default desktop path behavior is unchanged. This does not rely on a host executable manifest or a global long-path policy. UNC spelling is covered without implying live-share I/O verification.

Context diagnostics now use synchronized assign/clear/copy storage. The C getter returns a thread-local snapshot valid until the next getter on that same thread; other threads cannot invalidate it. It remains the latest context diagnostic, not operation-specific attribution, and does not make arbitrary context APIs thread-safe. UUID generation serializes the existing generator and format.

Ordinary buffer writes

CMake selects exactly one SaveBufferFileContent implementation by target:

  • Desktop: src/platform/buffer_file_save_desktop.cpp retains the original in-place writer from c3319ca, including stream-size checks and error mapping. Hardlink/symlink identity and writable handles that deny deletion keep their existing behavior. No Windows DACL modification or recovery-directory protocol is added. Generic AtomicFileWriter::Commit() retains its replacing behavior; the explicit CommitNoReplace() path is separate.
  • Android/iOS: src/mobile/buffer_file_save_mobile.cpp uses the POSIX-only MobileFileWriter. It writes bytes directly to an exclusive sibling, flushes the file, checks destination identity/type/mode, preserves mode bits, renames, and flushes the parent directory. Readonly, linked and nonregular destinations are rejected without changing their old bytes before publication. Failures do not mark buffers clean. A directory-flush error can occur after publication; an IO error does not universally mean the old body remains at the path.

The mobile policy targets app-owned files. It does not claim to copy arbitrary ownership, ACLs or extended attributes; iOS file-protection and interruption behavior still require device verification. Encrypted providers keep their existing persistence path. No text decoding or EOL conversion occurs in either ordinary writer. Neither desktop host tests nor file flushing establishes power-loss safety, unsaved-draft journaling or startup recovery.

Prepared cohort import and metadata-only indexing

vxcore_folder_index_children(context, notebook_id, parent_path, names_json) indexes an explicit batch of existing immediate children without copying, decoding, renaming or rewriting their bytes. The JSON input is bounded to 8 MiB and 10,000 names; core generates the new IDs and atomically publishes the parent once. It does not recursively filter hidden or unsupported files. All input names, types, aliases and metadata collisions are checked before publication. Failed prepublication work removes only newly created, still-owned child metadata; postpublication/store errors require inspecting actual state before retrying. Read-only refusal precedes unsupported raw-notebook refusal. This is a private construction primitive, not a replacement for the final cohort transaction.

vxcore_folder_attach_imported publishes already-final content/metadata and IDs from an ordinary immediate child of this notebook's vx_notebook/vx_import directory on the same filesystem. New schema-2 journals retain bounded binary before/after parent images and directory identities. No-replace moves prevent colliding targets from being overwritten. Parent replacement remains the commit point, but an error does not prove rollback: recovery checks actual parent/root identity and authoritative reachability, including a later rename or edit.

Recovery never restores old parent bytes over newer edits, removes foreign trees, or deletes an unreadable journal to force the notebook open. Proven uncommitted ownership permits rollback; ambiguity and incomplete rollback remain errors with the journal retained. Proven-committed cleanup may remain safe residue without making the notebook unopenable. Durable committed receipts do not replay content after later deletion. Recovery repairs affected derived-store state itself. Legacy journals are accepted only when ownership/commit is provable; uncommitted legacy targets without recorded identity can require explicit recovery rather than unsafe automatic deletion. Journal limits are depth 64, 100,000 IDs, 8 MiB per parent image and 64 MiB total serialized bytes.

Asset and attachment publication

Asset insertion now writes a complete temporary sibling and explicitly publishes without replacement. File sources stream in bounded chunks; unique filename selection remains, but a lost publication race fails rather than overwriting. Write/file-flush/close failures do not publish; a parent-directory flush failure after publication retains the complete file for reconciliation.

Attachment membership updates publish folder metadata atomically and keep caches consistent with disk after errors. Insert retains complete unindexed bytes if metadata publication fails. Delete stops before removing bytes when untracking fails. Rename keeps collision suffix behavior, uses a no-replace move, performs one membership replacement, and reports metadata errors instead of false success. Rename/remove do not rewrite note links. Physical removal still prefers recycling and may fall back to permanent deletion; callers must disclose that choice.

These are safer primitives, not an atomic multi-step attachment transaction. Callers must retain intent/source and reconcile physical bytes plus membership before retrying an ambiguous mutation. Protected note bodies are not decrypted by these resource operations. The existing replacing writer and ordinary desktop note-body save policy are unchanged. Windows checks file flush and WRITE_THROUGH; POSIX directory fsync and platform-specific no-replace calls require their own runtime evidence. No file test establishes physical power-loss safety.

An isolated ordinary Windows SDK smoke batch-indexed 10,000 Unicode Markdown files, attached the resulting cohort, reopened with all 10,002 cohort IDs intact, and preserved every source byte. It also reconciled an induced attachment metadata failure and a stale legacy post-commit journal. This is API/storage proof, not a mobile UI or performance guarantee.

Affected Windows suites (import bundle, folder manager, utilities, buffer, folder, desktop/read-only saves and node transfer) passed. Linux exercised utilities, import recovery, batch/folder metadata and unchanged desktop saves. Android API-28 x86_64 binaries ran on the emulator for mobile buffer/asset publication, import recovery and filesystem primitives. Android policy refused hardlink/FIFO fixture creation, so those Android fixture cases are not claimed; Linux exercised the special-file guards. iOS and physical power-loss remain unverified.

Unified Node API

The library provides unified APIs for working with both files and folders using a consistent (notebook_id, node_path) interface. The returned JSON includes a "type" field ("file" or "folder") for automatic type identification.

// Get config for any node (file or folder)
char *config_json = NULL;
VxCoreError err = vxcore_node_get_config(context, notebook_id, "path/to/node", &config_json);
if (err == VXCORE_OK) {
    // Parse JSON to check type
    // { "type": "file", "name": "...", ... } or { "type": "folder", "name": "...", ... }
    vxcore_string_free(config_json);
}

// Delete any node (automatically detects type)
vxcore_node_delete(context, notebook_id, "path/to/node");

// Rename any node
vxcore_node_rename(context, notebook_id, "old/path", "new_name");

// Move any node to different parent
vxcore_node_move(context, notebook_id, "src/path", "dest/parent");

// Copy any node with optional new name
char *copy_id = NULL;
vxcore_node_copy(context, notebook_id, "src/path", "dest/parent", "new_name", &copy_id);
vxcore_string_free(copy_id);

// Get/update metadata for any node
char *metadata_json = NULL;
vxcore_node_get_metadata(context, notebook_id, "path/to/node", &metadata_json);
vxcore_node_update_metadata(context, notebook_id, "path/to/node", "{\"key\": \"value\"}");
vxcore_string_free(metadata_json);

Unified APIs:

  • vxcore_node_get_config - Get node config with type indicator
  • vxcore_node_delete - Delete file or folder
  • vxcore_node_rename - Rename file or folder
  • vxcore_node_move - Move file or folder to different parent
  • vxcore_node_copy - Copy file or folder with optional new name
  • vxcore_node_get_metadata - Get metadata for file or folder
  • vxcore_node_update_metadata - Update metadata for file or folder

Create Operations: For creating folders and files, use vxcore_folder_create, vxcore_folder_create_path, and vxcore_file_create. For file-specific tag operations, use vxcore_file_update_tags, vxcore_file_tag, and vxcore_file_untag.

Build

iOS explicitly uses bundled curl and target OpenSSL; desktop Apple keeps SDK libcurl/SecureTransport. Cross-compilers must supply the target OpenSSL paths, not host libraries. All notebook, Git, encryption and WebDAV features remain linked. This selection alone is not evidence of an exercised iOS build or TLS trust setup.

Configure

cmake -B build -DVXCORE_BUILD_TESTS=ON

Build

cmake --build build

Run Tests

# All tests
ctest --test-dir build -C Debug  # Windows
ctest --test-dir build           # Unix

# Single module
ctest --test-dir build -C Debug -R test_core

License

See LICENSE file

About

Notebook management core for VNote

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages