macOS Sierra: Emulate Mouse Down and Up - mouseevent

after an update to Sierra I had to find that Karabiner is not working anymore, which could emulate pointer clicks really well.
Any chance to get that via Swift or Apple Script or Obj.C ?
Background: Using Karabiner(and seil) I could bind caps-lock + d down and up to mouse down and up and in between the trackpad movement was understood. My trackpad is not processing keypress anymore but works still fine for pointer moves.

Answering myself, hacked it in hammerspoon. Was quite tricky to get chrome select working, maybe it saves somebody an hour or two:
1 ~/.hammerspoon $ cat init.lua
--[[ Left Keyboard Mouse (alt-d)
The main problem was to get chrome based apps select text when we drag via
keyboard.
You MUST return true always in the handle_drag otherwise it fails to select.
FF works, terminal works, chrome apps (atom, ...) don't.
But true is preventing further processing of the drag coords,
hs.mouse.getAbsolutePosition remains constant while dragging (!)
=> i.e. we MUST calc them via DeltaX, DeltaY, see below.
--]]
hs.alert.show("Config loaded")
-- all mechanics stolen from here:
-- local vimouse = require('vimouse')
-- vimouse('cmd', 'm')
now = hs.timer.secondsSinceEpoch
evt = hs.eventtap
evte = evt.event
evtypes = evte.types
evp=evte.properties
drag_last = now(); drag_intv = 0.01 -- we only synth drags from time to time
mp = {['x']=0, ['y']=0} -- mouse point. coords and last posted event
l = hs.logger.new('keybmouse', 'debug')
dmp = hs.inspect
-- The event tap. Started with the keyboard click:
handled = {evtypes.mouseMoved, evtypes.keyUp }
handle_drag = evt.new(handled, function(e)
if e:getType() == evtypes.keyUp then
handle_drag:stop()
post_evt(2)
return nil -- otherwise the up seems not processed by the OS
end
mp['x'] = mp['x'] + e:getProperty(evp.mouseEventDeltaX)
mp['y'] = mp['y'] + e:getProperty(evp.mouseEventDeltaY)
-- giving the key up a chance:
if now() - drag_last > drag_intv then
-- l.d('pos', mp.x, 'dx', dx)
post_evt(6) -- that sometimes makes dx negative in the log above
drag_last = now()
end
return true -- important
end)
function post_evt(mode)
-- 1: down, 2: up, 6: drag
if mode == 1 or mode == 2 then
local p = hs.mouse.getAbsolutePosition()
mp['x'] = p.x
mp['y'] = p.y
end
local e = evte.newMouseEvent(mode, mp)
if mode == 6 then cs = 0 else cs=1 end
e:setProperty(evte.properties.mouseEventClickState, cs)
e:post()
end
hs.hotkey.bind({"alt"}, "d",
function(event)
post_evt(1)
handle_drag:start()
end
)
and alt I mapped to capslock via karabiner elements.

Related

Godot: advanced swiping mechanics

