Example #1
0
        public Core_Interception()
        {
            _providerDescriptor = new ProviderDescriptor
            {
                ProviderName = ProviderName
            };
            ProcessSettingsFile();

            _deviceLibrary = new IceptDeviceLibrary(_providerDescriptor, _blockingEnabled);
            if (_deviceLibrary.GetInputList().Devices?.Count > 0)
            {
                _isLive       = true;
                _errorMessage = string.Empty;
            }
            else
            {
                _isLive       = false;
                _errorMessage = "No Interception devices found, driver assumed to not be installed";
            }

            _deviceContext = ManagedWrapper.CreateContext();

            StartPollingIfNeeded();
            //_pollThreadDesired = true;
            _timer = new MultimediaTimer()
            {
                Interval = _pollRate
            };
            _timer.Elapsed += DoPoll;
        }
Example #2
0
        /// <summary>
        /// Same as <see cref="SendMouseButtonEvent" />, but sends button events in Absolute mode (with coordinates)
        /// </summary>
        /// <param name="btn">Button ID to send</param>
        /// <param name="state">State of the button</param>
        /// <param name="x">X position</param>
        /// <param name="y">Y position</param>
        public void SendMouseButtonEventAbsolute(int btn, int state, int x, int y)
        {
            var stroke = HelperFunctions.MouseButtonAndStateToStroke(btn, state);

            stroke.mouse.x     = x;
            stroke.mouse.y     = y;
            stroke.mouse.flags = (ushort)ManagedWrapper.MouseFlag.MouseMoveAbsolute;
            ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
        }
Example #3
0
        /// <summary>
        ///     Sends Relative Mouse Movement
        /// </summary>
        /// <param name="x">X movement</param>
        /// <param name="y">Y movement</param>
        /// <returns></returns>
        public void SendMouseMoveRelative(int x, int y)
        {
            var stroke = new ManagedWrapper.Stroke
            {
                mouse = { x = x, y = y, flags = (ushort)ManagedWrapper.MouseFlag.MouseMoveRelative }
            };

            ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
        }
        public static int[] cw_GetPlayerDistro()
        {
            IntPtr ptr = ManagedWrapper.cpp_GetDistro();

            int[] result = new int[35];
            Marshal.Copy(ptr, result, 0, 35);

            return(result);
        }
        //counter related
        public static int[] cw_SyncCount()
        {
            IntPtr ptr = ManagedWrapper.cpp_SyncCounter();

            int[] result = new int[2];
            Marshal.Copy(ptr, result, 0, 2);

            return(result);
        }
Example #6
0
        public IceptDeviceLibrary(ProviderDescriptor providerDescriptor)
        {
            _providerDescriptor = providerDescriptor;
            _deviceContext      = ManagedWrapper.CreateContext();

            InitKeyReports();
            InitMouseReports();

            RefreshConnectedDevices();
        }
Example #7
0
        /// <summary>
        /// Sends a keyboard key event
        /// </summary>
        /// <param name="code">The ScanCode to send</param>
        /// <param name="state">The State to send (1 = pressed, 0 = released)</param>
        public void SendKeyEvent(ushort code, int state)
        {
            var strokes = ScanCodeHelper.TranslateAhkCode(code, state);

            for (int i = 0; i < strokes.Count; i++)
            {
                var stroke = strokes[i];
                ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
            }
        }
Example #8
0
 /// <summary>
 /// Turns on / off filtering of devices
 /// Any filtered device will be blocked if the provider crashes
 /// Also controls which devices are filtered when filtering is on
 /// </summary>
 /// <param name="state">Set to true to turn filtering on</param>
 private void SetFilterState(bool state)
 {
     if (state && !_filterState)
     {
         HelperFunctions.Log("Enabling Interception filter");
         ManagedWrapper.SetFilter(_deviceContext, IsMonitoredKeyboard, ManagedWrapper.Filter.All);
         ManagedWrapper.SetFilter(_deviceContext, IsMonitoredMouse, ManagedWrapper.Filter.All);
         _filterState = true;
     }
     else if (!state && _filterState)
     {
         HelperFunctions.Log("Disabling Interception filter");
         ManagedWrapper.SetFilter(_deviceContext, IsMonitoredKeyboard, ManagedWrapper.Filter.None);
         ManagedWrapper.SetFilter(_deviceContext, IsMonitoredMouse, ManagedWrapper.Filter.None);
         _filterState = false;
     }
 }
