split notedeck into crates

This splits notedeck into crates, separating the browser chrome and
individual apps:

* notedeck: binary file, browser chrome
* notedeck_columns: our columns app
* enostr: same as before

We still need to do more work to cleanly separate the chrome apis
from the app apis. Soon I will create notedeck-notebook to see what
makes sense to be shared between the apps.

Some obvious ones that come to mind:

1. ImageCache

We will likely want to move this to the notedeck crate, as most apps
will want some kind of image cache. In web browsers, web pages do not
need to worry about this, so we will likely have to do something similar

2. Ndb

Since NdbRef is threadsafe and Ndb is an Arc<NdbRef>, it can be safely
copied to each app. This will simplify things. In the future we might
want to create an abstraction over this? Maybe each app shouldn't have
access to the same database... we assume the data in DBs are all public
anyways, but if we have unwrapped giftwraps that could be a problem.

3. RelayPool / Subscription Manager

The browser should probably maintain these. Then apps can use ken's
high level subscription manager api and not have to worry about
connection pool details

4. Accounts

Accounts and key management should be handled by the chrome. Apps should
only have a simple signer interface.

That's all for now, just something to think about!

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2024-12-11 02:53:05 -08:00
parent 10cbdf15f0
commit 74c5f0c748
156 changed files with 194 additions and 252 deletions

View File

@@ -0,0 +1,87 @@
pub mod picture;
pub mod preview;
use crate::ui::note::NoteOptions;
use egui::{ScrollArea, Widget};
use enostr::Pubkey;
use nostrdb::{Ndb, Transaction};
pub use picture::ProfilePic;
pub use preview::ProfilePreview;
use crate::{
actionbar::NoteAction, imgcache::ImageCache, muted::MuteFun, notecache::NoteCache,
notes_holder::NotesHolderStorage, profile::Profile,
};
use super::timeline::{tabs_ui, TimelineTabView};
pub struct ProfileView<'a> {
pubkey: &'a Pubkey,
col_id: usize,
profiles: &'a mut NotesHolderStorage<Profile>,
note_options: NoteOptions,
ndb: &'a Ndb,
note_cache: &'a mut NoteCache,
img_cache: &'a mut ImageCache,
}
impl<'a> ProfileView<'a> {
pub fn new(
pubkey: &'a Pubkey,
col_id: usize,
profiles: &'a mut NotesHolderStorage<Profile>,
ndb: &'a Ndb,
note_cache: &'a mut NoteCache,
img_cache: &'a mut ImageCache,
note_options: NoteOptions,
) -> Self {
ProfileView {
pubkey,
col_id,
profiles,
ndb,
note_cache,
img_cache,
note_options,
}
}
pub fn ui(&mut self, ui: &mut egui::Ui, is_muted: &MuteFun) -> Option<NoteAction> {
let scroll_id = egui::Id::new(("profile_scroll", self.col_id, self.pubkey));
ScrollArea::vertical()
.id_salt(scroll_id)
.show(ui, |ui| {
let txn = Transaction::new(self.ndb).expect("txn");
if let Ok(profile) = self.ndb.get_profile_by_pubkey(&txn, self.pubkey.bytes()) {
ProfilePreview::new(&profile, self.img_cache).ui(ui);
}
let profile = self
.profiles
.notes_holder_mutated(
self.ndb,
self.note_cache,
&txn,
self.pubkey.bytes(),
is_muted,
)
.get_ptr();
profile.timeline.selected_view = tabs_ui(ui);
let reversed = false;
TimelineTabView::new(
profile.timeline.current_view(),
reversed,
self.note_options,
&txn,
self.ndb,
self.note_cache,
self.img_cache,
)
.show(ui)
})
.inner
}
}

View File

