-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeskband.cs
308 lines (265 loc) · 12.8 KB
/
Deskband.cs
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
using System.Diagnostics;
using System.IO.Pipes;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace komoband;
[ComVisible(true)]
[Guid("6249307D-7F13-437B-BF13-13BE692C22A5")]
[CSDeskBand.CSDeskBandRegistration(Name = "komoband", ShowDeskBand = false)]
public class Deskband : CSDeskBand.CSDeskBandWin {
public Logger Logger = null!;
public LoggingLevelSwitch loggerSwitch = null!;
public Config config = null!;
private static Control control = null!;
private static NamedPipeServerStream server = null!;
private static Thread pipeThread = null!;
private static Thread watchdog = null!;
private bool awaitingReconnect = false;
private State lastState = null!;
private ConfigWindow configWindow = null!;
private static JsonSerializerOptions jsonOptions = new JsonSerializerOptions {
PropertyNameCaseInsensitive = true
};
public Deskband() {
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
Application.EnableVisualStyles();
if (!Directory.Exists(Constants.DATA_PATH))
Directory.CreateDirectory(Constants.DATA_PATH);
this.config = Config.Load();
this.loggerSwitch = new LoggingLevelSwitch();
this.loggerSwitch.MinimumLevel = this.config.DebugLogs ? LogEventLevel.Verbose : LogEventLevel.Information;
var logConfig = new LoggerConfiguration()
.MinimumLevel.ControlledBy(this.loggerSwitch)
.WriteTo.File(Path.Combine(Constants.DATA_PATH, "log.txt"));
this.Logger = logConfig.CreateLogger();
Log.Logger = Logger;
Logger.Information("komoband started");
Options.Title = "komoband";
Options.ShowTitle = false;
Options.MinHorizontalSize = new Size(30, 30);
Options.MaxHorizontalHeight = 30;
Options.HorizontalSize = new Size(192, 30);
Options.MinVerticalSize = new Size(30, 30);
Options.MaxVerticalWidth = 30;
Options.VerticalSize = new Size(30, 192);
this.TaskbarInfo.TaskbarOrientationChanged += OrientationChanged;
control = new BandControl(this);
var actionConfig = new CSDeskBand.ContextMenu.DeskBandMenuAction("Configure");
actionConfig.Enabled = true;
actionConfig.Clicked += (sender, args) => {
try {
// FIXME: focus existing
if (this.configWindow != null) configWindow.Dispose();
this.configWindow = new ConfigWindow(this);
} catch (Exception err) {
Logger.Error(err, "Failed to initiate ConfigWindow:");
}
};
Options.ContextMenuItems.Add(actionConfig);
var actionReload = new CSDeskBand.ContextMenu.DeskBandMenuAction("Reload Config");
actionReload.Enabled = true;
actionReload.Clicked += (sender, args) => {
config = Config.Load();
ApplyConfigUpdate();
};
Options.ContextMenuItems.Add(actionReload);
server = new NamedPipeServerStream("komoband", PipeDirection.In, -1);
pipeThread = new Thread(() => {
while (true) {
try {
if (server != null && server.CanRead) {
if (!server.IsConnected) {
try {
server.WaitForConnection();
Logger.Information("Connected to komorebi");
} catch {
if (server != null) server.Disconnect();
}
}
if (server != null && server.IsConnected) {
var dataStr = this.ReadString(server);
Logger.Verbose("Got data:\n{Data}", dataStr.Replace("\n",""));
if (dataStr.StartsWith("{")) {
try {
var data = JsonSerializer.Deserialize<Notification>(dataStr, jsonOptions);
if (data != null) {
this.lastState = data.State;
if (
data.Event is AddSubscriberPipeEvent ||
data.Event is ReloadConfigurationEvent ||
data.Event is ReloadStaticConfigurationEvent
) {
Logger.Debug("Got setup event");
var workspacesHolder = data.State.Monitors.Elements[0].Workspaces;
var workspaces = workspacesHolder.Elements;
((BandControl) control).SetupWorkspaces(workspaces, workspacesHolder.Focused);
} else if (data.Event is FocusWorkspaceNumberEvent) {
Logger.Debug("Got focus workspace event");
var workspaces = data.State.Monitors.Elements[0].Workspaces.Elements;
((BandControl) control).UpdateWorkspaces(workspaces, ((FocusWorkspaceNumberEvent) data.Event).Content);
} else if (
data.Event is SendContainerToWorkspaceNumberEvent ||
data.Event is FocusChangeEvent ||
data.Event is CloakEvent ||
data.Event is UncloakEvent ||
data.Event is ChangeLayoutEvent ||
data.Event is ChangeLayoutCustomEvent ||
data.Event is CycleLayoutEvent ||
data.Event is ToggleMonocleEvent ||
data.Event is ToggleTilingEvent
) {
Logger.Debug("Got event that calls generic update");
var workspacesHolder = data.State.Monitors.Elements[0].Workspaces;
var workspaces = workspacesHolder.Elements;
((BandControl) control).UpdateWorkspaces(workspaces, workspacesHolder.Focused);
}
}
} catch (Exception serErr) {
Logger.Error(serErr, "Failed to deserialize JSON:");
}
}
}
}
} catch (Exception err) {
if (err is ThreadAbortException) {
if (server != null) {
if (server.IsConnected) {
server.WaitForPipeDrain();
server.Disconnect();
}
server.Close();
}
} else {
Logger.Error(err, "Error in thread:");
((BandControl) control).ShowLabel();
try {
if (server != null && !this.awaitingReconnect) {
if (server.IsConnected) {
server.WaitForPipeDrain();
server.Disconnect();
}
this.ConnectPipe();
}
} catch (Exception err2) {
Logger.Error(err2,"Error reconnecting to pipe:");
}
}
}
}
});
pipeThread.Start();
watchdog = new Thread(() => {
while (true) {
try {
Process[] komorebi = Process.GetProcessesByName("komorebi");
if (komorebi.Length == 0 && !this.awaitingReconnect) {
Logger.Information("Lost komorebi");
((BandControl) control).ShowLabel();
this.awaitingReconnect = true;
if (server != null) {
if (server.IsConnected) {
server.WaitForPipeDrain();
server.Disconnect();
}
server.Close();
server = null!;
}
} else if (komorebi.Length > 0 && this.awaitingReconnect) {
Logger.Information("Found komorebi");
if (server == null) {
server = new NamedPipeServerStream("komoband", PipeDirection.In, -1);
}
if (server != null) {
this.ConnectPipe();
Thread.Sleep(1000);
if (server.IsConnected) this.awaitingReconnect = false;
}
}
} catch (Exception err) {
Logger.Error(err, "Watchdog fail:");
// noop
}
}
});
watchdog.Start();
try {
this.ConnectPipe();
} catch (Exception err) {
Logger.Error(err, "Error connecting to pipe:");
}
}
private void ConnectPipe() {
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "komorebic.exe";
startInfo.Arguments = "subscribe-pipe komoband";
process.StartInfo = startInfo;
process.Start();
}
private string ReadString(PipeStream stream) {
if (stream == null || !stream.IsConnected || !stream.CanRead) return "";
MemoryStream memoryStream = new MemoryStream();
byte[] buffer = new byte[4096];
int lastByte = 0x0;
do {
if (stream == null || !stream.IsConnected || !stream.CanRead) return "";
lastByte = stream.ReadByte();
memoryStream.WriteByte((byte) lastByte);
} while (lastByte != 0x0A);
memoryStream.Position = 0;
using (StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8)) {
return reader.ReadToEnd();
}
}
protected override void DeskbandOnClosed() {
Logger.Information("komoband closing");
try {
pipeThread.Abort();
watchdog.Abort();
control.Dispose();
} catch (Exception err) {
Logger.Error(err, "Failed to close properly:");
} finally {
Logger.Dispose();
}
}
private void OrientationChanged(object sender, CSDeskBand.TaskbarOrientationChangedEventArgs e) {
if (server != null && server.IsConnected && this.lastState != null) {
var workspacesHolder = this.lastState.Monitors.Elements[0].Workspaces;
var workspaces = workspacesHolder.Elements;
((BandControl) control).SetupWorkspaces(workspaces, workspacesHolder.Focused);
}
}
public void ApplyConfigUpdate() {
var band = (BandControl) control;
band.UpdateFont();
if (this.lastState != null) {
var workspacesHolder = this.lastState.Monitors.Elements[0].Workspaces;
var selected = workspacesHolder.Focused;
var workspaces = workspacesHolder.Elements;
band.SetupWorkspaces(workspaces, selected);
}
}
protected override Control Control => control;
// fix for Unsafe complaining about older version
// https://stackoverflow.com/a/73914330
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
var name = new AssemblyName(args.Name);
if (name.Name == "System.Runtime.CompilerServices.Unsafe") {
return typeof(System.Runtime.CompilerServices.Unsafe).Assembly;
} else if (name.Name == "System.Numerics.Vectors") {
return typeof(System.Numerics.Vector).Assembly;
} else if (name.Name == "System.Buffers") {
return typeof(System.Buffers.ArrayPool<>).Assembly;
} else if (name.Name == "System.Memory") {
return typeof(System.Memory<>).Assembly;
}
return null!;
}
}