previews: run previews as notedeck apps

This allows ./preview to be a notedeck app runner. I am currently
using it for the ProfilePic app (which will because notedeck_viz)

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2024-12-20 15:39:26 -08:00
parent 475314da75
commit fcac49a0a5
19 changed files with 222 additions and 238 deletions

1
.gitignore vendored
View File

@@ -3,6 +3,7 @@ build.log
perf.data perf.data
perf.data.old perf.data.old
.privenv .privenv
*.swp
target target
queries/damus-notifs.json queries/damus-notifs.json
.git .git

View File

@@ -1,5 +1,5 @@
use crate::AppContext; use crate::AppContext;
pub trait App { pub trait App {
fn update(&mut self, ctx: &mut AppContext<'_>); fn update(&mut self, ctx: &mut AppContext<'_>, ui: &mut egui::Ui);
} }

View File

@@ -15,5 +15,4 @@ pub struct AppContext<'a> {
pub path: &'a DataPath, pub path: &'a DataPath,
pub args: &'a Args, pub args: &'a Args,
pub theme: &'a mut ThemeHandler, pub theme: &'a mut ThemeHandler,
pub egui: &'a egui::Context,
} }

View File

@@ -22,18 +22,12 @@ impl DataPath {
pub fn default_base() -> Option<PathBuf> { pub fn default_base() -> Option<PathBuf> {
dirs::data_local_dir().map(|pb| pb.join("notedeck")) dirs::data_local_dir().map(|pb| pb.join("notedeck"))
} }
}
pub enum DataPathType { pub fn default_base_or_cwd() -> PathBuf {
Log, use std::str::FromStr;
Setting, Self::default_base().unwrap_or_else(|| PathBuf::from_str(".").unwrap())
Keys, }
SelectedKey,
Db,
Cache,
}
impl DataPath {
pub fn rel_path(&self, typ: DataPathType) -> PathBuf { pub fn rel_path(&self, typ: DataPathType) -> PathBuf {
match typ { match typ {
DataPathType::Log => PathBuf::from("logs"), DataPathType::Log => PathBuf::from("logs"),
@@ -50,6 +44,21 @@ impl DataPath {
} }
} }
impl Default for DataPath {
fn default() -> Self {
Self::new(Self::default_base_or_cwd())
}
}
pub enum DataPathType {
Log,
Setting,
Keys,
SelectedKey,
Db,
Cache,
}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub struct Directory { pub struct Directory {
pub file_path: PathBuf, pub file_path: PathBuf,

View File

@@ -10,18 +10,20 @@ description = "The nostr browser"
[dependencies] [dependencies]
eframe = { workspace = true } eframe = { workspace = true }
egui = { workspace = true }
egui_extras = { workspace = true } egui_extras = { workspace = true }
egui = { workspace = true }
enostr = { workspace = true } enostr = { workspace = true }
nostrdb = { workspace = true } nostrdb = { workspace = true }
notedeck = { workspace = true }
notedeck_columns = { workspace = true } notedeck_columns = { workspace = true }
notedeck = { workspace = true }
puffin = { workspace = true, optional = true }
puffin_egui = { workspace = true, optional = true }
serde_json = { workspace = true } serde_json = { workspace = true }
strum = { workspace = true } strum = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true } tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true } tracing-subscriber = { workspace = true }
tracing = { workspace = true }
[dev-dependencies] [dev-dependencies]
tempfile = { workspace = true } tempfile = { workspace = true }
@@ -39,7 +41,7 @@ path = "src/preview.rs"
[features] [features]
default = [] default = []
profiling = ["notedeck_columns/puffin"] profiling = ["notedeck_columns/puffin", "puffin", "puffin_egui"]
[target.'cfg(target_os = "android")'.dependencies] [target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.11.1" android_logger = "0.11.1"

View File

@@ -25,7 +25,38 @@ pub struct Notedeck {
theme: ThemeHandler, theme: ThemeHandler,
tabs: Tabs, tabs: Tabs,
app_rect_handler: AppSizeHandler, app_rect_handler: AppSizeHandler,
egui: egui::Context, }
fn margin_top(narrow: bool) -> f32 {
#[cfg(target_os = "android")]
{
// FIXME - query the system bar height and adjust more precisely
let _ = narrow; // suppress compiler warning on android
40.0
}
#[cfg(not(target_os = "android"))]
{
if narrow {
50.0
} else {
0.0
}
}
}
/// Our chrome, which is basically nothing
fn main_panel(style: &egui::Style, narrow: bool) -> egui::CentralPanel {
let inner_margin = egui::Margin {
top: margin_top(narrow),
left: 0.0,
right: 0.0,
bottom: 0.0,
};
egui::CentralPanel::default().frame(egui::Frame {
inner_margin,
fill: style.visuals.panel_fill,
..Default::default()
})
} }
impl eframe::App for Notedeck { impl eframe::App for Notedeck {
@@ -36,19 +67,34 @@ impl eframe::App for Notedeck {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// TODO: render chrome // TODO: render chrome
#[cfg(feature = "profiling")]
puffin::GlobalProfiler::lock().new_frame();
// render app main_panel(&ctx.style(), notedeck::ui::is_narrow(ctx)).show(ctx, |ui| {
if let Some(app) = &self.tabs.app { // render app
let app = app.clone(); if let Some(app) = &self.tabs.app {
app.borrow_mut().update(&mut self.app_context()); let app = app.clone();
} app.borrow_mut().update(&mut self.app_context(), ui);
}
});
self.app_rect_handler.try_save_app_size(ctx); self.app_rect_handler.try_save_app_size(ctx);
#[cfg(feature = "profiling")]
puffin_egui::profiler_window(ctx);
} }
} }
#[cfg(feature = "profiling")]
fn setup_profiling() {
puffin::set_scopes_on(true); // tell puffin to collect data
}
impl Notedeck { impl Notedeck {
pub fn new<P: AsRef<Path>>(ctx: &egui::Context, data_path: P, args: &[String]) -> Self { pub fn new<P: AsRef<Path>>(ctx: &egui::Context, data_path: P, args: &[String]) -> Self {
#[cfg(feature = "profiling")]
setup_profiling();
let parsed_args = Args::parse(args); let parsed_args = Args::parse(args);
let is_mobile = parsed_args let is_mobile = parsed_args
.is_mobile .is_mobile
@@ -139,7 +185,6 @@ impl Notedeck {
let img_cache = ImageCache::new(imgcache_dir); let img_cache = ImageCache::new(imgcache_dir);
let note_cache = NoteCache::default(); let note_cache = NoteCache::default();
let unknown_ids = UnknownIds::default(); let unknown_ids = UnknownIds::default();
let egui = ctx.clone();
let tabs = Tabs::new(None); let tabs = Tabs::new(None);
let parsed_args = Args::parse(args); let parsed_args = Args::parse(args);
let app_rect_handler = AppSizeHandler::new(&path); let app_rect_handler = AppSizeHandler::new(&path);
@@ -155,7 +200,6 @@ impl Notedeck {
path: path.clone(), path: path.clone(),
args: parsed_args, args: parsed_args,
theme, theme,
egui,
tabs, tabs,
} }
} }
@@ -171,7 +215,6 @@ impl Notedeck {
path: &self.path, path: &self.path,
args: &self.args, args: &self.args,
theme: &mut self.theme, theme: &mut self.theme,
egui: &self.egui,
} }
} }

