summaryrefslogtreecommitdiffstats
path: root/cucumber/features/support/helpers/dogtail.rb
blob: 2a92649b7d95f3e116f2d5eaba83bd80c76119f1 (plain)
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
module Dogtail
  module Mouse
    LEFT_CLICK = 1
    MIDDLE_CLICK = 2
    RIGHT_CLICK = 3
  end

  TREE_API_NODE_SEARCHES = [
    :button,
    :child,
    :childLabelled,
    :childNamed,
    :dialog,
    :menu,
    :menuItem,
    :tab,
    :textentry,
  ]

  TREE_API_NODE_SEARCH_FIELDS = [
    :parent,
  ]

  TREE_API_NODE_ACTIONS = [
    :click,
    :doubleClick,
    :grabFocus,
    :keyCombo,
    :point,
    :typeText,
  ]

  TREE_API_APP_SEARCHES = TREE_API_NODE_SEARCHES + [
    :dialog,
    :window,
  ]

  # We want to keep this class immutable so that handles always are
  # left intact when doing new (proxied) method calls.  This way we
  # can support stuff like:
  #
  #     app = Dogtail::Application.new('gedit')
  #     menu = app.menu('Menu')
  #     menu.click()
  #     menu.something_else()
  #     menu.click()
  #
  # i.e. the object referenced by `menu` is never modified by method
  # calls and can be used as expected.

  class Application
    @@node_counter ||= 0

    def initialize(app_name, opts = {})
      @var = "node#{@@node_counter += 1}"
      @app_name = app_name
      @opts = opts
      @opts[:user] ||= LIVE_USER
      @find_code = "dogtail.tree.root.application('#{@app_name}')"
      script_lines = [
        "import dogtail.config",
        "import dogtail.tree",
        "import dogtail.predicate",
        "dogtail.config.logDebugToFile = False",
        "dogtail.config.logDebugToStdOut = False",
        "dogtail.config.blinkOnActions = True",
        "dogtail.config.searchShowingOnly = True",
        "#{@var} = #{@find_code}",
      ]
      run(script_lines)
    end

    def to_s
      @var
    end

    def run(code)
      code = code.join("\n") if code.class == Array
      c = RemoteShell::PythonCommand.new($vm, code, user: @opts[:user])
      if c.failure?
        raise RuntimeError.new("The Dogtail script raised: #{c.exception}")
      end
      return c
    end

    def child?(*args)
      !!child(*args)
    rescue
      false
    end

    def exist?
      run("dogtail.config.searchCutoffCount = 0")
      run(@find_code)
      return true
    rescue
      return false
    ensure
      run("dogtail.config.searchCutoffCount = 20")
    end

    def self.value_to_s(v)
      if v == true
        'True'
      elsif v == false
        'False'
      elsif v.class == String
        "'#{v}'"
      elsif [Fixnum, Float].include?(v.class)
        v.to_s
      else
        raise "#{self.class.name} does not know how to handle argument type '#{v.class}'"
      end
    end

    # Generates a Python-style parameter list from `args`. If the last
    # element of `args` is a Hash, it's used as Python's kwargs dict.
    # In the end, the resulting string should be possible to copy-paste
    # into the parentheses of a Python function call.
    # Example: [42, {:foo => 'bar'}] => "42, foo = 'bar'"
    def self.args_to_s(args)
      return "" if args.size == 0
      args_list = args
      args_hash = nil
      if args_list.class == Array && args_list.last.class == Hash
        *args_list, args_hash = args_list
      end
      (
        (args_list.nil? ? [] : args_list.map { |e| self.value_to_s(e) }) +
        (args_hash.nil? ? [] : args_hash.map { |k, v| "#{k}=#{self.value_to_s(v)}" })
      ).join(', ')
    end

    # Equivalent to the Tree API's Node.findChildren(), with the
    # arguments constructing a GenericPredicate to use as parameter.
    def children(*args)
      non_predicates = [:recursive, :showingOnly]
      findChildren_opts = []
      findChildren_opts_hash = Hash.new
      if args.last.class == Hash
        args_hash = args.last
        non_predicates.each do |opt|
          if args_hash.has_key?(opt)
            findChildren_opts_hash[opt] = args_hash[opt]
            args_hash.delete(opt)
          end
        end
      end
      findChildren_opts = ""
      if findChildren_opts_hash.size > 0
        findChildren_opts = ", " + self.class.args_to_s([findChildren_opts_hash])
      end
      predicate_opts = self.class.args_to_s(args)
      nodes_var = "nodes#{@@node_counter += 1}"
      find_script_lines = [
        "#{nodes_var} = #{@var}.findChildren(dogtail.predicate.GenericPredicate(#{predicate_opts})#{findChildren_opts})",
        "print(len(#{nodes_var}))",
      ]
      size = run(find_script_lines).stdout.chomp.to_i
      return size.times.map do |i|
        Node.new("#{nodes_var}[#{i}]", @opts)
      end
    end

    def get_field(key)
      run("print(#{@var}.#{key})").stdout.chomp
    end

    def set_field(key, value)
      run("#{@var}.#{key} = #{self.class.value_to_s(value)}")
    end

    def text
      get_field('text')
    end

    def text=(value)
      set_field('text', value)
    end

    def name
      get_field('name')
    end

    def roleName
      get_field('roleName')
    end

    TREE_API_APP_SEARCHES.each do |method|
      define_method(method) do |*args|
        args_str = self.class.args_to_s(args)
        method_call = "#{method.to_s}(#{args_str})"
        Node.new("#{@var}.#{method_call}", @opts)
      end
    end

    TREE_API_NODE_SEARCH_FIELDS.each do |field|
      define_method(field) do
        Node.new("#{@var}.#{field}", @opts)
      end
    end

  end

  class Node < Application

    def initialize(expr, opts = {})
      @expr = expr
      @opts = opts
      @opts[:user] ||= LIVE_USER
      @find_code = expr
      @var = "node#{@@node_counter += 1}"
      run("#{@var} = #{@find_code}")
    end

    TREE_API_NODE_SEARCHES.each do |method|
      define_method(method) do |*args|
        args_str = self.class.args_to_s(args)
        method_call = "#{method.to_s}(#{args_str})"
        Node.new("#{@var}.#{method_call}", @opts)
      end
    end

    TREE_API_NODE_ACTIONS.each do |method|
      define_method(method) do |*args|
        args_str = self.class.args_to_s(args)
        method_call = "#{method.to_s}(#{args_str})"
        run("#{@var}.#{method_call}")
      end
    end

  end
end