File: plugins.py

package info (click to toggle)
pybik 0.5-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 776 kB
  • sloc: python: 4,591; makefile: 4; sh: 1
file content (408 lines) | stat: -rw-r--r-- 16,280 bytes parent folder | download
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#-*- coding:utf-8 -*-

#  Pybik -- A 3 dimensional magic cube game.
#  Copyright © 2009, 2011-2012  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Ported from GNUbik
# Original filename: guile-hooks.c
# Original copyright and license: 2004  Dale Mellor, GPL3+


import os
import sys
import imp
import re
from collections import namedtuple

from .debug import *
from . import config
from . import move_queue


class PluginHelper (object):
    def __init__(self, app):
        self.app = app
        # When a script runs,  the first cube movement that is requested by the script
        # must flush the move queue after the place of current insertion; further move
        # requests must be appended to the end of the move queue. This variable is used
        # to track the first request.
        self.moved = False
        plugin_funcs = [
                ('register_script',  self.plugin_register_script),
                ("cube_state",       self.plugin_cube_state),
                ("rotate_animated",  self.plugin_rotate_animated),
                ('rotate_flubrd',    self.plugin_rotate_flubrd),
                ("run_moves",        self.plugin_run_moves),
                ("error_dialog",     self.plugin_error_dialog),
                ('random',  lambda x:app.current_movement.current_cube_state.rand.randrange(x)),
            ]
        module = sys.modules['pybikplugin'] = type(sys)('pybikplugin')
        for name, func in plugin_funcs:
            setattr(module, name, func)
            
    def __del__(self):
        self.app = None
        
    def call(self, func):
        if not callable(func):
            return False
        self.moved = False
        func()
        return self.moved
        
    def plugin_register_script(self, path, func):
        self.scripts.append((path, func))
        
    def plugin_cube_state(self):
        '''Function callable from plugin which returns a structure
        reflecting the current state of the cube.'''
        return self.app.current_movement.current_cube_state.copy()
        
    def _start_moves_if_first(self):
        '''The first time a script makes a move on the cube,  the move_queue must be
        truncated to the current place,  and the place is marked so that the viewer
        can rewind the effects of the script. This script performs the necessary
        preparations.'''
        if not self.moved:
            self.moved = 1
            self.app.current_movement.all_moves.truncate()
            self.app.current_movement.all_moves.mark_current(True)
            
    def plugin_rotate_animated(self, moves):
        '''Function which, when called from plugins, causes one
        side of the cube to rotate on-screen.'''
        self._start_moves_if_first()
        for maxis, mslice, mdir in moves:
            data = move_queue.MoveData(maxis, mslice, mdir)
            self.app.current_movement.all_moves.push(data)
            
    def plugin_rotate_flubrd(self, code, size):
        self._start_moves_if_first()
        #TODO: here flubrd should be used, not the one in all_moves,
        # the converter in all_moves may be configurable in the future
        moves = []
        for move_data, unused_pos in self.app.current_movement.all_moves.parse_iter(code, len(code), size):
            moves.append((move_data.axis, move_data.slice, move_data.dir))
        return moves
        
    def plugin_run_moves(self):
        '''Function allowing a script to apply all its moves in one go to the cube,
        without creating animations on the display.'''
        self.app.current_movement.do_fast_forward()
        
    def plugin_error_dialog(self, message):
        '''Function to allow a plugin to display a message to the user.'''
        self.app.error_dialog(message)
        
    def _load_py_plugin(self, dirname, modulename):
        file_, path, desc = imp.find_module(modulename, [dirname])
        try:
            module = imp.load_module(modulename, file_, path, desc)
            debug('    import', modulename)
        except Exception as e:
            debug(e)
        finally:
            if file_:
                file_.close()
        
    def _load_plugins_from_directory(self, dirname):
        if os.path.isdir(dirname):
            debug('Plugins from', dirname)
            sys.path.insert(0, dirname)
            for filename in sorted(os.listdir(dirname), key=str.lower):
                debug('  script:', filename)
                name, ext = os.path.splitext(filename)
                if ext == '.py':
                    self._load_py_plugin(dirname, name)
                elif ext == '.script':
                    self._load_text_plugin(os.path.join(dirname, filename))
        
    def load_plugins(self):
        '''This function initializes the plugins for us, and once the plugins have
        all been imported, it returns the requested menu structure to the caller.'''
        self.scripts = []
        self._load_plugins_from_directory(config.SCRIPT_DIR)
        script_dir = os.path.join(config.get_data_home(), 'scripts')
        self._load_plugins_from_directory(script_dir)
        debug('  found', len(self.scripts))
        return self.scripts
        
    def _load_text_plugin(self, filename):
        with open(filename) as fp:
            lines = fp.readlines()
        paras = []
        
        # parse file
        para = {}
        key = None
        for line in lines:
            line = line.rstrip()
            if not line:
                # end para
                if para:
                    paras.append(para)
                para = {}
            elif line[0] == '#':
                # comment
                pass
            elif line[0] in ' \t':
                line = line.strip()
                if para and line[0] != '#':
                    # multiline
                    para[key].append(line)
            else:
                key, value = line.split(':')
                value = value.strip()
                para[key] = [value] if value else []
        if para:
            paras.append(para)
        
        if not paras:
            return
            
        # evaluate header
        header = paras[0].copy()
        value = header.get('File-Version', [])
        if value != ['1.0']:
            debug('Wrong file version:', '\n'.join(value))
            return
        models = header.get('Model', [])
        if not models:
            debug('Field "Model" not specified')
            return
        def split_model(model):
            type_ = model.split(' ', 1)
            if len(type_) != 2 or type_[0] != 'Cube':
                return 'unknown', 'unknown', None
            type_, size = type_
            try:
                size = int(size)
            except ValueError:
                return 'unknown', 'unknown', None
            return model, type_, size
        models = [split_model(m) for m in models]
        ref_blocks = header.get('Ref-Blocks', None)
        if ref_blocks:
            ref_blocks = ' '.join(ref_blocks).split()
            
        # evaluate solutions
        for para in paras:
            value = para.get('Path', [])
            if len(value) != 1 or not value[0]:
                debug('    skip Path:', value)
                para.clear()
                continue
            def split_path(value):
                if not value:
                    return None, ()
                sep = value[0]
                value = value.strip(sep).split(sep)
                return sep, tuple(v for v in value if v)
            sep, value = split_path(value[0])
            if not value:
                debug('    skip Path:', value)
                para.clear()
                continue
            debug('    Path:', value)
            para['Path'] = sep, value
            
            value = para.get('Depends', [])
            value = [split_path(v)[1] for v in value]
            para['Depends'] = value
            
            value = para.get('Ref-Blocks', None)
            if value:
                value = ' '.join(value).split()
            para['Ref-Blocks'] = value or ref_blocks
            
            value = para.get('Solution', None)
            def split_solution(value):
                value = value.split('#',1)[0]
                value = value.split(',', 1)
                if len(value) != 2:
                    return None
                cond = value[0].strip().split(' ')
                cond = [c.split('=') for c in cond if c]
                cond = [c for c in cond if len(c) == 2]
                return cond, value[1].strip()
            if value is not None:
                value = [split_solution(v) for v in value if v]
            para['Solution'] = value
            
        scripts = []
        for para in paras:
            if not para:
                continue
            sep, path = para['Path']
            params = namedtuple('ScriptParams', 'depends ref_blocks solution scripts models')(
                                depends=para['Depends'],
                                ref_blocks=para['Ref-Blocks'],
                                solution=para['Solution'],
                                scripts=scripts,
                                models=models,
                            )
            scripts.append((path, sep!='@', ScriptFactory(self, params)))
            
        self.scripts += [(path, func) for path, visible, func in scripts if visible]
        
        
