Skip to content

API

init module.

core

src package.

core

init module for winipyside6.core.

py_qiodevice

PySide6 QIODevice wrapper.

EncryptedPyQFile
EncryptedPyQFile(
    path: Path, aes_gcm: AESGCM, *args: Any, **kwargs: Any
)

Bases: PyQFile

Transparent AES-GCM encrypted file wrapper for secure media access.

This class provides transparent encryption/decryption for file operations using AES-GCM (Galois/Counter Mode), an authenticated encryption cipher. Data is encrypted in fixed-size chunks (64KB plaintext + overhead) to support efficient streaming and random-access playback without decrypting entire files into memory.

Why chunked encryption is used: This approach enables seeking through encrypted files and playing encrypted videos without temporary files, by mapping between encrypted and decrypted positions and decrypting only necessary chunks on demand.

Attributes:

Name Type Description
NONCE_SIZE

Size of random nonce per chunk (12 bytes).

CIPHER_SIZE

Size of plaintext per chunk (64 KB).

TAG_SIZE

Size of authentication tag per chunk (16 bytes).

CHUNK_SIZE

Total encrypted chunk size = CIPHER_SIZE + NONCE_SIZE + TAG_SIZE.

CHUNK_OVERHEAD

Total per-chunk overhead = NONCE_SIZE + TAG_SIZE (28 bytes).

Parameters:

Name Type Description Default
path Path

The file path to open.

required
aes_gcm AESGCM

The AES-GCM cipher instance for encryption/decryption.

required
*args Any

Additional positional arguments passed to parent constructor.

()
**kwargs Any

Additional keyword arguments passed to parent constructor.

