Skip to content

Commit f2b9ac1

Browse files
committed
System tray icon
Add code for creation of system tray icon, menu and handle menu events System tray icon - add code for creation of system tray icon, menu and handle menu events - add option to preferences dialog - add a kind of a single instance mode: only first launched instance creates system tray icon and does not quit
1 parent 21cfd17 commit f2b9ac1

13 files changed

+157
-21
lines changed

src/App.Commands.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ public static bool IsCheckForUpdateCommandVisible
3636
#endif
3737
}
3838
}
39-
39+
40+
public static readonly Command Unminimize = new Command(_ => ShowWindow());
4041
public static readonly Command OpenPreferencesCommand = new Command(_ => OpenDialog(new Views.Preferences()));
4142
public static readonly Command OpenHotkeysCommand = new Command(_ => OpenDialog(new Views.Hotkeys()));
4243
public static readonly Command OpenAppDataDirCommand = new Command(_ => Native.OS.OpenInFileManager(Native.OS.DataDir));

src/App.axaml.cs

+52-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
using Avalonia.Markup.Xaml;
1717
using Avalonia.Media;
1818
using Avalonia.Media.Fonts;
19+
using Avalonia.Media.Imaging;
20+
using Avalonia.Platform;
1921
using Avalonia.Platform.Storage;
2022
using Avalonia.Styling;
2123
using Avalonia.Threading;
@@ -169,6 +171,46 @@ public static void SetTheme(string theme, string themeOverridesFile)
169171
}
170172
}
171173

174+
public void SetupTrayIcon(bool enable)
175+
{
176+
if (enable && Native.OS.EnsureSingleInstance())
177+
{
178+
var icons = new TrayIcons {
179+
new TrayIcon {
180+
Icon = new WindowIcon(new Bitmap(AssetLoader.Open(new Uri("avares://SourceGit/App.ico")))),
181+
Menu = [
182+
new NativeMenuItem(Text("Open")) {Command = Unminimize},
183+
new NativeMenuItem(Text("Preferences")) {Command = OpenPreferencesCommand},
184+
new NativeMenuItemSeparator(),
185+
new NativeMenuItem(Text("Quit")) {Command = QuitCommand},
186+
]
187+
}
188+
};
189+
icons[0].Clicked += (_, _) => ToggleWindow();
190+
TrayIcon.SetIcons(Current, icons);
191+
_createdSystemTrayIcon = true;
192+
}
193+
}
194+
195+
private static void ToggleWindow() {
196+
if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
197+
if (desktop.MainWindow.IsVisible) {
198+
desktop.MainWindow.Hide();
199+
} else {
200+
ShowWindow();
201+
}
202+
}
203+
}
204+
205+
private static void ShowWindow()
206+
{
207+
if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
208+
desktop.MainWindow.WindowState = WindowState.Normal;
209+
desktop.MainWindow.Show();
210+
desktop.MainWindow.BringIntoView();
211+
desktop.MainWindow.Focus();
212+
}
213+
}
172214
public static void SetFonts(string defaultFont, string monospaceFont, bool onlyUseMonospaceFontInEditor)
173215
{
174216
var app = Current as App;
@@ -322,6 +364,7 @@ public override void OnFrameworkInitializationCompleted()
322364

323365
TryLaunchAsNormal(desktop);
324366
}
367+
base.OnFrameworkInitializationCompleted();
325368
}
326369
#endregion
327370

@@ -477,11 +520,17 @@ private void TryLaunchAsNormal(IClassicDesktopStyleApplicationLifetime desktop)
477520
if (desktop.Args != null && desktop.Args.Length == 1 && Directory.Exists(desktop.Args[0]))
478521
startupRepo = desktop.Args[0];
479522

480-
_launcher = new ViewModels.Launcher(startupRepo);
523+
var pref = ViewModels.Preferences.Instance;
524+
525+
SetupTrayIcon(pref.SystemTrayIcon);
526+
if (_createdSystemTrayIcon) {
527+
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
528+
}
529+
530+
_launcher = new ViewModels.Launcher(startupRepo) { InterceptQuit = _createdSystemTrayIcon };
481531
desktop.MainWindow = new Views.Launcher() { DataContext = _launcher };
482532

