summaryrefslogtreecommitdiff
path: root/wrapper/wrapper.cpp
blob: 54bfb91f4b14bf6fac9546ad8e03199b34e58f73 (plain) (blame)
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#pragma once

#include <type_traits>

#include <rawaccel.hpp>
#include <rawaccel-version.h>

#include "wrapper_io.hpp"

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Reflection;

using namespace Windows::Forms;

using namespace Newtonsoft::Json;

[JsonConverter(Converters::StringEnumConverter::typeid)]
public enum class AccelMode
{
    linear, classic, natural, naturalgain, power, motivity, noaccel
};

[JsonObject(ItemRequired = Required::Always)]
[StructLayout(LayoutKind::Sequential)]
public value struct AccelArgs
{
    double offset;
    [MarshalAs(UnmanagedType::U1)]
    bool legacyOffset;
    double acceleration;
    double scale;
    double limit;
    double exponent;
    double midpoint;
    double weight;
    [JsonProperty("legacyCap")]
    double scaleCap;
    double gainCap;
    [JsonProperty(Required = Required::Default)]
    double speedCap;
};

generic <typename T>
[JsonObject(ItemRequired = Required::Always)]
[StructLayout(LayoutKind::Sequential)]
public value struct Vec2
{
    T x;
    T y;
};

[JsonObject(ItemRequired = Required::Always)]
[StructLayout(LayoutKind::Sequential)]
public ref struct DriverSettings
{
    literal String^ Key = "Driver settings";

    [JsonProperty("Degrees of rotation")]
    double rotation;

    [JsonProperty("Use x as whole/combined accel")]
    [MarshalAs(UnmanagedType::U1)]
    bool combineMagnitudes;

    [JsonProperty("Accel modes")]
    Vec2<AccelMode> modes;

    [JsonProperty("Accel parameters")]
    Vec2<AccelArgs> args;

    [JsonProperty("Sensitivity multipliers")]
    Vec2<double> sensitivity;

    [JsonProperty("Negative directional multipliers", Required = Required::Default)]
    Vec2<double> negativeMultipliers;

    [JsonProperty(Required = Required::Default)]
    double minimumTime;

    bool ShouldSerializeminimumTime() 
    { 
        return minimumTime > 0 && minimumTime != DEFAULT_TIME_MIN;
    }
};


template <typename NativeSettingsFunc>
void as_native(DriverSettings^ managed_args, NativeSettingsFunc fn)
{
#ifndef NDEBUG
    if (Marshal::SizeOf(managed_args) != sizeof(settings))
        throw gcnew InvalidOperationException("setting sizes differ");
#endif
    settings args;
    Marshal::StructureToPtr(managed_args, (IntPtr)&args, false);
    fn(args);
    if constexpr (!std::is_invocable_v<NativeSettingsFunc, const settings&>) {
        Marshal::PtrToStructure((IntPtr)&args, managed_args);
    }
}

DriverSettings^ get_default()
{
    DriverSettings^ managed = gcnew DriverSettings();
    as_native(managed, [](settings& args) {
        args = {};
    });
    return managed;
}

void set_active(DriverSettings^ managed)
{
    as_native(managed, [](const settings& args) {
        wrapper_io::writeToDriver(args);
    });
}

DriverSettings^ get_active()
{
    DriverSettings^ managed = gcnew DriverSettings();
    as_native(managed, [](settings& args) {
        wrapper_io::readFromDriver(args);
    });
    return managed;
}

void update_modifier(mouse_modifier& mod, DriverSettings^ managed, vec2<si_pair*> luts = {})
{
    as_native(managed, [&](const settings& args) {
        mod = { args, luts };
    });
}

using error_list_t = Collections::Generic::List<String^>;

error_list_t^ get_accel_errors(AccelMode mode, AccelArgs^ args)
{
    accel_mode mode_native = (accel_mode)mode;

    auto is_mode = [mode_native](auto... modes) {
        return ((mode_native == modes) || ...);
    };
    
    using am = accel_mode;

    auto error_list = gcnew error_list_t();
    
    if (args->acceleration > 10 && is_mode(am::natural, am::naturalgain))
        error_list->Add("acceleration can not be greater than 10");
    else if (args->acceleration == 0 && is_mode(am::naturalgain))
        error_list->Add("acceleration must be positive");
    else if (args->acceleration < 0) {
        bool additive = mode_native < am::power;
        if (additive) error_list->Add("acceleration can not be negative, use a negative weight to compensate");
        else error_list->Add("acceleration can not be negative");
    }
        
    if (args->scale <= 0)
        error_list->Add("scale must be positive");

    if (args->exponent <= 1 && is_mode(am::classic))
        error_list->Add("exponent must be greater than 1");
    else if (args->exponent <= 0)
        error_list->Add("exponent must be positive");

    if (args->limit <= 1)
        error_list->Add("limit must be greater than 1");

    if (args->midpoint <= 0)
        error_list->Add("midpoint must be positive");

    if (args->offset < 0)
        error_list->Add("offset can not be negative");

    return error_list;
}