I have a VboxContainer as a child of a ScrollContainer and some text and buttons in it – a long list I can scoll through by finger-swiping on a touchscreen.
The code (based on https://github.com/godotengine/godot/issues/21137#issuecomment-414959543):
extends ScrollContainer
var swiping = false
var swipe_start
var swipe_mouse_start
var swipe_mouse_times = []
var swipe_mouse_positions = []
signal finger_is_swiping
func _ready():
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _input(ev):
if ev is InputEventMouseButton:
if ev.pressed:
swiping = true
swipe_start = Vector2(get_h_scroll(), get_v_scroll())
swipe_mouse_start = ev.position
swipe_mouse_times = [OS.get_ticks_msec()]
swipe_mouse_positions = [swipe_mouse_start]
else:
swipe_mouse_times.append(OS.get_ticks_msec())
swipe_mouse_positions.append(ev.position)
var source = Vector2(get_h_scroll(), get_v_scroll())
var idx = swipe_mouse_times.size() - 1
var now = OS.get_ticks_msec()
var cutoff = now - 100
for i in range(swipe_mouse_times.size() - 1, -1, -1):
if swipe_mouse_times[i] >= cutoff: idx = i
else: break
var flick_start = swipe_mouse_positions[idx]
var flick_dur = min(0.3, (ev.position - flick_start).length() / 1000)
if flick_dur > 0.0:
var tween = Tween.new()
add_child(tween)
var delta = ev.position - flick_start
var target = source - delta * flick_dur * 8.0
#tween.interpolate_method(self, 'set_h_scroll', source.x, target.x, flick_dur, Tween.TRANS_QUAD, Tween.EASE_OUT)
tween.interpolate_method(self, 'set_v_scroll', source.y, target.y, flick_dur, Tween.TRANS_QUAD, Tween.EASE_OUT)
tween.interpolate_callback(tween, flick_dur, 'queue_free')
tween.start()
swiping = false
elif swiping and ev is InputEventMouseMotion:
var delta = ev.position - swipe_mouse_start
set_h_scroll(swipe_start.x - delta.x)
set_v_scroll(swipe_start.y - delta.y)
swipe_mouse_times.append(OS.get_ticks_msec())
swipe_mouse_positions.append(ev.position)
emit_signal("finger_is_swiping")
print ("finger is swiping")
It works quite nicely, but there are three hurdles I need help with:
While swiping, the print "finger is swiping" is being printed all the time, many times, and I therefore assume that the signal "finger_is_swiping" is being emitted as often as well. How can I have the signal being emitted only once per swipe? (Or is that a problem at all?)
How can I set a signal when my finger stops swiping (so when it's lifted from the touchscreen)?
I'd like the swipe-movement not to cause scrolling at all when touching a button in the list first. (My buttons work in a way so I can hold them down and make them not trigger by dragging the finger off... in such a case I'd like the list not to scroll despite the dragging.) I'd assume that I could have the button emit a signal which causes some "ignore swipe" or set the swipe speed to 0 maybe?
EDIT:
Yes, a simple swiping = false does this trick!

tryCatch crashes while nls fit

I am trying to fit a non-linear model using nls function. The model has a conditioning and works by groups therefore I try to implement a loop which covers over 300 combinations of starting values. I am using tryCatch but to my surprise the loop crashes, I guess because of the starting values or lower and upper bounds.
tryCatch(
for(r in 1:nrow(st4)){
halfLE3[[r]] <- nls(
inty ~ I(time < (position/velocity) + dinitial) * Inty_S0 +
(time >= (position/velocity) + dinitial) *
I(Intyf[probe] + (Inty_S0[probe] - Intyf) *
(exp(-Decay * (time - (position/velocity) + dinitial)))),
data = Data4,
algorithm = "port",
control = list(warnOnly = TRUE),
start = list(Decay=st4[r,3], dinitial=st4[r,2],
Intyf=rep(st4[r,4], length(levels(Data4$probe))),
Inty_S0=rep(st4[r,5], length(levels(Data4$probe))),
velocity=st4[r,1]),
lower = list(Decay= .1, dinitial=0.1, velocity=10, Intyf=0.1, inty_S0=.5),
upper = list(Decay= 1, dinitial=10, velocity=8000, Intyf=1, inty_S0=1.5)
)
}
,error = function(e) {e}
)
st4 is a dataframe with 300 combinations of starting values.
probe refers to group.
Do you have any idea why the loop crashes even using the tryCatch? Do you have any idea what I can improve? I used the nls.control changing the maxiter and other parameters but works same as the control I use here above.
I would be very grateful for any suggestion.
I fixed the issue. The tryCatch should be located inside the for loop adding a bracket.
for(r in 1:nrow(st4)){
tryCatch({
nls()......
},error = function(e) {e}
)
}

Calling (importing) other .lua files outside main.lua in Love2D

So, I wanted to clean up my code by splitting it into seperate files. But for some reason I can't call the script I want to call through my main.lua.
Here's my main.lua script:
function love.load()
require "splash.lua"
splash.load()
end
function love.update(dt)
splash.update(dt)
end
function love.draw() print("Draw")
splash.draw()
love.graphics.print("FPS "..tostring(love.timer.getFPS( )), 5, 5) print("fps")
love.graphics.setColor(255,0,0) --Red
love.graphics.rectangle("fill", 3, 3, 60, 20)
end
And here's my splash.lua script, separate from the main.lua file:
function splash.load()
timer = 0 print("fadein")
alpha = 0
fadein = 2
display = 4
fadeout = 6
splashScreen = love.graphics.newImage("/images/Splash1.png")
end
function splash.update(dt)
timer = timer + dt
if 0 < timer and timer < fadein then
alpha = timer / fadein
end
if fadein < timer and timer < display then
alpha = 1
end
if display < timer and timer < fadeout then
alpha = 1 - ((timer - display) / (fadeout - display))
end
end
function splash.draw()
love.graphics.setColor(1, 1, 1, alpha)
local sx = love.graphics.getWidth() / splashScreen:getWidth()
local sy = love.graphics.getHeight() / splashScreen:getHeight()
love.graphics.draw(splashScreen, 0, 0, 0, sx, sy)
end
I've searched everywhere on this topic, and the other answers are either extremely vague or outdated. All I want to do is to make the splash.lua run when I start Love.
There were two problems which I noticed and once I fixed them something ran.
Problem 1
In main.lua, require "splash.lua" should be require "splash". If you code in other languages like python, java or javascript, you can think of require as similar to import.
Problem 2
In splash.lua, you are referencing an object(splash) which doesn't exist. To keep your code as similar as I could, I inserted the line splash = {} at the top of splash.lua. Once the object splash is created, you are then able to create functions for this object(splash.load(), splash.update(), and splash.draw()). This isn't a problem in main.lua because love is an object which already exists when the love2d game engine starts.
main.lua
function love.load()
require "splash"
splash.load()
end
function love.update(dt)
splash.update(dt)
end
function love.draw() print("Draw")
splash.draw()
love.graphics.print("FPS "..tostring(love.timer.getFPS( )), 5, 5) print("fps")
love.graphics.setColor(255,0,0) --Red
love.graphics.rectangle("fill", 3, 3, 60, 20)
end
splash.lua
splash = {}
function splash.load()
timer = 0 print("fadein")
alpha = 0
fadein = 2
display = 4
fadeout = 6
splashScreen = love.graphics.newImage("/images/Splash1.png")
end
function splash.update(dt)
timer = timer + dt
if 0 < timer and timer < fadein then
alpha = timer / fadein
end
if fadein < timer and timer < display then
alpha = 1
end
if display < timer and timer < fadeout then
alpha = 1 - ((timer - display) / (fadeout - display))
end
end
function splash.draw()
love.graphics.setColor(1, 1, 1, alpha)
local sx = love.graphics.getWidth() / splashScreen:getWidth()
local sy = love.graphics.getHeight() / splashScreen:getHeight()
love.graphics.draw(splashScreen, 0, 0, 0, sx, sy)
end
Side note: from reading your code, I'm not sure if you understand entirely how the load, update, and draw functions work. Love is an object created by the love2d game engine. The engine runs the load function only once when the game starts. The update function then continually checks for changes to the world that the game exists in and applies the code within love.update according to the conditions inside it. The draw function continually draws what it is told over and over again. These things happen automatically because it's already programmed into the love2d game engine.
The only reason I think you might be confused in this area is that you created a separate splash.load, splash.update, and splash.draw. You can technically name whatever functions you're calling anything you want, I just had the feeling that you might think that these load, update and draw functions might be called automatically, which they're not. Love2d only calls the load, update, and draw functions automatically for the love object.
Changing your require command to the following should work:
require("splash")
Additionally you should create the splash table before creating functions for said table.
splash = {}
splash.myFunction()
.
.
.

How would I rotate a character based on their camera? (Roblox)

In Roblox, your camera has a CFrame with a lookVector and so on. What I'm trying to accomplish is to detect when a player has pressed their right mouse button, and through a loop, rotate their character based on the CFrame of the camera until the button is released.
I've pretty much got it, but instead of rotating the character model, it turns the screen black and kills the player. I've seen this done in RPGs on Roblox before, so I know it's possible, and probably fairly easy. I've worked with CFrames quite a bit in the past, so I'm not sure why I'm having such a hard time with this.
After a couple hours of playing around with ideas and checking online, I thought I'd just ask the question to save time. What's the correct way to achieve this?
Edit: My bad, this is what I have so far. I fixed the black screen, but the player still just dies.
local UIS,Player,Camera,Character,MB2Down = game:GetService('UserInputService'),game.Players.LocalPlayer,workspace.Camera,script.Parent,false
local Torso = Character:FindFirstChild('Torso') or Character:FindFirstChild('UpperTorso')
UIS.InputEnded:Connect(function(Input)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and MB2Down then
MB2Down = false
Character.Humanoid.AutoRotate = true
end
end)
UIS.InputBegan:connect(function(Input,onGui)
if Input.UserInputType == Enum.UserInputType.MouseButton2 and not onGui then
MB2Down = true
Character.Humanoid.AutoRotate = false
while MB2Down and wait() do
Torso.CFrame = CFrame.new(Vector3.new(Torso.CFrame),Vector3.new(Camera.CFrame.p))
end
end
end)
You've almost got it, but let me take a slightly different approach to my solution. When the player presses the right mouse button, let's connect a function to the Heartbeat event that will update the character's rotation to the camera's. Also, we will rotate the HumanoidRootPart instead of the Torso/UpperTorso. The HumanoidRootPart is the PrimaryPart of the character model, and thus is the part we should manipulate if we want to manipulate the model as a whole.
The way we will lock the player's rotation to the camera is as follows:
Get the position of the character.
Get the rotation of the camera (by using arc-tangent and camera's look-vector).
Construct the new CFrame for the player using the position and rotation from steps 1 and 2.
Apply the CFrame to the character's HumanoidRootPart.
The following code is in a LocalScript and is placed under StarterCharacterScripts:
local userInput = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character = script.Parent
local root = character:WaitForChild("HumanoidRootPart")
local humanoid = character:WaitForChild("Humanoid")
local camera = workspace.CurrentCamera
local dead = false
local heartbeat = nil
function LockToCamera()
local pos = root.Position
local camLv = camera.CFrame.lookVector
local camRotation = math.atan2(-camLv.X, -camLv.Z)
root.CFrame = CFrame.new(root.Position) * CFrame.Angles(0, camRotation, 0)
end
userInput.InputEnded:Connect(function(input)
if (input.UserInputType == Enum.UserInputType.MouseButton2 and heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
humanoid.AutoRotate = true
end
end)
userInput.InputBegan:Connect(function(input, processed)
if (processed or dead) then return end
if (input.UserInputType == Enum.UserInputType.MouseButton2) then
humanoid.AutoRotate = false
heartbeat = game:GetService("RunService").Heartbeat:Connect(LockToCamera)
end
end)
humanoid.Died:Connect(function()
dead = true
if (heartbeat) then
heartbeat:Disconnect()
heartbeat = nil
end
end)
Let me know if you need any clarification.

Key Releases Psychopy

I'm fairly new to psychopy but I'm having a lot of trouble recording keyboard events so far. The keyboard demo works so I know it is possible, but when I implement the code in my own program it doesn't record any keyboard activity at all. Right now my program is super simple as I'm just trying to get the hang of it. I have a picture and want to record the duration of keypresses during the time the picture is on screen. I have a couple print statements as sanity checks and when I run it (and am using the keyboard) it doesn't print anything. Here's an outline of my code:
from psychopy.iohub import launchHubServer, EventConstants
io = launchHubServer()
keyboard = io.devices.keyboard
keyboard.reporting = True
#-------Start Routine "trial"-------
continueRoutine = True
io.clearEvents('all')
duration_lst=[]
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if t >= 0.0 and image.status == NOT_STARTED:
# keep track of start time/frame for later
image.tStart = t # underestimates by a little under one frame
image.frameNStart = frameN # exact frame index
image.setAutoDraw(True)
if image.status == STARTED and t >= (0.0 + (5.0- win.monitorFramePeriod*0.75)): #most of one frame period left
image.setAutoDraw(False)
# *ISI* period
if t >= 0.0 and ISI.status == NOT_STARTED:
# keep track of start time/frame for later
ISI.tStart = t # underestimates by a little under one frame
ISI.frameNStart = frameN # exact frame index
ISI.start(0.5)
elif ISI.status == STARTED: #one frame should pass before updating params and completing
ISI.complete() #finish the static period
# get keyboard events
for event in keyboard.getEvents():
print event
if event.type == EventConstants.KEYBOARD_CHAR:
key_press_duration=event.duration
duration_lst.append(key_press_duration)
print duration_lst
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
I tried stripping off all unnecessary stuff here (variables, window, stimuli etc.) and uses keyboard.getReleases() so it boils down to this:
from psychopy import iohub
io = iohub.launchHubServer()
keyboard = io.devices.keyboard
print 'press something now!'
while True:
# get keyboard releases
for event in keyboard.getReleases():
print 'Released!'
This should print all info about each key release in the console. It works for me, at least. If it also works for you, the problem is probably related to something else in your script.