483533
#if !DISABLE_UPDATE_DETECTION
484-
var pref = ViewModels.Preferences.Instance;
485534
if (pref.ShouldCheck4UpdateOnStartup())
486535
Check4Update();
487536
#endif
@@ -544,5 +593,6 @@ private void ShowSelfUpdateResult(object data)
544593
private ResourceDictionary _activeLocale = null;
545594
private ResourceDictionary _themeOverrides = null;
546595
private ResourceDictionary _fontsOverrides = null;
596+
private bool _createdSystemTrayIcon = false;
547597
}
548598
}

src/Native/Linux.cs

+21
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ namespace SourceGit.Native
1111
[SupportedOSPlatform("linux")]
1212
internal class Linux : OS.IBackend
1313
{
14+
private FileStream _fs = null;
1415
public void SetupApp(AppBuilder builder)
1516
{
1617
builder.With(new X11PlatformOptions() { EnableIme = true });
@@ -97,6 +98,26 @@ public void OpenWithDefaultEditor(string file)
9798
}
9899
}
99100

101+
public bool EnsureSingleInstance()
102+
{
103+
var pidfile = Path.Combine(Path.GetTempPath(), "sourcegit.pid");
104+
var pid = Process.GetCurrentProcess().Id.ToString();
105+
Console.WriteLine("pid " + pid);
106+
107+
try
108+
{
109+
_fs = File.OpenWrite(pidfile);
110+
_fs.Lock(0, 1000);
111+
new StreamWriter(_fs).Write(pid);
112+
return true;
113+
}
114+
catch (IOException)
115+
{
116+
Console.WriteLine("another SourceGit is running");
117+
return false;
118+
}
119+
}
120+
100121
private string FindExecutable(string filename)
101122
{
102123
var pathVariable = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;

src/Native/MacOS.cs

+2
Original file line numberDiff line numberDiff line change
@@ -88,5 +88,7 @@ public void OpenWithDefaultEditor(string file)
8888
{
8989
Process.Start("open", $"\"{file}\"");
9090
}
91+
92+
public bool EnsureSingleInstance() { return true; }
9193
}
9294
}

src/Native/OS.cs

+7
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ public interface IBackend
2323
void OpenInFileManager(string path, bool select);
2424
void OpenBrowser(string url);
2525
void OpenWithDefaultEditor(string file);
26+
27+
bool EnsureSingleInstance();
2628
}
2729

2830
public static string DataDir
@@ -220,6 +222,11 @@ private static void UpdateGitVersion()
220222
[GeneratedRegex(@"^git version[\s\w]*(\d+)\.(\d+)[\.\-](\d+).*$")]
221223
private static partial Regex REG_GIT_VERSION();
222224

225+
public static bool EnsureSingleInstance()
226+
{
227+
return _backend.EnsureSingleInstance();
228+
}
229+
223230
private static IBackend _backend = null;
224231
private static string _gitExecutable = string.Empty;
225232
}

src/Native/Windows.cs

+22
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ namespace SourceGit.Native
1414
[SupportedOSPlatform("windows")]
1515
internal class Windows : OS.IBackend
1616
{
17+
private FileStream _fs = null;
18+
1719
[StructLayout(LayoutKind.Sequential)]
1820
internal struct RTL_OSVERSIONINFOEX
1921
{
@@ -393,5 +395,25 @@ private string FindVSSolutionFile(DirectoryInfo dir, int leftDepth)
393395

394396
return null;
395397
}
398+
399+
public bool EnsureSingleInstance()
400+
{
401+
var pidfile = Path.Combine(Path.GetTempPath(), "sourcegit.pid");
402+
var pid = Process.GetCurrentProcess().Id.ToString();
403+
Console.WriteLine("pid " + pid);
404+
405+
try
406+
{
407+
_fs = File.OpenWrite(pidfile);
408+
_fs.Lock(0, 1000);
409+
new StreamWriter(_fs).Write(pid);
410+
return true;
411+
}
412+
catch (IOException)
413+
{
414+
Console.WriteLine("another SourceGit is running");
415+
return false;
416+
}
417+
}
396418
}
397419
}

src/Resources/Locales/en_US.axaml

