|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
|
|
import pygame
|
|
|
|
|
|
|
|
from config import WIDTH, CHAT_SELECTOR_WIDTH, MESSAGE_HEIGHT, font_medium, BLUE, DARK_BLUE, WHITE, DARKER_BLUE
|
|
|
|
from utils import render_text
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Message:
|
|
|
|
"""
|
|
|
|
The message (for now, it consists only of text)
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
:param text (str): the message text
|
|
|
|
:param is_from_me (bool): False if the message is not from the current user
|
|
|
|
:param chat_width (int): the width of the active chat widget
|
|
|
|
"""
|
|
|
|
text: str
|
|
|
|
is_from_me: bool
|
|
|
|
chat_width: int = WIDTH - CHAT_SELECTOR_WIDTH - 10
|
|
|
|
height: int = MESSAGE_HEIGHT
|
|
|
|
|
|
|
|
def render(self) -> pygame.Surface:
|
|
|
|
"""
|
|
|
|
Creates a surface with a rectangle and the message text written on it
|
|
|
|
:return: the surface with rendered message
|
|
|
|
"""
|
|
|
|
surface = pygame.Surface((self.chat_width, self.height * 10))
|
|
|
|
surface.fill(DARKER_BLUE)
|
|
|
|
bg_color = BLUE * self.is_from_me + DARK_BLUE * (not self.is_from_me)
|
|
|
|
padding = 7
|
|
|
|
# Size of the scaled text surface
|
|
|
|
blit_height: int = self.height - padding * 2
|
|
|
|
blit_width: int = self.chat_width // 2
|
|
|
|
x: int = 0 if not self.is_from_me else self.chat_width - blit_width - padding * 3.5
|
|
|
|
pygame.draw.rect(surface, bg_color, (x, 0, blit_width + padding * 2, self.height * 10))
|
|
|
|
text_surface: pygame.Surface = pygame.Surface((blit_width, blit_height * 10))
|
|
|
|
text_surface.fill(bg_color)
|
|
|
|
text_height = render_text(text_surface, (0, 0), font_medium, self.text, WHITE)
|
|
|
|
# text_surface = pygame.transform.chop(text_surface, (0, 0, blit_width, text_height))
|
|
|
|
surface.blit(text_surface, (x + padding, padding, blit_width, text_height))
|
|
|
|
new_surface = pygame.Surface((self.chat_width, text_height + 2 * padding))
|
|
|
|
new_surface.fill(bg_color)
|
|
|
|
new_surface.blit(surface, (0, 0, new_surface.get_width(), new_surface.get_height()))
|
|
|
|
return new_surface
|