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

File tree

13 files changed

+157
-21
lines changed

13 files changed

+157
-21
lines changed

src/App.Commands.cs

Lines changed: 2 additions & 1 deletion
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

Lines changed: 52 additions & 2 deletions
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

Lines changed: 21 additions & 0 deletions
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

Lines changed: 2 additions & 0 deletions
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

Lines changed: 7 additions & 0 deletions
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

Lines changed: 22 additions & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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

Lines changed: 2 additions & 1 deletion
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

Lines changed: 8 additions & 0 deletions
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
}

0 commit comments

Comments
 (0)