+1
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,7 @@
468468
<x:String x:Key="Text.Preferences.Appearance.ThemeOverrides" xml:space="preserve">Theme Overrides</x:String>
469469
<x:String x:Key="Text.Preferences.Appearance.UseFixedTabWidth" xml:space="preserve">Use fixed tab width in titlebar</x:String>
470470
<x:String x:Key="Text.Preferences.Appearance.UseNativeWindowFrame" xml:space="preserve">Use native window frame</x:String>
471+
<x:String x:Key="Text.Preferences.Appearance.SystemTrayIcon" xml:space="preserve">System tray icon (needs restart)</x:String>
471472
<x:String x:Key="Text.Preferences.DiffMerge" xml:space="preserve">DIFF/MERGE TOOL</x:String>
472473
<x:String x:Key="Text.Preferences.DiffMerge.Path" xml:space="preserve">Install Path</x:String>
473474
<x:String x:Key="Text.Preferences.DiffMerge.Path.Placeholder" xml:space="preserve">Input path for diff/merge tool</x:String>

src/Resources/Locales/ru_RU.axaml

+1
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,7 @@
460460
<x:String x:Key="Text.Preferences.Appearance.ThemeOverrides" xml:space="preserve">Переопределение темы</x:String>
461461
<x:String x:Key="Text.Preferences.Appearance.UseFixedTabWidth" xml:space="preserve">Использовать фиксированную ширину табуляции в строке заголовка.</x:String>
462462
<x:String x:Key="Text.Preferences.Appearance.UseNativeWindowFrame" xml:space="preserve">Использовать системное окно</x:String>
463+
<x:String x:Key="Text.Preferences.Appearance.SystemTrayIcon" xml:space="preserve">Иконка в системном лотке (нужен перезапуск)</x:String>
463464
<x:String x:Key="Text.Preferences.DiffMerge" xml:space="preserve">ИНСТРУМЕНТ РАЗЛИЧИЙ/СЛИЯНИЯ</x:String>
464465
<x:String x:Key="Text.Preferences.DiffMerge.Path" xml:space="preserve">Путь установки</x:String>
465466
<x:String x:Key="Text.Preferences.DiffMerge.Path.Placeholder" xml:space="preserve">Введите путь для инструмента различия/слияния</x:String>

src/ViewModels/Launcher.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ public Workspace ActiveWorkspace
2929
private set => SetProperty(ref _activeWorkspace, value);
3030
}
3131

32+
public bool InterceptQuit { get; set; } = false;
33+
3234
public LauncherPage ActivePage
3335
{
3436
get => _activePage;
@@ -47,7 +49,6 @@ public LauncherPage ActivePage
4749
public Launcher(string startupRepo)
4850
{
4951
_ignoreIndexChange = true;
50-
5152
Pages = new AvaloniaList<LauncherPage>();
5253
AddNewTab();
5354

src/ViewModels/Preferences.cs

+8
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,12 @@ public double LastCheckUpdateTime
348348
set => SetProperty(ref _lastCheckUpdateTime, value);
349349
}
350350

351+
public bool SystemTrayIcon
352+
{
353+
get => _systemTrayIcon;
354+
set => SetProperty(ref _systemTrayIcon, value);
355+
}
356+
351357
public bool IsGitConfigured()
352358
{
353359
var path = GitInstallPath;
@@ -682,5 +688,7 @@ private string FixFontFamilyName(string name)
682688
private string _externalMergeToolPath = string.Empty;
683689

684690
private uint _statisticsSampleColor = 0xFF00FF00;
691+
692+
private bool _systemTrayIcon = false;
685693
}
686694
}

src/Views/Launcher.axaml.cs

+7-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,13 @@ protected override void OnKeyUp(KeyEventArgs e)
262262

263263
protected override void OnClosing(WindowClosingEventArgs e)
264264
{
265-
(DataContext as ViewModels.Launcher)?.Quit(Width, Height);
265+
var launcher = DataContext as ViewModels.Launcher;
266+
if (launcher is { InterceptQuit: true }) {
267+
e.Cancel = true;
268+
Hide();
269+
} else {
270+
launcher?.Quit(Width, Height);
271+
}
266272
base.OnClosing(e);
267273
}
268274