View File

@@ -3,8 +3,6 @@ use notedeck_chrome::{setup::generate_native_options, Notedeck};
use notedeck::{DataPath, DataPathType}; use notedeck::{DataPath, DataPathType};
use notedeck_columns::Damus; use notedeck_columns::Damus;
use std::path::PathBuf;
use std::str::FromStr;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
// Entry point for wasm // Entry point for wasm
@@ -64,8 +62,8 @@ fn setup_logging(path: &DataPath) {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let base_path = DataPath::default_base().unwrap_or(PathBuf::from_str(".").unwrap()); let base_path = DataPath::default_base_or_cwd();
let path = DataPath::new(&base_path); let path = DataPath::new(base_path.clone());
setup_logging(&path); setup_logging(&path);

View File

@@ -1,7 +1,6 @@
use notedeck::DataPath; use notedeck::DataPath;
use notedeck_chrome::setup::{ use notedeck_chrome::setup::generate_native_options;
generate_mobile_emulator_native_options, generate_native_options, setup_cc, use notedeck_chrome::Notedeck;
};
use notedeck_columns::ui::configure_deck::ConfigureDeckView; use notedeck_columns::ui::configure_deck::ConfigureDeckView;
use notedeck_columns::ui::edit_deck::EditDeckView; use notedeck_columns::ui::edit_deck::EditDeckView;
use notedeck_columns::ui::{ use notedeck_columns::ui::{
@@ -10,42 +9,32 @@ use notedeck_columns::ui::{
}; };
use std::env; use std::env;
struct PreviewRunner { struct PreviewRunner {}
force_mobile: bool,
light_mode: bool,
}
impl PreviewRunner { impl PreviewRunner {
fn new(force_mobile: bool, light_mode: bool) -> Self { fn new() -> Self {
PreviewRunner { PreviewRunner {}
force_mobile,
light_mode,
}
} }
async fn run<P>(self, preview: P) async fn run<P>(self, preview: P)
where where
P: Into<PreviewApp> + 'static, P: notedeck::App + 'static,
{ {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
let native_options = if self.force_mobile { let base_path = DataPath::default_base_or_cwd();
generate_mobile_emulator_native_options() let path = DataPath::new(&base_path);
} else {
// TODO: tmp preview pathbuf?
generate_native_options(DataPath::new("previews"))
};
let is_mobile = self.force_mobile; let _res = eframe::run_native(
let light_mode = self.light_mode; "Notedeck Preview",
generate_native_options(path),
Box::new(|cc| {
let args: Vec<String> = std::env::args().collect();
let mut notedeck = Notedeck::new(&cc.egui_ctx, &base_path, &args);
let _ = eframe::run_native( notedeck.add_app(PreviewApp::new(preview));
"UI Preview Runner",
native_options, Ok(Box::new(notedeck))
Box::new(move |cc| {
let app = Into::<PreviewApp>::into(preview);
setup_cc(&cc.egui_ctx, is_mobile, light_mode);
Ok(Box::new(app))
}), }),
); );
} }
@@ -93,7 +82,7 @@ async fn main() {
if light_mode { "enabled" } else { "disabled" } if light_mode { "enabled" } else { "disabled" }
); );
let is_mobile = is_mobile.unwrap_or(notedeck::ui::is_compiled_as_mobile()); let is_mobile = is_mobile.unwrap_or(notedeck::ui::is_compiled_as_mobile());
let runner = PreviewRunner::new(is_mobile, light_mode); let runner = PreviewRunner::new();
previews!( previews!(
runner, runner,

View File

@@ -22,7 +22,6 @@ use notedeck::{Accounts, AppContext, DataPath, DataPathType, FilterState, ImageC
use enostr::{ClientMessage, Keypair, Pubkey, RelayEvent, RelayMessage, RelayPool}; use enostr::{ClientMessage, Keypair, Pubkey, RelayEvent, RelayMessage, RelayPool};
use uuid::Uuid; use uuid::Uuid;
use egui::{Frame, Style};
use egui_extras::{Size, StripBuilder}; use egui_extras::{Size, StripBuilder};
use nostrdb::{Ndb, Transaction}; use nostrdb::{Ndb, Transaction};
@@ -185,22 +184,11 @@ fn unknown_id_send(unknown_ids: &mut UnknownIds, pool: &mut RelayPool) {
pool.send(&msg); pool.send(&msg);
} }
#[cfg(feature = "profiling")] fn update_damus(damus: &mut Damus, app_ctx: &mut AppContext<'_>, ctx: &egui::Context) {
fn setup_profiling() {
puffin::set_scopes_on(true); // tell puffin to collect data
}
fn update_damus(damus: &mut Damus, app_ctx: &mut AppContext<'_>) {
let _ctx = app_ctx.egui.clone();
let ctx = &_ctx;
app_ctx.accounts.update(app_ctx.ndb, app_ctx.pool, ctx); // update user relay and mute lists app_ctx.accounts.update(app_ctx.ndb, app_ctx.pool, ctx); // update user relay and mute lists
match damus.state { match damus.state {
DamusState::Initializing => { DamusState::Initializing => {
#[cfg(feature = "profiling")]
setup_profiling();
damus.state = DamusState::Initialized; damus.state = DamusState::Initialized;
// this lets our eose handler know to close unknownids right away // this lets our eose handler know to close unknownids right away
damus damus
@@ -337,18 +325,15 @@ fn process_message(damus: &mut Damus, ctx: &mut AppContext<'_>, relay: &str, msg
} }
} }
fn render_damus(damus: &mut Damus, app_ctx: &mut AppContext<'_>) { fn render_damus(damus: &mut Damus, app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
if notedeck::ui::is_narrow(app_ctx.egui) { if notedeck::ui::is_narrow(ui.ctx()) {
render_damus_mobile(damus, app_ctx); render_damus_mobile(damus, app_ctx, ui);
} else { } else {
render_damus_desktop(damus, app_ctx); render_damus_desktop(damus, app_ctx, ui);
} }
// We use this for keeping timestamps and things up to date // We use this for keeping timestamps and things up to date
app_ctx.egui.request_repaint_after(Duration::from_secs(1)); ui.ctx().request_repaint_after(Duration::from_secs(1));
#[cfg(feature = "profiling")]
puffin_egui::profiler_window(ctx);
} }
/* /*
@@ -498,63 +483,24 @@ fn circle_icon(ui: &mut egui::Ui, openness: f32, response: &egui::Response) {
} }
*/ */
fn render_damus_mobile(app: &mut Damus, app_ctx: &mut AppContext<'_>) { fn render_damus_mobile(app: &mut Damus, app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
let _ctx = app_ctx.egui.clone();
let ctx = &_ctx;
#[cfg(feature = "profiling")] #[cfg(feature = "profiling")]
puffin::profile_function!(); puffin::profile_function!();
//let routes = app.timelines[0].routes.clone(); //let routes = app.timelines[0].routes.clone();
main_panel(&ctx.style(), notedeck::ui::is_narrow(ctx)).show(ctx, |ui| { if !app.columns(app_ctx.accounts).columns().is_empty()
if !app.columns(app_ctx.accounts).columns().is_empty() && nav::render_nav(0, app, app_ctx, ui).process_render_nav_response(app, app_ctx)
&& nav::render_nav(0, app, app_ctx, ui).process_render_nav_response(app, app_ctx)
{
storage::save_decks_cache(app_ctx.path, &app.decks_cache);
}
});
}
fn margin_top(narrow: bool) -> f32 {
#[cfg(target_os = "android")]
{ {
// FIXME - query the system bar height and adjust more precisely storage::save_decks_cache(app_ctx.path, &app.decks_cache);
let _ = narrow; // suppress compiler warning on android
40.0
}
#[cfg(not(target_os = "android"))]
{
if narrow {
50.0
} else {
0.0
}
} }
} }
fn main_panel(style: &Style, narrow: bool) -> egui::CentralPanel { fn render_damus_desktop(app: &mut Damus, app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
let inner_margin = egui::Margin {
top: margin_top(narrow),
left: 0.0,
right: 0.0,
bottom: 0.0,
};
egui::CentralPanel::default().frame(Frame {
inner_margin,
fill: style.visuals.panel_fill,
..Default::default()
})
}
fn render_damus_desktop(app: &mut Damus, app_ctx: &mut AppContext<'_>) {
let _ctx = app_ctx.egui.clone();
let ctx = &_ctx;
#[cfg(feature = "profiling")] #[cfg(feature = "profiling")]
puffin::profile_function!(); puffin::profile_function!();
let screen_size = ctx.screen_rect().width(); let screen_size = ui.ctx().screen_rect().width();
let calc_panel_width = (screen_size let calc_panel_width = (screen_size
/ get_active_columns(app_ctx.accounts, &app.decks_cache).num_columns() as f32) / get_active_columns(app_ctx.accounts, &app.decks_cache).num_columns() as f32)
- 30.0; - 30.0;
@@ -566,16 +512,14 @@ fn render_damus_desktop(app: &mut Damus, app_ctx: &mut AppContext<'_>) {
Size::remainder() Size::remainder()
}; };
main_panel(&ctx.style(), notedeck::ui::is_narrow(ctx)).show(ctx, |ui| { ui.spacing_mut().item_spacing.x = 0.0;
ui.spacing_mut().item_spacing.x = 0.0; if need_scroll {
if need_scroll { egui::ScrollArea::horizontal().show(ui, |ui| {
egui::ScrollArea::horizontal().show(ui, |ui| {
timelines_view(ui, panel_sizes, app, app_ctx);
});
} else {
timelines_view(ui, panel_sizes, app, app_ctx); timelines_view(ui, panel_sizes, app, app_ctx);
} });
}); } else {
timelines_view(ui, panel_sizes, app, app_ctx);
}
} }
fn timelines_view(ui: &mut egui::Ui, sizes: Size, app: &mut Damus, ctx: &mut AppContext<'_>) { fn timelines_view(ui: &mut egui::Ui, sizes: Size, app: &mut Damus, ctx: &mut AppContext<'_>) {
@@ -653,17 +597,15 @@ fn timelines_view(ui: &mut egui::Ui, sizes: Size, app: &mut Damus, ctx: &mut App
} }
impl notedeck::App for Damus { impl notedeck::App for Damus {
fn update(&mut self, ctx: &mut AppContext<'_>) { fn update(&mut self, ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
/* /*
self.app self.app
.frame_history .frame_history
.on_new_frame(ctx.input(|i| i.time), frame.info().cpu_usage); .on_new_frame(ctx.input(|i| i.time), frame.info().cpu_usage);
*/ */
#[cfg(feature = "profiling")] update_damus(self, ctx, ui.ctx());
puffin::GlobalProfiler::lock().new_frame(); render_damus(self, ctx, ui);
update_damus(self, ctx);
render_damus(self, ctx);
} }
} }

View File

@@ -1,5 +1,5 @@
use crate::login_manager::AcquireKeyState; use crate::login_manager::AcquireKeyState;
use crate::ui::{Preview, PreviewConfig, View}; use crate::ui::{Preview, PreviewConfig};
use egui::TextEdit; use egui::TextEdit;
use egui::{Align, Button, Color32, Frame, InnerResponse, Margin, RichText, Vec2}; use egui::{Align, Button, Color32, Frame, InnerResponse, Margin, RichText, Vec2};
use enostr::Keypair; use enostr::Keypair;
@@ -110,13 +110,14 @@ fn login_textedit(manager: &mut AcquireKeyState) -> TextEdit {
mod preview { mod preview {
use super::*; use super::*;
use notedeck::{App, AppContext};
pub struct AccountLoginPreview { pub struct AccountLoginPreview {
manager: AcquireKeyState, manager: AcquireKeyState,
} }
impl View for AccountLoginPreview { impl App for AccountLoginPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, _app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
AccountLoginView::new(&mut self.manager).ui(ui); AccountLoginView::new(&mut self.manager).ui(ui);
} }
} }

View File

@@ -297,10 +297,11 @@ fn paint_row(ui: &mut egui::Ui, row_glyphs: &[char], font_size: f32) -> Option<c
mod preview { mod preview {
use crate::{ use crate::{
deck_state::DeckState, deck_state::DeckState,
ui::{Preview, PreviewConfig, View}, ui::{Preview, PreviewConfig},
}; };
use super::ConfigureDeckView; use super::ConfigureDeckView;
use notedeck::{App, AppContext};
pub struct ConfigureDeckPreview { pub struct ConfigureDeckPreview {
state: DeckState, state: DeckState,
@@ -314,8 +315,8 @@ mod preview {
} }
} }
impl View for ConfigureDeckPreview { impl App for ConfigureDeckPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, _app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
ConfigureDeckView::new(&mut self.state).ui(ui); ConfigureDeckView::new(&mut self.state).ui(ui);
} }
} }

View File

@@ -58,10 +58,11 @@ fn delete_button() -> impl Widget {
mod preview { mod preview {
use crate::{ use crate::{
deck_state::DeckState, deck_state::DeckState,
ui::{Preview, PreviewConfig, View}, ui::{Preview, PreviewConfig},
}; };
use super::EditDeckView; use super::EditDeckView;
use notedeck::{App, AppContext};
pub struct EditDeckPreview { pub struct EditDeckPreview {
state: DeckState, state: DeckState,
@@ -75,8 +76,8 @@ mod preview {
} }
} }
impl View for EditDeckPreview { impl App for EditDeckPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, _app_ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
EditDeckView::new(&mut self.state).ui(ui); EditDeckView::new(&mut self.state).ui(ui);
} }
} }