Example #9
0
        private void handleKeyPress(KeyPress kp)
        {
            var stroke = new ManagedWrapper.Stroke();

            stroke.key.code = (ushort)kp.key;
            if (kp.action == Settings.Action.PRESSED)
            {
                stroke.key.state = (ushort)ManagedWrapper.KeyState.Down;
            }
            else
            {
                stroke.key.state = (ushort)ManagedWrapper.KeyState.Up;
            }
            int devId = 4;

            // Console.WriteLine(stroke.key.code + " " + kp.action);
            ManagedWrapper.Send(deviceContext, devId, ref stroke, 1);
            System.Threading.Thread.Sleep(10);
        }
Example #10
0
        public Core_Interception()
        {
            _providerDescriptor = new ProviderDescriptor
            {
                ProviderName = ProviderName
            };
            _deviceLibrary = new IceptDeviceLibrary(_providerDescriptor);

            ProcessSettingsFile();

            _deviceContext = ManagedWrapper.CreateContext();

            StartPollingIfNeeded();
            //_pollThreadDesired = true;
            _timer = new MultimediaTimer()
            {
                Interval = _pollRate
            };
            _timer.Elapsed += DoPoll;
        }
 static IntPtr[] wrapManaged(I[] managed, bool callAddRef)
 {
     if (null != managed)
     {
         // Not sure about the performance.
         // Theoretically, these small arrays should never leave generation 0 of the managed heap.
         // Practically, using `new` with GPU calls can create measurable load on GC.
         // Maybe we need to do something more sophisticated here, like use ArrayPool<IntPtr>.Shared for these arrays.
         IntPtr[] result = new IntPtr[managed.Length];
         for (int i = 0; i < managed.Length; i++)
         {
             I obj = managed[i];
             if (null != obj)
             {
                 result[i] = ManagedWrapper.wrap <I>(obj, callAddRef);
             }
         }
         return(result);
     }
     return(null);
 }
Example #12
0
        private bool TryFindKeyboardDeviceId(out int deviceId)
        {
            for (int i = 1; i <= 20; i++)
            {
                if (ManagedWrapper.IsKeyboard(i) <= 0)
                {
                    continue;
                }

                string name = ManagedWrapper.GetHardwareStr(context, i);
                if (!string.IsNullOrWhiteSpace(name))
                {
                    // Console.WriteLine($"Found device\nid = {i}\nname = {name}");
                    deviceId = i;
                    return(true);
                }
            }

            deviceId = -1;
            return(false);
        }
Example #13
0
        public void Run(Sequence sequence)
        {
            if (TryFindKeyboardDeviceId(out int device))
            {
                foreach (var action in sequence)
                {
                    if (ProcessSpecialAction(action))
                    {
                        continue;
                    }

                    var stroke = action.ToStroke();
                    ManagedWrapper.Send(context, device, ref stroke, 1);
                    Delay(Interval);
                }
            }
            else
            {
                throw new Exception("No keyboard found");
            }
        }