@@ -0,0 +1,220 @@
use crate::images::ImageType;
use crate::imgcache::ImageCache;
use crate::ui::{Preview, PreviewConfig, View};
use egui::{vec2, Sense, TextureHandle};
use nostrdb::{Ndb, Transaction};
pub struct ProfilePic<'cache, 'url> {
cache: &'cache mut ImageCache,
url: &'url str,
size: f32,
}
impl egui::Widget for ProfilePic<'_, '_> {
fn ui(self, ui: &mut egui::Ui) -> egui::Response {
render_pfp(ui, self.cache, self.url, self.size)
}
}
impl<'cache, 'url> ProfilePic<'cache, 'url> {
pub fn new(cache: &'cache mut ImageCache, url: &'url str) -> Self {
let size = Self::default_size();
ProfilePic { cache, url, size }
}
pub fn from_profile(
cache: &'cache mut ImageCache,
profile: &nostrdb::ProfileRecord<'url>,
) -> Option<Self> {
profile
.record()
.profile()
.and_then(|p| p.picture())
.map(|url| ProfilePic::new(cache, url))
}
#[inline]
pub fn default_size() -> f32 {
38.0
}
#[inline]
pub fn medium_size() -> f32 {
32.0
}
#[inline]
pub fn small_size() -> f32 {
24.0
}
#[inline]
pub fn no_pfp_url() -> &'static str {
"https://damus.io/img/no-profile.svg"
}
#[inline]
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
}
fn render_pfp(
ui: &mut egui::Ui,
img_cache: &mut ImageCache,
url: &str,
ui_size: f32,
) -> egui::Response {
#[cfg(feature = "profiling")]
puffin::profile_function!();
// We will want to downsample these so it's not blurry on hi res displays
let img_size = 128u32;
let m_cached_promise = img_cache.map().get(url);
if m_cached_promise.is_none() {
let res = crate::images::fetch_img(img_cache, ui.ctx(), url, ImageType::Profile(img_size));
img_cache.map_mut().insert(url.to_owned(), res);
}
match img_cache.map()[url].ready() {
None => paint_circle(ui, ui_size),
// Failed to fetch profile!
Some(Err(_err)) => {
let m_failed_promise = img_cache.map().get(url);
if m_failed_promise.is_none() {
let no_pfp = crate::images::fetch_img(
img_cache,
ui.ctx(),
ProfilePic::no_pfp_url(),
ImageType::Profile(img_size),
);
img_cache.map_mut().insert(url.to_owned(), no_pfp);
}
match img_cache.map().get(url).unwrap().ready() {
None => paint_circle(ui, ui_size),
Some(Err(_e)) => {
//error!("Image load error: {:?}", e);
paint_circle(ui, ui_size)
}
Some(Ok(img)) => pfp_image(ui, img, ui_size),
}
}
Some(Ok(img)) => pfp_image(ui, img, ui_size),
}
}
fn pfp_image(ui: &mut egui::Ui, img: &TextureHandle, size: f32) -> egui::Response {
#[cfg(feature = "profiling")]
puffin::profile_function!();
//img.show_max_size(ui, egui::vec2(size, size))
ui.add(egui::Image::new(img).max_width(size))
//.with_options()
}
fn paint_circle(ui: &mut egui::Ui, size: f32) -> egui::Response {
let (rect, response) = ui.allocate_at_least(vec2(size, size), Sense::hover());
ui.painter()
.circle_filled(rect.center(), size / 2.0, ui.visuals().weak_text_color());
response
}
mod preview {
use super::*;
use crate::ui;
use nostrdb::*;
use std::collections::HashSet;
pub struct ProfilePicPreview {
cache: ImageCache,
ndb: Ndb,
keys: Vec<ProfileKey>,
}
impl ProfilePicPreview {
fn new() -> Self {
let config = Config::new();
let ndb = Ndb::new(".", &config).expect("ndb");
let txn = Transaction::new(&ndb).unwrap();
let filters = vec![Filter::new().kinds(vec![0]).build()];
let cache = ImageCache::new("cache/img".into());
let mut pks = HashSet::new();
let mut keys = HashSet::new();
for query_result in ndb.query(&txn, &filters, 2000).unwrap() {
pks.insert(query_result.note.pubkey());
}
for pk in pks {
let profile = if let Ok(profile) = ndb.get_profile_by_pubkey(&txn, pk) {
profile
} else {
continue;
};
if profile
.record()
.profile()
.and_then(|p| p.picture())
.is_none()
{
continue;
}
keys.insert(profile.key().expect("should not be owned"));
}
let keys = keys.into_iter().collect();
ProfilePicPreview { cache, ndb, keys }
}
}
impl View for ProfilePicPreview {
fn ui(&mut self, ui: &mut egui::Ui) {
egui::ScrollArea::both().show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
let txn = Transaction::new(&self.ndb).unwrap();
for key in &self.keys {
let profile = self.ndb.get_profile_by_key(&txn, *key).unwrap();
let url = profile
.record()
.profile()
.expect("should have profile")
.picture()
.expect("should have picture");
let expand_size = 10.0;
let anim_speed = 0.05;
let (rect, size, _resp) = ui::anim::hover_expand(
ui,
egui::Id::new(profile.key().unwrap()),
ui::ProfilePic::default_size(),
expand_size,
anim_speed,
);
ui.put(rect, ui::ProfilePic::new(&mut self.cache, url).size(size))
.on_hover_ui_at_pointer(|ui| {
ui.set_max_width(300.0);
ui.add(ui::ProfilePreview::new(&profile, &mut self.cache));
});
}
});
});
}
}
impl Preview for ProfilePic<'_, '_> {
type Prev = ProfilePicPreview;
fn preview(_cfg: PreviewConfig) -> Self::Prev {
ProfilePicPreview::new()
}
}
}