{}
Source code in src/winipyside/core/core/py_qiodevice.py
def __init__(self, path: Path, aes_gcm: AESGCM, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the encrypted file wrapper.

    Args:
        path: The file path to open.
        aes_gcm: The AES-GCM cipher instance for encryption/decryption.
        *args: Additional positional arguments passed to parent constructor.
        **kwargs: Additional keyword arguments passed to parent constructor.
    """
    super().__init__(path, *args, **kwargs)
    self.q_device: QFile
    self.aes_gcm = aes_gcm
    self.dec_size = self.size()
chunk_generator classmethod
chunk_generator(
    data: bytes, *, is_encrypted: bool
) -> Generator[bytes, None, None]

Generate fixed-size chunks from data for streaming processing.

Yields chunks of the appropriate size based on whether data is encrypted or plaintext. Used internally for batch encryption/decryption operations.

Parameters:

Name Type Description Default
data bytes

The complete data to split into chunks.

required
is_encrypted bool

If True, uses CHUNK_SIZE (encrypted). If False, uses CIPHER_SIZE (plaintext).

required

Yields:

Type Description
bytes

Byte chunks of the appropriate size (last chunk may be smaller).

Source code in src/winipyside/core/core/py_qiodevice.py
@classmethod
def chunk_generator(
    cls,
    data: bytes,
    *,
    is_encrypted: bool,
) -> Generator[bytes, None, None]:
    """Generate fixed-size chunks from data for streaming processing.

    Yields chunks of the appropriate size based on whether data is encrypted
    or plaintext. Used internally for batch encryption/decryption operations.

    Args:
        data: The complete data to split into chunks.
        is_encrypted: If True, uses CHUNK_SIZE (encrypted). If False, uses
            CIPHER_SIZE (plaintext).

    Yields:
        Byte chunks of the appropriate size (last chunk may be smaller).
    """
    size = cls.CHUNK_SIZE if is_encrypted else cls.CIPHER_SIZE
    for i in range(0, len(data), size):
        yield data[i : i + size]
decrypt_chunk_static classmethod
decrypt_chunk_static(data: bytes, aes_gcm: AESGCM) -> bytes

Decrypt a single chunk with authenticated verification.

Extracts the nonce from the chunk prefix, verifies the authentication tag, and decrypts the ciphertext. The AAD must match what was used during encryption.

Parameters:

Name Type Description Default
data bytes

The encrypted chunk formatted as: nonce || ciphertext || authentication_tag.

required
aes_gcm AESGCM

The AES-GCM cipher instance for decryption.

required

Returns:

Type Description
bytes

The decrypted plaintext chunk.

Raises:

Type Description
InvalidTag

If the authentication tag is invalid, indicating the chunk was tampered with, corrupted, or encrypted with a different key.

Source code in src/winipyside/core/core/py_qiodevice.py
@classmethod
def decrypt_chunk_static(cls, data: bytes, aes_gcm: AESGCM) -> bytes:
    """Decrypt a single chunk with authenticated verification.

    Extracts the nonce from the chunk prefix, verifies the authentication tag,
    and decrypts the ciphertext. The AAD must match what was used during encryption.

    Args:
        data: The encrypted chunk formatted as:
            nonce || ciphertext || authentication_tag.
        aes_gcm: The AES-GCM cipher instance for decryption.

    Returns:
        The decrypted plaintext chunk.

    Raises:
        cryptography.exceptions.InvalidTag: If the authentication tag is invalid,
            indicating the chunk was tampered with, corrupted, or encrypted with
            a different key.
    """
    nonce = data[: cls.NONCE_SIZE]
    cipher_and_tag = data[cls.NONCE_SIZE :]
    aad = cls.__name__.encode()
    return aes_gcm.decrypt(nonce, cipher_and_tag, aad)
decrypt_data
decrypt_data(data: bytes) -> bytes

Decrypt encrypted data using this instance's AES-GCM cipher.

Delegates to the static decryption method with this instance's cipher.

Parameters:

Name Type Description Default
data bytes

The encrypted data with nonces and tags intact.

required

Returns:

Type Description
bytes

The decrypted plaintext data.

Raises:

Type Description
InvalidTag

If authentication tag verification fails (indicates tampering or corruption).

Source code in src/winipyside/core/core/py_qiodevice.py
def decrypt_data(self, data: bytes) -> bytes:
    """Decrypt encrypted data using this instance's AES-GCM cipher.

    Delegates to the static decryption method with this instance's cipher.

    Args:
        data: The encrypted data with nonces and tags intact.

    Returns:
        The decrypted plaintext data.

    Raises:
        cryptography.exceptions.InvalidTag: If authentication tag verification fails
            (indicates tampering or corruption).
    """
    return self.decrypt_data_static(data, self.aes_gcm)
decrypt_data_static classmethod
decrypt_data_static(data: bytes, aes_gcm: AESGCM) -> bytes

Decrypt encrypted data using AES-GCM in streaming chunks.

Processes encrypted data in chunk-sized blocks, decrypting each independently with authenticated verification. Each chunk contains its own nonce, making this suitable for random-access scenarios where only specific chunks need decryption.

Parameters:

Name Type Description Default
data bytes

The encrypted data with nonces and tags (any size multiple of CHUNK_SIZE).

required
aes_gcm AESGCM

The AES-GCM cipher instance for decryption.

required

Returns:

Type Description
bytes

The decrypted plaintext data.

Raises:

Type Description
InvalidTag

If any chunk fails authentication (indicates tampering, corruption, or wrong key).

Source code in src/winipyside/core/core/py_qiodevice.py
@classmethod
def decrypt_data_static(cls, data: bytes, aes_gcm: AESGCM) -> bytes:
    """Decrypt encrypted data using AES-GCM in streaming chunks.

    Processes encrypted data in chunk-sized blocks, decrypting each independently
    with authenticated verification. Each chunk contains its own nonce, making this
    suitable for random-access scenarios where only specific chunks need decryption.

    Args:
        data: The encrypted data with nonces and tags
            (any size multiple of CHUNK_SIZE).
        aes_gcm: The AES-GCM cipher instance for decryption.

    Returns:
        The decrypted plaintext data.

    Raises:
        cryptography.exceptions.InvalidTag: If any chunk fails authentication
            (indicates tampering, corruption, or wrong key).
    """
    encrypted_chunks = cls.chunk_generator(data, is_encrypted=True)
    decrypted_chunks = map(
        partial(cls.decrypt_chunk_static, aes_gcm=aes_gcm),
        encrypted_chunks,
    )
    return b"".join(decrypted_chunks)
encrypt_chunk_static classmethod
encrypt_chunk_static(data: bytes, aes_gcm: AESGCM) -> bytes

Encrypt a single plaintext chunk with authenticated encryption.

Generates a random 12-byte nonce and encrypts the chunk with Additional Authenticated Data (AAD) to prevent tampering. The nonce is prepended to the ciphertext for use during decryption.

Parameters:

Name Type Description Default
data bytes

The plaintext chunk to encrypt (up to CIPHER_SIZE bytes).

required
aes_gcm AESGCM

The AES-GCM cipher instance for encryption.

required

Returns:

Type Description
bytes

Encrypted chunk formatted as: nonce || ciphertext || authentication_tag.

Source code in src/winipyside/core/core/py_qiodevice.py
@classmethod
def encrypt_chunk_static(cls, data: bytes, aes_gcm: AESGCM) -> bytes:
    """Encrypt a single plaintext chunk with authenticated encryption.

    Generates a random 12-byte nonce and encrypts the chunk with Additional
    Authenticated Data (AAD) to prevent tampering. The nonce is prepended to
    the ciphertext for use during decryption.

    Args:
        data: The plaintext chunk to encrypt (up to CIPHER_SIZE bytes).
        aes_gcm: The AES-GCM cipher instance for encryption.

    Returns:
        Encrypted chunk formatted as: nonce || ciphertext || authentication_tag.
    """
    nonce = os.urandom(12)
    aad = cls.__name__.encode()
    return nonce + aes_gcm.encrypt(nonce, data, aad)
encrypt_data
encrypt_data(data: bytes) -> bytes

Encrypt plaintext data using this instance's AES-GCM cipher.

Delegates to the static encryption method with this instance's cipher.

Parameters:

Name Type Description Default
data bytes

The plaintext data to encrypt.

required

Returns:

Type Description
bytes

The encrypted data with nonce

bytes

and authentication tag prepended to each chunk.

Source code in src/winipyside/core/core/py_qiodevice.py
def encrypt_data(self, data: bytes) -> bytes:
    """Encrypt plaintext data using this instance's AES-GCM cipher.

    Delegates to the static encryption method with this instance's cipher.

    Args:
        data: The plaintext data to encrypt.

    Returns:
        The encrypted data with nonce
        and authentication tag prepended to each chunk.
    """
    return self.encrypt_data_static(data, self.aes_gcm)
encrypt_data_static classmethod
encrypt_data_static(data: bytes, aes_gcm: AESGCM) -> bytes

Encrypt plaintext data using AES-GCM in streaming chunks.

Processes data in fixed-size plaintext chunks, encrypting each independently. Each chunk receives its own random nonce and authentication tag, enabling random-access decryption (decrypting any chunk without decrypting others).

Parameters:

Name Type Description Default
data bytes

The plaintext data to encrypt (any size).

required
aes_gcm AESGCM

The AES-GCM cipher instance for encryption.

required

Returns:

Type Description
bytes

The encrypted data with nonces

bytes

and authentication tags prepended to each chunk.

Source code in src/winipyside/core/core/py_qiodevice.py
@classmethod
def encrypt_data_static(cls, data: bytes, aes_gcm: AESGCM) -> bytes:
    """Encrypt plaintext data using AES-GCM in streaming chunks.

    Processes data in fixed-size plaintext chunks, encrypting each independently.
    Each chunk receives its own random nonce and authentication tag, enabling
    random-access decryption (decrypting any chunk without decrypting others).

    Args:
        data: The plaintext data to encrypt (any size).
        aes_gcm: The AES-GCM cipher instance for encryption.

    Returns:
        The encrypted data with nonces
        and authentication tags prepended to each chunk.
    """
    decrypted_chunks = cls.chunk_generator(data, is_encrypted=False)
    encrypted_chunks = map(
        partial(cls.encrypt_chunk_static, aes_gcm=aes_gcm),
        decrypted_chunks,
    )
    return b"".join(encrypted_chunks)
get_chunk_end
get_chunk_end(pos: int, maxlen: int) -> int

Get the end byte position of chunk range for given position and length.

Determines how many chunks are needed to read maxlen bytes starting from pos, and returns the byte offset of the end of the last required chunk.

Parameters:

Name Type Description Default
pos int

The starting byte position in the encrypted file.

required
maxlen int

The number of bytes to potentially read.

required

Returns:

Type Description
int

The byte offset of the end of the last chunk needed for the read.

Source code in src/winipyside/core/core/py_qiodevice.py
def get_chunk_end(self, pos: int, maxlen: int) -> int:
    """Get the end byte position of chunk range for given position and length.

    Determines how many chunks are needed to read maxlen bytes starting from pos,
    and returns the byte offset of the end of the last required chunk.

    Args:
        pos: The starting byte position in the encrypted file.
        maxlen: The number of bytes to potentially read.

    Returns:
        The byte offset of the end of the last chunk needed for the read.
    """
    return (pos + maxlen) // self.CHUNK_SIZE * self.CHUNK_SIZE + self.CHUNK_SIZE
get_chunk_start
get_chunk_start(pos: int) -> int

Get the start byte position of the chunk containing the given position.

Calculates which chunk boundary contains the position and returns the byte offset where that chunk begins in the encrypted file.

Parameters:

Name Type Description Default
pos int

The byte position within a chunk (encrypted file coordinates).

required

Returns:

Type Description
int

The byte offset of the start of the chunk containing the position.

Source code in src/winipyside/core/core/py_qiodevice.py
def get_chunk_start(self, pos: int) -> int:
    """Get the start byte position of the chunk containing the given position.

    Calculates which chunk boundary contains the position and returns the
    byte offset where that chunk begins in the encrypted file.

    Args:
        pos: The byte position within a chunk (encrypted file coordinates).

    Returns:
        The byte offset of the start of the chunk containing the position.
    """
    return pos // self.CHUNK_SIZE * self.CHUNK_SIZE
get_decrypted_pos
get_decrypted_pos(enc_pos: int) -> int

Convert encrypted file position to decrypted (plaintext) position.

Maps positions from the encrypted file layout to the corresponding position in the plaintext stream. Accounts for nonces and tags distributed across chunks.

This is essential for seeking operations - when user seeks to position X in the plaintext, we need to find the corresponding position in the encrypted file.

Parameters:

Name Type Description Default
enc_pos int

The byte position in the encrypted file.

required

Returns:

Type Description
int

The corresponding byte position in the decrypted plaintext.

Source code in src/winipyside/core/core/py_qiodevice.py
def get_decrypted_pos(self, enc_pos: int) -> int:
    """Convert encrypted file position to decrypted (plaintext) position.

    Maps positions from the encrypted file layout to the corresponding position
    in the plaintext stream. Accounts for nonces and tags distributed across chunks.

    This is essential for seeking operations - when user seeks to position X in the
    plaintext, we need to find the corresponding position in the encrypted file.

    Args:
        enc_pos: The byte position in the encrypted file.

    Returns:
        The corresponding byte position in the decrypted plaintext.
    """
    if enc_pos >= self.enc_size:
        return self.dec_size

    num_chunks_before = enc_pos // self.CHUNK_SIZE
    last_enc_chunk_start = num_chunks_before * self.CHUNK_SIZE
    last_dec_chunk_start = num_chunks_before * self.CIPHER_SIZE

    enc_bytes_to_move = enc_pos - last_enc_chunk_start

    return last_dec_chunk_start + enc_bytes_to_move - self.NONCE_SIZE
get_encrypted_pos
get_encrypted_pos(dec_pos: int) -> int

Convert decrypted (plaintext) position to encrypted file position.

Maps positions from the plaintext stream to the corresponding position in the encrypted file layout. Accounts for nonces and tags distributed across chunks.

This is the inverse of get_decrypted_pos() and is used when seeking - we convert the desired plaintext position to find where to read in the encrypted file.

Parameters:

Name Type Description Default
dec_pos int

The byte position in the decrypted plaintext stream.

required

Returns:

Type Description
int

The corresponding byte position in the encrypted file.

Source code in src/winipyside/core/core/py_qiodevice.py
def get_encrypted_pos(self, dec_pos: int) -> int:
    """Convert decrypted (plaintext) position to encrypted file position.

    Maps positions from the plaintext stream to the corresponding position
    in the encrypted file layout.
    Accounts for nonces and tags distributed across chunks.

    This is the inverse of get_decrypted_pos() and is used when seeking - we convert
    the desired plaintext position to find where to read in the encrypted file.

    Args:
        dec_pos: The byte position in the decrypted plaintext stream.

    Returns:
        The corresponding byte position in the encrypted file.
    """
    if dec_pos >= self.dec_size:
        return self.enc_size
    num_chunks_before = dec_pos // self.CIPHER_SIZE
    last_dec_chunk_start = num_chunks_before * self.CIPHER_SIZE
    last_enc_chunk_start = num_chunks_before * self.CHUNK_SIZE

    dec_bytes_to_move = dec_pos - last_dec_chunk_start

    return last_enc_chunk_start + self.NONCE_SIZE + dec_bytes_to_move
readData
readData(maxlen: int) -> bytes

Read and decrypt data from the encrypted file.

Implements transparent decryption by reading encrypted chunks from the file and decrypting them. Handles position mapping between encrypted and decrypted data, enabling random access and seeking within encrypted content.

This method is called internally by the QIODevice read() method and handles the complexity of chunk boundaries and position tracking.

Parameters:

Name Type Description Default
maxlen int

The maximum number of decrypted bytes to read from current position.

required

Returns:

Type Description
bytes

The decrypted data as bytes (may be less than maxlen if at end of file).

Source code in src/winipyside/core/core/py_qiodevice.py
def readData(self, maxlen: int) -> bytes:  # noqa: N802
    """Read and decrypt data from the encrypted file.

    Implements transparent decryption by reading encrypted chunks from the file
    and decrypting them. Handles position mapping between encrypted and decrypted
    data, enabling random access and seeking within encrypted content.

    This method is called internally by the QIODevice read() method and handles
    the complexity of chunk boundaries and position tracking.

    Args:
        maxlen: The maximum number of decrypted bytes to read from current position.

    Returns:
        The decrypted data as bytes (may be less than maxlen if at end of file).
    """
    # where we are in the encrypted data
    dec_pos = self.pos()
    # where we are in the decrypted data
    enc_pos = self.get_encrypted_pos(dec_pos)

    # get the chunk start and end
    chunk_start = self.get_chunk_start(enc_pos)
    chunk_end = self.get_chunk_end(enc_pos, maxlen)
    new_maxlen = chunk_end - chunk_start

    # read the chunk
    self.seek(chunk_start)
    enc_data = super().readData(new_maxlen)
    # decrypt the chunk
    dec_data = self.decrypt_data(enc_data)

    # get the start and end of the requested data in the decrypted data
    dec_chunk_start = self.get_decrypted_pos(chunk_start + self.NONCE_SIZE)

    req_data_start = dec_pos - dec_chunk_start
    req_data_end = req_data_start + maxlen

    dec_pos += maxlen
    self.seek(dec_pos)

    return dec_data[req_data_start:req_data_end]
size
size() -> int

Get the decrypted file size.

Calculates and caches the decrypted file size based on the encrypted file size and chunk structure. This is used internally by the media player to determine file bounds without decrypting the entire file.

Returns:

Type Description
int

The total plaintext size of the file in bytes.

Source code in src/winipyside/core/core/py_qiodevice.py
def size(self) -> int:
    """Get the decrypted file size.

    Calculates and caches the decrypted file size based on the encrypted file size
    and chunk structure. This is used internally by the media player to determine
    file bounds without decrypting the entire file.

    Returns:
        The total plaintext size of the file in bytes.
    """
    self.enc_size = super().size()
    self.num_chunks = self.enc_size // self.CHUNK_SIZE + 1
    self.dec_size = self.num_chunks * self.CIPHER_SIZE
    return self.dec_size
writeData
writeData(
    data: bytes | bytearray | memoryview, len: int
) -> int

Encrypt and write data to the file.

Encrypts the provided plaintext data using AES-GCM and writes the encrypted chunks to the underlying file device. Each chunk includes a random nonce and authentication tag for authenticated encryption.

Parameters:

Name Type Description Default
data bytes | bytearray | memoryview

The plaintext data to encrypt and write.

required
len int

The length parameter (unused in this implementation, actual data length is used).

required

Returns:

Type Description
int

The number of plaintext bytes that were encrypted and written.

Source code in src/winipyside/core/core/py_qiodevice.py
def writeData(self, data: bytes | bytearray | memoryview, len: int) -> int:  # noqa: A002, ARG002, N802
    """Encrypt and write data to the file.

    Encrypts the provided plaintext data using AES-GCM and writes the encrypted
    chunks to the underlying file device. Each chunk includes a random nonce and
    authentication tag for authenticated encryption.

    Args:
        data: The plaintext data to encrypt and write.
        len: The length parameter (unused in this implementation,
            actual data length is used).

    Returns:
        The number of plaintext bytes that were encrypted and written.
    """
    encrypted_data = self.encrypt_data(bytes(data))
    encrypted_len = encrypted_data.__len__()
    return super().writeData(encrypted_data, encrypted_len)
PyQFile
PyQFile(path: Path, *args: Any, **kwargs: Any)

Bases: PyQIODevice

Pythonic wrapper for PySide6 QFile with file path support.

A specialized PyQIODevice wrapper that handles file path initialization and provides convenient file I/O operations. This class extends PyQIODevice with automatic QFile instantiation from file paths, simplifying file-based I/O operations throughout the application.

Parameters:

Name Type Description Default
path Path

The file path to open.

required
*args Any

Additional positional arguments passed to parent constructor.

()
**kwargs Any

Additional keyword arguments passed to parent constructor.

{}
Source code in src/winipyside/core/core/py_qiodevice.py
def __init__(self, path: Path, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the PyQFile with a file path.

    Args:
        path: The file path to open.
        *args: Additional positional arguments passed to parent constructor.
        **kwargs: Additional keyword arguments passed to parent constructor.
    """
    super().__init__(QFile(path), *args, **kwargs)
    self.q_device: QFile
PyQIODevice
PyQIODevice(q_device: QIODevice, *args: Any, **kwargs: Any)

Bases: QIODevice

Pythonic wrapper for PySide6 QIODevice with transparent delegation.

This class provides a Python-friendly interface to PySide6's QIODevice by wrapping an existing QIODevice instance and delegating all I/O operations to it. This pattern allows for composition-based enhancement of QIODevice functionality while maintaining full API compatibility.

The wrapper implements all standard QIODevice methods, making it suitable as a drop-in replacement for QIODevice in contexts requiring Pythonic behavior or additional processing layers (e.g., encryption/decryption in subclasses).

Parameters:

Name Type Description Default
q_device QIODevice

The QIODevice instance to wrap and delegate operations to.

required
*args Any

Additional positional arguments passed to parent QIODevice constructor.

()
**kwargs Any

Additional keyword arguments passed to parent QIODevice constructor.

{}
Source code in src/winipyside/core/core/py_qiodevice.py
def __init__(self, q_device: QIODevice, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the PyQIODevice wrapper.

    Args:
        q_device: The QIODevice instance to wrap and delegate operations to.
        *args:
            Additional positional arguments passed to parent QIODevice constructor.
        **kwargs:
            Additional keyword arguments passed to parent QIODevice constructor.
    """
    super().__init__(*args, **kwargs)
    self.q_device = q_device
atEnd
atEnd() -> bool

Check if the device is at the end of data.

Returns:

Type Description
bool

True if the device is at the end, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def atEnd(self) -> bool:  # noqa: N802
    """Check if the device is at the end of data.

    Returns:
        True if the device is at the end, False otherwise.
    """
    return self.q_device.atEnd()
bytesAvailable
bytesAvailable() -> int

Get the number of bytes available for reading.

Returns:

Type Description
int

The number of bytes available for reading.

Source code in src/winipyside/core/core/py_qiodevice.py
def bytesAvailable(self) -> int:  # noqa: N802
    """Get the number of bytes available for reading.

    Returns:
        The number of bytes available for reading.
    """
    return self.q_device.bytesAvailable()
bytesToWrite
bytesToWrite() -> int

Get the number of bytes waiting to be written.

Returns:

Type Description
int

The number of bytes waiting to be written.

Source code in src/winipyside/core/core/py_qiodevice.py
def bytesToWrite(self) -> int:  # noqa: N802
    """Get the number of bytes waiting to be written.

    Returns:
        The number of bytes waiting to be written.
    """
    return self.q_device.bytesToWrite()
canReadLine
canReadLine() -> bool

Check if a complete line can be read from the device.

Returns:

Type Description
bool

True if a complete line can be read, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def canReadLine(self) -> bool:  # noqa: N802
    """Check if a complete line can be read from the device.

    Returns:
        True if a complete line can be read, False otherwise.
    """
    return self.q_device.canReadLine()
close
close() -> None

Close the device and release resources.

Closes the underlying QIODevice and calls the parent close method.

Source code in src/winipyside/core/core/py_qiodevice.py
def close(self) -> None:
    """Close the device and release resources.

    Closes the underlying QIODevice and calls the parent close method.
    """
    self.q_device.close()
    return super().close()
isSequential
isSequential() -> bool

Check if the device is sequential.

Returns:

Type Description
bool

True if the device is sequential, False if it supports random access.

Source code in src/winipyside/core/core/py_qiodevice.py
def isSequential(self) -> bool:  # noqa: N802
    """Check if the device is sequential.

    Returns:
        True if the device is sequential, False if it supports random access.
    """
    return self.q_device.isSequential()
open
open(mode: OpenModeFlag) -> bool

Open the device with the specified mode.

Parameters:

Name Type Description Default
mode OpenModeFlag

The open mode flag specifying how to open the device.

required

Returns:

Type Description
bool

True if the device was opened successfully, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def open(self, mode: QIODevice.OpenModeFlag) -> bool:
    """Open the device with the specified mode.

    Args:
        mode: The open mode flag specifying how to open the device.

    Returns:
        True if the device was opened successfully, False otherwise.
    """
    self.q_device.open(mode)
    return super().open(mode)
pos
pos() -> int

Get the current position in the device.

Returns:

Type Description
int

The current position in the device.

Source code in src/winipyside/core/core/py_qiodevice.py
def pos(self) -> int:
    """Get the current position in the device.

    Returns:
        The current position in the device.
    """
    return self.q_device.pos()
readData
readData(maxlen: int) -> bytes

Read data from the device.

Parameters:

Name Type Description Default
maxlen int

The maximum number of bytes to read.

required

Returns:

Type Description
bytes

The data read from the device as bytes.

Source code in src/winipyside/core/core/py_qiodevice.py
def readData(self, maxlen: int) -> bytes:  # noqa: N802
    """Read data from the device.

    Args:
        maxlen: The maximum number of bytes to read.

    Returns:
        The data read from the device as bytes.
    """
    return bytes(self.q_device.read(maxlen).data())
readLineData
readLineData(maxlen: int) -> object

Read a line from the device.

Parameters:

Name Type Description Default
maxlen int

The maximum number of bytes to read.

required

Returns:

Type Description
object

The line data read from the device.

Source code in src/winipyside/core/core/py_qiodevice.py
def readLineData(self, maxlen: int) -> object:  # noqa: N802
    """Read a line from the device.

    Args:
        maxlen: The maximum number of bytes to read.

    Returns:
        The line data read from the device.
    """
    return self.q_device.readLine(maxlen)
reset
reset() -> bool

Reset the device to its initial state.

Returns:

Type Description
bool

True if the device was reset successfully, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def reset(self) -> bool:
    """Reset the device to its initial state.

    Returns:
        True if the device was reset successfully, False otherwise.
    """
    return self.q_device.reset()
seek
seek(pos: int) -> bool

Seek to a specific position in the device.

Parameters:

Name Type Description Default
pos int

The position to seek to.

required

Returns:

Type Description
bool

True if the seek operation was successful, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def seek(self, pos: int) -> bool:
    """Seek to a specific position in the device.

    Args:
        pos: The position to seek to.

    Returns:
        True if the seek operation was successful, False otherwise.
    """
    return self.q_device.seek(pos)
size
size() -> int

Get the size of the device.

Returns:

Type Description
int

The size of the device in bytes.

Source code in src/winipyside/core/core/py_qiodevice.py
def size(self) -> int:
    """Get the size of the device.

    Returns:
        The size of the device in bytes.
    """
    return self.q_device.size()
skipData
skipData(maxSize: int) -> int

Skip data in the device.

Parameters:

Name Type Description Default
maxSize int

The maximum number of bytes to skip.

required

Returns:

Type Description
int

The actual number of bytes skipped.

Source code in src/winipyside/core/core/py_qiodevice.py
def skipData(self, maxSize: int) -> int:  # noqa: N802, N803
    """Skip data in the device.

    Args:
        maxSize: The maximum number of bytes to skip.

    Returns:
        The actual number of bytes skipped.
    """
    return self.q_device.skip(maxSize)
waitForBytesWritten
waitForBytesWritten(msecs: int) -> bool

Wait for bytes to be written to the device.

Parameters:

Name Type Description Default
msecs int

The maximum time to wait in milliseconds.

required

Returns:

Type Description
bool

True if bytes were written within the timeout, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def waitForBytesWritten(self, msecs: int) -> bool:  # noqa: N802
    """Wait for bytes to be written to the device.

    Args:
        msecs: The maximum time to wait in milliseconds.

    Returns:
        True if bytes were written within the timeout, False otherwise.
    """
    return self.q_device.waitForBytesWritten(msecs)
waitForReadyRead
waitForReadyRead(msecs: int) -> bool

Wait for the device to be ready for reading.

Parameters:

Name Type Description Default
msecs int

The maximum time to wait in milliseconds.

required

Returns:

Type Description
bool

True if the device became ready within the timeout, False otherwise.

Source code in src/winipyside/core/core/py_qiodevice.py
def waitForReadyRead(self, msecs: int) -> bool:  # noqa: N802
    """Wait for the device to be ready for reading.

    Args:
        msecs: The maximum time to wait in milliseconds.

    Returns:
        True if the device became ready within the timeout, False otherwise.
    """
    return self.q_device.waitForReadyRead(msecs)
writeData
writeData(
    data: bytes | bytearray | memoryview, len: int
) -> int

Write data to the device.

Parameters:

Name Type Description Default
data bytes | bytearray | memoryview

The data to write to the device.

required
len int

The length parameter (unused in this implementation).

required

Returns:

Type Description
int

The number of bytes actually written.

Source code in src/winipyside/core/core/py_qiodevice.py
def writeData(self, data: bytes | bytearray | memoryview, len: int) -> int:  # noqa: A002, ARG002, N802
    """Write data to the device.

    Args:
        data: The data to write to the device.
        len: The length parameter (unused in this implementation).

    Returns:
        The number of bytes actually written.
    """
    return self.q_device.write(data)

ui

init module for winipyside6.ui.

base

init module.

base

Base UI module.

This module contains the base UI class for the VideoVault application.

Base
Base(*args: Any, **kwargs: Any)

Abstract base class for all UI components with lifecycle hooks.

Defines a common initialization pattern for UI elements with four ordered setup phases, enabling predictable initialization flow. All UI components (pages, widgets, windows) inherit from this base to ensure consistent lifecycle management.

Subclasses must implement all abstract methods in the prescribed order: base_setup() → pre_setup() → setup() → post_setup()

Calls setup methods in a fixed order: base_setup(), pre_setup(), setup(), and post_setup(). This ensures all UI initialization happens in the correct sequence, with dependencies resolved before dependent setup runs.

Source code in src/winipyside/core/ui/base/base.py
def __init__(self, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the UI component and execute all setup lifecycle hooks.

    Calls setup methods in a fixed order: base_setup(), pre_setup(), setup(),
    and post_setup(). This ensures all UI initialization happens in the correct
    sequence, with dependencies resolved before dependent setup runs.
    """
    super().__init__(*args, **kwargs)
    self.base_setup()
    self.pre_setup()
    self.setup()
    self.post_setup()
base_setup abstractmethod
base_setup() -> None

Initialize core Qt objects required by the UI component.

This is the first lifecycle hook, called before any other setup. Must create and configure fundamental Qt widgets/layouts that other setup phases depend on.

Examples:

  • Creating QWidget or QMainWindow
  • Setting up top-level layouts
  • Initializing core visual structure
Source code in src/winipyside/core/ui/base/base.py
@abstractmethod
def base_setup(self) -> None:
    """Initialize core Qt objects required by the UI component.

    This is the first lifecycle hook, called before any other setup. Must create
    and configure fundamental Qt widgets/layouts that other setup phases depend on.

    Examples:
        - Creating QWidget or QMainWindow
        - Setting up top-level layouts
        - Initializing core visual structure
    """
get_display_name classmethod
get_display_name() -> str

Generate human-readable display name from class name.

Converts the class name from CamelCase to space-separated words. For example: 'BrowserPage' becomes 'Browser Page'.

Returns:

Type Description
str

The human-readable display name derived from the class name.

Source code in src/winipyside/core/ui/base/base.py
@classmethod
def get_display_name(cls) -> str:
    """Generate human-readable display name from class name.

    Converts the class name from CamelCase to space-separated words.
    For example: 'BrowserPage' becomes 'Browser Page'.

    Returns:
        The human-readable display name derived from the class name.
    """
    return " ".join(split_on_uppercase(cls.__name__))
get_page
get_page[T: Base](page_cls: type[T]) -> T

Get a specific page instance from the stack by class type.

Finds the single instance of the specified page class in the stack. Uses type equality check to handle inheritance correctly.

Parameters:

Name Type Description Default
page_cls type[T]

The page class type to retrieve. Uses PEP 695 generic syntax.

required

Returns:

Type Description
T

The page instance of the specified class, cast to correct type.

Raises:

Type Description
StopIteration

If no page of the specified class is in the stack.

Source code in src/winipyside/core/ui/base/base.py
def get_page[T: "BasePage"](self, page_cls: type[T]) -> T:
    """Get a specific page instance from the stack by class type.

    Finds the single instance of the specified page class in the stack.
    Uses type equality check to handle inheritance correctly.

    Args:
        page_cls: The page class type to retrieve. Uses PEP 695 generic syntax.

    Returns:
        The page instance of the specified class, cast to correct type.

    Raises:
        StopIteration: If no page of the specified class is in the stack.
    """
    page = next(
        page for page in self.get_stack_pages() if page.__class__ is page_cls
    )
    return cast("T", page)
get_page_static classmethod
get_page_static[T: Base](page_cls: type[T]) -> T

Get a page instance directly from the main application window.

This static method provides a global way to access any page without needing a reference to the window. Searches through top-level widgets to find the BaseWindow instance, then retrieves the desired page from it.

Useful for accessing pages from deep within nested widget hierarchies where passing window references would be impractical.

Parameters:

Name Type Description Default
page_cls type[T]

The page class type to retrieve. Uses PEP 695 generic syntax.

required

Returns:

Type Description
T

The page instance of the specified class from the main window.

Raises:

Type Description
StopIteration

If no BaseWindow is found or if the page doesn't exist.

Source code in src/winipyside/core/ui/base/base.py
@classmethod
def get_page_static[T: "BasePage"](cls, page_cls: type[T]) -> T:
    """Get a page instance directly from the main application window.

    This static method provides a global way to access any page without needing
    a reference to the window. Searches through top-level widgets to find the
    BaseWindow instance, then retrieves the desired page from it.

    Useful for accessing pages from deep within nested widget hierarchies where
    passing window references would be impractical.

    Args:
        page_cls: The page class type to retrieve. Uses PEP 695 generic syntax.

    Returns:
        The page instance of the specified class from the main window.

    Raises:
        StopIteration: If no BaseWindow is found or if the page doesn't exist.
    """
    from winipyside.core.ui.windows.base.base import (  # noqa: PLC0415  bc of circular import
        Base as BaseWindow,
    )

    top_level_widgets = QApplication.topLevelWidgets()
    main_window = next(
        widget for widget in top_level_widgets if isinstance(widget, BaseWindow)
    )
    return main_window.get_page(page_cls)
get_stack
get_stack() -> QStackedWidget

Get the stacked widget containing all pages.

Assumes the window object has a 'stack' attribute (QStackedWidget) that holds all pages.

Returns:

Type Description
QStackedWidget

The QStackedWidget managing page navigation.

Raises:

Type Description
AttributeError

If the window doesn't have a 'stack' attribute.

Source code in src/winipyside/core/ui/base/base.py
def get_stack(self) -> QStackedWidget:
    """Get the stacked widget containing all pages.

    Assumes the window object has a 'stack' attribute (QStackedWidget)
    that holds all pages.

    Returns:
        The QStackedWidget managing page navigation.

    Raises:
        AttributeError: If the window doesn't have a 'stack' attribute.
    """
    window = cast("BaseWindow", (getattr(self, "window", lambda: None)()))

    return window.stack
get_stack_pages
get_stack_pages() -> list[Base]

Get all page instances from the stacked widget.

Retrieves all currently instantiated pages in the stacked widget, maintaining their widget index order.

Returns:

Type Description
list[Base]

A list of all BasePage instances in the stack.

Source code in src/winipyside/core/ui/base/base.py
def get_stack_pages(self) -> list["BasePage"]:
    """Get all page instances from the stacked widget.

    Retrieves all currently instantiated pages in the stacked widget,
    maintaining their widget index order.

    Returns:
        A list of all BasePage instances in the stack.
    """
    # Import here to avoid circular import

    stack = self.get_stack()
    # get all the pages
    return [cast("BasePage", stack.widget(i)) for i in range(stack.count())]
get_subclasses classmethod
get_subclasses(
    package: ModuleType | None = None,
) -> list[type[Self]]

Get all non-abstract subclasses of this UI class.

Dynamically discovers all concrete (non-abstract) subclasses within the specified package. Forces module imports to ensure all subclasses are loaded and discoverable. Returns results sorted by class name for consistent ordering.

Parameters:

Name Type Description Default
package ModuleType | None

The package to search for subclasses in. If None, searches the main package. Common use is winipyside root package.

None

Returns:

Type Description
list[type[Self]]

A sorted list of all non-abstract subclass types.

Source code in src/winipyside/core/ui/base/base.py
@classmethod
def get_subclasses(cls, package: ModuleType | None = None) -> list[type[Self]]:
    """Get all non-abstract subclasses of this UI class.

    Dynamically discovers all concrete (non-abstract)
    subclasses within the specified package. Forces module imports to
    ensure all subclasses are loaded and discoverable.
    Returns results sorted by class name for consistent ordering.

    Args:
        package: The package to search for subclasses in. If None, searches
            the main package. Common use is winipyside root package.

    Returns:
        A sorted list of all non-abstract subclass types.
    """
    if package is None:
        # find the main package
        package = sys.modules[__name__]

    if is_package(package):
        register_package_modules(package)

    children = filter_leaf_classes(
        discover_subclasses(cls),
    )
    return sorted(children, key=lambda cls: cls.__name__)
get_svg_icon classmethod
get_svg_icon(
    svg_name: str, package: ModuleType | None = None
) -> QIcon

Load an SVG file and return it as a QIcon.

Locates SVG files in the resources package and creates Qt icons from them. Automatically appends .svg extension if not provided. The SVG is loaded from the assets, enabling dynamic icon theming and scaling.

Parameters:

Name Type Description Default
svg_name str

The SVG filename (with or without .svg extension).

required
package ModuleType | None

The package to search for SVG files. If None, uses the default resources package. Override for custom resource locations.

None

Returns:

Type Description
QIcon

A QIcon created from the SVG file, ready for use in UI widgets.

Raises:

Type Description
FileNotFoundError

If the SVG file is not found in the resources.

Source code in src/winipyside/core/ui/base/base.py
@classmethod
def get_svg_icon(cls, svg_name: str, package: ModuleType | None = None) -> QIcon:
    """Load an SVG file and return it as a QIcon.

    Locates SVG files in the resources package and creates Qt icons from them.
    Automatically appends .svg extension if not provided. The SVG is loaded
    from the assets, enabling dynamic icon theming and scaling.

    Args:
        svg_name: The SVG filename (with or without .svg extension).
        package: The package to search for SVG files. If None, uses the default
            resources package. Override for custom resource locations.

    Returns:
        A QIcon created from the SVG file, ready for use in UI widgets.

    Raises:
        FileNotFoundError: If the SVG file is not found in the resources.
    """
    if package is None:
        package = resources
    if not svg_name.endswith(".svg"):
        svg_name = f"{svg_name}.svg"

    return QIcon(str(resource_path(svg_name, package=package)))
post_setup abstractmethod
post_setup() -> None

Execute finalization operations after main setup.

This is the fourth and final lifecycle hook. Use this for cleanup, final configuration, or operations that should run after setup() is complete, such as layout adjustments or state initialization.

Source code in src/winipyside/core/ui/base/base.py
@abstractmethod
def post_setup(self) -> None:
    """Execute finalization operations after main setup.

    This is the fourth and final lifecycle hook. Use this for cleanup, final
    configuration, or operations that should run after setup() is complete,
    such as layout adjustments or state initialization.
    """
pre_setup abstractmethod
pre_setup() -> None

Execute setup operations before main setup.

This is the second lifecycle hook. Use this for operations that should run after base_setup() but before setup(), such as signal connections that rely on base_setup() completing.

Source code in src/winipyside/core/ui/base/base.py
@abstractmethod
def pre_setup(self) -> None:
    """Execute setup operations before main setup.

    This is the second lifecycle hook. Use this for operations that should run
    after base_setup() but before setup(), such as signal connections that rely
    on base_setup() completing.
    """
set_current_page
set_current_page(page_cls: type[Base]) -> None

Switch the currently displayed page in the stacked widget.

Finds the page instance of the specified type and brings it to the front of the stacked widget, making it the visible page.

Parameters:

Name Type Description Default
page_cls type[Base]

The page class type to display. The corresponding instance must already exist in the stack.

required

Raises:

Type Description
StopIteration

If no page of the specified class exists in the stack.

Source code in src/winipyside/core/ui/base/base.py
def set_current_page(self, page_cls: type["BasePage"]) -> None:
    """Switch the currently displayed page in the stacked widget.

    Finds the page instance of the specified type and brings it to the front
    of the stacked widget, making it the visible page.

    Args:
        page_cls: The page class type to display. The corresponding instance
            must already exist in the stack.

    Raises:
        StopIteration: If no page of the specified class exists in the stack.
    """
    self.get_stack().setCurrentWidget(self.get_page(page_cls))
setup abstractmethod
setup() -> None

Execute main UI initialization.

This is the third lifecycle hook. Contains the primary UI initialization logic, such as creating widgets, connecting signals, and populating components.

Source code in src/winipyside/core/ui/base/base.py
@abstractmethod
def setup(self) -> None:
    """Execute main UI initialization.

    This is the third lifecycle hook. Contains the primary UI initialization logic,
    such as creating widgets, connecting signals, and populating components.
    """
QABCLoggingMeta

Bases: ABCLoggingMeta, type(QObject)

Metaclass combining ABC enforcement with Qt and logging integration.

This metaclass merges ABCLoggingMeta (which enforces abstract methods and logs implementation status) with QObject's metaclass. This enables Qt-based UI classes to use abstract methods while maintaining proper Qt initialization.

pages

init module.

base

init module.

base

Base page module.

This module contains the base page class for the VideoVault application.

Base
Base(base_window: Base, *args: Any, **kwargs: Any)

Bases: Base, QWidget

Abstract base class for all pages in the stacked widget navigation system.

A page is a full-screen view that can be displayed within a QStackedWidget. Each page inherits from BaseUI to get the standard lifecycle hooks and provides a top navigation bar with a menu dropdown. Pages are responsible for their own content layout and child widgets.

Attributes:

Name Type Description
v_layout

Main vertical layout for the page content.

h_layout

Horizontal layout for top navigation bar.

menu_button

Menu button that provides navigation to other pages.

base_window

Reference to the containing BaseWindow.

Parameters:

Name Type Description Default
base_window Base

The parent BaseWindow containing this page's stack.

required
*args Any

Additional positional arguments passed to parent QWidget.

()
**kwargs Any

Additional keyword arguments passed to parent QWidget.

{}
Source code in src/winipyside/core/ui/pages/base/base.py
def __init__(self, base_window: "BaseWindow", *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the page with a reference to the base window.

    Args:
        base_window: The parent BaseWindow containing this page's stack.
        *args: Additional positional arguments passed to parent QWidget.
        **kwargs: Additional keyword arguments passed to parent QWidget.
    """
    self.base_window = base_window
    super().__init__(*args, **kwargs)
add_menu_dropdown_button
add_menu_dropdown_button() -> None

Create and configure the page navigation menu button.

Creates a dropdown menu button in the top-left corner that lists all available pages as menu actions. Clicking an action switches to that page. The menu auto-populates with all page subclasses from the window.

The menu uses SVG icons for a modern appearance and is aligned to the top-left of the navigation bar.

Source code in src/winipyside/core/ui/pages/base/base.py
def add_menu_dropdown_button(self) -> None:
    """Create and configure the page navigation menu button.

    Creates a dropdown menu button in the top-left corner that lists all available
    pages as menu actions. Clicking an action switches to that page. The menu
    auto-populates with all page subclasses from the window.

    The menu uses SVG icons for a modern appearance and is aligned to the top-left
    of the navigation bar.
    """
    self.menu_button = QPushButton("Menu")
    self.menu_button.setIcon(self.get_svg_icon("menu_icon"))
    self.menu_button.setSizePolicy(
        QSizePolicy.Policy.Minimum,
        QSizePolicy.Policy.Minimum,
    )
    self.h_layout.addWidget(
        self.menu_button,
        alignment=Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft,
    )
    self.menu_dropdown = QMenu(self.menu_button)
    self.menu_button.setMenu(self.menu_dropdown)

    for page_cls in self.base_window.get_all_page_classes():
        action = self.menu_dropdown.addAction(page_cls.get_display_name())
        action.triggered.connect(partial(self.set_current_page, page_cls))
add_to_page_button
add_to_page_button(
    to_page_cls: type[Base], layout: QLayout
) -> QPushButton

Create a navigation button that switches to the specified page.

Creates a styled button with the target page's display name and connects it to automatically navigate to that page when clicked. The button is added to the provided layout.

Parameters:

Name Type Description Default
to_page_cls type[Base]

The page class to navigate to when the button is clicked.

required
layout QLayout

The layout to add the button to (typically h_layout or a child layout).

required

Returns:

Type Description
QPushButton

The created QPushButton widget (if you need to store or modify it).

Source code in src/winipyside/core/ui/pages/base/base.py
def add_to_page_button(
    self,
    to_page_cls: type["Base"],
    layout: QLayout,
) -> QPushButton:
    """Create a navigation button that switches to the specified page.

    Creates a styled button with the target page's display name and connects it
    to automatically navigate to that page when clicked. The button is added to
    the provided layout.

    Args:
        to_page_cls: The page class to navigate to when the button is clicked.
        layout: The layout to add the button to
            (typically h_layout or a child layout).

    Returns:
        The created QPushButton widget (if you need to store or modify it).
    """
    button = QPushButton(to_page_cls.get_display_name())

    # connect to open page on click
    button.clicked.connect(lambda: self.set_current_page(to_page_cls))

    # add to layout
    layout.addWidget(button)

    return button
base_setup
base_setup() -> None

Initialize the page structure with vertical and horizontal layouts.

Creates the main vertical layout for page content, a horizontal layout for the top navigation bar, and registers this page with the base window. This is the first lifecycle hook and must run before other setup methods.

The layout structure is: - v_layout (QVBoxLayout) - Main page layout - h_layout (QHBoxLayout) - Top navigation/menu bar - [page content added here by subclasses]

Source code in src/winipyside/core/ui/pages/base/base.py
def base_setup(self) -> None:
    """Initialize the page structure with vertical and horizontal layouts.

    Creates the main vertical layout for page content, a horizontal layout
    for the top navigation bar, and registers this page with the base window.
    This is the first lifecycle hook and must run before other setup methods.

    The layout structure is:
    - v_layout (QVBoxLayout) - Main page layout
      - h_layout (QHBoxLayout) - Top navigation/menu bar
      - [page content added here by subclasses]
    """
    self.v_layout = QVBoxLayout()
    self.setLayout(self.v_layout)

    # add a horizontal layout for the top row
    self.h_layout = QHBoxLayout()
    self.v_layout.addLayout(self.h_layout)

    self.add_menu_dropdown_button()
    self.base_window.add_page(self)
browser

Browser page module.

This module contains the Browser page class for displaying web content within the application.

Browser
Browser(base_window: Base, *args: Any, **kwargs: Any)

Bases: Base

Web browser page for embedded internet browsing.

A page that provides full web browsing capabilities through an embedded Chromium-based browser. Includes navigation controls (back/forward/address bar) and automatic cookie tracking for web interactions.

Source code in src/winipyside/core/ui/pages/base/base.py
def __init__(self, base_window: "BaseWindow", *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the page with a reference to the base window.

    Args:
        base_window: The parent BaseWindow containing this page's stack.
        *args: Additional positional arguments passed to parent QWidget.
        **kwargs: Additional keyword arguments passed to parent QWidget.
    """
    self.base_window = base_window
    super().__init__(*args, **kwargs)
add_browser
add_browser() -> None

Create and add a web browser widget to the page.

Creates a BrowserWidget instance and adds it to the vertical layout, making the embedded browser available for web navigation. The browser automatically handles cookies and provides standard navigation controls.

Note: Method name has a typo (browser) but kept for backward compatibility.

Source code in src/winipyside/core/ui/pages/browser.py
def add_browser(self) -> None:
    """Create and add a web browser widget to the page.

    Creates a BrowserWidget instance and adds it to the vertical layout,
    making the embedded browser available for web navigation. The browser
    automatically handles cookies and provides standard navigation controls.

    Note: Method name has a typo (browser) but kept for backward compatibility.
    """
    self.browser = BrowserWidget(self.v_layout)
setup
setup() -> None

Initialize the browser page with a web browser widget.

Creates and configures the BrowserWidget for web browsing and adds it to the page's layout. The browser provides full navigation capabilities.

Source code in src/winipyside/core/ui/pages/browser.py
def setup(self) -> None:
    """Initialize the browser page with a web browser widget.

    Creates and configures the BrowserWidget for web browsing and adds it to
    the page's layout. The browser provides full navigation capabilities.
    """
    self.add_browser()
player

Player page module.

This module contains the player page class for the VideoVault application.

Player
Player(base_window: Base, *args: Any, **kwargs: Any)

Bases: Base

Media player page for video playback with encryption support.

A page dedicated to video playback with full media controls (play/pause, speed control, volume, progress slider, fullscreen). Supports both regular and AES-GCM encrypted video files with seamless playback from encrypted sources without temporary file extraction.

The page manages a MediaPlayer widget and provides convenient methods for starting playback with optional position resumption.

Source code in src/winipyside/core/ui/pages/base/base.py
def __init__(self, base_window: "BaseWindow", *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the page with a reference to the base window.

    Args:
        base_window: The parent BaseWindow containing this page's stack.
        *args: Additional positional arguments passed to parent QWidget.
        **kwargs: Additional keyword arguments passed to parent QWidget.
    """
    self.base_window = base_window
    super().__init__(*args, **kwargs)
play_encrypted_file
play_encrypted_file(
    path: Path, aes_gcm: AESGCM, position: int = 0
) -> None

Play an AES-GCM encrypted video file with transparent decryption.

Switches to the player page and starts playback of the encrypted file. The file is decrypted on-the-fly during playback without extracting temporary files, providing secure playback of protected content.

Parameters:

Name Type Description Default
path Path

The file path to the encrypted video file to play.

required
aes_gcm AESGCM

The AES-GCM cipher instance initialized with the decryption key.

required
position int

The position to start playback from in milliseconds (default 0).

0
Source code in src/winipyside/core/ui/pages/player.py
def play_encrypted_file(
    self,
    path: Path,
    aes_gcm: AESGCM,
    position: int = 0,
) -> None:
    """Play an AES-GCM encrypted video file with transparent decryption.

    Switches to the player page and starts playback of the encrypted file.
    The file is decrypted on-the-fly during playback without extracting
    temporary files, providing secure playback of protected content.

    Args:
        path: The file path to the encrypted video file to play.
        aes_gcm: The AES-GCM cipher instance initialized with the decryption key.
        position: The position to start playback from in milliseconds (default 0).
    """
    self.play_file_from_func(
        self.media_player.play_encrypted_file,
        path=path,
        position=position,
        aes_gcm=aes_gcm,
    )
play_file
play_file(path: Path, position: int = 0) -> None

Play a regular (unencrypted) video file.

Switches to the player page and starts playback of the specified file. Delegates to play_file_from_func with the MediaPlayer's play_file method.

Parameters:

Name Type Description Default
path Path

The file path to the video file to play.

required
position int

The position to start playback from in milliseconds (default 0).

0
Source code in src/winipyside/core/ui/pages/player.py
def play_file(self, path: Path, position: int = 0) -> None:
    """Play a regular (unencrypted) video file.

    Switches to the player page and starts playback of the specified file.
    Delegates to play_file_from_func with the MediaPlayer's play_file method.

    Args:
        path: The file path to the video file to play.
        position: The position to start playback from in milliseconds (default 0).
    """
    self.play_file_from_func(
        self.media_player.play_file,
        path=path,
        position=position,
    )
play_file_from_func
play_file_from_func(
    play_func: Callable[..., Any],
    path: Path,
    position: int = 0,
    **kwargs: Any,
) -> None

Play a file using a provided playback function with page navigation.

A helper method that switches to the player page and invokes the specified play function. This pattern allows reusing the same playback logic for different file types (regular, encrypted, etc.) via different play functions.

Parameters:

Name Type Description Default
play_func Callable[..., Any]

The playback function to call (e.g., play_file or play_encrypted_file).

required
path Path

The file path to play.

required
position int

The position to start playback from in milliseconds (default 0).

0
**kwargs Any

Additional keyword arguments passed to play_func (e.g., aes_gcm for encryption).

{}
Source code in src/winipyside/core/ui/pages/player.py
def play_file_from_func(
    self,
    play_func: Callable[..., Any],
    path: Path,
    position: int = 0,
    **kwargs: Any,  # noqa: ANN401
) -> None:
    """Play a file using a provided playback function with page navigation.

    A helper method that switches to the player page and invokes the specified
    play function. This pattern allows reusing the same playback logic for
    different file types (regular, encrypted, etc.) via different play functions.

    Args:
        play_func: The playback function to call
            (e.g., play_file or play_encrypted_file).
        path: The file path to play.
        position: The position to start playback from in milliseconds (default 0).
        **kwargs: Additional keyword arguments passed to play_func
            (e.g., aes_gcm for encryption).
    """
    # set current page to player
    self.set_current_page(self.__class__)
    # Stop current playback and clean up resources
    play_func(path=path, position=position, **kwargs)
setup
setup() -> None

Initialize the player page with a media player widget.

Creates a MediaPlayer widget and adds it to the page's layout, enabling video playback with full controls.

Source code in src/winipyside/core/ui/pages/player.py
def setup(self) -> None:
    """Initialize the player page with a media player widget.

    Creates a MediaPlayer widget and adds it to the page's layout,
    enabling video playback with full controls.
    """
    self.media_player = MediaPlayer(self.v_layout)
start_playback abstractmethod
start_playback(path: Path, position: int = 0) -> None

Start video playback (to be implemented by subclasses).

Parameters:

Name Type Description Default
path Path

The file path to start playback for.

required
position int

The position to start playback from in milliseconds.

0
Source code in src/winipyside/core/ui/pages/player.py
@abstractmethod
def start_playback(self, path: Path, position: int = 0) -> None:
    """Start video playback (to be implemented by subclasses).

    Args:
        path: The file path to start playback for.
        position: The position to start playback from in milliseconds.
    """

widgets

init module.

browser

Browser widget module.

This module contains the Browser widget class for embedded web browsing with cookie management.

Browser
Browser(parent_layout: QLayout, *args: Any, **kwargs: Any)

Bases: QWebEngineView

Chromium-based web browser widget with navigation controls and cookie tracking.

A self-contained browser widget that extends QWebEngineView with a complete UI including back/forward buttons, address bar, and go button. Automatically tracks and stores cookies for each domain, with conversion between Qt and Python cookie formats.

The browser initializes with Google as the home page and provides methods to retrieve cookies in both QNetworkCookie and http.cookiejar.Cookie formats.

Attributes:

Name Type Description
cookies

Dict mapping domain strings to lists of QNetworkCookie objects.

address_bar

QLineEdit widget showing the current URL.

back_button

QPushButton for browser back navigation.

forward_button

QPushButton for browser forward navigation.

go_button

QPushButton to navigate to the URL in the address bar.

Creates the browser UI (address bar, buttons), connects signals for navigation and cookie tracking, and loads the default homepage. The browser widget is immediately added to the provided layout.

Parameters:

Name Type Description Default
parent_layout QLayout

The parent QLayout to add the complete browser widget to.

required
*args Any

Additional positional arguments passed to parent QWebEngineView.

()
**kwargs Any

Additional keyword arguments passed to parent QWebEngineView.

{}
Source code in src/winipyside/core/ui/widgets/browser.py
def __init__(self, parent_layout: QLayout, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the browser widget and add it to the parent layout.

    Creates the browser UI (address bar, buttons), connects signals for navigation
    and cookie tracking, and loads the default homepage. The browser widget is
    immediately added to the provided layout.

    Args:
        parent_layout: The parent QLayout to add the complete browser widget to.
        *args: Additional positional arguments passed to parent QWebEngineView.
        **kwargs: Additional keyword arguments passed to parent QWebEngineView.
    """
    super().__init__(*args, **kwargs)
    self.parent_layout = parent_layout
    self.make_widget()
    self.connect_signals()
    self.load_first_url()
http_cookies property
http_cookies: dict[str, list[Cookie]]

Get all tracked cookies converted to http.cookiejar.Cookie format.

Provides cookies in Python's standard http.cookiejar.Cookie format, suitable for use with the requests library, urllib, or other Python HTTP clients. This is useful for exporting cookies from the browser for external HTTP operations.

Returns:

Type Description
dict[str, list[Cookie]]

Dictionary mapping domain strings to lists of http.cookiejar.Cookie objects.

connect_load_finished_signal
connect_load_finished_signal() -> None

Connect the page load completion signal to the handler.

Connects QWebEngineView's loadFinished signal to update the address bar when a page finishes loading.

Source code in src/winipyside/core/ui/widgets/browser.py
def connect_load_finished_signal(self) -> None:
    """Connect the page load completion signal to the handler.

    Connects QWebEngineView's loadFinished signal to update the address bar
    when a page finishes loading.
    """
    self.loadFinished.connect(self.on_load_finished)
connect_on_cookie_added_signal
connect_on_cookie_added_signal() -> None

Initialize cookie tracking and connect the cookie added signal.

Creates the cookies dictionary (defaulting empty lists per domain) and connects the QWebEngineCookieStore's cookieAdded signal to the handler. Call this during initialization to enable automatic cookie tracking.

Source code in src/winipyside/core/ui/widgets/browser.py
def connect_on_cookie_added_signal(self) -> None:
    """Initialize cookie tracking and connect the cookie added signal.

    Creates the cookies dictionary (defaulting empty lists per domain) and
    connects the QWebEngineCookieStore's cookieAdded signal to the handler.
    Call this during initialization to enable automatic cookie tracking.
    """
    self.cookies: dict[str, list[QNetworkCookie]] = defaultdict(list)
    self.page().profile().cookieStore().cookieAdded.connect(self.on_cookie_added)
connect_signals
connect_signals() -> None

Connect browser signals to their corresponding handler methods.

Establishes connections for: - Page load completion (updates address bar with new URL) - Cookie addition (tracks new cookies by domain)

Source code in src/winipyside/core/ui/widgets/browser.py
def connect_signals(self) -> None:
    """Connect browser signals to their corresponding handler methods.

    Establishes connections for:
    - Page load completion (updates address bar with new URL)
    - Cookie addition (tracks new cookies by domain)
    """
    self.connect_load_finished_signal()
    self.connect_on_cookie_added_signal()
get_domain_cookies
get_domain_cookies(domain: str) -> list[QNetworkCookie]

Get all tracked cookies for a specific domain in Qt format.

Parameters:

Name Type Description Default
domain str

The domain to retrieve cookies for (e.g., 'github.com').

required

Returns:

Type Description
list[QNetworkCookie]

List of QNetworkCookie objects for the specified domain.

Source code in src/winipyside/core/ui/widgets/browser.py
def get_domain_cookies(self, domain: str) -> list[QNetworkCookie]:
    """Get all tracked cookies for a specific domain in Qt format.

    Args:
        domain: The domain to retrieve cookies for (e.g., 'github.com').

    Returns:
        List of QNetworkCookie objects for the specified domain.
    """
    return self.cookies[domain]
get_domain_http_cookies
get_domain_http_cookies(domain: str) -> list[Cookie]

Get all tracked cookies for a specific domain in http.cookiejar format.

Retrieves domain cookies and converts them to Python's standard http.cookiejar format, useful for exporting to requests, urllib, or other HTTP libraries.

Parameters:

Name Type Description Default
domain str

The domain to retrieve cookies for (e.g., 'github.com').

required

Returns:

Type Description
list[Cookie]

List of http.cookiejar.Cookie objects for the specified domain.

Source code in src/winipyside/core/ui/widgets/browser.py
def get_domain_http_cookies(self, domain: str) -> list[Cookie]:
    """Get all tracked cookies for a specific domain in http.cookiejar format.

    Retrieves domain cookies and converts them to Python's standard http.cookiejar
    format, useful for exporting to requests, urllib, or other HTTP libraries.

    Args:
        domain: The domain to retrieve cookies for (e.g., 'github.com').

    Returns:
        List of http.cookiejar.Cookie objects for the specified domain.
    """
    cookies = self.get_domain_cookies(domain)
    return self.qcookies_to_httpcookies(cookies)
load_first_url
load_first_url() -> None

Load the default homepage when the browser initializes.

Loads Google's homepage (https://www.google.com/) as the initial page, providing a familiar starting point for users.

Source code in src/winipyside/core/ui/widgets/browser.py
def load_first_url(self) -> None:
    """Load the default homepage when the browser initializes.

    Loads Google's homepage (https://www.google.com/) as the initial page,
    providing a familiar starting point for users.
    """
    self.load(QUrl("https://www.google.com/"))
make_address_bar
make_address_bar() -> None

Create the navigation bar with back, forward, address input, and go button.

Constructs a horizontal layout containing: - Back button (previous page) - Forward button (next page) - Address input field (URL entry) - Go button (navigate to entered URL)

The address bar updates automatically when pages load and handles Enter key presses for quick navigation.

Source code in src/winipyside/core/ui/widgets/browser.py
def make_address_bar(self) -> None:
    """Create the navigation bar with back, forward, address input, and go button.

    Constructs a horizontal layout containing:
    - Back button (previous page)
    - Forward button (next page)
    - Address input field (URL entry)
    - Go button (navigate to entered URL)

    The address bar updates automatically when pages load and handles Enter key
    presses for quick navigation.
    """
    self.address_bar_layout = QHBoxLayout()

    # Add back button
    self.back_button = QPushButton()
    self.back_button.setIcon(QIcon.fromTheme("go-previous"))
    self.back_button.setToolTip("Go back")
    self.back_button.clicked.connect(self.back)
    self.address_bar_layout.addWidget(self.back_button)

    # Add forward button
    self.forward_button = QPushButton()
    self.forward_button.setIcon(QIcon.fromTheme("go-next"))
    self.forward_button.setToolTip("Go forward")
    self.forward_button.clicked.connect(self.forward)
    self.address_bar_layout.addWidget(self.forward_button)

    # Add address bar
    self.address_bar = QLineEdit()
    self.address_bar.setPlaceholderText("Enter URL...")
    self.address_bar.returnPressed.connect(self.navigate_to_url)
    self.address_bar_layout.addWidget(self.address_bar)

    # Add go button
    self.go_button = QPushButton("Go")
    self.go_button.clicked.connect(self.navigate_to_url)
    self.address_bar_layout.addWidget(self.go_button)

    self.browser_layout.addLayout(self.address_bar_layout)
make_widget
make_widget() -> None

Create the complete browser widget and add it to the parent layout.

Constructs the visual hierarchy: - QWidget container (browser_widget) - QVBoxLayout - Address bar (horizontal layout with buttons and input) - QWebEngineView (actual browser)

Sets appropriate size policies and adds the complete widget to the parent layout.

Source code in src/winipyside/core/ui/widgets/browser.py
def make_widget(self) -> None:
    """Create the complete browser widget and add it to the parent layout.

    Constructs the visual hierarchy:
    - QWidget container (browser_widget)
      - QVBoxLayout
        - Address bar (horizontal layout with buttons and input)
        - QWebEngineView (actual browser)

    Sets appropriate size policies
    and adds the complete widget to the parent layout.
    """
    self.browser_widget = QWidget()
    self.browser_layout = QVBoxLayout(self.browser_widget)
    self.set_size_policy()
    self.make_address_bar()
    self.browser_layout.addWidget(self)
    self.parent_layout.addWidget(self.browser_widget)
navigate_to_url
navigate_to_url() -> None

Load the URL currently entered in the address bar.

Retrieves the text from the address bar and loads it as the browser's current URL. Called when the user presses Enter in the address bar or clicks the Go button.

Source code in src/winipyside/core/ui/widgets/browser.py
def navigate_to_url(self) -> None:
    """Load the URL currently entered in the address bar.

    Retrieves the text from the address bar and loads it as the browser's
    current URL. Called when the user presses Enter in the address bar or
    clicks the Go button.
    """
    url = self.address_bar.text()
    self.load(QUrl(url))
on_cookie_added
on_cookie_added(cookie: Any) -> None

Handle new cookie added to the store and track it by domain.

Called automatically when a cookie is set during web browsing. Stores the cookie in the cookies dictionary using the cookie's domain as the key.

Parameters:

Name Type Description Default
cookie Any

The QNetworkCookie that was added to the cookie store.

required
Source code in src/winipyside/core/ui/widgets/browser.py
def on_cookie_added(self, cookie: Any) -> None:  # noqa: ANN401
    """Handle new cookie added to the store and track it by domain.

    Called automatically when a cookie is set during web browsing. Stores the
    cookie in the cookies dictionary using the cookie's domain as the key.

    Args:
        cookie: The QNetworkCookie that was added to the cookie store.
    """
    self.cookies[cookie.domain()].append(cookie)
on_load_finished
on_load_finished(_ok: bool) -> None

Handle page load completion and update the address bar.

Called when a page finishes loading (successfully or not). Updates the address bar to reflect the current URL of the loaded page.

Parameters:

Name Type Description Default
_ok bool

Boolean indicating successful page load (unused, kept for signal compatibility).

required
Source code in src/winipyside/core/ui/widgets/browser.py
def on_load_finished(self, _ok: bool) -> None:  # noqa: FBT001
    """Handle page load completion and update the address bar.

    Called when a page finishes loading (successfully or not). Updates the
    address bar to reflect the current URL of the loaded page.

    Args:
        _ok: Boolean indicating successful page
            load (unused, kept for signal compatibility).
    """
    self.update_address_bar(self.url())
qcookie_to_httpcookie
qcookie_to_httpcookie(qcookie: QNetworkCookie) -> Cookie

Convert a single Qt network cookie to a Python http.cookiejar cookie.

Translates between Qt's QNetworkCookie format and Python's http.cookiejar.Cookie format, preserving all attributes including name, value, domain, path, security flags, expiration, and HTTP-only status.

Parameters:

Name Type Description Default
qcookie QNetworkCookie

The QNetworkCookie to convert.

required

Returns:

Type Description
Cookie

The equivalent http.cookiejar.Cookie object.

Source code in src/winipyside/core/ui/widgets/browser.py
def qcookie_to_httpcookie(self, qcookie: QNetworkCookie) -> Cookie:
    """Convert a single Qt network cookie to a Python http.cookiejar cookie.

    Translates between Qt's QNetworkCookie format and Python's http.cookiejar.Cookie
    format, preserving all attributes including name, value, domain, path, security
    flags, expiration, and HTTP-only status.

    Args:
        qcookie: The QNetworkCookie to convert.

    Returns:
        The equivalent http.cookiejar.Cookie object.
    """
    name = bytes(qcookie.name().data()).decode()
    value = bytes(qcookie.value().data()).decode()
    domain = qcookie.domain()
    path = qcookie.path() or "/"
    secure = qcookie.isSecure()
    expires = None
    if qcookie.expirationDate().isValid():
        expires = int(qcookie.expirationDate().toSecsSinceEpoch())
    rest = {"HttpOnly": str(qcookie.isHttpOnly())}

    return Cookie(
        version=0,
        name=name,
        value=value,
        port=None,
        port_specified=False,
        domain=domain,
        domain_specified=bool(domain),
        domain_initial_dot=domain.startswith("."),
        path=path,
        path_specified=bool(path),
        secure=secure,
        expires=expires or None,
        discard=False,
        comment=None,
        comment_url=None,
        rest=rest,
        rfc2109=False,
    )
qcookies_to_httpcookies
qcookies_to_httpcookies(
    qcookies: list[QNetworkCookie],
) -> list[Cookie]

Convert a list of Qt network cookies to Python http.cookiejar cookies.

Parameters:

Name Type Description Default
qcookies list[QNetworkCookie]

List of QNetworkCookie objects to convert.

required

Returns:

Type Description
list[Cookie]

List of equivalent http.cookiejar.Cookie objects preserving all attributes.

Source code in src/winipyside/core/ui/widgets/browser.py
def qcookies_to_httpcookies(self, qcookies: list[QNetworkCookie]) -> list[Cookie]:
    """Convert a list of Qt network cookies to Python http.cookiejar cookies.

    Args:
        qcookies: List of QNetworkCookie objects to convert.

    Returns:
        List of equivalent http.cookiejar.Cookie objects preserving all attributes.
    """
    return [self.qcookie_to_httpcookie(q_cookie) for q_cookie in qcookies]
set_size_policy
set_size_policy() -> None

Set the browser to expand and fill available space.

Configures the size policy to expand in both horizontal and vertical directions, allowing the browser to grow with the parent widget.

Source code in src/winipyside/core/ui/widgets/browser.py
def set_size_policy(self) -> None:
    """Set the browser to expand and fill available space.

    Configures the size policy to expand in both horizontal and vertical directions,
    allowing the browser to grow with the parent widget.
    """
    self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
update_address_bar
update_address_bar(url: QUrl) -> None

Update the address bar to display the given URL.

Parameters:

Name Type Description Default
url QUrl

The QUrl to display in the address bar text field.

required
Source code in src/winipyside/core/ui/widgets/browser.py
def update_address_bar(self, url: QUrl) -> None:
    """Update the address bar to display the given URL.

    Args:
        url: The QUrl to display in the address bar text field.
    """
    self.address_bar.setText(url.toString())
clickable_widget

Clickable widget module.

This module provides custom Qt widgets that emit clicked signals for interactive UI elements.

ClickableVideoWidget

Bases: QVideoWidget

Video display widget that emits a clicked signal on left mouse button press.

Extends QVideoWidget to make video playback areas interactive by emitting a custom clicked signal when clicked. Commonly used for play/pause toggling or fullscreen mode switching in media player UIs.

Signals

clicked: Emitted when the left mouse button is pressed on the video widget.

mousePressEvent
mousePressEvent(event: Any) -> None

Handle left mouse button press on video and emit clicked signal.

Emits the clicked signal when the left mouse button is pressed on the video widget, then passes the event to the parent class for standard processing.

Parameters:

Name Type Description Default
event Any

The QMouseEvent containing button type and position information.

required
Source code in src/winipyside/core/ui/widgets/clickable_widget.py
def mousePressEvent(self, event: Any) -> None:  # noqa: ANN401, N802
    """Handle left mouse button press on video and emit clicked signal.

    Emits the clicked signal
    when the left mouse button is pressed on the video widget,
    then passes the event to the parent class for standard processing.

    Args:
        event: The QMouseEvent containing button type and position information.
    """
    if event.button() == Qt.MouseButton.LeftButton:
        self.clicked.emit()
    super().mousePressEvent(event)
ClickableWidget

Bases: QWidget

Regular QWidget that emits a clicked signal on left mouse button press.

A simple extension of QWidget that makes it interactive by emitting a custom clicked signal when the user clicks on it. Useful for creating custom button-like areas or interactive widget regions that don't inherit from QPushButton.

Signals

clicked: Emitted when the left mouse button is pressed on the widget.

mousePressEvent
mousePressEvent(event: Any) -> None

Handle left mouse button press and emit clicked signal.

Emits the clicked signal when the left mouse button is pressed on the widget, then passes the event to the parent class for standard processing.

Parameters:

Name Type Description Default
event Any

The QMouseEvent containing button type and position information.

required
Source code in src/winipyside/core/ui/widgets/clickable_widget.py
def mousePressEvent(self, event: Any) -> None:  # noqa: ANN401, N802
    """Handle left mouse button press and emit clicked signal.

    Emits the clicked signal when the left mouse button is pressed on the widget,
    then passes the event to the parent class for standard processing.

    Args:
        event: The QMouseEvent containing button type and position information.
    """
    if event.button() == Qt.MouseButton.LeftButton:
        self.clicked.emit()
    super().mousePressEvent(event)
media_player

Media player widget module.

This module contains the MediaPlayer widget class with full playback controls.

MediaPlayer
MediaPlayer(
    parent_layout: QLayout, *args: Any, **kwargs: Any
)

Bases: QMediaPlayer

Full-featured video player widget.

A complete media player implementation with UI controls for play/pause, speed selection, volume control, progress seeking, and fullscreen mode. Supports both regular and AES-GCM encrypted video files with transparent decryption during playback.

The player automatically manages IO device lifecycle and provides throttled slider updates to prevent excessive position changes during scrubbing.

Attributes:

Name Type Description
video_widget

ClickableVideoWidget displaying the video.

audio_output

QAudioOutput for volume control.

progress_slider

QSlider for playback position control.

volume_slider

QSlider for volume adjustment (0-100).

playback_button

Play/pause toggle button.

speed_button

Playback speed selector button.

fullscreen_button

Fullscreen mode toggle button.

Creates the complete player widget with video display and control bars (above and below the video) and adds it to the parent layout.

Parameters:

Name Type Description Default
parent_layout QLayout

The parent layout to add the complete player widget to.

required
*args Any

Additional positional arguments passed to parent QMediaPlayer.

()
**kwargs Any

Additional keyword arguments passed to parent QMediaPlayer.

{}
Source code in src/winipyside/core/ui/widgets/media_player.py
def __init__(self, parent_layout: QLayout, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the media player and create its UI.

    Creates the complete player widget with video display and control bars
    (above and below the video) and adds it to the parent layout.

    Args:
        parent_layout: The parent layout to add the complete player widget to.
        *args: Additional positional arguments passed to parent QMediaPlayer.
        **kwargs: Additional keyword arguments passed to parent QMediaPlayer.
    """
    super().__init__(*args, **kwargs)
    self.parent_layout = parent_layout
    self.io_device: PyQIODevice | None = None
    self.make_widget()
add_fullscreen_control
add_fullscreen_control() -> None

Create a fullscreen toggle button and discover sibling widgets to hide.

Creates a button with fullscreen/exit-fullscreen icons and discovers which other widgets in the window should be hidden when entering fullscreen mode. Placed in the right control section.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_fullscreen_control(self) -> None:
    """Create a fullscreen toggle button and discover sibling widgets to hide.

    Creates a button with fullscreen/exit-fullscreen icons and discovers which
    other widgets in the window should be hidden when entering fullscreen mode.
    Placed in the right control section.
    """
    self.fullscreen_icon = BaseUI.get_svg_icon("fullscreen_icon")
    self.exit_fullscreen_icon = BaseUI.get_svg_icon("exit_fullscreen_icon")
    self.fullscreen_button = QPushButton()
    self.fullscreen_button.setIcon(self.fullscreen_icon)

    self.parent_widget = self.parent_layout.parentWidget()
    if self.parent_widget is None:
        msg = "no parent widget found"
        raise RuntimeError(msg)
    self.other_visible_widgets = [
        w
        for w in set(self.parent_widget.findChildren(QWidget))
        - {
            self.media_player_widget,
            *self.media_player_widget.findChildren(QWidget),
        }
        if w.isVisible() or not (w.isHidden() or w.isVisible())
    ]
    self.fullscreen_button.clicked.connect(self.toggle_fullscreen)

    self.right_controls_layout.addWidget(self.fullscreen_button)
add_media_controls_above
add_media_controls_above() -> None

Create the top control bar with organized button sections.

Creates a horizontal layout divided into left, center, and right sections, then populates each with appropriate controls: - Left: Speed control - Center: Play/pause button - Right: Volume control and fullscreen button

This layout pattern allows flexible positioning of controls.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_media_controls_above(self) -> None:
    """Create the top control bar with organized button sections.

    Creates a horizontal layout divided into left, center, and right sections,
    then populates each with appropriate controls:
    - Left: Speed control
    - Center: Play/pause button
    - Right: Volume control and fullscreen button

    This layout pattern allows flexible positioning of controls.
    """
    # main above widget
    self.media_controls_widget_above = QWidget()
    self.media_controls_layout_above = QHBoxLayout(self.media_controls_widget_above)
    self.media_player_layout.addWidget(self.media_controls_widget_above)
    # left controls
    self.left_controls_widget = QWidget()
    self.left_controls_layout = QHBoxLayout(self.left_controls_widget)
    self.media_controls_layout_above.addWidget(
        self.left_controls_widget,
        alignment=Qt.AlignmentFlag.AlignLeft,
    )
    # center controls
    self.center_controls_widget = QWidget()
    self.center_controls_layout = QHBoxLayout(self.center_controls_widget)
    self.media_controls_layout_above.addWidget(
        self.center_controls_widget,
        alignment=Qt.AlignmentFlag.AlignCenter,
    )
    self.right_controls_widget = QWidget()
    self.right_controls_layout = QHBoxLayout(self.right_controls_widget)
    self.media_controls_layout_above.addWidget(
        self.right_controls_widget,
        alignment=Qt.AlignmentFlag.AlignRight,
    )

    self.add_speed_control()
    self.add_volume_control()
    self.add_playback_control()
    self.add_fullscreen_control()
add_media_controls_below
add_media_controls_below() -> None

Create the bottom control bar with the progress slider.

Creates a horizontal layout for the bottom controls and adds the seekable progress slider for playback position control.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_media_controls_below(self) -> None:
    """Create the bottom control bar with the progress slider.

    Creates a horizontal layout for the bottom controls and adds the
    seekable progress slider for playback position control.
    """
    self.media_controls_widget_below = QWidget()
    self.media_controls_layout_below = QHBoxLayout(self.media_controls_widget_below)
    self.media_player_layout.addWidget(self.media_controls_widget_below)
    self.add_progress_control()
add_playback_control
add_playback_control() -> None

Create a play/pause toggle button in the center control area.

Creates a button with play/pause icons that toggles between playing and paused states. The button is placed in the center control section.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_playback_control(self) -> None:
    """Create a play/pause toggle button in the center control area.

    Creates a button with play/pause icons that toggles between playing and
    paused states. The button is placed in the center control section.
    """
    self.play_icon = BaseUI.get_svg_icon("play_icon")
    self.pause_icon = BaseUI.get_svg_icon("pause_icon")
    # Pause symbol: ⏸ (U+23F8)
    self.playback_button = QPushButton()
    self.playback_button.setIcon(self.pause_icon)
    self.playback_button.clicked.connect(self.toggle_playback)

    self.center_controls_layout.addWidget(self.playback_button)
add_progress_control
add_progress_control() -> None

Create the seekable progress slider and connect position signals.

Creates a horizontal slider for playback position and establishes connections between the media player's position/duration signals and the slider, with throttled updates to prevent excessive updates during scrubbing.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_progress_control(self) -> None:
    """Create the seekable progress slider and connect position signals.

    Creates a horizontal slider for playback position and establishes connections
    between the media player's position/duration signals and the slider, with
    throttled updates to prevent excessive updates during scrubbing.
    """
    self.progress_slider = QSlider(Qt.Orientation.Horizontal)
    self.media_controls_layout_below.addWidget(self.progress_slider)

    # Connect media player signals to update the progress slider
    self.positionChanged.connect(self.update_slider_position)
    self.durationChanged.connect(self.set_slider_range)

    # Connect slider signals to update video position
    self.last_slider_moved_update = time.time()
    self.slider_moved_update_interval = 0.1
    self.progress_slider.sliderMoved.connect(self.on_slider_moved)
    self.progress_slider.sliderReleased.connect(self.on_slider_released)
add_speed_control
add_speed_control() -> None

Create a speed selector button with dropdown menu.

Creates a button showing the current playback speed (default 1.0x) with a dropdown menu listing predefined speed options (0.2x to 5x). Placed in the left control section.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_speed_control(self) -> None:
    """Create a speed selector button with dropdown menu.

    Creates a button showing the current playback speed (default 1.0x) with a
    dropdown menu listing predefined speed options (0.2x to 5x). Placed in the
    left control section.
    """
    self.default_speed = 1
    self.speed_options = [0.2, 0.5, self.default_speed, 1.5, 2, 3, 4, 5]
    self.speed_button = QPushButton(f"{self.default_speed}x")
    self.speed_menu = QMenu(self.speed_button)
    for speed in self.speed_options:
        action = self.speed_menu.addAction(f"{speed}x")
        action.triggered.connect(partial(self.change_speed, speed))

    self.speed_button.setMenu(self.speed_menu)
    self.left_controls_layout.addWidget(self.speed_button)
add_volume_control
add_volume_control() -> None

Create a horizontal volume slider with 0-100 range.

Creates a slider for user volume adjustment and connects it to the volume change handler. Placed in the left control section.

Source code in src/winipyside/core/ui/widgets/media_player.py
def add_volume_control(self) -> None:
    """Create a horizontal volume slider with 0-100 range.

    Creates a slider for user volume adjustment and connects it to the
    volume change handler. Placed in the left control section.
    """
    self.volume_slider = QSlider(Qt.Orientation.Horizontal)
    self.volume_slider.setRange(0, 100)
    self.volume_slider.valueChanged.connect(self.on_volume_changed)
    self.left_controls_layout.addWidget(self.volume_slider)
change_speed
change_speed(speed: float) -> None

Set the playback speed multiplier and update the speed button label.

Parameters:

Name Type Description Default
speed float

The new playback speed multiplier (e.g., 1.0 for normal, 2.0 for 2x).

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def change_speed(self, speed: float) -> None:
    """Set the playback speed multiplier and update the speed button label.

    Args:
        speed: The new playback speed multiplier (e.g., 1.0 for normal, 2.0 for 2x).
    """
    self.setPlaybackRate(speed)
    self.speed_button.setText(f"{speed}x")
hide_media_controls
hide_media_controls() -> None

Make both top and bottom control bars invisible.

Source code in src/winipyside/core/ui/widgets/media_player.py
def hide_media_controls(self) -> None:
    """Make both top and bottom control bars invisible."""
    self.media_controls_widget_above.hide()
    self.media_controls_widget_below.hide()
make_video_widget
make_video_widget() -> None

Create the video display widget with audio output configuration.

Creates a ClickableVideoWidget, connects its click signal for fullscreen toggling, sets it to expand and fill available space, and configures audio output.

Source code in src/winipyside/core/ui/widgets/media_player.py
def make_video_widget(self) -> None:
    """Create the video display widget with audio output configuration.

    Creates a ClickableVideoWidget,
        connects its click signal for fullscreen toggling,
    sets it to expand and fill available space, and configures audio output.
    """
    self.video_widget = ClickableVideoWidget()
    self.video_widget.clicked.connect(self.on_video_clicked)
    self.video_widget.setSizePolicy(
        QSizePolicy.Policy.Expanding,
        QSizePolicy.Policy.Expanding,
    )
    self.setVideoOutput(self.video_widget)

    self.audio_output = QAudioOutput()
    self.setAudioOutput(self.audio_output)

    self.media_player_layout.addWidget(self.video_widget)
make_widget
make_widget() -> None

Create the complete media player widget structure.

Builds the visual hierarchy: - QWidget container (media_player_widget) - QVBoxLayout - Control bar (above) with play, speed, volume, fullscreen buttons - ClickableVideoWidget (video display) - Control bar (below) with progress slider

The structure allows for hiding/showing control bars independently.

Source code in src/winipyside/core/ui/widgets/media_player.py
def make_widget(self) -> None:
    """Create the complete media player widget structure.

    Builds the visual hierarchy:
    - QWidget container (media_player_widget)
      - QVBoxLayout
        - Control bar (above) with play, speed, volume, fullscreen buttons
        - ClickableVideoWidget (video display)
        - Control bar (below) with progress slider

    The structure allows for hiding/showing control bars independently.
    """
    self.media_player_widget = QWidget()
    self.media_player_layout = QVBoxLayout(self.media_player_widget)
    self.parent_layout.addWidget(self.media_player_widget)
    self.add_media_controls_above()
    self.make_video_widget()
    self.add_media_controls_below()
on_slider_moved
on_slider_moved(position: int) -> None

Handle slider movement with throttled position updates.

Implements throttling (minimum 100ms between updates) to prevent excessive seeking during fast slider drags, improving performance and reducing audio stuttering.

Parameters:

Name Type Description Default
position int

The new position from the slider in milliseconds.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def on_slider_moved(self, position: int) -> None:
    """Handle slider movement with throttled position updates.

    Implements throttling (minimum 100ms between updates) to prevent excessive
    seeking during fast slider drags, improving performance and reducing
    audio stuttering.

    Args:
        position: The new position from the slider in milliseconds.
    """
    current_time = time.time()
    if (
        current_time - self.last_slider_moved_update
        > self.slider_moved_update_interval
    ):
        self.setPosition(position)
        self.last_slider_moved_update = current_time
on_slider_released
on_slider_released() -> None

Seek to the slider position when the user releases it.

Ensures the final position is set even if the last move event was throttled.

Source code in src/winipyside/core/ui/widgets/media_player.py
def on_slider_released(self) -> None:
    """Seek to the slider position when the user releases it.

    Ensures the final position is set even if the last move event was throttled.
    """
    self.setPosition(self.progress_slider.value())
on_video_clicked
on_video_clicked() -> None

Toggle visibility of all media control bars when video is clicked.

Provides a common media player pattern where clicking the video hides controls for a cleaner viewing experience, and clicking again shows them.

Source code in src/winipyside/core/ui/widgets/media_player.py
def on_video_clicked(self) -> None:
    """Toggle visibility of all media control bars when video is clicked.

    Provides a common media player pattern where clicking the video hides
    controls for a cleaner viewing experience, and clicking again shows them.
    """
    if self.media_controls_widget_above.isVisible():
        self.hide_media_controls()
        return
    self.show_media_controls()
on_volume_changed
on_volume_changed(value: int) -> None

Update audio output volume based on slider value.

Converts the slider value (0-100) to audio volume range (0.0-1.0) and applies it to the audio output.

Parameters:

Name Type Description Default
value int

The slider value from 0-100.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def on_volume_changed(self, value: int) -> None:
    """Update audio output volume based on slider value.

    Converts the slider value (0-100) to audio volume range (0.0-1.0) and
    applies it to the audio output.

    Args:
        value: The slider value from 0-100.
    """
    volume = value / 100.0  # Convert to 0.0-1.0 range
    self.audio_output.setVolume(volume)
play_encrypted_file
play_encrypted_file(
    path: Path, aes_gcm: AESGCM, position: int = 0
) -> None

Play an AES-GCM encrypted video file with transparent decryption.

Opens an encrypted video file and decrypts it on-the-fly during playback. No temporary files are created; decryption happens in memory as needed. Supports seeking without decrypting the entire file first.

Parameters:

Name Type Description Default
path Path

The file path to the encrypted video file to play.

required
aes_gcm AESGCM

The AES-GCM cipher instance initialized with the correct key.

required
position int

The position to start playback from in milliseconds (default 0).

0
Source code in src/winipyside/core/ui/widgets/media_player.py
def play_encrypted_file(
    self,
    path: Path,
    aes_gcm: AESGCM,
    position: int = 0,
) -> None:
    """Play an AES-GCM encrypted video file with transparent decryption.

    Opens an encrypted video file and decrypts it on-the-fly during playback.
    No temporary files are created; decryption happens in memory as needed.
    Supports seeking without decrypting the entire file first.

    Args:
        path: The file path to the encrypted video file to play.
        aes_gcm: The AES-GCM cipher instance initialized with the correct key.
        position: The position to start playback from in milliseconds (default 0).
    """
    self.play_video(
        position=position,
        io_device=EncryptedPyQFile(path, aes_gcm),
        source_url=QUrl.fromLocalFile(path),
    )
play_file
play_file(path: Path, position: int = 0) -> None

Play a regular (unencrypted) video file.

Opens the file at the given path and starts playback. The file must be in a format supported by the system's media engine (MP4, WebM, MKV, etc.).

Parameters:

Name Type Description Default
path Path

The file path to the video file to play.

required
position int

The position to start playback from in milliseconds (default 0).

0
Source code in src/winipyside/core/ui/widgets/media_player.py
def play_file(self, path: Path, position: int = 0) -> None:
    """Play a regular (unencrypted) video file.

    Opens the file at the given path and starts playback. The file must be
    in a format supported by the system's media engine (MP4, WebM, MKV, etc.).

    Args:
        path: The file path to the video file to play.
        position: The position to start playback from in milliseconds (default 0).
    """
    self.play_video(
        position=position,
        io_device=PyQFile(path),
        source_url=QUrl.fromLocalFile(path),
    )
play_video
play_video(
    io_device: PyQIODevice,
    source_url: QUrl,
    position: int = 0,
) -> None

Start playback of a video from the specified IO device.

Stops any current playback, sets up the new source, and starts playing. Uses a timer to delay playback start, preventing freezing when switching between videos. Automatically resumes to the specified position once media is buffered.

Parameters:

Name Type Description Default
io_device PyQIODevice

The PyQIODevice to use as the media source.

required
source_url QUrl

The QUrl representing the source location for error reporting.

required
position int

The position to resume playback from in milliseconds (default 0).

0
Source code in src/winipyside/core/ui/widgets/media_player.py
def play_video(
    self,
    io_device: PyQIODevice,
    source_url: QUrl,
    position: int = 0,
) -> None:
    """Start playback of a video from the specified IO device.

    Stops any current playback, sets up the new source, and starts playing.
    Uses a timer to delay playback start, preventing freezing when switching
    between videos. Automatically resumes to the specified position once media
    is buffered.

    Args:
        io_device: The PyQIODevice to use as the media source.
        source_url: The QUrl representing the source location for error reporting.
        position: The position to resume playback from in milliseconds (default 0).
    """
    self.stop_and_close_io_device()

    self.resume_func = partial(self.resume_to_position, position=position)
    self.mediaStatusChanged.connect(self.resume_func)

    # SingleShot prevents freezing when starting new video while another is playing
    QTimer.singleShot(
        100,
        partial(
            self.set_source_and_play,
            io_device=io_device,
            source_url=source_url,
        ),
    )
resume_to_position
resume_to_position(
    status: MediaStatus, position: int
) -> None

Seek to the target position once media is buffered and ready.

Called when media status changes. Once the media reaches BufferedMedia status (fully buffered and ready to play), seeks to the specified position and disconnects this handler to avoid repeated seeking.

Parameters:

Name Type Description Default
status MediaStatus

The current media status.

required
position int

The target position to seek to in milliseconds.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def resume_to_position(
    self,
    status: QMediaPlayer.MediaStatus,
    position: int,
) -> None:
    """Seek to the target position once media is buffered and ready.

    Called when media status changes. Once the media reaches BufferedMedia status
    (fully buffered and ready to play), seeks to the specified position and
    disconnects this handler to avoid repeated seeking.

    Args:
        status: The current media status.
        position: The target position to seek to in milliseconds.
    """
    if status == QMediaPlayer.MediaStatus.BufferedMedia:
        self.setPosition(position)
        self.mediaStatusChanged.disconnect(self.resume_func)
set_slider_range
set_slider_range(duration: int) -> None

Set the progress slider range to match media duration.

Parameters:

Name Type Description Default
duration int

The total media duration in milliseconds.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def set_slider_range(self, duration: int) -> None:
    """Set the progress slider range to match media duration.

    Args:
        duration: The total media duration in milliseconds.
    """
    self.progress_slider.setRange(0, duration)
set_source_and_play
set_source_and_play(
    io_device: PyQIODevice, source_url: QUrl
) -> None

Set the media source and start playback.

Called via timer to delay playback start and prevent freezing. Configures the IO device as the source and begins playback.

Parameters:

Name Type Description Default
io_device PyQIODevice

The PyQIODevice to use as the media source.

required
source_url QUrl

The QUrl representing the source location.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def set_source_and_play(
    self,
    io_device: PyQIODevice,
    source_url: QUrl,
) -> None:
    """Set the media source and start playback.

    Called via timer to delay playback start and prevent freezing.
    Configures the IO device as the source and begins playback.

    Args:
        io_device: The PyQIODevice to use as the media source.
        source_url: The QUrl representing the source location.
    """
    self.set_source_device(io_device, source_url)
    self.play()
set_source_device
set_source_device(
    io_device: PyQIODevice, source_url: QUrl
) -> None

Configure the media source from an IO device.

Parameters:

Name Type Description Default
io_device PyQIODevice

The PyQIODevice to use as the media source.

required
source_url QUrl

The QUrl representing the source location for error reporting.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def set_source_device(self, io_device: PyQIODevice, source_url: QUrl) -> None:
    """Configure the media source from an IO device.

    Args:
        io_device: The PyQIODevice to use as the media source.
        source_url: The QUrl representing the source location for error reporting.
    """
    self.source_url = source_url
    self.io_device = io_device
    self.setSourceDevice(self.io_device, self.source_url)
show_media_controls
show_media_controls() -> None

Make both top and bottom control bars visible.

Source code in src/winipyside/core/ui/widgets/media_player.py
def show_media_controls(self) -> None:
    """Make both top and bottom control bars visible."""
    self.media_controls_widget_above.show()
    self.media_controls_widget_below.show()
stop_and_close_io_device
stop_and_close_io_device() -> None

Stop playback and close the current IO device.

Safely closes any previously opened IO device to release resources and prevent memory leaks.

Source code in src/winipyside/core/ui/widgets/media_player.py
def stop_and_close_io_device(self) -> None:
    """Stop playback and close the current IO device.

    Safely closes any previously opened IO device to release resources
    and prevent memory leaks.
    """
    self.stop()
    if self.io_device is not None:
        self.io_device.close()
toggle_fullscreen
toggle_fullscreen() -> None

Toggle between fullscreen and windowed mode.

Switches the window to fullscreen (hiding sibling widgets and controls) or back to windowed mode (showing everything). Updates the button icon accordingly.

Source code in src/winipyside/core/ui/widgets/media_player.py
def toggle_fullscreen(self) -> None:
    """Toggle between fullscreen and windowed mode.

    Switches the window to fullscreen (hiding sibling widgets and controls) or back
    to windowed mode (showing everything). Updates the button icon accordingly.
    """
    # Get the main window
    main_window = self.media_player_widget.window()
    if main_window.isFullScreen():
        for widget in self.other_visible_widgets:
            widget.show()
        # show the window in the previous size
        main_window.showMaximized()
        self.fullscreen_button.setIcon(self.fullscreen_icon)
    else:
        for widget in self.other_visible_widgets:
            widget.hide()
        main_window.showFullScreen()
        self.fullscreen_button.setIcon(self.exit_fullscreen_icon)
toggle_playback
toggle_playback() -> None

Toggle between play and pause states and update the button icon.

If currently playing, pauses and shows the play icon. If paused or stopped, starts playback and shows the pause icon.

Source code in src/winipyside/core/ui/widgets/media_player.py
def toggle_playback(self) -> None:
    """Toggle between play and pause states and update the button icon.

    If currently playing, pauses and shows the play icon. If paused or stopped,
    starts playback and shows the pause icon.
    """
    if self.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
        self.pause()
        self.playback_button.setIcon(self.play_icon)
    else:
        self.play()
        self.playback_button.setIcon(self.pause_icon)
update_slider_position
update_slider_position(position: int) -> None

Update the progress slider to reflect current playback position.

Only updates the slider if the user is not currently dragging it, preventing jumpy behavior during manual seeking.

Parameters:

Name Type Description Default
position int

The current media position in milliseconds.

required
Source code in src/winipyside/core/ui/widgets/media_player.py
def update_slider_position(self, position: int) -> None:
    """Update the progress slider to reflect current playback position.

    Only updates the slider if the user is not currently dragging it,
    preventing jumpy behavior during manual seeking.

    Args:
        position: The current media position in milliseconds.
    """
    # Only update if not being dragged to prevent jumps during manual sliding
    if not self.progress_slider.isSliderDown():
        self.progress_slider.setValue(position)
notification

Notification widget module.

This module provides a notification toast widget for displaying temporary messages.

Notification
Notification(
    title: str,
    text: str,
    icon: ToastIcon = INFORMATION,
    duration: int = 10000,
)

Bases: Toast

Toast notification widget with automatic text truncation.

A configurable toast notification that appears in the top-middle of the screen and automatically disappears after a set duration. Truncates long title and text to fit within half the window width, ensuring notifications don't expand the window or look excessively large.

Signals inherit from the underlying Toast class and fire when the notification is shown/hidden.

Attributes:

Name Type Description
duration

How long the notification stays visible in milliseconds (default 10000).

icon

The icon to display with the notification.

Creates a toast notification with the given title, text, and icon. The notification automatically appears in the top-middle of the active window and disappears after the specified duration.

Parameters:

Name Type Description Default
title str

The notification title (will be truncated to window width).

required
text str

The notification body text (will be truncated to window width).

required
icon ToastIcon

The ToastIcon to display. Defaults to INFORMATION.

INFORMATION
duration int

How long the notification stays visible in milliseconds. Defaults to 10000 (10 seconds).

10000
Source code in src/winipyside/core/ui/widgets/notification.py
def __init__(
    self,
    title: str,
    text: str,
    icon: ToastIcon = ToastIcon.INFORMATION,
    duration: int = 10000,
) -> None:
    """Initialize and display the notification.

    Creates a toast notification with the given title, text, and icon.
    The notification automatically appears in the top-middle of the active window
    and disappears after the specified duration.

    Args:
        title: The notification title (will be truncated to window width).
        text: The notification body text (will be truncated to window width).
        icon: The ToastIcon to display. Defaults to INFORMATION.
        duration: How long the notification stays visible in milliseconds.
            Defaults to 10000 (10 seconds).
    """
    super().__init__(QApplication.activeWindow())
    self.setDuration(duration)
    self.setIcon(icon)
    self.set_title(title)
    self.set_text(text)
set_text
set_text(text: str) -> None

Set the notification body text and truncate if necessary.

Truncates the text to fit within half the active window width before displaying. This prevents excessively long messages from making the notification too wide.

Parameters:

Name Type Description Default
text str

The notification text to set (may be longer than the window).

required
Source code in src/winipyside/core/ui/widgets/notification.py
def set_text(self, text: str) -> None:
    """Set the notification body text and truncate if necessary.

    Truncates the text to fit within half the active window width before displaying.
    This prevents excessively long messages from making the notification too wide.

    Args:
        text: The notification text to set (may be longer than the window).
    """
    text = self.str_to_half_window_width(text)
    self.setText(text)
set_title
set_title(title: str) -> None

Set the notification title and truncate if necessary.

Truncates the title to fit within half the active window width before displaying. This prevents excessively long titles from making the notification too wide.

Parameters:

Name Type Description Default
title str

The title text to set (may be longer than the window).

required
Source code in src/winipyside/core/ui/widgets/notification.py
def set_title(self, title: str) -> None:
    """Set the notification title and truncate if necessary.

    Truncates the title to fit within half the active window width
    before displaying.
    This prevents excessively long titles from making the notification too wide.

    Args:
        title: The title text to set (may be longer than the window).
    """
    title = self.str_to_half_window_width(title)
    self.setTitle(title)
str_to_half_window_width
str_to_half_window_width(string: str) -> str

Truncate a string to fit within half the active window width.

Calculates half the width of the currently active window and truncates the string to fit within that width. Uses a fallback of 500 pixels if no window is active, ensuring the function always returns a reasonable result.

This prevents notifications from becoming too wide and potentially expanding their parent window or becoming unreadable.

Parameters:

Name Type Description Default
string str

The string to potentially truncate.

required

Returns:

Type Description
str

The string, truncated if necessary to fit within half the window width.

Source code in src/winipyside/core/ui/widgets/notification.py
def str_to_half_window_width(self, string: str) -> str:
    """Truncate a string to fit within half the active window width.

    Calculates half the width of the currently active window and truncates the
    string to fit within that width. Uses a fallback of 500 pixels if no window
    is active, ensuring the function always returns a reasonable result.

    This prevents notifications from becoming too wide and potentially expanding
    their parent window or becoming unreadable.

    Args:
        string: The string to potentially truncate.

    Returns:
        The string, truncated if necessary to fit within half the window width.
    """
    main_window = QApplication.activeWindow()
    width = main_window.width() / 2 if main_window is not None else 500
    width = int(width)
    return value_to_truncated_string(string, width)

windows

init module.

base

init module.

base

Base window module.

This module contains the base window class for the VideoVault application.

Base
Base(*args: Any, **kwargs: Any)

Bases: Base, QMainWindow

Abstract base class for the main application window.

A QMainWindow-based window that implements the stacked widget navigation pattern. Subclasses define which pages are available and which page should be shown at startup. The window manages a QStackedWidget containing all pages and handles page switching.

Attributes:

Name Type Description
stack

The QStackedWidget managing all pages.

Source code in src/winipyside/core/ui/base/base.py
def __init__(self, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
    """Initialize the UI component and execute all setup lifecycle hooks.

    Calls setup methods in a fixed order: base_setup(), pre_setup(), setup(),
    and post_setup(). This ensures all UI initialization happens in the correct
    sequence, with dependencies resolved before dependent setup runs.
    """
    super().__init__(*args, **kwargs)
    self.base_setup()
    self.pre_setup()
    self.setup()
    self.post_setup()
add_page
add_page(page: Base) -> None

Add a page to the stacked widget.

Called by page instances during their setup to register themselves with the window. Each page is added to the stack widget.

Parameters:

Name Type Description Default
page Base

The BasePage instance to add to the stack.

required
Source code in src/winipyside/core/ui/windows/base/base.py
def add_page(self, page: BasePage) -> None:
    """Add a page to the stacked widget.

    Called by page instances during their setup to register themselves with
    the window. Each page is added to the stack widget.

    Args:
        page: The BasePage instance to add to the stack.
    """
    self.stack.addWidget(page)
base_setup
base_setup() -> None

Initialize the main window structure with title and stacked pages.

Sets the window title to the window's display name, creates the stacked widget, instantiates all pages, and sets the starting page. This is the first lifecycle hook and establishes the complete window structure.

Source code in src/winipyside/core/ui/windows/base/base.py
def base_setup(self) -> None:
    """Initialize the main window structure with title and stacked pages.

    Sets the window title to the window's display name, creates the stacked widget,
    instantiates all pages, and sets the starting page. This is the first lifecycle
    hook and establishes the complete window structure.
    """
    self.setWindowTitle(self.get_display_name())

    self.stack = QStackedWidget()
    self.setCentralWidget(self.stack)

    self.make_pages()

    self.set_start_page()
get_all_page_classes abstractmethod classmethod
get_all_page_classes() -> list[type[Base]]

Get all page classes to be added to this window.

Subclasses must return a list of all page classes that should be available in the window's stack. These pages will be instantiated during window setup.

Returns:

Type Description
list[type[Base]]

A list of BasePage subclass types to include in the window.

Source code in src/winipyside/core/ui/windows/base/base.py
@classmethod
@abstractmethod
def get_all_page_classes(cls) -> list[type[BasePage]]:
    """Get all page classes to be added to this window.

    Subclasses must return a list of all page classes that should be available
    in the window's stack. These pages will be instantiated during window setup.

    Returns:
        A list of BasePage subclass types to include in the window.
    """
get_start_page_cls abstractmethod classmethod
get_start_page_cls() -> type[Base]

Get the page class to display when the window first opens.

Subclasses must return the page class that should be shown initially. This page must be one of the classes returned by get_all_page_classes().

Returns:

Type Description
type[Base]

The BasePage subclass type to display at startup.

Source code in src/winipyside/core/ui/windows/base/base.py
@classmethod
@abstractmethod
def get_start_page_cls(cls) -> type[BasePage]:
    """Get the page class to display when the window first opens.

    Subclasses must return the page class that should be shown initially.
    This page must be one of the classes returned by get_all_page_classes().

    Returns:
        The BasePage subclass type to display at startup.
    """
make_pages
make_pages() -> None

Instantiate all page classes and add them to the stack.

Iterates through all page classes returned by get_all_page_classes() and instantiates each one, which triggers their base_setup() hooks and adds them to the stack. Must be called during window initialization.

Source code in src/winipyside/core/ui/windows/base/base.py
def make_pages(self) -> None:
    """Instantiate all page classes and add them to the stack.

    Iterates through all page classes returned by get_all_page_classes()
    and instantiates each one, which triggers their base_setup() hooks
    and adds them to the stack. Must be called during window initialization.
    """
    for page_cls in self.get_all_page_classes():
        page_cls(base_window=self)
set_start_page
set_start_page() -> None

Switch to the startup page as returned by get_start_page_cls().

Source code in src/winipyside/core/ui/windows/base/base.py
def set_start_page(self) -> None:
    """Switch to the startup page as returned by get_start_page_cls()."""
    self.set_current_page(self.get_start_page_cls())

rig

init module.

configs

init module.

configs

Configs for pyrig.

All subclasses of ConfigFile in the configs package are automatically called.

HealthCheckWorkflowConfigFile

Bases: PySideWorkflowConfigFileMixin, HealthCheckWorkflowConfigFile

Health check workflow.

Extends winiutils health check workflow to add additional steps. This is necessary to make pyside6 work on github actions which is a headless linux environment.

step_run_tests
step_run_tests() -> dict[str, Any]

Get the pre-commit step.

We need to add some env vars so QtWebEngine doesn't try to use GPU acceleration etc.

Source code in src/winipyside/rig/configs/configs.py
def step_run_tests(self) -> dict[str, Any]:
    """Get the pre-commit step.

    We need to add some env vars
    so QtWebEngine doesn't try to use GPU acceleration etc.
    """
    step = super().step_run_tests()
    step.setdefault("env", {}).update(
        {
            "QT_QPA_PLATFORM": "offscreen",
            "QTWEBENGINE_DISABLE_SANDBOX": "1",
            "QTWEBENGINE_CHROMIUM_FLAGS": Args(
                "--no-sandbox",
                "--disable-gpu",
                "--disable-software-rasterizer",
                "--disable-dev-shm-usage",
            ).multiline(),
        },
    )
    return step
PySideWorkflowConfigFileMixin

Bases: WorkflowConfigFile

Mixin to add PySide6-specific workflow steps.

This mixin provides common overrides for PySide6 workflows to work on GitHub Actions headless Linux environments.

step_install_pyside_system_dependencies
step_install_pyside_system_dependencies() -> dict[str, Any]

Get the step to install PySide6 dependencies.

Source code in src/winipyside/rig/configs/configs.py
def step_install_pyside_system_dependencies(self) -> dict[str, Any]:
    """Get the step to install PySide6 dependencies."""
    return self.step(
        self.step_install_pyside_system_dependencies,
        run=Args(
            "sudo",
            "apt-get",
            "update",
            "&&",
            "sudo",
            "apt-get",
            "install",
            "-y",
            "libegl1",
            "libpulse0",
        ).multiline(),
        if_condition="runner.os == 'Linux'",
    )
steps_core_installed_setup
steps_core_installed_setup(
    *args: Any, **kwargs: Any
) -> list[dict[str, Any]]

Get the core installed setup steps.

We need to install additional system dependencies for pyside6.

Source code in src/winipyside/rig/configs/configs.py
def steps_core_installed_setup(
    self,
    *args: Any,  # noqa: ANN401
    **kwargs: Any,  # noqa: ANN401
) -> list[dict[str, Any]]:
    """Get the core installed setup steps.

    We need to install additional system dependencies for pyside6.
    """
    steps = super().steps_core_installed_setup(
        *args,
        **kwargs,
    )

    steps.append(
        self.step_install_pyside_system_dependencies(),
    )
    return steps
ReleaseWorkflowConfigFile

Bases: PySideWorkflowConfigFileMixin, ReleaseWorkflowConfigFile

Release workflow.

Extends winiutils release workflow to add additional steps. This is necessary to make pyside6 work on github actions which is a headless linux environment.

resources

init module.

tools

Tool wrappers for CLI tools used in development workflows.

Tools are subclasses of Tool providing methods that return Args objects for type-safe command construction and execution.

project_tester

Override pyrig's ProjectTester to add custom dev dependencies.

ProjectTester

Bases: ProjectTester

Override pyrig's ProjectTester to add custom dev dependencies.

dev_dependencies
dev_dependencies() -> tuple[str, ...]

Add custom dev dependencies to pyrig's ProjectTester default list.

Source code in src/winipyside/rig/tools/project_tester.py
def dev_dependencies(self) -> tuple[str, ...]:
    """Add custom dev dependencies to pyrig's ProjectTester default list."""
    return (*super().dev_dependencies(), "pytest-qt")