• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

luttje / Key2Joy / 6517266969

14 Oct 2023 11:05AM UTC coverage: 12.469% (+0.2%) from 12.308%
6517266969

push

github

web-flow
Implementing plugins for better separation (#39)

* Start implementing plugins for better separation
* massive refactor in attempt to split appdomains for plugins
* (breaks old mapping profiles)
* Fix error when switching from mouse button trigger to keyboard trigger and clicking in the combobox where the mouse button capture textbox is.
* Simplify code by removing legacy
* SImplify grouping actions
* Fix profile and add helpful opposite mapping generator tool
* Change solution hierarchy
* Restrict AppDomain plugins went from Zone.MyComputer -> .Internet
* create keypair in ci
* Install the .NET framework tools
* Run command in workflow
* Plugin permissions. Plugins disabled by default
* update readme (icon is no longer used)
* Plugin action runs in seperated process
* Remove unused dependencies.
* Fix action name display for mapping
* Fix Lua plugin script calls (NOTE: laggy when using MessageBox)
* convert project to sdk style
* Add editorconfig and start cleaning up
* Fix documentation. Update namespaces to match files (breaks profiles)
* Include all projects in tests, disable building docs on debug
* Add messagebox script action
* Add tests for pluginhost
* Remove administrator from window title test
* add some icons to ui
* Add enabling/disabling plugins
* Close plugins when Key2Joy shuts down
* Fix appcommand failing
* Fix plugin permission form crashing. Fix plugin load exception not showing warning
* Handle plugin host closing better when app has crashed
* Seperate host and client logic in remote event subscriber
* Ensure the PluginHost shuts down if the app crashes
* Better error output for plugins
* Fix cmd interop not working, add some tests
* also generate docs on plugins
* Fix build order with docs
* Fix enum script parameters and ensure actions share environment scopes
* Fix _wpftmp folders being created dotnet/wpf#2930
* Fix sequence action. Add disabled trigger/action for unloaded plugins on start... (continued)

180 of 1703 branches covered (0.0%)

Branch coverage included in aggregate %.

6419 of 6419 new or added lines in 207 files covered. (100.0%)

1035 of 8041 relevant lines covered (12.87%)

8445.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/Core/Key2Joy.Core/Key2JoyManager.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Diagnostics;
4
using System.IO;
5
using System.Linq;
6
using System.Reflection;
7
using System.Windows.Forms;
8
using Key2Joy.Config;
9
using Key2Joy.Contracts.Mapping;
10
using Key2Joy.Contracts.Mapping.Actions;
11
using Key2Joy.Contracts.Mapping.Triggers;
12
using Key2Joy.Interop;
13
using Key2Joy.LowLevelInput;
14
using Key2Joy.Mapping;
15
using Key2Joy.Mapping.Actions.Logic;
16
using Key2Joy.Mapping.Triggers.Keyboard;
17
using Key2Joy.Mapping.Triggers.Mouse;
18
using Key2Joy.Plugins;
19
using SimWinInput;
20

21
namespace Key2Joy;
22

23
public delegate bool AppCommandRunner(AppCommand command);
24

25
public class Key2JoyManager : IMessageFilter
26
{
27
    /// <summary>
28
    /// Directory where plugins are located
29
    /// </summary>
30
    public const string PluginsDirectory = "Plugins";
31

32
    private const string READY_MESSAGE = "Key2Joy is ready";
33
    private static AppCommandRunner commandRunner;
34
    private MappingProfile armedProfile;
35
    private Form mainForm;
36
    private readonly List<IWndProcHandler> wndProcListeners = new();
×
37

38
    public static Key2JoyManager instance;
39

40
    public static Key2JoyManager Instance
41
    {
42
        get
43
        {
×
44
            if (instance == null)
×
45
            {
×
46
                throw new Exception("Key2JoyManager not initialized using InitSafely yet!");
×
47
            }
48

49
            return instance;
×
50
        }
×
51
    }
52

53
    public event EventHandler<StatusChangedEventArgs> StatusChanged;
54

55
    private Key2JoyManager()
×
56
    { }
×
57

58
    /// <summary>
59
    /// Ensures Key2Joy is running and ready to accept commands as long as the main loop does not end.
60
    /// </summary>
61
    public static void InitSafely(AppCommandRunner commandRunner, Action<PluginSet> mainLoop)
62
    {
×
63
        instance = new Key2JoyManager();
×
64

65
        var pluginDirectoriesPaths = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
×
66
        pluginDirectoriesPaths = Path.Combine(pluginDirectoriesPaths, PluginsDirectory);
×
67

68
        PluginSet plugins = new(pluginDirectoriesPaths);
×
69
        plugins.LoadAll();
×
70
        plugins.RefreshPluginTypes();
×
71

72
        Key2JoyManager.commandRunner = commandRunner;
×
73

74
        try
75
        {
×
76
            InteropServer.Instance.RestartListening();
×
77
            mainLoop(plugins);
×
78
        }
×
79
        finally
80
        {
×
81
            InteropServer.Instance.StopListening();
×
82
            SimGamePad.Instance.ShutDown();
×
83
        }
×
84
    }
×
85

86
    // Run the event on the same thread as the main form
87
    internal void CallOnUiThread(Action action) => this.mainForm.Invoke(action);
×
88

89
    private static IList<AbstractTriggerListener> GetScriptingListeners()
90
    {
×
91
        List<AbstractTriggerListener> listeners = new()
×
92
        {
×
93
            // Always add these listeners so scripts can ask them if stuff has happened.
×
94
            KeyboardTriggerListener.Instance,
×
95
            MouseButtonTriggerListener.Instance,
×
96
            MouseMoveTriggerListener.Instance
×
97
        };
×
98

99
        return listeners;
×
100
    }
×
101

102
    internal static bool RunAppCommand(AppCommand command) => commandRunner(command);
×
103

104
    public bool PreFilterMessage(ref System.Windows.Forms.Message m)
105
    {
×
106
        for (var i = 0; i < this.wndProcListeners.Count; i++)
×
107
        {
×
108
            // Check if the proc listeners haven't changed (this can happen when a plugin opens a MessageBox, the user aborts, and we then close the messagebox)
109
            if (i >= this.wndProcListeners.Count)
×
110
            {
×
111
                Debug.WriteLine("Key2JoyManager.PreFilterMessage: wndProcListeners changed while processing message!");
×
112
                break;
×
113
            }
114

115
            var wndProcListener = this.wndProcListeners[i];
×
116

117
            wndProcListener.WndProc(new Contracts.Mapping.Message(m.HWnd, m.Msg, m.WParam, m.LParam));
×
118
        }
×
119

120
        return false;
×
121
    }
×
122

123
    public void SetMainForm(Form form)
124
    {
×
125
        this.mainForm = form;
×
126
        Application.AddMessageFilter(this);
×
127

128
        Console.WriteLine(READY_MESSAGE);
×
129
    }
×
130

131
    public bool GetIsArmed(MappingProfile profile = null)
132
    {
×
133
        if (profile == null)
×
134
        {
×
135
            return this.armedProfile != null;
×
136
        }
137

138
        return this.armedProfile == profile;
×
139
    }
×
140

141
    public void ArmMappings(MappingProfile profile)
142
    {
×
143
        this.armedProfile = profile;
×
144

145
        var allListeners = GetScriptingListeners();
×
146
        var allActions = (IList<AbstractAction>)profile.MappedOptions.Select(m => m.Action).ToList();
×
147

148
        foreach (var mappedOption in profile.MappedOptions)
×
149
        {
×
150
            if (mappedOption.Trigger == null)
×
151
            {
×
152
                continue;
×
153
            }
154

155
            var listener = mappedOption.Trigger.GetTriggerListener();
×
156

157
            if (!allListeners.Contains(listener))
×
158
            {
×
159
                allListeners.Add(listener);
×
160
            }
×
161

162
            if (listener is IWndProcHandler listenerWndProcHAndler)
×
163
            {
×
164
                this.wndProcListeners.Add(listenerWndProcHAndler);
×
165
            }
×
166

167
            mappedOption.Action.OnStartListening(listener, ref allActions);
×
168
            listener.AddMappedOption(mappedOption);
×
169
        }
×
170

171
        foreach (var listener in allListeners)
×
172
        {
×
173
            if (listener is IWndProcHandler listenerWndProcHAndler)
×
174
            {
×
175
                listenerWndProcHAndler.Handle = this.mainForm.Handle;
×
176
            }
×
177

178
            listener.StartListening(ref allListeners);
×
179
        }
×
180

181
        StatusChanged?.Invoke(this, new StatusChangedEventArgs
×
182
        {
×
183
            IsEnabled = true,
×
184
            Profile = this.armedProfile
×
185
        });
×
186
    }
×
187

188
    public void DisarmMappings()
189
    {
×
190
        var listeners = GetScriptingListeners();
×
191
        this.wndProcListeners.Clear();
×
192

193
        // Clear all intervals
194
        IdPool.CancelAll();
×
195

196
        foreach (var mappedOption in this.armedProfile.MappedOptions)
×
197
        {
×
198
            if (mappedOption.Trigger == null)
×
199
            {
×
200
                continue;
×
201
            }
202

203
            var listener = mappedOption.Trigger.GetTriggerListener();
×
204
            mappedOption.Action.OnStopListening(listener);
×
205

206
            if (!listeners.Contains(listener))
×
207
            {
×
208
                listeners.Add(listener);
×
209
            }
×
210
        }
×
211

212
        foreach (var listener in listeners)
×
213
        {
×
214
            listener.StopListening();
×
215
        }
×
216

217
        GamePadManager.Instance.EnsureAllUnplugged();
×
218
        this.armedProfile = null;
×
219

220
        StatusChanged?.Invoke(this, new StatusChangedEventArgs
×
221
        {
×
222
            IsEnabled = false,
×
223
        });
×
224
    }
×
225

226
    /// <summary>
227
    /// Starts Key2Joy, pausing until it's ready
228
    /// </summary>
229
    public static void StartKey2Joy(bool startMinimized = true, bool pauseUntilReady = true)
230
    {
×
231
        var executablePath = ConfigManager.Config.LastInstallPath;
×
232

233
        if (executablePath == null)
×
234
        {
×
235
            Console.WriteLine("Error! Key2Joy executable path is not known, please start Key2Joy at least once!");
×
236
            return;
×
237
        }
238

239
        if (!File.Exists(executablePath))
×
240
        {
×
241
            Console.WriteLine("Error! Key2Joy executable path is invalid, please start Key2Joy at least once (and don't move the executable)!");
×
242
            return;
×
243
        }
244

245
        Process process = new()
×
246
        {
×
247
            StartInfo = new ProcessStartInfo
×
248
            {
×
249
                FileName = executablePath,
×
250
                Arguments = startMinimized ? "--minimized" : "",
×
251
                UseShellExecute = false,
×
252
                RedirectStandardOutput = true
×
253
            }
×
254
        };
×
255

256
        process.Start();
×
257

258
        if (!pauseUntilReady)
×
259
        {
×
260
            return;
×
261
        }
262

263
        while (!process.StandardOutput.EndOfStream)
×
264
        {
×
265
            if (process.StandardOutput.ReadLine() == READY_MESSAGE)
×
266
            {
×
267
                break;
×
268
            }
269
        }
×
270
    }
×
271
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc