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
34 changes: 34 additions & 0 deletions src/Waehlhilfe.App/CompositionRoot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Waehlhilfe.App.Platform;
using Waehlhilfe.AppLogic;
using Waehlhilfe.AppLogic.ViewModels;
using Waehlhilfe.Modem;

namespace Waehlhilfe.App;

/// <summary>Wires Wählhilfe by hand: no container.</summary>
internal sealed class CompositionRoot
{
private readonly JsonSettingsStore _store = new JsonSettingsStore(JsonSettingsStore.DefaultPath());
private readonly AtDialer _dialer = new AtDialer(new SerialPorts());
private readonly ITelHandlerRegistration _registration = CreateRegistration();

public SettingsViewModel Settings() => new(_store, _dialer, SerialPorts.List, _registration);

// Settings are read for every dial, so a change in the settings window applies to the next click.
public DialViewModel Dial(string link) => new(link, _store.Load(), _dialer);

private static ITelHandlerRegistration CreateRegistration()
{
if (OperatingSystem.IsWindows())
{
return new WindowsTelHandlerRegistration();
}

if (OperatingSystem.IsMacOS())
{
return new MacTelHandlerRegistration();
}

return new UnsupportedTelHandlerRegistration();
}
}
12 changes: 12 additions & 0 deletions src/Waehlhilfe.App/LaunchArguments.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Waehlhilfe.App;

internal static class LaunchArguments
{
/// <summary>
/// The <c>tel:</c> link Windows and Linux pass on the command line when a link is clicked,
/// or <c>null</c> when Wählhilfe was started on its own. macOS delivers links as an Apple
/// event instead, which arrives through <c>IActivatableLifetime</c>.
/// </summary>
public static string? TelLink(IEnumerable<string> args) =>
args.FirstOrDefault(a => a.StartsWith("tel:", StringComparison.OrdinalIgnoreCase));
}
94 changes: 94 additions & 0 deletions src/Waehlhilfe.App/Platform/MacTelHandlerRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Waehlhilfe.AppLogic;

namespace Waehlhilfe.App.Platform;

/// <summary>The bundle declares <c>tel</c> in CFBundleURLTypes; Launch Services picks the default.</summary>
[SupportedOSPlatform("macos")]
internal sealed partial class MacTelHandlerRegistration : ITelHandlerRegistration
{
/// <summary>Must match CFBundleIdentifier in packaging/macos/build-dmg.sh.</summary>
internal const string BundleId = "io.github.deepdiver1975.waehlhilfe";

private const string CoreFoundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
private const string CoreServices = "/System/Library/Frameworks/CoreServices.framework/CoreServices";
private const uint Utf8 = 0x08000100;

public bool IsDefaultHandler()
{
var scheme = CFStringCreateWithCString(IntPtr.Zero, "tel", Utf8);
try
{
var handler = LSCopyDefaultHandlerForURLScheme(scheme);
try
{
return string.Equals(ToManaged(handler), BundleId, StringComparison.OrdinalIgnoreCase);
}
finally
{
Release(handler);
}
}
finally
{
Release(scheme);
}
}

public Task MakeDefaultAsync(CancellationToken cancellationToken = default)
{
var scheme = CFStringCreateWithCString(IntPtr.Zero, "tel", Utf8);
var bundle = CFStringCreateWithCString(IntPtr.Zero, BundleId, Utf8);
try
{
var status = LSSetDefaultHandlerForURLScheme(scheme, bundle);
return status == 0
? Task.CompletedTask
: throw new InvalidOperationException($"LSSetDefaultHandlerForURLScheme returned {status}.");
}
finally
{
Release(bundle);
Release(scheme);
}
}

private static string? ToManaged(IntPtr text)
{
if (text == IntPtr.Zero)
{
return null;
}

var buffer = new byte[256];
return CFStringGetCString(text, buffer, buffer.Length, Utf8)
? Encoding.UTF8.GetString(buffer, 0, Array.IndexOf(buffer, (byte)0) is var end and >= 0 ? end : buffer.Length)
: null;
}

private static void Release(IntPtr reference)
{
if (reference != IntPtr.Zero)
{
CFRelease(reference);
}
}

[LibraryImport(CoreFoundation, StringMarshalling = StringMarshalling.Utf8)]
private static partial IntPtr CFStringCreateWithCString(IntPtr allocator, string text, uint encoding);

[LibraryImport(CoreFoundation)]
[return: MarshalAs(UnmanagedType.U1)]
private static partial bool CFStringGetCString(IntPtr text, [Out] byte[] buffer, nint bufferSize, uint encoding);

[LibraryImport(CoreFoundation)]
private static partial void CFRelease(IntPtr reference);

[LibraryImport(CoreServices)]
private static partial IntPtr LSCopyDefaultHandlerForURLScheme(IntPtr scheme);

[LibraryImport(CoreServices)]
private static partial int LSSetDefaultHandlerForURLScheme(IntPtr scheme, IntPtr bundleId);
}
12 changes: 12 additions & 0 deletions src/Waehlhilfe.App/Platform/UnsupportedTelHandlerRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Waehlhilfe.AppLogic;