public ref class SettingsErrors
{
public:
    error_list_t^ x;
    error_list_t^ y;

    bool Empty()
    {
        return (x == nullptr || x->Count == 0) && 
            (y == nullptr || y->Count == 0);
    }

    virtual String^ ToString() override 
    {
        if (x == nullptr) throw;

        Text::StringBuilder^ sb = gcnew Text::StringBuilder();

        if (y == nullptr) // assume combineMagnitudes
        {
            for each (String^ str in x)
            {
                sb->AppendLine(str);
            }
        }
        else
        {
            for each (String^ str in x)
            {
                sb->AppendFormat("x: {0}\n", str);
            }
            for each (String^ str in y)
            {
                sb->AppendFormat("y: {0}\n", str);
            }
        }
        
        return sb->ToString();
    }
};

public ref struct DriverInterop
{
    literal double WriteDelayMs = WRITE_DELAY;
    static initonly DriverSettings^ DefaultSettings = get_default();

    static DriverSettings^ GetActiveSettings()
    {
        return get_active();
    }

    static void Write(DriverSettings^ args)
    {
        set_active(args);
    }

    static DriverSettings^ GetDefaultSettings()
    {
        return get_default();
    }

    static SettingsErrors^ GetSettingsErrors(DriverSettings^ args)
    {
        auto errors = gcnew SettingsErrors();

        errors->x = get_accel_errors(args->modes.x, args->args.x);

        if (!args->combineMagnitudes) {
            errors->y = get_accel_errors(args->modes.y, args->args.y);
        }

        return errors;
    }

    static error_list_t^ GetAccelErrors(AccelMode mode, AccelArgs^ args)
    {
        return get_accel_errors(mode, args);
    }
};

public ref class ManagedAccel
{
    mouse_modifier* const modifier_instance = new mouse_modifier();
#ifdef RA_LOOKUP
    si_pair* const lut_x = new si_pair[LUT_SIZE];
    si_pair* const lut_y = new si_pair[LUT_SIZE];
#else
    si_pair* lut_x = nullptr;
    si_pair* lut_y = nullptr;
#endif

public:

    virtual ~ManagedAccel()
    {
        delete modifier_instance;
        delete[] lut_x;
        delete[] lut_y;
    }

    !ManagedAccel()
    {
        delete modifier_instance;
        delete[] lut_x;
        delete[] lut_y;
    }

    Tuple<double, double>^ Accelerate(int x, int y, double time)
    {
        vec2d in_out_vec = {
            (double)x,
            (double)y
        };
        modifier_instance->modify(in_out_vec, time);

        return gcnew Tuple<double, double>(in_out_vec.x, in_out_vec.y);
    }

    void UpdateFromSettings(DriverSettings^ args)
    {
        update_modifier(
            *modifier_instance, 
            args, 
            vec2<si_pair*>{ lut_x, lut_y }
        );
    }

    static ManagedAccel^ GetActiveAccel()
    {
        settings args;
        wrapper_io::readFromDriver(args);

        auto active = gcnew ManagedAccel();
        *active->modifier_instance = { 
            args
            , vec2<si_pair*> { active->lut_x, active->lut_y }
        };
        return active;
    }
};

public ref struct RawAccelVersion
{
    literal String^ value = RA_VER_STRING;
};

public ref struct VersionException : public Exception 
{
public:
    VersionException() {}
    VersionException(String^ what) : Exception(what) {}
};

Version^ convert(rawaccel::version_t v)
{
    return gcnew Version(v.major, v.minor, v.patch, 0);
}

public ref struct VersionHelper
{

    static Version^ ValidateAndGetDriverVersion(Version^ wrapperTarget)
    {
        Version^ wrapperActual = VersionHelper::typeid->Assembly->GetName()->Version;

        if (wrapperTarget != wrapperActual) {
            throw gcnew VersionException("version mismatch, expected wrapper.dll v" + wrapperActual);
        }

        version_t drv_ver;

        try {
            wrapper_io::getDriverVersion(drv_ver);
        }
        catch (DriverNotInstalledException^ ex) {
            throw gcnew VersionException(ex->Message);
        }
        catch (DriverIOException^) {
            // Assume version ioctl is unimplemented (driver version < v1.3.0)
            throw gcnew VersionException("driver version is out of date, run installer.exe to reinstall");
        }

        Version^ drv_ver_managed = convert(drv_ver);

        if (drv_ver_managed < convert(min_driver_version)) {
            throw gcnew VersionException("driver version is out of date, run installer.exe to reinstall");
        }
        else if (drv_ver_managed > wrapperActual) {
            throw gcnew VersionException("newer driver version is installed");
        }
        else {
            return drv_ver_managed;
        }
    }

};