github.com/MontFerret/ferret@v0.18.0/pkg/drivers/cdp/input/mouse.go (about)

     1  package input
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/mafredri/cdp"
     8  	"github.com/mafredri/cdp/protocol/input"
     9  )
    10  
    11  type Mouse struct {
    12  	client *cdp.Client
    13  	x      float64
    14  	y      float64
    15  }
    16  
    17  func NewMouse(client *cdp.Client) *Mouse {
    18  	return &Mouse{client, 0, 0}
    19  }
    20  
    21  func (m *Mouse) Click(ctx context.Context, x, y float64, delay time.Duration) error {
    22  	return m.ClickWithCount(ctx, x, y, delay, 1)
    23  }
    24  
    25  func (m *Mouse) ClickWithCount(ctx context.Context, x, y float64, delay time.Duration, count int) error {
    26  	if err := m.Move(ctx, x, y); err != nil {
    27  		return err
    28  	}
    29  
    30  	if err := m.DownWithCount(ctx, input.MouseButtonLeft, count); err != nil {
    31  		return err
    32  	}
    33  
    34  	time.Sleep(randomDuration(int(delay)))
    35  
    36  	return m.UpWithCount(ctx, input.MouseButtonLeft, count)
    37  }
    38  
    39  func (m *Mouse) Down(ctx context.Context, button input.MouseButton) error {
    40  	return m.DownWithCount(ctx, button, 1)
    41  }
    42  
    43  func (m *Mouse) DownWithCount(ctx context.Context, button input.MouseButton, count int) error {
    44  	return m.client.Input.DispatchMouseEvent(
    45  		ctx,
    46  		input.NewDispatchMouseEventArgs("mousePressed", m.x, m.y).
    47  			SetButton(button).
    48  			SetClickCount(count),
    49  	)
    50  }
    51  
    52  func (m *Mouse) Up(ctx context.Context, button input.MouseButton) error {
    53  	return m.UpWithCount(ctx, button, 1)
    54  }
    55  
    56  func (m *Mouse) UpWithCount(ctx context.Context, button input.MouseButton, count int) error {
    57  	return m.client.Input.DispatchMouseEvent(
    58  		ctx,
    59  		input.NewDispatchMouseEventArgs("mouseReleased", m.x, m.y).
    60  			SetButton(button).
    61  			SetClickCount(count),
    62  	)
    63  }
    64  
    65  func (m *Mouse) Move(ctx context.Context, x, y float64) error {
    66  	return m.MoveBySteps(ctx, x, y, 1)
    67  }
    68  
    69  func (m *Mouse) MoveBySteps(ctx context.Context, x, y float64, steps int) error {
    70  	fromX := m.x
    71  	fromY := m.y
    72  
    73  	for i := 0; i <= steps; i++ {
    74  		iFloat := float64(i)
    75  		stepFloat := float64(steps)
    76  		toX := fromX + (x-fromX)*(iFloat/stepFloat)
    77  		toY := fromY + (y-fromY)*(iFloat/stepFloat)
    78  
    79  		err := m.client.Input.DispatchMouseEvent(
    80  			ctx,
    81  			input.NewDispatchMouseEventArgs("mouseMoved", toX, toY),
    82  		)
    83  
    84  		if err != nil {
    85  			return err
    86  		}
    87  	}
    88  
    89  	m.x = x
    90  	m.y = y
    91  
    92  	return nil
    93  }