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
2 changes: 1 addition & 1 deletion PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,6 @@ Status of each Windows feature on Linux. This file describes the tree it ships w
| Recording options: system sound, microphone, device, frame rate, quality, cursor, countdown, copy file | working | `linux/SettingsWindow.cs` |
| Reset defaults, including the recording options and video folder | working | `linux/SettingsWindow.cs`, `linux/SettingsDefaults.cs` |
| Start on login | working. XDG autostart. | `linux/Autostart.cs` |
| First-run tray balloon | missing. The tray menu is available as soon as the icon is. | `src/TrayApp.cs`, `linux/App.cs` |
| First-run tray balloon | done. Linux shows a first-launch desktop notification with the X11 shortcut or Wayland bind command; its default action snips when supported. Silently skipped without a notification server. | `src/TrayApp.cs`, `linux/App.cs`, `linux/Notifications.cs` |
| Diagnostics include capture, clipboard, ffmpeg, and audio devices | working | `linux/Diagnostics.cs` |
| Second launch forwards snip, delay, repeat, record, and settings | working | `linux/SingleInstance.cs` |
11 changes: 11 additions & 0 deletions linux/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ sealed class App : Application

IClassicDesktopStyleApplicationLifetime _desktop;
TrayIcon _tray;
Notifications _notifications;
NativeMenuItem _delayItem;
NativeMenuItem _recordItem;
SettingsWindow _settingsWindow;
Expand Down Expand Up @@ -124,6 +125,15 @@ async Task StartAsyncCore()
break;
}

if (Notifications.TakeFirstRun(Settings))
{
Settings.Save();
_notifications = new Notifications();
await _notifications.ShowAsync(
Notifications.BuildMessage(Settings, PlatformInfo.IsWayland, PlatformInfo.Command("--snip")),
() => Dispatcher.UIThread.Post(() => { if (!_exiting) StartSnip(); }));
}

_started = true;
QuitIfIdle();
}
Expand Down Expand Up @@ -762,6 +772,7 @@ public void ExitApp()
_hotkeys = null;
try { _tray?.Dispose(); } catch { }
_tray = null;
_notifications?.Dispose();
SingleInstance.Stop();
_desktop?.Shutdown();
}
Expand Down
2 changes: 1 addition & 1 deletion linux/DBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ static string SessionAddress

public static bool SessionAvailable => !string.IsNullOrWhiteSpace(SessionAddress);