namespace Waehlhilfe.App.Platform;

/// <summary>Linux: Wählhilfe dials there (it is where the DL500A is tested), but ships no handler registration.</summary>
internal sealed class UnsupportedTelHandlerRegistration : ITelHandlerRegistration
{
public bool IsDefaultHandler() => false;

public Task MakeDefaultAsync(CancellationToken cancellationToken = default) =>
throw new PlatformNotSupportedException("Wählhilfe registers as the tel: handler on Windows and macOS only.");
}
38 changes: 38 additions & 0 deletions src/Waehlhilfe.App/Platform/WindowsTelHandlerRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System.Diagnostics;
using System.Runtime.Versioning;
using Microsoft.Win32;
using Waehlhilfe.AppLogic;

namespace Waehlhilfe.App.Platform;

/// <summary>
/// The MSI registers Wählhilfe as *capable* of handling <c>tel:</c> (ProgId, Capabilities,
/// RegisteredApplications). Windows lets no program make itself the default, so this opens the
/// Settings page where the user picks it once.
/// </summary>
[SupportedOSPlatform("windows")]
internal sealed class WindowsTelHandlerRegistration : ITelHandlerRegistration
{
/// <summary>Must match the ProgId and the RegisteredApplications name in packaging/windows/Waehlhilfe.wxs.</summary>
internal const string ProgId = "Waehlhilfe.tel";

internal const string RegisteredApplicationName = "Waehlhilfe";

private const string UserChoiceKey = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\tel\UserChoice";

public bool IsDefaultHandler()
{
using var key = Registry.CurrentUser.OpenSubKey(UserChoiceKey);
return string.Equals(key?.GetValue("ProgId") as string, ProgId, StringComparison.Ordinal);
}

public Task MakeDefaultAsync(CancellationToken cancellationToken = default)
{
// A fixed URI, nothing from input: the Settings page that lists Wählhilfe's link types.
using var _ = Process.Start(new ProcessStartInfo($"ms-settings:defaultapps?registeredAppMachine={RegisteredApplicationName}")
{
UseShellExecute = true,
});
return Task.CompletedTask;
}
}
32 changes: 32 additions & 0 deletions src/Waehlhilfe.App/Views/DialWindow.axaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Waehlhilfe.AppLogic.ViewModels;assembly=Waehlhilfe.AppLogic"
x:Class="Waehlhilfe.App.Views.DialWindow"
x:ClassModifier="internal"
x:DataType="vm:DialViewModel"
Title="Wählhilfe – Anrufen"
Width="420" SizeToContent="Height"
CanResize="False" Topmost="True"
WindowStartupLocation="CenterScreen">
<Window.Styles>
<Style Selector="TextBlock.status.error">
<Setter Property="Foreground" Value="{DynamicResource SystemControlErrorTextForegroundBrush}" />
</Style>
</Window.Styles>

<StackPanel Margin="24" Spacing="12">
<TextBlock Text="Anrufen über das Telefon" Opacity="0.7" />
<SelectableTextBlock x:Name="NumberText"
Text="{Binding Number}"
FontSize="30" FontWeight="SemiBold"
IsVisible="{Binding Number, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
<TextBlock x:Name="StatusText"
Classes="status" Classes.error="{Binding IsError}"
Text="{Binding Status}" TextWrapping="Wrap" />
<ProgressBar IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button x:Name="CancelButton" Content="Abbrechen" IsCancel="True" Command="{Binding CancelCommand}" />
<Button x:Name="DialButton" Content="Wählen" IsDefault="True" Classes="accent" Command="{Binding DialCommand}" />
</StackPanel>
</StackPanel>
</Window>
37 changes: 37 additions & 0 deletions src/Waehlhilfe.App/Views/DialWindow.axaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Avalonia.Controls;
using Waehlhilfe.AppLogic.ViewModels;

namespace Waehlhilfe.App.Views;

