/*
 * LibInputSynth
 * Copyright 2018 Collabora Ltd.
 * Author: Christoph Haag <christoph.haag@collabora.com>
 * SPDX-License-Identifier: MIT
 */

#include "inputsynth-xdo.h"

struct _InputSynthXdo
{
  InputSynth parent;
  xdo_t *xdo;
};

G_DEFINE_TYPE (InputSynthXdo, input_synth_xdo, INPUT_TYPE_SYNTH)

InputSynthXdo *
input_synth_xdo_new (void)
{
  InputSynthXdo *self = (InputSynthXdo*) g_object_new (INPUT_TYPE_SYNTH_XDO, 0);
  return self;
}

static void
input_synth_xdo_init (InputSynthXdo *self)
{
  self->xdo = xdo_new(NULL);
}

static void
click_xdo (InputSynth *self_parent, int x, int y,
                       int button, gboolean press)
{
  (void) x;
  (void) y;
  InputSynthXdo *self = INPUT_SYNTH_XDO (self_parent);
  if (press)
    xdo_mouse_down (self->xdo, CURRENTWINDOW, button);
  else
    xdo_mouse_up (self->xdo, CURRENTWINDOW, button);
}

static void
move_cursor_xdo (InputSynth *self_parent, int x, int y)
{
  InputSynthXdo *self = INPUT_SYNTH_XDO (self_parent);
  xdo_move_mouse (self->xdo, x, y, 0);
}

static void
character_xdo (InputSynth *self_parent, char character)
{
  InputSynthXdo *self = INPUT_SYNTH_XDO (self_parent);
  /* null terminated */
  char string[2] = { character, 0 };
  xdo_enter_text_window (self->xdo, CURRENTWINDOW, string, 0);
}

static void
input_synth_xdo_finalize (GObject *gobject)
{
  InputSynthXdo *self = INPUT_SYNTH_XDO (gobject);
  xdo_free(self->xdo);

  G_OBJECT_CLASS (input_synth_xdo_parent_class)->finalize (gobject);
}

static GString *
get_backend_name_xdo (InputSynth *self_parent)
{
  (void) self_parent;
  return g_string_new ("libxdo from xdotool");
}

static void
input_synth_xdo_class_init (InputSynthXdoClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = input_synth_xdo_finalize;

  InputSynthClass *input_synth_class = INPUT_SYNTH_CLASS (klass);
  input_synth_class->click = click_xdo;
  input_synth_class->move_cursor = move_cursor_xdo;
  input_synth_class->character = character_xdo;
  input_synth_class->get_backend_name = get_backend_name_xdo;
}