static async Task<Connection> ConnectAsync()
internal static async Task<Connection> ConnectAsync()
{
if (!SessionAvailable) throw new InvalidOperationException("No session bus");
var connection = new Connection(SessionAddress);
Expand Down
88 changes: 88 additions & 0 deletions linux/Notifications.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System.Security;
using Tmds.DBus.Protocol;

namespace OpenSnip;

/// <summary>A best-effort first-run notification; keeps the bus open for its default action.</summary>
sealed class Notifications : IDisposable
{
const string Service = "org.freedesktop.Notifications";
const string Path = "/org/freedesktop/Notifications";
Connection _connection;
IDisposable _actions;
uint _id;
bool _invoked;

public static bool TakeFirstRun(Settings settings)
{
if (settings.Welcomed) return false;
settings.Welcomed = true;
return true;
}

public static string BuildMessage(Settings settings, bool wayland, string snipCommand)
{
var bindings = HotkeyBindings.From(settings);
string keys = !bindings.Snip.IsEmpty ? bindings.Snip.Display
: bindings.UsePrintScreen ? "PrtSc" : null;
return (wayland ? $"Bind {snipCommand} to snip. "
: keys != null ? $"Press {keys} to snip. " : "Click the tray icon to snip. ") +
"Right-click the tray icon to change shortcuts and options.";
}

public async Task ShowAsync(string body, Action snip)
{
try
{
_connection = await DBus.ConnectAsync();
var writer = _connection.GetMessageWriter();
writer.WriteMethodCallHeader(Service, Path, Service, "GetCapabilities", "", MessageFlags.None);
var capabilities = await _connection.CallMethodAsync(writer.CreateMessage(),
(Message message, object state) => message.GetBodyReader().ReadArrayOfString(), null)
.WaitAsync(TimeSpan.FromSeconds(3));
bool actions = capabilities.Contains("actions");
if (actions)
{
_actions = await _connection.AddMatchAsync(
new MatchRule { Type = MessageType.Signal, Sender = Service, Path = Path,
Interface = Service, Member = "ActionInvoked" },
(Message message, object state) =>
{
var reader = message.GetBodyReader();
return (Id: reader.ReadUInt32(), Key: reader.ReadString());
},
(Exception error, (uint Id, string Key) value, object readerState, object handlerState) =>
{
if (error == null && value.Id == _id && value.Key == "default" && !_invoked)
{
_invoked = true;
snip();
}
}, ObserverFlags.None, readerState: null, handlerState: null, emitOnCapturedContext: false);
}
writer = _connection.GetMessageWriter();
writer.WriteMethodCallHeader(Service, Path, Service, "Notify", "susssasa{sv}i", MessageFlags.None);
writer.WriteString("OpenSnip");
writer.WriteUInt32(0);
writer.WriteString("opensnip");
writer.WriteString("OpenSnip is running");
writer.WriteString(capabilities.Contains("body-markup") ? SecurityElement.Escape(body) : body);
writer.WriteArray(actions ? new[] { "default", "Snip" } : Array.Empty<string>());
writer.WriteDictionary(new Dictionary<string, VariantValue>());
writer.WriteInt32(8000);
_id = await _connection.CallMethodAsync(writer.CreateMessage(),
(Message message, object state) => message.GetBodyReader().ReadUInt32(), null)
.WaitAsync(TimeSpan.FromSeconds(3));
if (!actions) Dispose();
}
catch { Dispose(); } // No bus/server, or unsupported notifications: startup proceeds silently.
}

public void Dispose()
{
try { _actions?.Dispose(); } catch { }
_actions = null;
try { _connection?.Dispose(); } catch { }
_connection = null;
}
}
39 changes: 39 additions & 0 deletions tests/OpenSnip.Hotkeys.Tests/NotificationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Text.Json;

namespace OpenSnip.Hotkeys.Tests;

public class NotificationTests
{
const string Options = "Right-click the tray icon to change shortcuts and options.";

[Fact]
public void FirstRunIsConsumedOnceAndSurvivesSettingsRoundTrip()
{
var settings = JsonSerializer.Deserialize<Settings>("{}");
Assert.True(Notifications.TakeFirstRun(settings));
Assert.True(settings.Welcomed);
Assert.False(Notifications.TakeFirstRun(settings));
var loaded = JsonSerializer.Deserialize<Settings>(JsonSerializer.Serialize(settings));
Assert.False(Notifications.TakeFirstRun(loaded));
}

[Theory]
[InlineData("Ctrl+Shift+S", true, "Press Ctrl + Shift + S to snip. ")]
[InlineData("", true, "Press PrtSc to snip. ")]
[InlineData("", false, "Click the tray icon to snip. ")]
[InlineData("invalid", false, "Click the tray icon to snip. ")]
public void X11UsesConfiguredShortcutOrWindowsFallback(string shortcut, bool printScreen, string prefix)
{
var settings = new Settings { SnipHotkey = shortcut, UsePrintScreen = printScreen };
Assert.Equal(prefix + Options, Notifications.BuildMessage(settings, false, "opensnip --snip"));
}

[Theory]
[InlineData("opensnip --snip")]
[InlineData("\"/home/user/My Apps/OpenSnip\" --snip")]
public void WaylandUsesTheCommandToBind(string command)
{
Assert.Equal($"Bind {command} to snip. " + Options,
Notifications.BuildMessage(new Settings(), true, command));
}
}
Loading