View File

@@ -1,11 +1,11 @@
use crate::draft::{Draft, Drafts}; use crate::draft::{Draft, Drafts};
use crate::post::NewPost; use crate::post::NewPost;
use crate::ui::{self, Preview, PreviewConfig, View}; use crate::ui::{self, Preview, PreviewConfig};
use crate::Result; use crate::Result;
use egui::widgets::text_edit::TextEdit; use egui::widgets::text_edit::TextEdit;
use egui::{Frame, Layout}; use egui::{Frame, Layout};
use enostr::{FilledKeypair, FullKeypair, NoteId, RelayPool}; use enostr::{FilledKeypair, FullKeypair, NoteId, RelayPool};
use nostrdb::{Config, Ndb, Transaction}; use nostrdb::{Ndb, Transaction};
use tracing::info; use tracing::info;
use notedeck::{ImageCache, NoteCache}; use notedeck::{ImageCache, NoteCache};
@@ -257,38 +257,31 @@ fn post_button(interactive: bool) -> impl egui::Widget {
mod preview { mod preview {
use super::*; use super::*;
use notedeck::{App, AppContext};
pub struct PostPreview { pub struct PostPreview {
ndb: Ndb,
img_cache: ImageCache,
note_cache: NoteCache,
draft: Draft, draft: Draft,
poster: FullKeypair, poster: FullKeypair,
} }
impl PostPreview { impl PostPreview {
fn new() -> Self { fn new() -> Self {
let ndb = Ndb::new(".", &Config::new()).expect("ndb");
PostPreview { PostPreview {
ndb,
img_cache: ImageCache::new(".".into()),
note_cache: NoteCache::default(),
draft: Draft::new(), draft: Draft::new(),
poster: FullKeypair::generate(), poster: FullKeypair::generate(),
} }
} }
} }
impl View for PostPreview { impl App for PostPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, app: &mut AppContext<'_>, ui: &mut egui::Ui) {
let txn = Transaction::new(&self.ndb).expect("txn"); let txn = Transaction::new(app.ndb).expect("txn");
PostView::new( PostView::new(
&self.ndb, app.ndb,
&mut self.draft, &mut self.draft,
PostType::New, PostType::New,
&mut self.img_cache, app.img_cache,
&mut self.note_cache, app.note_cache,
self.poster.to_filled(), self.poster.to_filled(),
) )
.ui(&txn, ui); .ui(&txn, ui);

View File

@@ -1,37 +1,26 @@
use crate::ui::View;
pub struct PreviewConfig { pub struct PreviewConfig {
pub is_mobile: bool, pub is_mobile: bool,
} }
pub trait Preview { pub trait Preview {
type Prev: View; type Prev: notedeck::App;
fn preview(cfg: PreviewConfig) -> Self::Prev; fn preview(cfg: PreviewConfig) -> Self::Prev;
} }
pub struct PreviewApp { pub struct PreviewApp {
view: Box<dyn View>, view: Box<dyn notedeck::App>,
}
impl<V> From<V> for PreviewApp
where
V: View + 'static,
{
fn from(v: V) -> Self {
PreviewApp::new(v)
}
} }
impl PreviewApp { impl PreviewApp {
pub fn new(view: impl View + 'static) -> PreviewApp { pub fn new(view: impl notedeck::App + 'static) -> PreviewApp {
let view = Box::new(view); let view = Box::new(view);
Self { view } Self { view }
} }
} }
impl eframe::App for PreviewApp { impl notedeck::App for PreviewApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { fn update(&mut self, app_ctx: &mut notedeck::AppContext<'_>, ui: &mut egui::Ui) {
egui::CentralPanel::default().show(ctx, |ui| self.view.ui(ui)); self.view.update(app_ctx, ui);
} }
} }

View File

@@ -0,0 +1,2 @@
// profile menu

View File

@@ -1,9 +1,10 @@
use crate::images::ImageType; use crate::images::ImageType;
use crate::ui::{Preview, PreviewConfig, View}; use crate::ui::{Preview, PreviewConfig};
use egui::{vec2, Sense, TextureHandle}; use egui::{vec2, Sense, TextureHandle};
use nostrdb::{Ndb, Transaction}; use nostrdb::{Ndb, Transaction};
use tracing::info;
use notedeck::ImageCache; use notedeck::{AppContext, ImageCache};
pub struct ProfilePic<'cache, 'url> { pub struct ProfilePic<'cache, 'url> {
cache: &'cache mut ImageCache, cache: &'cache mut ImageCache,
@@ -132,22 +133,62 @@ mod preview {
use std::collections::HashSet; use std::collections::HashSet;
pub struct ProfilePicPreview { pub struct ProfilePicPreview {
cache: ImageCache, keys: Option<Vec<ProfileKey>>,
ndb: Ndb,
keys: Vec<ProfileKey>,
} }
impl ProfilePicPreview { impl ProfilePicPreview {
fn new() -> Self { fn new() -> Self {
let config = Config::new(); ProfilePicPreview { keys: None }
let ndb = Ndb::new(".", &config).expect("ndb"); }
let txn = Transaction::new(&ndb).unwrap();
fn show(&mut self, app: &mut AppContext<'_>, ui: &mut egui::Ui) {
egui::ScrollArea::both().show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
let txn = Transaction::new(app.ndb).unwrap();
let keys = if let Some(keys) = &self.keys {
keys
} else {
return;
};
for key in keys {
let profile = app.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(app.img_cache, url).size(size))
.on_hover_ui_at_pointer(|ui| {
ui.set_max_width(300.0);
ui.add(ui::ProfilePreview::new(&profile, app.img_cache));
});
}
});
});
}
fn setup(&mut self, ndb: &Ndb) {
let txn = Transaction::new(ndb).unwrap();
let filters = vec![Filter::new().kinds(vec![0]).build()]; let filters = vec![Filter::new().kinds(vec![0]).build()];
let cache = ImageCache::new("cache/img".into());
let mut pks = HashSet::new(); let mut pks = HashSet::new();
let mut keys = HashSet::new(); let mut keys = HashSet::new();
for query_result in ndb.query(&txn, &filters, 2000).unwrap() { for query_result in ndb.query(&txn, &filters, 20000).unwrap() {
pks.insert(query_result.note.pubkey()); pks.insert(query_result.note.pubkey());
} }
@@ -170,44 +211,19 @@ mod preview {
keys.insert(profile.key().expect("should not be owned")); keys.insert(profile.key().expect("should not be owned"));
} }
let keys = keys.into_iter().collect(); let keys: Vec<ProfileKey> = keys.into_iter().collect();
ProfilePicPreview { cache, ndb, keys } info!("Loaded {} profiles", keys.len());
self.keys = Some(keys);
} }
} }
impl View for ProfilePicPreview { impl notedeck::App for ProfilePicPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, ctx: &mut AppContext<'_>, ui: &mut egui::Ui) {
egui::ScrollArea::both().show(ui, |ui| { if self.keys.is_none() {
ui.horizontal_wrapped(|ui| { self.setup(ctx.ndb);
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; self.show(ctx, ui)
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));
});
}
});
});
} }
} }