class ScriptFactory (object):
    def __init__(self, plugin, params):
        self.solved_face_colors = {}
        self.plugin = plugin
        self.params = params
        
    def __call__(self):
        cube = self.plugin.plugin_cube_state()
        for model, type_, dimension in self.params.models:
            if cube.type == type_ and cube.dimension == dimension:
                break
        else:
            self.plugin.plugin_error_dialog(
                            _('This script only works for:') +
                            ''.join('\n    '+m for m,t,d in self.params.models))
            return
            
        depends = list(reversed(self.params.depends))
        scripts = {path: func for path, visible, func in self.params.scripts}
        for depend in depends:
            instance = scripts[depend]
            depends += instance.params.depends
        for depend in reversed(depends):
            instance = scripts[depend]
            self.execute(cube, instance.params.ref_blocks, instance.params.solution)
        self.execute(cube, self.params.ref_blocks, self.params.solution)
        
    def get_color(self, cube, face, block):
        facenum = 'udlrfb'.index(face)
        f, l, u = 1, 1, 1
        for match in re.finditer(r'(.)(\d*)', block):
            blockface, blockslice = match.groups()
            blockslicenum = int(blockslice) if blockslice else 1
            if blockface == 'u':   u = blockslicenum - 1
            elif blockface == 'd': u = cube.dimension - blockslicenum
            elif blockface == 'l': l = blockslicenum - 1
            elif blockface == 'r': l = cube.dimension - blockslicenum
            elif blockface == 'f': f = blockslicenum - 1
            elif blockface == 'b': f = cube.dimension - blockslicenum
        if face in 'ud': index = f + cube.dimension * l
        if face in 'lr': index = f + cube.dimension * u
        if face in 'fb': index = l + cube.dimension * u
        
        return cube.faces[facenum][index]
        
    @debug_func
    def test_face(self, cube, position, condition, face):
        try:
            color2 = self.solved_face_colors[condition[face]]
        except KeyError:
            return True
        color1 = self.get_color(cube, position[face], position)
        return color1 == color2
        
    @debug_func
    def test_basic_condition(self, cube, position, condition):
        assert len(position) == len(condition)
        for i in xrange(len(position)):
            if not self.test_face(cube, position, condition, i):
                return False
        return True
        
    def opposite(self, face):
        return {  'f': 'b', 'b': 'f',
                  'l': 'r', 'r': 'l',
                  'u': 'd', 'd': 'u',
               }[face]
        
    @debug_func
    def test_pattern_condition(self, cube, position, condition):
        if '?' in condition:
            conditions = (condition.replace('?', face, 1)
                            for face in 'flubrd'
                                if face not in condition
                                if self.opposite(face) not in condition)
            return self.test_or_conditions(cube, position, conditions)
        else:
            return self.test_basic_condition(cube, position, condition)
            
    def rotated_conditions(self, condition):
        for i in range(len(condition)):
            yield condition[i:] + condition[:i]
        
    @debug_func
    def test_prefix_condition(self, cube, position, condition):
        if condition.startswith('!*'):
            return not self.test_or_conditions(cube, position, self.rotated_conditions(condition[2:]))
        elif condition.startswith('*'):
            #TODO: Instead of testing only rotated conditions, test all permutations.
            #      This should not break existing rules, and would allow to match
            #      e.g. dfr and dfl. Could be done by comparing sorted strings after
            #      expanding patterns.
            return self.test_or_conditions(cube, position, self.rotated_conditions(condition[1:]))
        elif condition.startswith('!'):
            return not self.test_pattern_condition(cube, position, condition[1:])
        else:
            return self.test_pattern_condition(cube, position, condition)
        
    @debug_func
    def test_or_conditions(self, cube, position, conditions):
        for prefix_cond in conditions:
            if self.test_prefix_condition(cube, position, prefix_cond):
                return True
        return False
        
    @debug_func
    def test_and_conditions(self, cube, conditions):
        for position, or_cond in conditions:
            if not self.test_or_conditions(cube, position, or_cond.split('|')):
                return False
        return True
        
    def execute(self, cube, ref_blocks, rules):
        if rules is None:
            return
        count = 0
        pos = 0
        while pos < len(rules):
            self.solved_face_colors.clear()
            for block in ref_blocks:
                for face in block:
                    self.solved_face_colors[face] = self.get_color(cube, face, block)
            conditions, moves = rules[pos]
            if self.test_and_conditions(cube, conditions):
                debug('positive: {}. {!r}, {!r}'.format(
                                pos, ' '.join('='.join(c) for c in conditions), moves))
                if moves == '@@solved':
                    return
                if count > 4 * len(rules): # this value is just guessed
                    self.plugin.plugin_error_dialog(
                        'An infinite loop was detected. '
                        'This is probably an error in the solution.')
                    return
                count += 1
                
                moves_ = self.plugin.plugin_rotate_flubrd(moves, cube.dimension)
                for move in moves_:
                    cube._rotate_slice(*move)
                pos = 0
            else:
                pos += 1
        self.plugin.plugin_error_dialog(
            'No matching rules found. '
            'This is probably an error in the solution.')