Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/src-tauri/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,18 @@
const LONG_ENOUGH_TO_PAINT: std::time::Duration = std::time::Duration::from_millis(1500);

fn build_settings<R: Runtime>(app: &AppHandle<R>, theme: Theme, page: Option<&str>) {
let url = page.map_or_else(tauri::WebviewUrl::default, |page| {
tauri::WebviewUrl::App(format!("index.html#{page}").into())
});
let builder = hidden(app, SETTINGS, url, theme)
.inner_size(780.0, 560.0)
.min_inner_size(640.0, 480.0)
.resizable(true);
.resizable(true)
// WebView2 keeps the page's own drag and drop for itself while files may be dropped.
.disable_drag_drop_handler();
if let Ok(window) = builder.build() {
dressed(&window, theme);
}

Check warning on line 124 in app/src-tauri/src/shell.rs

View workflow job for this annotation

GitHub Actions / settings / the lines this branch changed

Missed mutant

replace build_settings with ()
}

/// Over settings on a first run, and again whenever the person asks for it there.
Expand Down
48 changes: 47 additions & 1 deletion app/src/settings/Browsers.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { render, screen, within } from "@testing-library/react";
import { createEvent, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import Browsers from "./Browsers";

const invoke = vi.fn();

function dragOver(row: Element, clientY: number) {
const over = createEvent.dragOver(row);
Object.defineProperty(over, "clientY", { value: clientY });
fireEvent(row, over);
}
vi.mock("@tauri-apps/api/core", () => ({ invoke: (...a: unknown[]) => invoke(...a) }));

const CHROME = {
Expand Down Expand Up @@ -99,6 +105,46 @@ describe("browsers", () => {
});
});

it("drops a dragged browser above the one it lands on", async () => {
answers([MINE, CHROME, EDGE, ODD]);
render(<Browsers />);
const odd = (await screen.findByText("Navegador raro")).closest("[draggable]") as Element;
const chrome = screen.getByText("Google Chrome").closest("[draggable]") as Element;
fireEvent.dragStart(odd);
dragOver(chrome, 0);
fireEvent.drop(chrome);
expect(invoke).toHaveBeenCalledWith("browsers_reorder", {
ids: [MINE.id, ODD.id, CHROME.id, EDGE.id],
});
});

it("drops below the one it lands on when let go over its lower half", async () => {
answers([MINE, CHROME, EDGE, ODD]);
render(<Browsers />);
const chrome = (await screen.findByText("Google Chrome")).closest("[draggable]") as Element;
const edge = screen.getByText("Microsoft Edge").closest("[draggable]") as Element;
vi.spyOn(edge, "getBoundingClientRect").mockReturnValue(new DOMRect(0, -40, 300, 40));
fireEvent.dragStart(chrome);
dragOver(edge, 0);
fireEvent.drop(edge);
expect(invoke).toHaveBeenCalledWith("browsers_reorder", {
ids: [MINE.id, EDGE.id, CHROME.id, ODD.id],
});
});

it("keeps a dragged browser in its own section", async () => {
answers([MINE, CHROME, EDGE, ODD]);
render(<Browsers />);
const mine = (await screen.findByText("Chrome sin extensiones")).closest(
"[draggable]",
) as Element;
const chrome = screen.getByText("Google Chrome").closest("[draggable]") as Element;
fireEvent.dragStart(mine);
dragOver(chrome, 0);
fireEvent.drop(chrome);
expect(invoke).not.toHaveBeenCalledWith("browsers_reorder", expect.anything());
});