Example #14
0
        public void EchoInput()
        {
            Console.WriteLine("Echo mode activated. Press Ctrl-C to exit.");
            Console.WriteLine("code\tstate\tname");

            ManagedWrapper.SetFilter(context, ManagedWrapper.IsKeyboard, ManagedWrapper.Filter.All);
            try
            {
                while (true)
                {
                    int device;
                    var stroke = new ManagedWrapper.Stroke();
                    if (ManagedWrapper.Receive(context, device = ManagedWrapper.WaitWithTimeout(context, 5), ref stroke, 1) > 0)
                    {
                        if (ManagedWrapper.IsKeyboard(device) > 0)
                        {
                            int scancode = stroke.key.code;
                            if ((stroke.key.state & 2) != 0)
                            {
                                scancode += 256;
                            }

                            Console.WriteLine($"{stroke.key.code}\t"
                                              + $"{(ManagedWrapper.KeyState) stroke.key.state}\t"
                                              + $"{KeyNameHelper.GetNameFromScanCode(scancode)}");

                            ManagedWrapper.Send(context, device, ref stroke, 1);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
        }
Example #15
0
 private void ReleaseUnmanagedResources()
 {
     ManagedWrapper.DestroyContext(context);
 }
Example #16
0
        // ScanCode notes: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html
        public override void ProcessStroke(List <ManagedWrapper.Stroke> strokes)
        {
            var hasSubscription = false;
            var hasContext      = ContextCallback != null;

            // Process any waiting input for this keyboard
            var block = false;

            if (_isFiltered)
            {
                var            isKeyMapping   = false; // True if this is a mapping to a single key, else it would be a mapping to a whole device
                var            processedState = ScanCodeHelper.TranslateScanCodes(strokes);
                var            code           = processedState.Code;
                var            state          = processedState.State;
                MappingOptions mapping        = null;

                // If there is a mapping to this specific key, then use that ...
                if (SingleButtonMappings.ContainsKey(code))
                {
                    isKeyMapping = true;
                    mapping      = SingleButtonMappings[code];
                }
                // ... otherwise, if there is a mapping to the whole keyboard, use that
                else if (AllButtonsMapping != null)
                {
                    mapping = AllButtonsMapping;
                }

                if (mapping != null)
                {
                    hasSubscription = true;

                    if (mapping.Block)
                    {
                        block = true;
                    }
                    if (mapping.Concurrent)
                    {
                        if (isKeyMapping)
                        {
                            ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(state));
                        }
                        else
                        {
                            ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(code, state));
                        }
                    }
                    else
                    {
                        //mapping.Callback(code, state);
                        if (isKeyMapping)
                        {
                            WorkerThreads[code]?.Actions.Add(() => mapping.Callback(state));
                        }
                        else
                        {
                            DeviceWorkerThread?.Actions.Add(() => mapping.Callback(code, state));
                        }
                    }
                }
                // If the key was blocked by Subscription Mode, then move on to next key...
                if (block)
                {
                    return;
                }

                // If this key had no subscriptions, but Context Mode is set for this keyboard...
                // ... then set the Context before sending the key
                if (!hasSubscription && hasContext)
                {
                    ContextCallback(1);
                }

                // Pass the key(s) through to the OS.
                for (int i = 0; i < strokes.Count; i++)
                {
                    var stroke = strokes[i];
                    ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
                }

                // If we are processing Context Mode, then Unset the context variable after sending the key
                if (!hasSubscription && hasContext)
                {
                    ContextCallback(0);
                }
            }
        }
        protected override void ProcessRecord()
        {
            ManagedWrapper foo = new ManagedWrapper();

            foo.Run();
        }
Example #18
0
        // public static void GetVidPid(string str, ref int vid, ref int pid)
        // {
        //     var matches = Regex.Matches(str, @"VID_(\w{4})&PID_(\w{4})");
        //     if (matches.Count <= 0 || matches[0].Groups.Count <= 1) return;
        //     vid = Convert.ToInt32(matches[0].Groups[1].Value, 16);
        //     pid = Convert.ToInt32(matches[0].Groups[2].Value, 16);
        // }

        public void start()
        {
            // var stroke = new ManagedWrapper.Stroke();
            // stroke.key.code = (ushort)Keys.J;
            // stroke.key.state = (ushort)ManagedWrapper.KeyState.Down;
            // int devId = 1;
            // ManagedWrapper.Send(_deviceContext, devId, ref stroke, 1);

            //use this code to determine keys
            // ManagedWrapper.SetFilter(deviceContext, ManagedWrapper.IsKeyboard, ManagedWrapper.Filter.All);
            // var stroke = new ManagedWrapper.Stroke();
            // int device = 0;
            // while (ManagedWrapper.Receive(deviceContext, device = ManagedWrapper.Wait(deviceContext), ref stroke, 1) > 0)
            // {
            //     if(ManagedWrapper.IsKeyboard(device) > 0) {
            //         Console.WriteLine(stroke.key.code);
            //         if(stroke.key.code == 1)
            //             break;
            //     }
            // }
            // ManagedWrapper.SetFilter(deviceContext, ManagedWrapper.IsKeyboard, ManagedWrapper.Filter.None);

            // var ret = new List<DeviceInfo>();
            for (var i = 1; i < 21; i++)
            {
                var handle = ManagedWrapper.GetHardwareStr(deviceContext, i, 1000);
                if (handle == "")
                {
                    continue;
                }
                // int foundVid = 0, foundPid = 0;
                // GetVidPid(handle, ref foundVid, ref foundPid);
                //if (foundVid == 0 || foundPid == 0) continue;
                // Console.WriteLine(i + " " + handle);
                // ret.Add(new DeviceInfo {Id = i, IsMouse = i > 10, Handle = handle});
            }

            // foreach (var device in ret)
            // {
            //     Console.WriteLine(device);
            // }


            var controllers = new[] { new Controller(), new Controller(UserIndex.One), new Controller(UserIndex.Two), new Controller(UserIndex.Three), new Controller(UserIndex.Four) };

            // Get 1st controller available
            Controller controller = controllers[0];

            foreach (var selectControler in controllers)
            {
                // Console.WriteLine(selectControler);
                if (selectControler.IsConnected)
                {
                    controller = selectControler;
                    break;
                }
            }

            if (controller == null)
            {
                Console.WriteLine("No XInput controller installed");
            }
            else
            {
                Console.WriteLine("KeyMapper loaded");
                // Console.WriteLine("Found a XInput controller available");
                // Console.WriteLine("Press buttons on the controller to display events or escape key to exit... ");

                // Poll events from joystick
                SharpDX.XInput.State      previousControllerState = controller.GetState();
                Dictionary <Button, bool> lastSimpleGamepadState  = determineSimpleButtonState(previousControllerState);

                StateTransition lastState = null;

                while (!ModuleData.getInstance().cancellationToken.IsCancellationRequested)
                {
                    if (controller.IsConnected)
                    {
                        SharpDX.XInput.State controllerState = controller.GetState();
                        if (previousControllerState.PacketNumber != controllerState.PacketNumber)
                        {
                            // Console.WriteLine(controllerState.Gamepad);

                            Dictionary <Button, bool>            simpleGamepadState = determineSimpleButtonState(controllerState);
                            Dictionary <Button, Settings.Action> changedState       = determineStateDifferences(lastSimpleGamepadState, simpleGamepadState);
                            printStateChanges(changedState);
                            // Console.WriteLine(GetActiveWindowTitle());

                            //determine if we are transitioning to a new 'state'
                            //  this is based on the current state, the game state and the keys pressed/not pressed
                            //  NOTE: the first state wins, for speed
                            StateTransition newState = getNewState(simpleGamepadState, ModuleData.getInstance().companionSettings.stateTransitions);
                            if (newState == null && lastState == null)
                            {
                                //nothing to do
                            }
                            else if (newState != null && lastState == null)
                            {
                                activateState(newState);
                            }
                            else if (newState == null && lastState != null)
                            {
                                deactivateState(lastState);
                            }
                            else if (newState != null && lastState != null && !newState.transitionName.Equals(lastState.transitionName))
                            {
                                deactivateState(lastState);
                                activateState(newState);
                            }

                            //now that we have the state name determined, load the correct mappings
                            StateControllerMapping stateControllerMappings = findStateControllerMappings(newState, ModuleData.getInstance().companionSettings.stateMappings);

                            //apply button presses and such
                            foreach (Button key in changedState.Keys)
                            {
                                Settings.Action action = changedState[key];
                                foreach (ControllerMapping controllerMapping in stateControllerMappings.controllerMappings)
                                {
                                    if (controllerMapping.button.button == key && action == controllerMapping.button.action)
                                    {
                                        handleCommand(controllerMapping);
                                    }
                                }
                            }

                            lastState = newState;
                            lastSimpleGamepadState = simpleGamepadState;
                        }
                        Thread.Sleep(10);
                        previousControllerState = controllerState;
                    }
                }
            }
        }
 //function at the start that is called by C# and passes all the callback functions
 public static void cw_AssignCallbacks(Delegate UpdatePlayers, Delegate SyncCounter)
 {
     ManagedWrapper.cpp_AssignCallbacks(UpdatePlayers, SyncCounter);
 }
 //create counter in c++
 public static void cw_CreateCounter(int set, int update)
 {
     ManagedWrapper.cpp_CreateCounter(set, update);
 }
Example #21
0
        private void DoPoll(object sender, EventArgs e)
        {
            _pollThreadRunning = true;
            var stroke = new ManagedWrapper.Stroke();

            // Process Keyboard input
            for (var i = 1; i < 11; i++)
            {
                var isMonitoredKeyboard = _monitoredKeyboards.ContainsKey(i);

                while (ManagedWrapper.Receive(_deviceContext, i, ref stroke, 1) > 0)
                {
                    if (isMonitoredKeyboard)
                    {
                        var blockingRequestedByUi = _monitoredKeyboards[i].ProcessUpdate(stroke);

                        // Block for keyboard either blocks whole stroke or allows whole stroke through
                        if (_blockingEnabled && (!_blockingControlledByUi || blockingRequestedByUi))
                        {
                            continue; // Block input
                        }
                    }

                    // Pass through stroke
                    if (_fireStrokeOnThread)
                    {
                        var threadStroke = stroke;
                        var deviceId     = i;
                        ThreadPool.QueueUserWorkItem(cb => ManagedWrapper.Send(_deviceContext, deviceId, ref threadStroke, 1));
                    }
                    else
                    {
                        ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);
                    }
                }
            }

            // Process Mouse input
            // As a mouse stroke can contain multiple updates (buttons, movement etc) per stroke...
            // ...blocking is handled in ProcessUpdate, so if part of the stroke is blocked, it will be removed from the stroke
            for (var i = 11; i < 21; i++)
            {
                var isMonitoredMouse = _monitoredMice.ContainsKey(i);

                while (ManagedWrapper.Receive(_deviceContext, i, ref stroke, 1) > 0)
                {
                    if (isMonitoredMouse)
                    {
                        stroke = _monitoredMice[i].ProcessUpdate(stroke);
                        // Handle blocking - if all updates have been removed from stroke, do not bother to pass the stroke through
                        if (stroke.mouse.x == 0 && stroke.mouse.y == 0 && stroke.mouse.state == 0)
                        {
                            continue;
                        }
                    }

                    // Pass through stroke
                    if (_fireStrokeOnThread)
                    {
                        var threadStroke = stroke;
                        var deviceId     = i;
                        ThreadPool.QueueUserWorkItem(cb => ManagedWrapper.Send(_deviceContext, deviceId, ref threadStroke, 1));
                    }
                    else
                    {
                        ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);
                    }
                }
            }
            _pollThreadRunning = false;
        }