View File

@@ -6,7 +6,7 @@ use egui_extras::Size;
use enostr::{NoteId, Pubkey}; use enostr::{NoteId, Pubkey};
use nostrdb::{Ndb, ProfileRecord, Transaction}; use nostrdb::{Ndb, ProfileRecord, Transaction};
use notedeck::{DataPath, DataPathType, ImageCache, NotedeckTextStyle, UserAccount}; use notedeck::{ImageCache, NotedeckTextStyle, UserAccount};
pub struct ProfilePreview<'a, 'cache> { pub struct ProfilePreview<'a, 'cache> {
profile: &'a ProfileRecord<'a>, profile: &'a ProfileRecord<'a>,
@@ -147,21 +147,17 @@ impl egui::Widget for SimpleProfilePreview<'_, '_> {
mod previews { mod previews {
use super::*; use super::*;
use crate::test_data::test_profile_record; use crate::test_data::test_profile_record;
use crate::ui::{Preview, PreviewConfig, View}; use crate::ui::{Preview, PreviewConfig};
use notedeck::{App, AppContext};
pub struct ProfilePreviewPreview<'a> { pub struct ProfilePreviewPreview<'a> {
profile: ProfileRecord<'a>, profile: ProfileRecord<'a>,
cache: ImageCache,
} }
impl ProfilePreviewPreview<'_> { impl ProfilePreviewPreview<'_> {
pub fn new() -> Self { pub fn new() -> Self {
let profile = test_profile_record(); let profile = test_profile_record();
let path = DataPath::new("previews") ProfilePreviewPreview { profile }
.path(DataPathType::Cache)
.join(ImageCache::rel_dir());
let cache = ImageCache::new(path);
ProfilePreviewPreview { profile, cache }
} }
} }
@@ -171,9 +167,9 @@ mod previews {
} }
} }
impl View for ProfilePreviewPreview<'_> { impl App for ProfilePreviewPreview<'_> {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, app: &mut AppContext<'_>, ui: &mut egui::Ui) {
ProfilePreview::new(&self.profile, &mut self.cache).ui(ui); ProfilePreview::new(&self.profile, app.img_cache).ui(ui);
} }
} }

View File

@@ -184,6 +184,7 @@ fn get_connection_icon(status: &RelayStatus) -> egui::Image<'static> {
mod preview { mod preview {
use super::*; use super::*;
use crate::test_data::sample_pool; use crate::test_data::sample_pool;
use notedeck::{App, AppContext};
pub struct RelayViewPreview { pub struct RelayViewPreview {
pool: RelayPool, pool: RelayPool,
@@ -197,8 +198,8 @@ mod preview {
} }
} }
impl View for RelayViewPreview { impl App for RelayViewPreview {
fn ui(&mut self, ui: &mut egui::Ui) { fn update(&mut self, _app: &mut AppContext<'_>, ui: &mut egui::Ui) {
self.pool.try_recv(); self.pool.try_recv();
RelayView::new(RelayPoolManager::new(&mut self.pool)).ui(ui); RelayView::new(RelayPoolManager::new(&mut self.pool)).ui(ui);
} }

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# pass --mobile for mobile previews # pass --mobile for mobile previews
RUST_LOG=info cargo run --bin ui_preview --release -- "$@" #RUST_LOG=info cargo run --bin ui_preview --features profiling --release -- "$@"
cargo run --bin ui_preview --release -- "$@"