1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
|
use std::sync::Arc;
use adw::prelude::*;
use gtk::GridLayoutChild;
use relm4::{gtk, prelude::{AsyncComponent, AsyncComponentController, AsyncComponentParts, AsyncController, ComponentController, Controller}, AsyncComponentSender, Component, RelmWidgetExt};
pub mod components {
pub(crate) mod smart_summary;
pub(crate) use smart_summary::{
SmartSummaryButton, Output as SmartSummaryOutput, Input as SmartSummaryInput
};
}
mod widgets;
pub mod secrets;
pub mod micropub;
pub mod util;
pub const APPLICATION_ID: &str = "xyz.vikanezrimaya.kittybox.Bowl";
pub const VISIBILITY: [&str; 2] = ["public", "private"];
#[tracker::track]
#[derive(Debug)]
pub struct PostComposerModel {
/// Busy guard for generating the summary using an LLM.
/// Makes the summary field read-only and blocks the Smart Summary button.
#[no_eq] smart_summary_busy_guard: Option<gtk::gio::ApplicationBusyGuard>,
#[no_eq] submit_busy_guard: Option<gtk::gio::ApplicationBusyGuard>,
#[do_not_track] name_buffer: gtk::EntryBuffer,
#[do_not_track] summary_buffer: gtk::EntryBuffer,
#[do_not_track] content_buffer: gtk::TextBuffer,
#[do_not_track] wide_layout: gtk::GridLayout,
#[do_not_track] narrow_layout: gtk::BoxLayout,
#[do_not_track] micropub: Arc<micropub::Client>,
#[do_not_track] smart_summary: Controller<components::SmartSummaryButton>,
}
impl PostComposerModel {
fn busy_changed(&self) -> bool {
self.changed(Self::submit_busy_guard() | Self::smart_summary_busy_guard())
}
fn busy(&self) -> bool {
self.submit_busy_guard.is_some() || self.smart_summary_busy_guard.is_some()
}
}
#[derive(Debug)]
#[allow(private_interfaces)]
pub enum PostComposerInput {
#[doc(hidden)] SmartSummary(components::smart_summary::Output),
Submit,
}
#[derive(Debug)]
pub enum PostComposerCommandOutput {
}
#[relm4::component(pub async)]
impl AsyncComponent for PostComposerModel {
/// The type of the messages that this component can receive.
type Input = PostComposerInput;
/// The type of the messages that this component can send.
type Output = ();
/// The type of data with which this component will be initialized.
type Init = micropub::Client;
/// The type of the command outputs that this component can receive.
type CommandOutput = PostComposerCommandOutput;
view! {
#[root]
adw::ApplicationWindow {
set_title: Some("Create post"),
set_width_request: 360,
set_height_request: 480,
adw::ToolbarView {
add_top_bar: &{
relm4::view! {
send_button = gtk::Button {
set_label: "Post",
connect_clicked => Self::Input::Submit,
#[track = "model.busy_changed()"]
set_sensitive: !model.busy(),
},
bar = adw::HeaderBar::new() {
pack_end: &send_button,
},
}
bar
},
#[name = "toast_overlay"]
adw::ToastOverlay {
#[name = "content_wrapper"]
adw::BreakpointBin {
set_width_request: 360,
set_height_request: 480,
#[name = "content"]
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_spacing: 5,
set_margin_all: 5,
#[name = "name_label"]
gtk::Label {
set_markup: "Name",
set_margin_vertical: 10,
set_margin_horizontal: 10,
set_halign: gtk::Align::Start,
set_valign: gtk::Align::Start,
},
#[name = "name_field"]
gtk::Entry {
set_hexpand: true,
set_buffer: &model.name_buffer,
#[track = "model.changed(Self::submit_busy_guard())"]
set_sensitive: model.submit_busy_guard.is_none(),
},
#[name = "summary_label"]
gtk::Label {
set_markup: "Summary",
set_margin_vertical: 10,
set_margin_horizontal: 10,
set_halign: gtk::Align::Start,
set_valign: gtk::Align::Start,
},
#[name = "summary_field"]
gtk::Box {
set_orientation: gtk::Orientation::Horizontal,
add_css_class: "linked",
gtk::Entry {
set_hexpand: true,
set_buffer: &model.summary_buffer,
#[track = "model.busy_changed()"]
set_sensitive: !model.busy(),
},
model.smart_summary.widget(),
},
#[name = "tag_label"]
gtk::Label {
set_markup: "Tags",
set_margin_vertical: 10,
set_margin_horizontal: 10,
set_halign: gtk::Align::Start,
set_valign: gtk::Align::Start,
},
#[name = "tag_holder"]
// TODO: tag component (because of complex logic)
gtk::Box {
add_css_class: "frame",
set_hexpand: true,
set_orientation: gtk::Orientation::Horizontal,
set_spacing: 5,
set_height_request: 36,
},
#[name = "content_label"]
gtk::Label {
set_markup: "Content",
set_halign: gtk::Align::Start,
set_valign: gtk::Align::Start,
set_margin_vertical: 10,
set_margin_horizontal: 10,
},
#[name = "content_textarea"]
gtk::ScrolledWindow {
set_vexpand: true,
gtk::TextView {
set_buffer: Some(&model.content_buffer),
set_hexpand: true,
#[iterate]
add_css_class: &["frame", "view"],
set_monospace: true,
set_wrap_mode: gtk::WrapMode::Word,
set_vscroll_policy: gtk::ScrollablePolicy::Natural,
set_left_margin: 8,
set_right_margin: 8,
set_top_margin: 8,
set_bottom_margin: 8,
#[track = "model.changed(Self::submit_busy_guard())"]
set_sensitive: model.submit_busy_guard.is_none(),
}
},
#[name = "misc_prop_wrapper"]
gtk::Box {
set_hexpand: true,
gtk::FlowBox {
set_hexpand: false,
set_orientation: gtk::Orientation::Horizontal,
set_homogeneous: false,
set_column_spacing: 0,
set_min_children_per_line: 2,
set_max_children_per_line: 6,
set_selection_mode: gtk::SelectionMode::None,
append = >k::Box {
set_spacing: 5,
#[name = "visibility_label"]
gtk::Label {
set_markup: "Visibility",
set_halign: gtk::Align::Start,
set_valign: gtk::Align::Start,
set_margin_vertical: 10,
set_margin_horizontal: 10,
},
#[name = "visibility_selector"]
gtk::DropDown {
set_model: Some(>k::StringList::new(&VISIBILITY)),
set_hexpand: false,
#[track = "model.changed(Self::submit_busy_guard())"]
set_sensitive: model.submit_busy_guard.is_none(),
},
},
},
},
},
add_breakpoint = adw::Breakpoint::new(
adw::BreakpointCondition::new_length(
adw::BreakpointConditionLengthType::MinWidth,
512.0,
adw::LengthUnit::Px
)
) {
add_setter: (&content, "layout_manager", Some(&model.wide_layout.to_value())),
add_setter: (&name_label, "halign", Some(>k::Align::End.to_value())),
add_setter: (&summary_label, "halign", Some(>k::Align::End.to_value())),
add_setter: (&tag_label, "halign", Some(>k::Align::End.to_value())),
add_setter: (&content_label, "halign", Some(>k::Align::End.to_value())),
},
}
}
}
}
}
/// Initialize the UI and model.
async fn init(
init: Self::Init,
window: Self::Root,
sender: AsyncComponentSender<Self>,
) -> AsyncComponentParts<Self> {
let content_buffer = gtk::TextBuffer::default();
let model = PostComposerModel {
smart_summary_busy_guard: None,
submit_busy_guard: None,
name_buffer: gtk::EntryBuffer::default(),
summary_buffer: gtk::EntryBuffer::default(),
content_buffer: content_buffer.clone(),
wide_layout: gtk::GridLayout::new(),
narrow_layout: gtk::BoxLayout::new(gtk::Orientation::Vertical),
micropub: Arc::new(init),
smart_summary: components::SmartSummaryButton::builder()
.launch(())
.forward(sender.input_sender(), PostComposerInput::SmartSummary),
tracker: Default::default()
};
let widgets = view_output!();
#[cfg(debug_assertions)]
window.add_css_class("devel");
let layout = &model.wide_layout;
widgets.content.set_layout_manager(Some(layout.clone()));
layout.set_column_homogeneous(false);
layout.set_row_spacing(10);
enum Row<'a> {
TwoColumn(&'a gtk::Label, &'a gtk::Widget),
Span(&'a gtk::Widget)
}
for (row, content) in [
Row::TwoColumn(&widgets.name_label, widgets.name_field.upcast_ref::<gtk::Widget>()),
Row::TwoColumn(&widgets.summary_label, widgets.summary_field.upcast_ref::<gtk::Widget>()),
Row::TwoColumn(&widgets.tag_label, widgets.tag_holder.upcast_ref::<gtk::Widget>()),
Row::TwoColumn(&widgets.content_label, widgets.content_textarea.upcast_ref::<gtk::Widget>()),
Row::Span(widgets.misc_prop_wrapper.upcast_ref::<gtk::Widget>()),
].into_iter().enumerate() {
match content {
Row::TwoColumn(label, field) => {
let label_layout = layout.layout_child(label)
.downcast::<GridLayoutChild>()
.unwrap();
label_layout.set_row(row as i32);
label_layout.set_column(0);
let field_layout = layout.layout_child(field)
.downcast::<GridLayoutChild>()
.unwrap();
field_layout.set_row(row as i32);
field_layout.set_column(1);
},
Row::Span(widget) => {
let widget_layout = layout.layout_child(widget)
.downcast::<GridLayoutChild>()
.unwrap();
widget_layout.set_row(row as i32);
widget_layout.set_column_span(2);
}
}
}
widgets.content.set_layout_manager(Some(model.narrow_layout.clone()));
AsyncComponentParts { model, widgets }
}
async fn update_with_view(
&mut self,
widgets: &mut Self::Widgets,
message: Self::Input,
sender: AsyncComponentSender<Self>,
root: &Self::Root
) {
self.reset(); // Reset the tracker
match message {
PostComposerInput::SmartSummary(components::SmartSummaryOutput::Start) => {
widgets.content_textarea.set_sensitive(false);
if self.content_buffer.char_count() == 0 {
let _ = self.smart_summary.sender().send(
components::SmartSummaryInput::Cancel
);
} else {
let text = self.content_buffer.text(
&self.content_buffer.start_iter(),
&self.content_buffer.end_iter(),
false
);
self.set_smart_summary_busy_guard(
Some(relm4::main_adw_application().mark_busy())
);
if self.smart_summary.sender().send(
components::SmartSummaryInput::Text(text.into())
).is_ok() {
self.summary_buffer.set_text("");
}
}
widgets.content_textarea.set_sensitive(true);
},
PostComposerInput::SmartSummary(components::SmartSummaryOutput::Chunk(text)) => {
self.summary_buffer.insert_text(self.summary_buffer.length(), text);
},
PostComposerInput::SmartSummary(components::SmartSummaryOutput::Done) => {
self.set_smart_summary_busy_guard(None);
}
PostComposerInput::SmartSummary(components::SmartSummaryOutput::Error(err)) => {
self.set_smart_summary_busy_guard(None);
let toast = adw::Toast::new(&format!("Smart Summary error: {}", err));
toast.set_timeout(0);
toast.set_priority(adw::ToastPriority::High);
widgets.toast_overlay.add_toast(toast);
},
PostComposerInput::Submit => {
if self.content_buffer.char_count() == 0 {
self.update_view(widgets, sender);
return
}
self.set_submit_busy_guard(
Some(relm4::main_adw_application().mark_busy())
);
// Update view to lock the interface up
self.update_view(widgets, sender.clone());
self.reset();
use microformats::types::{Item, Class, KnownClass, PropertyValue};
let mut mf2 = Item::new(vec![Class::Known(KnownClass::Entry)]);
if self.name_buffer.length() > 0 {
let proplist = mf2.properties.entry("name".to_owned()).or_default();
proplist.push(PropertyValue::Plain(self.name_buffer.text().into()));
}
if self.summary_buffer.length() > 0 {
let proplist = mf2.properties.entry("summary".to_owned()).or_default();
proplist.push(PropertyValue::Plain(self.summary_buffer.text().into()));
}
// TODO: tags
{
let proplist = mf2.properties.entry("content".to_owned()).or_default();
proplist.push(PropertyValue::Plain(self.content_buffer.text(
&self.content_buffer.start_iter(),
&self.content_buffer.end_iter(),
false
).into()));
}
{
let proplist = mf2.properties.entry("visibility".to_owned()).or_default();
let selected = VISIBILITY[widgets.visibility_selector.selected() as usize];
proplist.push(PropertyValue::Plain(selected.to_owned()));
}
match self.micropub.send_post(mf2).await {
Ok(location) => {
self.name_buffer.set_text("");
self.summary_buffer.set_text("");
// TODO: tags
self.content_buffer.set_text("");
let toast = adw::Toast::new("Post submitted");
toast.set_button_label(Some("Open"));
toast.connect_button_clicked(glib::clone!(#[strong] root, move |toast| {
gtk::UriLauncher::new(&location.to_string()).launch(
Some(root.upcast_ref::<gtk::ApplicationWindow>()),
None::<&gio::Cancellable>,
glib::clone!(#[weak] toast, move |result| {
if let Err(err) = result {
log::warn!("Error opening post URI: {}", err);
} else {
toast.dismiss()
}
})
);
}));
widgets.toast_overlay.add_toast(toast);
},
Err(err) => {
log::warn!("Error sending post: {}", err);
let toast = adw::Toast::new(&format!("Error sending post: {}", err));
toast.set_timeout(0);
toast.set_priority(adw::ToastPriority::High);
widgets.toast_overlay.add_toast(toast);
}
}
self.set_submit_busy_guard(None);
},
}
self.update_view(widgets, sender);
}
}
|