Example #22
0
        public bool SetOutputState(OutputSubscriptionRequest subReq, BindingDescriptor bindingDescriptor, int state)
        {
            int devId;

            try
            {
                devId = _deviceLibrary.GetInputDeviceIdentifier(subReq.DeviceDescriptor);
            }
            catch
            {
                return(false);
            }
            //Log("SetOutputState. Type: {0}, Index: {1}, State: {2}, Device: {3}", inputType, inputIndex, state, devId);
            var stroke = new ManagedWrapper.Stroke();

            if (HelperFunctions.IsKeyboard(devId))
            {
                var st   = (ushort)(1 - state);
                var code = (ushort)(bindingDescriptor.Index + 1);
                if (code > 255)
                {
                    st   += 2;
                    code -= 256;
                }
                stroke.key.code  = code;
                stroke.key.state = st;
            }
            else
            {
                switch (bindingDescriptor.Type)
                {
                case BindingType.Axis:
                    var mouse = new ManagedWrapper.MouseStroke
                    {
                        //ToDo: This only implements mouse relative mode - can we allow absolute mode too?
                        flags = (ushort)ManagedWrapper.MouseFlag.MouseMoveRelative
                    };
                    if (bindingDescriptor.Index != 0)
                    {
                        if (bindingDescriptor.Index == 1)
                        {
                            mouse.y = state;
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        mouse.x = state;
                    }

                    stroke.mouse = mouse;
                    break;

                case BindingType.Button:
                    var btn  = bindingDescriptor.Index;
                    var flag = (int)ManagedWrapper.MouseButtonFlags[btn];
                    if (btn < 5)
                    {
                        // Regular buttons
                        if (state == 0)
                        {
                            flag *= 2;
                        }
                    }
                    else
                    {
                        // Wheel
                        stroke.mouse.rolling = (short)((btn == 5 || btn == 8) ? 120 : -120);
                    }

                    stroke.mouse.state = (ushort)flag;
                    break;

                case BindingType.POV:
                default:
                    throw new NotImplementedException();
                }
            }
            ManagedWrapper.Send(_deviceContext, devId, ref stroke, 1);
            return(true);
        }
Example #23
0
        /// <summary>
        /// Sends Mouse button events
        /// </summary>
        /// <param name="btn">Button ID to send</param>
        /// <param name="state">State of the button</param>
        /// <returns></returns>
        public void SendMouseButtonEvent(int btn, int state)
        {
            var stroke = HelperFunctions.MouseButtonAndStateToStroke(btn, state);

            ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
        }
 //player related
 public static void cw_GetMakePlayer(int addPlayers)
 {
     ManagedWrapper.cpp_MakePlayer(addPlayers);
 }
Example #25
0
        public void RefreshConnectedDevices()
        {
            _deviceHandleToId = new Dictionary <string, List <int> >();
            _deviceReports    = new List <DeviceReport>();

            string handle;

            for (var i = 1; i < 11; i++)
            {
                if (ManagedWrapper.IsKeyboard(i) != 1)
                {
                    continue;
                }
                handle = ManagedWrapper.GetHardwareStr(_deviceContext, i, 1000);
                if (handle == "")
                {
                    continue;
                }
                int vid = 0, pid = 0;
                GetVidPid(handle, ref vid, ref pid);
                var name = "";
                if (vid != 0 && pid != 0)
                {
                    name = DeviceHelper.GetDeviceName(vid, pid);
                }

                if (name == "")
                {
                    name = handle;
                }

                handle = $@"Keyboard\{handle}";

                if (!_deviceHandleToId.ContainsKey(handle))
                {
                    _deviceHandleToId.Add(handle, new List <int>());
                }

                var instance = _deviceHandleToId[handle].Count;
                _deviceHandleToId[handle].Add(i);

                name = $"K: {name}";
                if (instance > 0)
                {
                    name += $" #{instance + 1}";
                }

                _deviceReports.Add(new DeviceReport
                {
                    DeviceName       = name,
                    DeviceDescriptor = new DeviceDescriptor
                    {
                        DeviceHandle   = handle,
                        DeviceInstance = instance
                    },
                    Nodes = new List <DeviceReportNode>
                    {
                        _keyboardList
                    }
                });
                //Log(String.Format("{0} (Keyboard) = VID: {1}, PID: {2}, Name: {3}", i, vid, pid, name));
            }

            for (var i = 11; i < 21; i++)
            {
                if (ManagedWrapper.IsMouse(i) != 1)
                {
                    continue;
                }
                handle = ManagedWrapper.GetHardwareStr(_deviceContext, i, 1000);
                if (handle == "")
                {
                    continue;
                }
                int vid = 0, pid = 0;
                GetVidPid(handle, ref vid, ref pid);
                var name = "";
                if (vid != 0 && pid != 0)
                {
                    name = DeviceHelper.GetDeviceName(vid, pid);
                }

                if (name == "")
                {
                    name = handle;
                }

                handle = $@"Mouse\{handle}";

                if (!_deviceHandleToId.ContainsKey(handle))
                {
                    _deviceHandleToId.Add(handle, new List <int>());
                }

                var instance = _deviceHandleToId[handle].Count;
                _deviceHandleToId[handle].Add(i);

                name = $"M: {name}";
                if (instance > 0)
                {
                    name += $" #{instance + 1}";
                }

                _deviceReports.Add(new DeviceReport
                {
                    DeviceName       = name,
                    DeviceDescriptor = new DeviceDescriptor
                    {
                        DeviceHandle   = handle,
                        DeviceInstance = instance
                    },
                    Nodes = new List <DeviceReportNode>
                    {
                        _mouseButtonList,
                        StaticData.MouseAxisList
                    }
                });
                //Log(String.Format("{0} (Mouse) = VID/PID: {1}", i, handle));
                //Log(String.Format("{0} (Mouse) = VID: {1}, PID: {2}, Name: {3}", i, vid, pid, name));
            }

            _providerReport = new ProviderReport
            {
                Title              = "Interception (Core)",
                Description        = "Supports per-device Keyboard and Mouse Input/Output, with blocking\nRequires custom driver from http://oblita.com/interception",
                API                = "Interception",
                ProviderDescriptor = _providerDescriptor,
                Devices            = _deviceReports
            };
        }
        static IntPtr factory(Stream managed, bool addRef)
        {
            NativeReadStream wrapper = new NativeReadStream(managed);

            return(ManagedWrapper.wrap <iReadStream>(wrapper, addRef));
        }
Example #27
0
        public override void ProcessStroke(List <ManagedWrapper.Stroke> strokes)
        {
            for (int i = 0; i < strokes.Count; i++)
            {
                var stroke          = strokes[i];
                var hasSubscription = false;
                var hasContext      = ContextCallback != null;

                var moveRemoved = false;
                var hasMove     = false;

                var x = stroke.mouse.x;
                var y = stroke.mouse.y;

                // Process mouse movement
                var isAbsolute = (stroke.mouse.flags & (ushort)ManagedWrapper.MouseFlag.MouseMoveAbsolute) ==
                                 (ushort)ManagedWrapper.MouseFlag.MouseMoveAbsolute;
                //Determine whether or not to report mouse movement.
                // For Relative mode, this is fairly simple - if x and y are both 0, no movement was reported (Since a real mouse never reports x=0/y=0)
                // For Absolute mode, x=0/y=0 is reported, but we should limit this to only reporting once...
                // ... so when x=0/y=0 is seen in absolute mode, set the flag _absoluteMode00Reported to true and allow it to be reported...
                // then on subsequent reports of x=0/y=0 for absolute mode, if _absoluteMode00Reported is already true, then do not report movement...
                // ... In absolute mode, when x!=0/y!=0 is received, clear the _absoluteMode00Reported flag
                if (isAbsolute)
                {
                    if (x == 0 && y == 0)
                    {
                        if (!_absoluteMode00Reported)
                        {
                            hasMove = true;
                            _absoluteMode00Reported = true;
                        }
                        else
                        {
                            hasMove = false;
                        }
                    }
                    else
                    {
                        hasMove = true;
                        _absoluteMode00Reported = false;
                    }
                }
                else
                {
                    hasMove = (x != 0 || y != 0);
                }

                if (hasMove)
                {
                    // Process Absolute Mouse Move
                    if (isAbsolute)
                    {
                        if (_mouseMoveAbsoluteMapping != null)
                        {
                            var mapping = _mouseMoveAbsoluteMapping;
                            hasSubscription = true;
                            //var debugStr = $"AHK| Mouse stroke has absolute move of {x}, {y}...";

                            if (mapping.Concurrent)
                            {
                                ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(x, y));
                            }
                            else if (WorkerThreads.ContainsKey(7))
                            {
                                WorkerThreads[7]?.Actions.Add(() => mapping.Callback(x, y));
                            }
                            if (mapping.Block)
                            {
                                moveRemoved    = true;
                                stroke.mouse.x = 0;
                                stroke.mouse.y = 0;
                                //debugStr += "Blocking";
                            }
                            else
                            {
                                //debugStr += "Not Blocking";
                            }

                            //Debug.WriteLine(debugStr);
                        }
                    }
                    else
                    {
                        if (_mouseMoveRelativeMapping != null)
                        {
                            var mapping = _mouseMoveRelativeMapping;
                            hasSubscription = true;
                            //var debugStr = $"AHK| Mouse stroke has relative move of {x}, {y}...";

                            if (mapping.Concurrent)
                            {
                                ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(x, y));
                            }
                            else if (WorkerThreads.ContainsKey(8))
                            {
                                WorkerThreads[8]?.Actions.Add(() => mapping.Callback(x, y));
                            }
                            if (mapping.Block)
                            {
                                moveRemoved    = true;
                                stroke.mouse.x = 0;
                                stroke.mouse.y = 0;
                                //debugStr += "Blocking";
                            }
                            else
                            {
                                //debugStr += "Not Blocking";
                            }

                            //Debug.WriteLine(debugStr);
                        }
                    }
                }

                var isMouseButtonsMapping = AllButtonsMapping != null;

                // Process Mouse Buttons - do this AFTER mouse movement, so that absolute mode has coordinates available at the point that the button callback is fired
                if (stroke.mouse.state != 0 && SingleButtonMappings.Count > 0 || isMouseButtonsMapping)
                {
                    var btnStates = HelperFunctions.MouseStrokeToButtonStates(stroke);
                    foreach (var btnState in btnStates)
                    {
                        if (!isMouseButtonsMapping && !SingleButtonMappings.ContainsKey(btnState.Button))
                        {
                            continue;
                        }

                        hasSubscription = true;
                        MappingOptions mapping = null;
                        if (isMouseButtonsMapping)
                        {
                            mapping = AllButtonsMapping;
                        }
                        else
                        {
                            mapping = SingleButtonMappings[btnState.Button];
                        }

                        var state = btnState;

                        if (mapping.Concurrent)
                        {
                            if (isMouseButtonsMapping)
                            {
                                ThreadPool.QueueUserWorkItem(threadProc =>
                                                             mapping.Callback(btnState.Button, state.State));
                            }
                            else
                            {
                                ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(state.State));
                            }
                        }
                        else
                        {
                            if (isMouseButtonsMapping)
                            {
                                DeviceWorkerThread?.Actions
                                .Add(() => mapping.Callback(btnState.Button, state.State));
                            }
                            else
                            {
                                WorkerThreads[btnState.Button]?.Actions
                                .Add(() => mapping.Callback(state.State));
                            }
                        }


                        if (mapping.Block)
                        {
                            // Remove the event for this button from the stroke, leaving other button events intact
                            stroke.mouse.state -= btnState.Flag;
                            // If we are removing a mouse wheel event, then set rolling to 0 if no mouse wheel event left
                            if (btnState.Flag == 0x400 || btnState.Flag == 0x800)
                            {
                                if ((stroke.mouse.state & 0x400) != 0x400 &&
                                    (stroke.mouse.state & 0x800) != 0x800)
                                {
                                    //Debug.WriteLine("AHK| Removing rolling flag from stroke");
                                    stroke.mouse.rolling = 0;
                                }
                            }

                            //Debug.WriteLine($"AHK| Removing flag {btnState.Flag} from stoke, leaving state {stroke.mouse.state}");
                        }
                        else
                        {
                            //Debug.WriteLine($"AHK| Leaving flag {btnState.Flag} in stroke");
                        }
                    }
                }

                // Forward on the stroke if required
                if (hasSubscription)
                {
                    // Subscription mode
                    // If the stroke has a move that was not removed, OR it has remaining button events, then forward on the stroke
                    if ((hasMove && !moveRemoved) || stroke.mouse.state != 0)
                    {
                        //Debug.WriteLine($"AHK| Sending stroke. State = {stroke.mouse.state}. hasMove={hasMove}, moveRemoved={moveRemoved}");
                        ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
                    }
                    else
                    {
                        // Everything removed from stroke, do not forward
                        //Debug.WriteLine("AHK| Mouse stroke now empty, not forwarding");
                    }
                }
                else if (hasContext)
                {
                    // Context Mode - forward stroke with context wrapping
                    ContextCallback(1);
                    ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
                    ContextCallback(0);
                }
                else
                {
                    // No subscription or context mode - forward on
                    //Debug.WriteLine($"AHK| Sending stroke. State = {stroke.mouse.state}. hasMove={hasMove}, moveRemoved={moveRemoved}");
                    ManagedWrapper.Send(DeviceContext, DeviceId, ref stroke, 1);
                }
            }
        }
 //get count from c++ counter
 public static int cw_GetCount()
 {
     return(ManagedWrapper.cpp_GetCount());
 }
Example #29
0
 public Mapper()
 {
     this.deviceContext = ManagedWrapper.CreateContext();
 }