# window.py
#
# Copyright 2024 Lucas Fryzek
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# SPDX-License-Identifier: GPL-3.0-or-later
from gi.repository import Adw, Gtk, GLib
import re
re_url_exp = r"(\S+://\S+)"
re_url = re.compile(re_url_exp)
@Gtk.Template(resource_path='/com/fryzekconcepts/weegtk/gtk/message.ui')
class WeegtkMessage(Gtk.Box):
__gtype_name__ = 'WeegtkMessage'
username = Gtk.Template.Child()
avatar = Gtk.Template.Child()
message_list = Gtk.Template.Child()
def __init__(self, username="username", messages=[], **kwargs):
super().__init__(**kwargs)
data = {
"type": "empty"
}
self.set_contents(data)
def parse_message(self, message, pos=0):
res = re_url.search(message, pos)
if res != None:
res_span = res.span()
escaped = message[pos:res_span[0]]
link = res.group()
result = GLib.markup_escape_text(escaped) + f"{link}"
return result + self.parse_message(message, res_span[1])
else:
return GLib.markup_escape_text(message[pos:])
def set_contents(self, data):
if data["type"] == "empty":
self.set_visible(False)
else:
self.set_visible(True)
self.username.set_label(data["username"])
# Hide avatar for system messages
if data["type"] == "system":
self.avatar.set_visible(False)
else:
self.avatar.set_text(data["username"])
self.avatar.set_visible(True)
first = True
for message in data["text"]:
margin = 5 if not first else 0
first = False
markuped = self.parse_message(message)
msg = Gtk.Label(label=markuped, selectable=True,
wrap=True, halign=0, hexpand=True, hexpand_set=True,
xalign=0, margin_top=margin, use_markup=True)
self.message_list.append(msg)