it("does not offer to move the first of a section above a browser in the other", async () => {
answers([MINE, CHROME, EDGE, ODD]);
render(<Browsers />);
Expand Down
62 changes: 53 additions & 9 deletions app/src/settings/Browsers.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useState } from "react";
import { type DragEvent, useCallback, useEffect, useState } from "react";
import { type Key, useSpoken, useWords } from "../i18n";
import { saidPlainly } from "../refusal";
import Confirm from "./Confirm";
Expand Down Expand Up @@ -309,6 +309,14 @@ function Form({
const GHOST =
"grid h-6 w-6 shrink-0 place-items-center rounded text-neutral-500 hover:bg-black/[0.06] disabled:opacity-25 dark:text-[#8B92A1] dark:hover:bg-white/[0.08]";

const ROW =
"group flex cursor-grab items-center gap-3 border-black/[0.08] px-3.5 py-3 transition-[opacity,box-shadow] duration-150 not-first:border-t active:cursor-grabbing dark:border-white/[0.08]";

const LANDS_BEFORE = "shadow-[inset_0_2px_0_#2F62D8] dark:shadow-[inset_0_2px_0_#6E9BFF]";
const LANDS_AFTER = "shadow-[inset_0_-2px_0_#2F62D8] dark:shadow-[inset_0_-2px_0_#6E9BFF]";

type Landing = { id: string; after: boolean };

export default function Browsers() {
const t = useWords();
const language = useSpoken();
Expand All @@ -318,6 +326,8 @@ export default function Browsers() {
const [asking, setAsking] = useState<BrowserView | null>(null);
const [rescanning, setRescanning] = useState(false);
const [counted, setCounted] = useState<string | null>(null);
const [carried, setCarried] = useState<string | null>(null);
const [landing, setLanding] = useState<Landing | null>(null);

const run = useCallback(
(command: string, params: Record<string, unknown> = {}) => {
Expand Down Expand Up @@ -352,6 +362,46 @@ export default function Browsers() {
run("browsers_reorder", { ids: order });
};

const land = (id: string, { id: target, after }: Landing) => {
const order = list.map((b) => b.id).filter((o) => o !== id);
order.splice(order.indexOf(target) + (after ? 1 : 0), 0, id);
if (order.every((o, i) => o === list[i]?.id)) return;
run("browsers_reorder", { ids: order });
};

const letGo = () => {
setCarried(null);
setLanding(null);
};

const landsOn = (id: string) => {
if (landing?.id !== id) return "";
return landing.after ? LANDS_AFTER : LANDS_BEFORE;
};

const carry = (b: BrowserView, within: BrowserView[]) => ({
draggable: true,
onDragStart: (e: DragEvent<HTMLDivElement>) => {
e.dataTransfer?.setData("text/plain", b.id);
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
setCarried(b.id);
},
onDragEnd: letGo,
onDragOver: (e: DragEvent<HTMLDivElement>) => {
if (!carried || carried === b.id || !within.some((o) => o.id === carried)) return;
e.preventDefault();
const box = e.currentTarget.getBoundingClientRect();
const after = e.clientY > box.top + box.height / 2;
if (landing?.id !== b.id || landing.after !== after) setLanding({ id: b.id, after });
},
onDrop: (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
if (carried && landing) land(carried, landing);
letGo();
},
className: [ROW, carried === b.id ? "opacity-40" : "", landsOn(b.id)].join(" "),
});

const detected = list.filter((b) => !b.custom);
const mine = list.filter((b) => b.custom);

Expand Down Expand Up @@ -421,10 +471,7 @@ export default function Browsers() {
onSave={(edit) => run("browsers_update", { id: b.id, edit })}
/>
) : (
<div
key={b.id}
className="group flex items-center gap-3 border-black/[0.08] px-3.5 py-3 not-first:border-t dark:border-white/[0.08]"
>
<div key={b.id} {...carry(b, detected)}>
<Icon browser={b} />
<div className="min-w-0 flex-1">
<p className={`text-[12.5px] ${b.hidden ? "opacity-55" : ""}`}>{b.name}</p>
Expand Down Expand Up @@ -507,10 +554,7 @@ export default function Browsers() {
onSave={(edit) => run("browsers_update", { id: b.id, edit })}
/>
) : (
<div
key={b.id}
className="group flex items-center gap-3 border-black/[0.08] px-3.5 py-3 not-first:border-t dark:border-white/[0.08]"
>
<div key={b.id} {...carry(b, mine)}>
<Icon browser={b} />
<div className="min-w-0 flex-1">
<p className={`truncate text-[12.5px] ${b.hidden ? "opacity-55" : ""}`}>
Expand Down
132 changes: 119 additions & 13 deletions crates/linkunbound-shell/src/mascot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use linkunbound_shell::{BearHead, BearPaws, Look, Palette, Picker};
use slint::ComponentHandle;
use slint::winit_030::winit::event::WindowEvent;
use slint::winit_030::{EventResult, WinitWindowAccessor};

/// Sizes in logical pixels: the head, how far it rises over the edge, a paw, the room between
/// the paws, and where across the picker the head is centred.
Expand Down Expand Up @@ -74,30 +76,45 @@
self.paws.set_gap(pose.gap);
// Measured from what the look asks for, not from the window: right after a change of
// look or place the window still reports the size and spot it had before.
let window = picker.window();
let scale = placing_scale(window);
let (x, y) = self.anchor.get().unwrap_or_else(|| where_it_is(window));
let at = self
.anchor
.get()
.unwrap_or_else(|| where_it_is(picker.window()));
self.lean_on(pose, picker, at);
self.mood(0.0, picker.get_private_on());
let _ = self.head.show();
let _ = self.paws.show();
stack(&self.head, &self.paws, picker);
}

/// The picker was carried off: the bear goes along, keeping the mood it had.
pub fn shift(&self, picker: &Picker, at: (i32, i32)) {
let Some(pose) = pose(picker) else { return };
if !self.head.window().is_visible() {
return;
}
self.anchor.set(Some(at));
self.lean_on(pose, picker, at);
}

fn lean_on(&self, pose: &Pose, picker: &Picker, at: (i32, i32)) {
let (head, paws) = spots(
pose,
(x, y),
at,
picker.get_wanted_width(),
picker.get_halo(),
scale,
placing_scale(picker.window()),
);
put(
self.head.window(),
head,
(self.head.get_wide(), self.head.get_tall()),
);
put(
self.paws.window(),
paws,
(self.paws.get_wide(), self.paws.get_tall()),
);

Check warning on line 117 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace Mascot::lean_on with ()
self.mood(0.0, picker.get_private_on());
let _ = self.head.show();
let _ = self.paws.show();
stack(&self.head, &self.paws, picker);
}

pub fn mood(&self, aim: f32, masked: bool) {
Expand Down Expand Up @@ -142,7 +159,10 @@
}

fn where_it_is(window: &slint::Window) -> (i32, i32) {
let at = window.position();
in_placing_units(window, window.position())

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (-1, -1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (-1, 1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (-1, 0)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (1, -1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (1, 1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (1, 0)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (0, -1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (0, 1)

Check warning on line 162 in crates/linkunbound-shell/src/mascot.rs

View workflow job for this annotation

GitHub Actions / crates / the lines this branch changed

Missed mutant

replace where_it_is -> (i32, i32) with (0, 0)
}

fn in_placing_units(window: &slint::Window, at: slint::PhysicalPosition) -> (i32, i32) {
if cfg!(target_os = "macos") {
let at = at.to_logical(window.scale_factor());
(at.x.round() as i32, at.y.round() as i32)
Expand All @@ -166,8 +186,8 @@
}
}

/// The picker says where the bear should look and whether it wears the mask, and an empty slot
/// sends the person to settings to fill it.
/// The picker says where the bear should look and whether it wears the mask, an empty slot
/// sends the person to settings to fill it, and the head carries the picker with the bear along.
pub fn listen(picker: &Picker) {
picker.on_mood(|aim, masked| {
if let Some(ui) = crate::ui() {
Expand All @@ -181,6 +201,37 @@
}
crate::run_settings(&[linkunbound_core::BROWSERS]);
});
let handle = picker.as_weak();
picker.on_grabbed(move || {
if let Some(picker) = handle.upgrade() {
carry(&picker);
}
});
let handle = picker.as_weak();
picker
.window()
.on_winit_window_event(move |_, event| bear_follows(&handle, event));
}

fn bear_follows(picker: &slint::Weak<Picker>, event: &WindowEvent) -> EventResult {
if let WindowEvent::Moved(at) = event
&& let (Some(picker), Some(ui)) = (picker.upgrade(), crate::ui())
{
let at = in_placing_units(picker.window(), slint::PhysicalPosition::new(at.x, at.y));
ui.mascot.shift(&picker, at);
}
EventResult::Propagate
}

fn carry(picker: &Picker) {
let window = picker.window();
let _ = window.with_winit_window(|winit| winit.drag_window());
// AppKit swallows the release that ends the drag, and the head would keep the pointer.
#[cfg(target_os = "macos")]
let _ = window.dispatch_event_with_result(slint::platform::WindowEvent::PointerReleased {
position: slint::LogicalPosition::new(0.0, 0.0),
button: slint::platform::PointerEventButton::Left,
});
}

#[cfg(windows)]
Expand Down Expand Up @@ -220,9 +271,11 @@

#[cfg(test)]
mod tests {
use super::{BEAR, COMPACT, Mascot, rise, spots};
use super::{BEAR, COMPACT, Mascot, bear_follows, listen, rise, spots};
use linkunbound_shell::{Look, Palette, Picker};
use slint::ComponentHandle;
use slint::winit_030::EventResult;
use slint::winit_030::winit::{dpi::PhysicalPosition, event::WindowEvent};

fn picker(look: Look, clear: bool) -> Picker {
let picker = Picker::new().expect("a window");
Expand Down Expand Up @@ -266,6 +319,59 @@
assert!(!mascot.paws.window().is_visible());
}

fn carried_to(picker: &Picker, x: i32, y: i32) -> EventResult {
bear_follows(
&picker.as_weak(),
&WindowEvent::Moved(PhysicalPosition::new(x, y)),
)
}

#[test]
fn the_bear_goes_where_the_picker_is_carried() {
let ui = crate::tests::headless_ui();
ui.picker.set_look(Look::Bear);
ui.picker.global::<Palette>().set_clear(true);
ui.mascot.follow(&ui.picker);
ui.mascot.mood(0.7, true);

assert!(matches!(
carried_to(&ui.picker, 400, 500),
EventResult::Propagate
));
assert_eq!(ui.mascot.anchor.get(), Some((400, 500)));
assert_eq!(ui.mascot.head.get_look(), 0.7, "the mood stays as it was");
assert!(ui.mascot.head.get_masked());
}

#[test]
fn a_bear_that_is_not_out_stays_where_it_was() {
let ui = crate::tests::headless_ui();
ui.picker.set_look(Look::Bear);
ui.picker.global::<Palette>().set_clear(true);
carried_to(&ui.picker, 400, 500);
assert_eq!(ui.mascot.anchor.get(), None, "never shown");

ui.mascot.anchor(10, 20);
ui.mascot.follow(&ui.picker);
ui.picker.set_look(Look::List);
carried_to(&ui.picker, 900, 100);
assert_eq!(ui.mascot.anchor.get(), Some((10, 20)), "a look without it");

ui.picker.set_look(Look::Bear);
bear_follows(&ui.picker.as_weak(), &WindowEvent::Focused(true));
assert_eq!(ui.mascot.anchor.get(), Some((10, 20)), "not a move");
}

#[test]
fn grabbing_the_head_without_a_system_window_moves_nothing() {
i_slint_backend_testing::init_no_event_loop();
let picker = Picker::new().expect("a window");
listen(&picker);
let before = picker.window().position();
picker.invoke_grabbed();
assert_eq!(picker.window().position(), before);
}

/// The head stands over the middle of the sheet and rises its pose's height over it, the paws
/// on the edge, whatever the scale the picker was placed at.
#[test]
Expand Down
9 changes: 8 additions & 1 deletion crates/linkunbound-shell/ui/looks.slint
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Destination, Palette, KeyCap, Badge, Tools } from "parts.slint";
import { Destination, Palette, KeyCap, Badge, Tools, Grip } from "parts.slint";

// The rows: key, icon, name, profile; nine on screen and the rest scroll under them.
export component ListLook inherits Rectangle {
Expand Down Expand Up @@ -279,8 +279,15 @@ export component CompactLook inherits Rectangle {
callback copy();
callback close();
callback turn-reach();
callback grabbed();
property <int> aimed: root.hovered-at >= 0 ? root.hovered-at : root.chosen-at;

Grip {
height: 40px;
y: 0;
grabbed => { root.grabbed(); }
}

VerticalLayout {
padding-left: 10px;
padding-right: 10px;
Expand Down
Loading
Loading