Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/sites.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Site options such as `tls` and `handle_errors` aren't supported, and neither is
## Listing sites

:::app
**Settings → Sites** lists every linked and parked site with its domain and a lock when it's secured. Select one to see its PHP and Node versions, domains and server. Sites from a project folder carry a **Project folder** badge. The **Sites** section of the Flock panel lists them too: click one to open it in your browser.
**Settings → Sites** lists every linked and parked site with its domain and a lock when it's secured. Select one to see its PHP and Node versions, domains and server. Sites from a project folder carry a **Project folder** badge. The **Sites** section of the Flock panel lists them too: click one to open it in your browser. To keep the panel short, switch on **Hide sites in the menu bar panel** in **Settings → General** (**Hide sites in the panel** on Windows). On Linux, **Hide sites in the tray menu** in **General** leaves out the tray menu's **Sites** submenu.
:::

:::cli
Expand Down
16 changes: 16 additions & 0 deletions linux/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use gtk::{gio, glib};
use crate::api::{Client, Error, SettingsChange, Status};
use crate::installation;
use crate::links::Link;
use crate::prefs;

/// How often the daemon is asked for its status.
const POLL_INTERVAL: Duration = Duration::from_secs(2);
Expand All @@ -31,15 +32,30 @@ pub struct AppModel {
listeners: RefCell<Vec<Rc<dyn Fn()>>>,
/// Worktrees whose job a progress dialog follows, by folder: their failures aren't notified.
followed_worktrees: RefCell<HashSet<String>>,
/// Whether the tray menu leaves out the Sites submenu, from the preferences.
hides_sites: Cell<bool>,
}