internal sealed partial class DialWindow : Window
{
private DialViewModel? _viewModel;

public DialWindow() => InitializeComponent();

protected override void OnDataContextChanged(EventArgs e)
{
base.OnDataContextChanged(e);
_viewModel?.CloseRequested -= OnCloseRequested;
_viewModel = DataContext as DialViewModel;
_viewModel?.CloseRequested += OnCloseRequested;
}

// However the window goes — title bar, or a newer link replacing it — a dial still running
// behind it is cancelled, so no call is placed from a window nobody can see.
protected override void OnClosed(EventArgs e)
{
if (_viewModel is { } viewModel)
{
viewModel.CloseRequested -= OnCloseRequested;
if (viewModel.IsBusy)
{
viewModel.CancelCommand.Execute(null);
}
}

base.OnClosed(e);
}

private void OnCloseRequested(object? sender, EventArgs e) => Close();
}
66 changes: 63 additions & 3 deletions src/Waehlhilfe.App/Views/SettingsWindow.axaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,72 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Waehlhilfe.AppLogic.ViewModels;assembly=Waehlhilfe.AppLogic"
x:Class="Waehlhilfe.App.Views.SettingsWindow"
x:ClassModifier="internal"
x:DataType="vm:SettingsViewModel"
Title="Wählhilfe"
Width="480" SizeToContent="Height"
Width="520" SizeToContent="Height"
WindowStartupLocation="CenterScreen">
<StackPanel Margin="24" Spacing="12">
<Window.Styles>
<Style Selector="TextBlock.status.error">
<Setter Property="Foreground" Value="{DynamicResource SystemControlErrorTextForegroundBrush}" />
</Style>
<Style Selector="TextBlock.hint">
<Setter Property="Opacity" Value="0.7" />
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
<Style Selector="TextBlock.section">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Margin" Value="0,12,0,0" />
</Style>
</Window.Styles>

<StackPanel Margin="24" Spacing="10">
<TextBlock Text="Wählhilfe" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="Wählt tel:-Links über ein Gigaset-Telefon per Bluetooth." TextWrapping="Wrap" />
<TextBlock Classes="hint" Text="Wählt tel:-Links über ein Gigaset DL500A per Bluetooth." />

<TextBlock Classes="section" Text="Telefon" />
<TextBlock Classes="hint" Text="Das Telefon per Bluetooth mit diesem PC koppeln – nicht als Audiogerät verbinden. Sein Port erscheint dann hier." />
<Label Content="Bluetooth-Port" Target="PortBox" />
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="8">
<ComboBox x:Name="PortBox" HorizontalAlignment="Stretch"
AutomationProperties.Name="Bluetooth-Port"
ItemsSource="{Binding Ports}" SelectedItem="{Binding SelectedPort}"
PlaceholderText="Kein Port gefunden" />
<Button x:Name="RefreshPortsButton" Grid.Column="1" Content="Aktualisieren" Command="{Binding RefreshPortsCommand}" />
</Grid>

<Grid ColumnDefinitions="*,*" ColumnSpacing="16" RowDefinitions="Auto,Auto">
<Label Content="Ländervorwahl" Target="CountryCodeBox" />
<Label Grid.Column="1" Content="Amtsholung" Target="PrefixBox" />
<TextBox x:Name="CountryCodeBox" Grid.Row="1" AutomationProperties.Name="Ländervorwahl" Text="{Binding HomeCountryCode}" />
<TextBox x:Name="PrefixBox" Grid.Row="1" Grid.Column="1" AutomationProperties.Name="Amtsholung"
Text="{Binding OutsideLinePrefix}" PlaceholderText="keine" />
</Grid>

<StackPanel Orientation="Horizontal" Spacing="8">
<Button x:Name="SaveButton" Content="Speichern" Classes="accent" Command="{Binding SaveCommand}" />
<Button x:Name="TestConnectionButton" Content="Verbindung testen" Command="{Binding TestConnectionCommand}" />
</StackPanel>

<TextBlock Classes="section" Text="Testanruf" />
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="8">
<TextBox x:Name="TestNumberBox" AutomationProperties.Name="Rufnummer für den Testanruf"
Text="{Binding TestNumber}" PlaceholderText="Rufnummer, z. B. das eigene Handy" />
<Button x:Name="TestCallButton" Grid.Column="1" Content="Testanruf" Command="{Binding TestCallCommand}" />
</Grid>

<TextBlock Classes="section" Text="tel:-Links" />
<TextBlock x:Name="IsDefaultText" Text="Wählhilfe öffnet tel:-Links." IsVisible="{Binding IsDefaultHandler}" />
<TextBlock x:Name="NotDefaultText" Classes="hint" Text="Ein anderes Programm öffnet tel:-Links." IsVisible="{Binding !IsDefaultHandler}" />
<StackPanel Orientation="Horizontal" Spacing="8">
<Button x:Name="MakeDefaultButton" Content="Als Standard festlegen" Command="{Binding MakeDefaultHandlerCommand}" />
<Button x:Name="RefreshDefaultButton" Content="Prüfen" Command="{Binding RefreshDefaultHandlerCommand}" />
</StackPanel>

<ProgressBar IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
<TextBlock x:Name="StatusText" Classes="status" Classes.error="{Binding IsError}"
Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0" />
</StackPanel>
</Window>
2 changes: 2 additions & 0 deletions src/Waehlhilfe.App/Waehlhilfe.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
<Product>Wählhilfe</Product>
<AssemblyTitle>Wählhilfe</AssemblyTitle>
<Version>0.1.0</Version>
<!-- LibraryImport marshals the CoreFoundation strings of the macOS tel: registration. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
Loading
Loading