Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QByteArrayCursor #741

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions crates/cxx-qt-lib-headers/include/gui/qimage.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// clang-format off
// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
// clang-format on
// SPDX-FileContributor: Leon Matthes <[email protected]>
//
// SPDX-License-Identifier: MIT OR Apache-2.0
#pragma once

#ifdef CXX_QT_GUI_FEATURE

#include <QtGui/QImage>

#include "rust/cxx.h"

#include <cstdint>

namespace rust {

// QImage has a move constructor, however it is basically trivial.
template<>
struct IsRelocatable<QImage> : ::std::true_type
{
};

namespace cxxqtlib1 {
using QImageFormat = QImage::Format;

QImage
qimageInitFromData(const rust::Slice<std::uint8_t const> data,
rust::Str format);

} // namespace cxxqtlib1
} // namespace rust
#endif
2 changes: 2 additions & 0 deletions crates/cxx-qt-lib-headers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ pub fn write_headers(directory: impl AsRef<Path>) {
"qguiapplication.h",
),
#[cfg(feature = "qt_gui")]
(include_str!("../include/gui/qimage.h"), "qimage.h"),
#[cfg(feature = "qt_gui")]
(include_str!("../include/gui/qvector2d.h"), "qvector2d.h"),
#[cfg(feature = "qt_gui")]
(include_str!("../include/gui/qvector3d.h"), "qvector3d.h"),
Expand Down
2 changes: 2 additions & 0 deletions crates/cxx-qt-lib/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ fn main() {
"core/qvector/qvector_qcolor",
"gui/qcolor",
"gui/qguiapplication",
"gui/qimage",
"gui/qvector2d",
"gui/qvector3d",
"gui/qvector4d",
Expand Down Expand Up @@ -225,6 +226,7 @@ fn main() {
cpp_files.extend([
"gui/qcolor",
"gui/qguiapplication",
"gui/qimage",
"gui/qvector2d",
"gui/qvector3d",
"gui/qvector4d",
Expand Down
1 change: 1 addition & 0 deletions crates/cxx-qt-lib/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

mod qbytearray;
pub use qbytearray::QByteArray;
pub use qbytearray::QByteArrayCursor;

mod qcoreapplication;
pub use qcoreapplication::QCoreApplication;
Expand Down
96 changes: 95 additions & 1 deletion crates/cxx-qt-lib/src/core/qbytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
//
// SPDX-License-Identifier: MIT OR Apache-2.0
use cxx::{type_id, ExternType};
use std::mem::MaybeUninit;
use std::{
io::{Cursor, Seek, Write},
mem::MaybeUninit,
};

#[cxx::bridge]
mod ffi {
Expand Down Expand Up @@ -122,6 +125,97 @@ impl AsRef<[u8]> for QByteArray {
}
}

/// A QByteArray cursor allows seeking inside a QByteArray
/// and writing to it.
/// Comparable with [std::io::Cursor].
pub struct QByteArrayCursor {
inner: QByteArray,
position: isize,
}

impl QByteArrayCursor {
/// Constructs a new QByteArrayCursor at location 0.
/// Like [`std::io::Cursor<Vec<u8>>`] this will overwrite
/// existing data in the QByteArray before starting to resize.
pub fn new(bytearray: QByteArray) -> Self {
Self {
inner: bytearray,
position: 0,
}
}

/// Returns a reference to the underlying QByteArray.
pub fn into_inner(self) -> QByteArray {
self.inner
}
}

/// Like the implementation of `Cursor<Vec<u8>>`, the QByteArrayCursor
/// will overwrite existing data in the QByteArray.
/// The QByteArray is resized as needed.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this doc go on the impl or on the fn ? does it work in a cargo doc ?

impl Write for QByteArrayCursor {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let length_after_append = buf.len() as isize + self.position;
let bytearray_length = self.inner.len();
if length_after_append > bytearray_length {
self.inner.resize(length_after_append);
}

let bytes = self.inner.as_mut_slice();

// If the resize operation failed, then we need to do additional
// error handling.
// Luckily we can just leave this up to the `Cursor<&mut [u8]>` implementation.
let mut bytes_cursor = Cursor::new(bytes);
bytes_cursor.set_position(self.position as u64);

bytes_cursor.write(buf).map(|bytes_written| {
self.position += bytes_written as isize;
bytes_written
})
}

fn flush(&mut self) -> std::io::Result<()> {
// Nothing to flush, we always write everything
Ok(())
}
}

impl AsRef<QByteArray> for QByteArrayCursor {
fn as_ref(&self) -> &QByteArray {
&self.inner
}
}

impl Seek for QByteArrayCursor {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
use std::io::{Error, ErrorKind, SeekFrom};
let (base_pos, offset) = match pos {
SeekFrom::Start(n) => (
0_usize,
n.try_into().map_err(|_err| {
Error::new(
ErrorKind::InvalidInput,
"invalid seek to an overflowing position",
)
})?,
),
SeekFrom::End(n) => (self.inner.len() as usize, n),
SeekFrom::Current(n) => (self.position as usize, n),
};
match base_pos.checked_add_signed(offset as isize) {
Some(n) => {
self.position = (n as isize).min(self.inner.len());
Ok(self.position as u64)
}
None => Err(Error::new(
ErrorKind::InvalidInput,
"invalid seek to a negative or overflowing position",
)),
}
}
}

impl Clone for QByteArray {
/// Constructs a copy of other.
///
Expand Down
3 changes: 3 additions & 0 deletions crates/cxx-qt-lib/src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ pub use qvector3d::QVector3D;

mod qvector4d;
pub use qvector4d::QVector4D;

mod qimage;
pub use qimage::QImage;
51 changes: 51 additions & 0 deletions crates/cxx-qt-lib/src/gui/qimage.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// clang-format off
// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
// clang-format on
// SPDX-FileContributor: Leon Matthes <[email protected]>
//
// SPDX-License-Identifier: MIT OR Apache-2.0

#ifdef CXX_QT_GUI_FEATURE

#include "cxx-qt-lib/qimage.h"
#include "../assertion_utils.h"
#include <string>

// A QImage inherits from QPaintDevice.

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
// QPaintDevice in Qt5 contains two things:
// 1. ushort painters; (due to the following field this has padding to make it
// 64-bit long)
// 2. QPaintDevicePrivate *reserved;
// Then QImage adds an additional field:
// 3. QImageData *d;
// For a total of 3 pointers in length.
// Because of the added v-table, it's a total of 4 pointers in size.
assert_alignment_and_size(QImage,
alignof(::std::size_t),
sizeof(::std::size_t) * 4);
#else
// In Qt6 the QPaintDevice doesn't contain the `reserved` pointer, making it 1
// pointer smaller
assert_alignment_and_size(QImage,
alignof(::std::size_t),
sizeof(::std::size_t) * 3);
#endif

namespace rust {
namespace cxxqtlib1 {

QImage
qimageInitFromData(const rust::Slice<std::uint8_t const> data, rust::Str format)
{
std::string formatString(format);
return QImage::fromData(static_cast<const unsigned char*>(data.data()),
static_cast<int>(data.size()),
formatString.empty() ? nullptr : formatString.data());
}

}
}

#endif
82 changes: 82 additions & 0 deletions crates/cxx-qt-lib/src/gui/qimage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
// SPDX-FileContributor: Leon Matthes <[email protected]>
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use cxx::{type_id, ExternType};
use std::mem::MaybeUninit;

#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
include!("cxx-qt-lib/qimage.h");
type QImage = super::QImage;

/// Whether the QImage is null.
///
/// This means that the QImage has all parameters set to zero and no allocated data.
#[rust_name = "is_null"]
fn isNull(self: &QImage) -> bool;
}

#[namespace = "rust::cxxqtlib1"]
unsafe extern "C++" {
include!("cxx-qt-lib/common.h");

#[doc(hidden)]
#[rust_name = "qimage_drop"]
fn drop(image: &mut QImage);

#[doc(hidden)]
#[rust_name = "qimage_init_from_data"]
fn qimageInitFromData(data: &[u8], format: &str) -> QImage;
}
}

/// > ⚠ **Warning**: The QImage API in CXX-Qt-lib is not yet complete and subject to change.
///
/// This struct is the Rust representation of the [`QImage`](https://doc.qt.io/qt-6/qimage.html)
/// class.
///
/// It provides a way to store and manipulate images in a hardware-independent manner.
#[repr(C)]
pub struct QImage {
// Static checks on the C++ side ensure this is true.
// See qcolor.cpp
#[cfg(qt_version_major = "5")]
_data: MaybeUninit<[usize; 4]>,
#[cfg(qt_version_major = "6")]
_data: MaybeUninit<[usize; 3]>,
}

// Safety:
//
// Static checks on the C++ side to ensure the size & alignment is the same.
unsafe impl ExternType for QImage {
type Id = type_id!("QImage");
type Kind = cxx::kind::Trivial;
}

impl Drop for QImage {
fn drop(&mut self) {
ffi::qimage_drop(self);
}
}

impl QImage {
/// Convert raw image data to a [`QImage`].
///
/// The data must be in the given `format`.
/// See [`QImageReader::supportedImageFormats()`](https://doc.qt.io/qt-6/qimagereader.html#supportedImageFormats) for the list of supported formats.
///
/// If no `format` is provided, the format will be quessed from the image header.
pub fn from_data(data: &[u8], format: Option<&str>) -> Option<Self> {
let image = ffi::qimage_init_from_data(data, format.unwrap_or(""));

if !image.is_null() {
Some(image)
} else {
None
}
}
}
Loading