impl AppModel {
pub fn new() -> Rc<Self> {
let model = Rc::new(Self::default());
model.needs_setup.set(installation::needs_setup());
model.hides_sites.set(prefs::load().hide_sites);
model
}

pub fn hides_sites(&self) -> bool {
self.hides_sites.get()
}

/// Shows or hides the Sites submenu in the tray menu, and remembers it in the preferences.
pub fn set_hides_sites(&self, hide: bool) -> std::io::Result<()> {
prefs::set_hide_sites(hide)?;
self.hides_sites.set(hide);
self.changed();
Ok(())
}

pub fn status(&self) -> Option<Status> {
self.status.borrow().clone()
}
Expand Down
28 changes: 26 additions & 2 deletions linux/src/panes/general.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! General: the daemon, the domain, the data folder, opening at login, updates and the project
//! folders.
//! General: the daemon, the domain, the data folder, opening at login, the tray menu, updates and
//! the project folders.

use std::cell::RefCell;
use std::rc::Rc;
Expand Down Expand Up @@ -105,6 +105,29 @@ impl GeneralPane {
group
}

fn tray(&self) -> adw::PreferencesGroup {
let group = group("Tray", "");
let row = adw::SwitchRow::builder()
.title("Hide sites in the tray menu")
.subtitle("The Sites page still lists them.")
.active(self.model.hides_sites())
.build();
let (model, banner) = (self.model.clone(), self.banner.clone());
row.connect_active_notify(move |row| {
let on = row.is_active();
// Also the switch going back after a failed save.
if on == model.hides_sites() {
return;
}
if let Err(e) = model.set_hides_sites(on) {
report(&banner, Some(format!("Could not change the tray setting: {e}")));
row.set_active(!on);
}
});
group.add(&row);
group
}

/// Linux apps don't update themselves: the flockphp package comes with the system's updates.
fn updates(&self, config: &Config, status: &Status) -> adw::PreferencesGroup {
let group = group("Updates", "");
Expand Down Expand Up @@ -242,6 +265,7 @@ impl Pane for GeneralPane {
groups.push(self.network(config, &status).upcast());
groups.push(self.data(config).upcast());
groups.push(self.startup().upcast());
groups.push(self.tray().upcast());
groups.push(self.updates(config, &status).upcast());
groups.push(self.project_folders(config).upcast());
}
Expand Down
25 changes: 25 additions & 0 deletions linux/src/prefs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub struct Prefs {
pub editor: String,
/// The sites whose worktrees the Sites list shows, by name; the others are collapsed.
pub expanded_sites: Vec<String>,
/// Leaves the Sites submenu out of the tray menu (General → Tray).
pub hide_sites: bool,
}

/// Editors the Dumps window can open files in: id, name and URL scheme ("" for none).
Expand Down Expand Up @@ -50,7 +52,30 @@ pub fn set_expanded(site: &str, expanded: bool) {
let _ = save(&prefs);
}

/// Remembers whether the tray menu leaves out the Sites submenu.
pub fn set_hide_sites(hide: bool) -> std::io::Result<()> {
let mut prefs = load();
prefs.hide_sites = hide;
save(&prefs)
}

pub fn save(prefs: &Prefs) -> std::io::Result<()> {
std::fs::create_dir_all(dir())?;
std::fs::write(file(), serde_json::to_vec_pretty(prefs).expect("prefs"))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn shows_sites_unless_the_preference_says_otherwise() {
// app.json from before the preference existed.
let prefs: Prefs = serde_json::from_str(r#"{"editor":"zed","expanded_sites":["acme"]}"#).unwrap();
assert!(!prefs.hide_sites);
assert!(!Prefs::default().hide_sites);

let saved = serde_json::to_vec(&Prefs { hide_sites: true, ..Default::default() }).unwrap();
assert!(serde_json::from_slice::<Prefs>(&saved).unwrap().hide_sites);
}
}
37 changes: 36 additions & 1 deletion linux/src/tray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ struct State {
running: bool,
/// The sites, each with its worktrees; problems are in the main window.
sites: Vec<SiteItem>,
/// The Sites submenu is left out (General → Tray).
hide_sites: bool,
/// The proxies (`flock proxy`), after the sites.
proxies: Vec<SiteItem>,
mail_count: u32,
Expand All @@ -71,6 +73,7 @@ impl State {
warning: status.as_ref().and_then(|s| s.warnings.first().cloned()),
needs_setup,
sites: status.as_ref().map(SiteItem::all).unwrap_or_default(),
hide_sites: model.hides_sites(),
proxies: status.as_ref().map(|s| s.proxies.iter().map(SiteItem::proxy).collect()).unwrap_or_default(),
mail_count: status.as_ref().map_or(0, |s| s.mail_count),
dump_count: status.as_ref().map_or(0, |s| s.dump_count),
Expand Down Expand Up @@ -251,7 +254,7 @@ impl ksni::Tray for FlockTray {
items.extend([item("Set Up Flock…", || Command::Open("setup")), MenuItem::Separator]);
} else {
items.extend([item("Open Flock", || Command::Show), MenuItem::Separator]);
if self.state.running {
if self.state.running && !self.state.hide_sites {
items.push(self.sites());
}
items.extend([
Expand Down Expand Up @@ -376,4 +379,36 @@ mod tests {
.unwrap();
assert_eq!(SiteItem::proxy(&started.proxies[0]).label, "admin.test · Starting…");
}

/// The labels of the menu's submenus.
fn submenus(hide_sites: bool) -> Vec<String> {
let state = State {
icon: "",
headline: "Running".to_owned(),
warning: None,
needs_setup: false,
running: true,
sites: vec![SiteItem { label: "acme.test".to_owned(), url: None, worktrees: Vec::new() }],
hide_sites,
proxies: Vec::new(),
mail_count: 0,
dump_count: 0,
xdebug: false,
dumps: false,
};
let tray = FlockTray { state, icon_theme_path: String::new(), sender: async_channel::unbounded().0 };
ksni::Tray::menu(&tray)
.into_iter()
.filter_map(|item| match item {
MenuItem::SubMenu(submenu) => Some(submenu.label),
_ => None,
})
.collect()
}

#[test]
fn hides_the_sites_submenu_when_asked() {
assert_eq!(submenus(false), ["Sites"]);
assert!(submenus(true).is_empty());
}
}
10 changes: 8 additions & 2 deletions macos/Sources/FlockUI/PanelView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import SwiftUI
struct PanelView: View {
@Environment(AppModel.self) private var model
@Environment(\.openWindow) private var openWindow
@AppStorage(PanelView.hideSitesKey) private var hideSites = false

/// UserDefaults key: whether the Sites section is left out of the panel (Settings → General).
static let hideSitesKey = "panel.hideSites"

var body: some View {
VStack(alignment: .leading, spacing: 12) {
Expand All @@ -27,8 +31,10 @@ struct PanelView: View {
Divider()
services(status)
Divider()
sites(status.sites, proxies: status.proxies)
Divider()
if !hideSites {
sites(status.sites, proxies: status.proxies)
Divider()
}
toggles(status)
Divider()
shortcuts(status)
Expand Down
8 changes: 8 additions & 0 deletions macos/Sources/FlockUI/Settings/GeneralPane.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct GeneralPane: View {
get { confirmUnparkState.wrappedValue }
nonmutating set { confirmUnparkState.wrappedValue = newValue }
}
@AppStorage(PanelView.hideSitesKey) private var hideSitesInPanel = false
private let launchAtLoginState = State<Bool>(initialValue: LoginItem.isEnabled)
private var launchAtLogin: Bool {
get { launchAtLoginState.wrappedValue }
Expand Down Expand Up @@ -87,6 +88,13 @@ struct GeneralPane: View {
}
}

Section("Menu bar") {
Toggle(isOn: $hideSitesInPanel) {
Text("Hide sites in the menu bar panel")
Text("Settings → Sites still lists them.")
}
}

Section {
appUpdates
if let config = store.config {
Expand Down
8 changes: 8 additions & 0 deletions windows/Flock.Tray.Tests/PanelViewModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ public void SiteRowOffersAToggleAndListsWorktreesOnlyWhenExpanded()
Assert.Equal(Microsoft.UI.Xaml.Visibility.Visible, row.Worktrees[1].DatabaseVisibility);
}

[Fact]
public void SitesSectionShowsUntilThePreferenceHidesIt()
{
Assert.Equal(Microsoft.UI.Xaml.Visibility.Visible, PanelViewModel.SitesSection(new Features.Preferences.PreferenceData()));
Assert.Equal(Microsoft.UI.Xaml.Visibility.Collapsed,
PanelViewModel.SitesSection(new Features.Preferences.PreferenceData { HideSitesInPanel = true }));
}

[Fact]
public void ServiceRowUpdatesInPlaceAndRaisesNotification()
{
Expand Down
26 changes: 26 additions & 0 deletions windows/Flock.Tray.Tests/PreferencesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,32 @@ public async Task LoadIsPassiveAndIgnoresLegacyEditorChoiceInAnyOrder()
}
}

[Fact]
public async Task PanelShowsSitesUntilTheyAreHiddenAndRemembersIt()
{
var directory = Directory.CreateTempSubdirectory("flock-preferences-");
try
{
var path = Path.Combine(directory.FullName, "tray.json");
// A file from before the preference existed.
await File.WriteAllTextAsync(path, "{\"Editor\":\"Cursor\",\"ExpandedSites\":\"acme\"}");
var service = new PreferencesService(path);
Assert.False((await service.LoadAsync()).HideSitesInPanel);
Assert.False(new PreferenceData().HideSitesInPanel);

await service.UpdateAsync(value => value with { HideSitesInPanel = true });

var reloaded = await new PreferencesService(path).LoadAsync();
Assert.True(reloaded.HideSitesInPanel);
Assert.Equal("Cursor", reloaded.Editor);
Assert.Equal("acme", reloaded.ExpandedSites);
}
finally
{
Directory.Delete(directory.FullName, recursive: true);
}
}

[Fact]
public async Task MissingAndCorruptFilesUseDefaultsWithoutWriting()
{
Expand Down
2 changes: 2 additions & 0 deletions windows/Flock.Tray/Features/Preferences/PreferenceData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ public sealed record PreferenceData
public string Channel { get; init; } = "stable";
/// <summary>The sites whose worktrees the panel shows, one per line (a string, so the record keeps its value equality).</summary>
public string ExpandedSites { get; init; } = "";
/// <summary>Leaves the Sites section out of the panel (Settings → General).</summary>
public bool HideSitesInPanel { get; init; }
}
5 changes: 3 additions & 2 deletions windows/Flock.Tray/PanelWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,10 @@
</ItemsControl>
</StackPanel>

<Border Height="1" Background="{ThemeResource DividerStrokeColorDefaultBrush}" Margin="-16,0" />
<Border Height="1" Background="{ThemeResource DividerStrokeColorDefaultBrush}" Margin="-16,0"
Visibility="{Binding SitesSectionVisibility}" />

<StackPanel Spacing="4">
<StackPanel Spacing="4" Visibility="{Binding SitesSectionVisibility}">
<TextBlock Text="SITES" Style="{StaticResource CaptionTextBlockStyle}" FontSize="11" FontWeight="SemiBold"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<TextBlock
Expand Down
20 changes: 19 additions & 1 deletion windows/Flock.Tray/Settings/GeneralPane.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
x:Class="Flock.Tray.Settings.GeneralPane"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Flock.Tray.Controls">
xmlns:controls="using:Flock.Tray.Controls"
xmlns:automation="using:Microsoft.UI.Xaml.Automation">
<StackPanel Spacing="0">
<StackPanel Spacing="4" Margin="0,0,0,24">
<TextBlock Text="Daemon" Style="{StaticResource BodyStrongTextBlockStyle}" Margin="1,0,0,6" />
Expand Down Expand Up @@ -97,6 +98,23 @@
</Grid>
</Border>
</StackPanel>
<StackPanel Spacing="4" Margin="0,0,0,24">
<TextBlock Text="Panel" Style="{StaticResource BodyStrongTextBlockStyle}" Margin="1,0,0,6" />
<Border Style="{StaticResource CardStyle}">
<Grid Style="{StaticResource SettingRowStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" /><ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Spacing="1">
<TextBlock Text="Hide sites in the panel" />
<TextBlock Text="Settings → Sites still lists them."
Style="{StaticResource CaptionTextBlockStyle}" Foreground="{ThemeResource TextFillColorSecondaryBrush}" TextWrapping="Wrap" />
</StackPanel>
<ToggleSwitch x:Name="HideSites" Grid.Column="1" MinWidth="0" Toggled="HideSitesToggled" OnContent="" OffContent=""
automation:AutomationProperties.Name="Hide sites in the panel" />
</Grid>
</Border>
</StackPanel>
<StackPanel Spacing="4" Margin="0,0,0,24">
<TextBlock Text="Updates" Style="{StaticResource BodyStrongTextBlockStyle}" Margin="1,0,0,6" />
<StackPanel x:Name="UpdateHost" Spacing="4" />
Expand Down
25 changes: 25 additions & 0 deletions windows/Flock.Tray/Settings/GeneralPane.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public GeneralPane(SettingsWindow window, RuntimeService model)
viewModel = new GeneralViewModel(model);
DataContext = viewModel;
Startup.IsOn = Native.StartsAtSignIn;
HideSites.IsOn = model.Preferences.Snapshot.HideSitesInPanel;
model.UpdateService.Changed += UpdateChanged;
viewModel.PropertyChanged += ViewModelChanged;
loaded = true;
Expand Down Expand Up @@ -170,6 +171,30 @@ private void StartupToggled(object sender, RoutedEventArgs args)
}
}

private async void HideSitesToggled(object sender, RoutedEventArgs args)
{
if (!loaded || sender is not ToggleSwitch toggle || toggle.IsOn == model.Preferences.Snapshot.HideSitesInPanel)
{
return;
}
var hide = toggle.IsOn;
// Until the save commits, the snapshot still has the old value: a second toggle would be ignored.
toggle.IsEnabled = false;
try
{
await model.Preferences.UpdateAsync(data => data with { HideSitesInPanel = hide });
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.Text.Json.JsonException or OperationCanceledException)
{
toggle.IsOn = model.Preferences.Snapshot.HideSitesInPanel;
model.ShowRuntimeError($"Could not change the panel setting: {e.Message}");
}
finally
{
toggle.IsEnabled = true;
}
}

private async void BetaToggled(object sender, RoutedEventArgs args)
{
if (loaded && Beta.IsOn != viewModel.IsBeta)
Expand Down
Loading
Loading