View File

@@ -0,0 +1,322 @@
use crate::app_style::{get_font_size, NotedeckTextStyle};
use crate::imgcache::ImageCache;
use crate::storage::{DataPath, DataPathType};
use crate::ui::ProfilePic;
use crate::user_account::UserAccount;
use crate::{colors, images, DisplayName};
use egui::load::TexturePoll;
use egui::{Frame, Label, RichText, Sense, Widget};
use egui_extras::Size;
use enostr::{NoteId, Pubkey};
use nostrdb::{Ndb, ProfileRecord, Transaction};
pub struct ProfilePreview<'a, 'cache> {
profile: &'a ProfileRecord<'a>,
cache: &'cache mut ImageCache,
banner_height: Size,
}
impl<'a, 'cache> ProfilePreview<'a, 'cache> {
pub fn new(profile: &'a ProfileRecord<'a>, cache: &'cache mut ImageCache) -> Self {
let banner_height = Size::exact(80.0);
ProfilePreview {
profile,
cache,
banner_height,
}
}
pub fn banner_height(&mut self, size: Size) {
self.banner_height = size;
}
fn banner_texture(
ui: &mut egui::Ui,
profile: &ProfileRecord<'_>,
) -> Option<egui::load::SizedTexture> {
// TODO: cache banner
let banner = profile.record().profile().and_then(|p| p.banner());
if let Some(banner) = banner {
let texture_load_res =
egui::Image::new(banner).load_for_size(ui.ctx(), ui.available_size());
if let Ok(texture_poll) = texture_load_res {
match texture_poll {
TexturePoll::Pending { .. } => {}
TexturePoll::Ready { texture, .. } => return Some(texture),
}
}
}
None
}
fn banner(ui: &mut egui::Ui, profile: &ProfileRecord<'_>) -> egui::Response {
if let Some(texture) = Self::banner_texture(ui, profile) {
images::aspect_fill(
ui,
Sense::hover(),
texture.id,
texture.size.x / texture.size.y,
)
} else {
// TODO: default banner texture
ui.label("")
}
}
fn body(self, ui: &mut egui::Ui) {
crate::ui::padding(12.0, ui, |ui| {
ui.add(ProfilePic::new(self.cache, get_profile_url(Some(self.profile))).size(80.0));
ui.add(display_name_widget(
get_display_name(Some(self.profile)),
false,
));
ui.add(about_section_widget(self.profile));
});
}
}
impl egui::Widget for ProfilePreview<'_, '_> {
fn ui(self, ui: &mut egui::Ui) -> egui::Response {
ui.vertical(|ui| {
ui.add_sized([ui.available_size().x, 80.0], |ui: &mut egui::Ui| {
ProfilePreview::banner(ui, self.profile)
});
self.body(ui);
})
.response
}
}
pub struct SimpleProfilePreview<'a, 'cache> {
profile: Option<&'a ProfileRecord<'a>>,
cache: &'cache mut ImageCache,
is_nsec: bool,
}
impl<'a, 'cache> SimpleProfilePreview<'a, 'cache> {
pub fn new(
profile: Option<&'a ProfileRecord<'a>>,
cache: &'cache mut ImageCache,
is_nsec: bool,
) -> Self {
SimpleProfilePreview {
profile,
cache,
is_nsec,
}
}
}
impl egui::Widget for SimpleProfilePreview<'_, '_> {
fn ui(self, ui: &mut egui::Ui) -> egui::Response {
Frame::none()
.show(ui, |ui| {
ui.add(ProfilePic::new(self.cache, get_profile_url(self.profile)).size(48.0));
ui.vertical(|ui| {
ui.add(display_name_widget(get_display_name(self.profile), true));
if !self.is_nsec {
ui.add(
Label::new(
RichText::new("Read only")
.size(get_font_size(ui.ctx(), &NotedeckTextStyle::Tiny))
.color(ui.visuals().warn_fg_color),
)
.selectable(false),
);
}
});
})
.response
}
}
mod previews {
use super::*;
use crate::test_data::test_profile_record;
use crate::ui::{Preview, PreviewConfig, View};
pub struct ProfilePreviewPreview<'a> {
profile: ProfileRecord<'a>,
cache: ImageCache,
}
impl ProfilePreviewPreview<'_> {
pub fn new() -> Self {
let profile = test_profile_record();
let path = DataPath::new("previews")
.path(DataPathType::Cache)
.join(ImageCache::rel_dir());
let cache = ImageCache::new(path);
ProfilePreviewPreview { profile, cache }
}
}
impl Default for ProfilePreviewPreview<'_> {
fn default() -> Self {
ProfilePreviewPreview::new()
}
}
impl View for ProfilePreviewPreview<'_> {
fn ui(&mut self, ui: &mut egui::Ui) {
ProfilePreview::new(&self.profile, &mut self.cache).ui(ui);
}
}
impl<'a> Preview for ProfilePreview<'a, '_> {
/// A preview of the profile preview :D
type Prev = ProfilePreviewPreview<'a>;
fn preview(_cfg: PreviewConfig) -> Self::Prev {
ProfilePreviewPreview::new()
}
}
}
pub fn get_display_name<'a>(profile: Option<&ProfileRecord<'a>>) -> DisplayName<'a> {
if let Some(name) = profile.and_then(|p| crate::profile::get_profile_name(p)) {
name
} else {
DisplayName::One("??")
}
}
pub fn get_profile_url<'a>(profile: Option<&ProfileRecord<'a>>) -> &'a str {
if let Some(url) = profile.and_then(|pr| pr.record().profile().and_then(|p| p.picture())) {
url
} else {
ProfilePic::no_pfp_url()
}
}
pub fn get_profile_url_owned(profile: Option<ProfileRecord<'_>>) -> &str {
if let Some(url) = profile.and_then(|pr| pr.record().profile().and_then(|p| p.picture())) {
url
} else {
ProfilePic::no_pfp_url()
}
}
pub fn get_account_url<'a>(
txn: &'a nostrdb::Transaction,
ndb: &nostrdb::Ndb,
account: Option<&UserAccount>,
) -> &'a str {
if let Some(selected_account) = account {
if let Ok(profile) = ndb.get_profile_by_pubkey(txn, selected_account.pubkey.bytes()) {
get_profile_url_owned(Some(profile))
} else {
get_profile_url_owned(None)
}
} else {
get_profile_url(None)
}
}
fn display_name_widget(
display_name: DisplayName<'_>,
add_placeholder_space: bool,
) -> impl egui::Widget + '_ {
move |ui: &mut egui::Ui| match display_name {
DisplayName::One(n) => {
let name_response = ui.add(
Label::new(RichText::new(n).text_style(NotedeckTextStyle::Heading3.text_style()))
.selectable(false),
);
if add_placeholder_space {
ui.add_space(16.0);
}
name_response
}
DisplayName::Both {
display_name,
username,
} => {
ui.add(
Label::new(
RichText::new(display_name)
.text_style(NotedeckTextStyle::Heading3.text_style()),
)
.selectable(false),
);
ui.add(
Label::new(
RichText::new(format!("@{}", username))
.size(12.0)
.color(colors::MID_GRAY),
)
.selectable(false),
)
}
}
}
pub fn one_line_display_name_widget(
display_name: DisplayName<'_>,
style: NotedeckTextStyle,
) -> impl egui::Widget + '_ {
let text_style = style.text_style();
move |ui: &mut egui::Ui| match display_name {
DisplayName::One(n) => ui.label(
RichText::new(n)
.text_style(text_style)
.color(colors::GRAY_SECONDARY),
),
DisplayName::Both {
display_name,
username: _,
} => ui.label(
RichText::new(display_name)
.text_style(text_style)
.color(colors::GRAY_SECONDARY),
),
}
}
fn about_section_widget<'a, 'b>(profile: &'b ProfileRecord<'a>) -> impl egui::Widget + 'b
where
'b: 'a,
{
move |ui: &mut egui::Ui| {
if let Some(about) = profile.record().profile().and_then(|p| p.about()) {
ui.label(about)
} else {
// need any Response so we dont need an Option
ui.allocate_response(egui::Vec2::ZERO, egui::Sense::hover())
}
}
}
fn get_display_name_as_string<'a>(profile: Option<&ProfileRecord<'a>>) -> &'a str {
let display_name = get_display_name(profile);
match display_name {
DisplayName::One(n) => n,
DisplayName::Both { display_name, .. } => display_name,
}
}
pub fn get_profile_displayname_string<'a>(txn: &'a Transaction, ndb: &Ndb, pk: &Pubkey) -> &'a str {
let profile = ndb.get_profile_by_pubkey(txn, pk.bytes()).ok();
get_display_name_as_string(profile.as_ref())
}
pub fn get_note_users_displayname_string<'a>(
txn: &'a Transaction,
ndb: &Ndb,
id: &NoteId,
) -> &'a str {
let note = ndb.get_note_by_id(txn, id.bytes());
let profile = if let Ok(note) = note {
ndb.get_profile_by_pubkey(txn, note.pubkey()).ok()
} else {
None
};
get_display_name_as_string(profile.as_ref())
}