src/Views/Preferences.axaml

+21-16
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@
148148
<TabItem.Header>
149149
<TextBlock Classes="tab_header" Text="{DynamicResource Text.Preferences.Appearance}"/>
150150
</TabItem.Header>
151-
<Grid Margin="8" RowDefinitions="32,32,32,32,32,32,32,Auto" ColumnDefinitions="Auto,*">
151+
<Grid Margin="8" RowDefinitions="32,32,32,32,32,Auto" ColumnDefinitions="Auto,*">
152152
<TextBlock Grid.Row="0" Grid.Column="0"
153153
Text="{DynamicResource Text.Preferences.Appearance.Theme}"
154154
HorizontalAlignment="Right"
@@ -232,21 +232,26 @@
232232
</TextBox.InnerRightContent>
233233
</TextBox>
234234

235-
<CheckBox Grid.Row="5" Grid.Column="1"
236-
Content="{DynamicResource Text.Preferences.Appearance.OnlyUseMonoFontInEditor}"
237-
IsChecked="{Binding OnlyUseMonoFontInEditor, Mode=TwoWay}"/>
238-
239-
<CheckBox Grid.Row="6" Grid.Column="1"
240-
Height="32"
241-
Content="{DynamicResource Text.Preferences.Appearance.UseFixedTabWidth}"
242-
IsChecked="{Binding Source={x:Static vm:Preferences.Instance}, Path=UseFixedTabWidth, Mode=TwoWay}"/>
243-
244-
<CheckBox Grid.Row="7" Grid.Column="1"
245-
Height="32"
246-
Content="{DynamicResource Text.Preferences.Appearance.UseNativeWindowFrame}"
247-
IsChecked="{Binding Source={x:Static vm:Preferences.Instance}, Path=UseSystemWindowFrame, Mode=OneTime}"
248-
IsVisible="{OnPlatform False, Linux=True}"
249-
IsCheckedChanged="OnUseNativeWindowFrameChanged"/>
235+
<StackPanel Grid.Row="5" Grid.Column="1">
236+
<CheckBox Content="{DynamicResource Text.Preferences.Appearance.OnlyUseMonoFontInEditor}"
237+
IsChecked="{Binding OnlyUseMonoFontInEditor, Mode=TwoWay}"/>
238+
239+
<CheckBox Height="32"
240+
Content="{DynamicResource Text.Preferences.Appearance.UseFixedTabWidth}"
241+
IsChecked="{Binding Source={x:Static vm:Preferences.Instance}, Path=UseFixedTabWidth, Mode=TwoWay}"/>
242+
243+
<CheckBox Height="32"
244+
Content="{DynamicResource Text.Preferences.Appearance.UseNativeWindowFrame}"
245+
IsChecked="{Binding Source={x:Static vm:Preferences.Instance}, Path=UseSystemWindowFrame, Mode=OneTime}"
246+
IsVisible="{OnPlatform False, Linux=True}"
247+
IsCheckedChanged="OnUseNativeWindowFrameChanged"/>
248+
249+
<CheckBox Height="32"
250+
Content="{DynamicResource Text.Preferences.Appearance.SystemTrayIcon}"
251+
IsChecked="{Binding Path=SystemTrayIcon, Mode=OneTime}"
252+
IsVisible="True"
253+
IsCheckedChanged="OnSystemTrayIconCheckedChanged"/>
254+
</StackPanel>
250255
</Grid>
251256
</TabItem>
252257

src/Views/Preferences.axaml.cs

+11
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,17 @@ private void OnUseNativeWindowFrameChanged(object sender, RoutedEventArgs e)
342342

343343
e.Handled = true;
344344
}
345+
private void OnSystemTrayIconCheckedChanged(object sender, RoutedEventArgs e)
346+
{
347+
if (sender is CheckBox box)
348+
{
349+
ViewModels.Preferences.Instance.SystemTrayIcon = box.IsChecked == true;
350+
var dialog = new ConfirmRestart();
351+
App.OpenDialog(dialog);
352+
}
353+
354+
e.Handled = true;
355+
}
345356

346357
private void OnGitInstallPathChanged(object sender, TextChangedEventArgs e)
347358
{

0 commit comments

Comments
 (0)