aboutsummaryrefslogtreecommitdiff
path: root/src/GetWindowsv2.cs
blob: ea61cb7eaf8771705b561ee901471e20c7857011 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
namespace hyprwatch.Window
{
  using System;
  using System.Net.Sockets;
  using System.Text;
  using System.IO;
  using System.Text.RegularExpressions;

  public partial class GetWindowsv2
  {
    public static string ActiveWindow()
    {
      string xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR"); 
      string hyprlandInstanceSig = Environment.GetEnvironmentVariable("HYPRLAND_INSTANCE_SIGNATURE");

      string socketPath = Path.Combine(xdgRuntimeDir, "hypr", hyprlandInstanceSig, ".socket2.sock");

      string? activeWindow = null;

      var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

      try 
      {
        socket.Connect(new UnixDomainSocketEndPoint(socketPath));

        using (var stream = new NetworkStream(socket))
        using (var reader = new StreamReader(stream))
        {
            string line = reader.ReadLine();

            if (line != null)
            {

              var classMatch = ClassRegex().Match(line);
              if(classMatch.Success)
              {
                activeWindow = classMatch.Groups[1].Value.Trim();
              }
            }
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally 
      {
        socket.Close();
      }

      return activeWindow ?? "Home-Screen";
    }

    [GeneratedRegex(@"activewindow>>([^,]+)")]
    public static partial Regex ClassRegex();
  }
}