File: main.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 (197 lines) | stat: -rw-r--r-- 7,680 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
#-*- 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: main.c
# Original copyright and license: 1998, 2003--2004  John Darrington, GPL3+


import sys
import argparse
argparse._ = _
# These strings are defined in the module argparse
# and repeated here so that they are included in the translation template.
if False:
    #Translators: Strings from file main.py are visible only on the commandline and/or in the man-page
    _('usage: ')
    _('optional arguments')

from . import debug, config


def import_ext(pure_python):
    if not pure_python:
        try:
            import cube_c
            sys.modules['pybiklib.cube'] = cube_c
            sys.modules['cube_c'] = cube_c
        except ImportError as e:
            print e
            print 'Unable to import module cube_c, using slow fallback.'
            pure_python = True
    if not pure_python:
        try:
            import drwBlock_c
            sys.modules['pybiklib.drwBlock'] = drwBlock_c
            sys.modules['drwBlock_c'] = drwBlock_c
        except ImportError as e:
            del sys.modules['pybiklib.cube']
            del sys.modules['cube_c']
            print e
            print 'Unable to import module drwBlock_c, using slow fallback.'
            pure_python = True
    if not pure_python:
        try:
            import glarea_common_c
            sys.modules['pybiklib.glarea_common'] = glarea_common_c
        except ImportError as e:
            del sys.modules['pybiklib.cube']
            del sys.modules['cube_c']
            del sys.modules['pybiklib.drwBlock']
            del sys.modules['drwBlock_c']
            print e
            print 'Unable to import module glarea_common_c, using slow fallback.'
        else:
            return
    try:
        import cython
        debug.debug('cython found')
        cython.float[5]
        debug.debug('cython types support indexing')
    except (ImportError, TypeError):
        debug.debug('cython not found or types do not support indexing: simulate')
        def _ctype(type_):
            class _CType (object):
                def __call__(self, *args):
                    return type_(*args)
                def __getitem__(self, n):
                    return lambda: [None]*n
            return _CType()
        
        sys.modules['cython'] = cython = type(sys)('cython')
        cython.compiled = False
        def declare(*args, **kwags):
            if len(args) == 1:
                return args[0]()
            if len(args) == 2:
                return args[0](args[1])
        cython.declare = declare
        def struct(**kwargs):
            class _Struct (object):
                def __init__(self):
                    for k in kwargs:
                        setattr(self, k, None)
            return _Struct
        cython.struct = struct
        def locals(**kwargs):
            return lambda func: func
        cython.locals = locals
        cython.NULL = None
        cython.int = _ctype(int)
        cython.p_int = object
        cython.float = _ctype(float)
        cython.p_float = object
        cython.double = _ctype(float)
        cython.short = _ctype(int)
        cython.uchar = _ctype(int)
        cython.p_char = object
        

def run():
    options = app_opts()
    
    debug.install(debug, options.debug_modes)
    debug.debug('debug output enabled:')
    debug.debug(' ', *[m for m, v in options.debug_modes.items() if v is True])
    debug.debug(' ', *['%s=%d'%(m, v) for m, v in options.debug_modes.items() if type(v) is int])
    debug.debug(config.PACKAGE, config.VERSION)
    
    import_ext(options.pure_python)
    
    import application
    app = application.Application()
    if options.frameQty is not None:
        app.cube_area.frameQty = options.frameQty
    app.first_new_game(options.cube_dimension, options.solved)
    app.run_main_loop()
    

debug_level_names = [__a[6:].lower()
                        for __a in debug.__all__
                            if __a.startswith('DEBUG_') and __a != 'DEBUG_LEVEL']

def arg_parser():
    '''Create parser for pybik arguments.
    Used for command line and to create man page
    '''
    parser = argparse.ArgumentParser(
            description=unicode(config.get_description(),'utf-8'),
            add_help=False,
            )
            
    parser.add_argument('-h', '--help', action='help',
                help=unicode(_("Show help message and exit"),'utf-8'))
    parser.add_argument('--version', action='version', version=config.VERSION,
                help=unicode(_("Show version number and exit"),'utf-8'))
    parser.add_argument("-s", "--solved", action="store_true", default=False,
                help=unicode(_("Start with the cube already solved"),'utf-8'))
    parser.add_argument("--size", type=int, dest='cube_dimension',
                help=unicode(_("Start with a N x N x N sized cube"),'utf-8'), metavar="N")
    parser.add_argument("--animation", type=int, dest='frameQty',
                help=unicode(_("Show N intermediate positions in animations"),'utf-8'), metavar="N")
    parser.add_argument("--pure-python", action="store_true", default=False,
                help=unicode(_("Use python module for rendering (very slow)"),'utf-8'))
    parser.add_argument("--debug", type=str, dest='debug_level', default=-1,
                help=unicode(_("Enable debug output, D is an integer or"
                               " a comma-separated list of [{0}]"),'utf-8')
                                .format(','.join(debug_level_names)),
                metavar="D")
    return parser
    
def app_opts():
    '''Returns parsed args from command line'''
    parser = arg_parser()
    args = parser.parse_args()
    
    debug_level = args.debug_level
    debug_level_names_u = [a.upper() for a in debug_level_names]
    try:
        debug_level = int(debug_level)
        debug_level_max = sum([1<<i for i, n in enumerate(debug_level_names_u)])
        if not (-1 <= debug_level <= debug_level_max):
            parser.error(_("debug level out of range: {0}").format(debug_level))
    except ValueError:
        debug_level = debug_level.split(',')
        _debug_level_names = dict([(n, 1<<i) for i, n in enumerate(debug_level_names_u)])
        debug_level = [(d.upper() if d.upper() in _debug_level_names else d) for d in debug_level]
        try:
            debug_level = sum([_debug_level_names[d] for d in debug_level])
        except KeyError as e:
            parser.error(_("unknown debug option: {0}").format(e.args[0]))
    args.debug_modes = {'DEBUG_LEVEL': debug_level}
    
    if debug_level < 0:
        debug_level = 0
    debug_modes = reversed(bin(debug_level)[2:].rjust(len(debug_level_names_u),'0'))
    debug_modes = [bool(int(c)) for c in debug_modes]
    debug_modes = zip(debug_level_names_u, debug_modes)
    args.debug_modes.update(dict(('DEBUG_'+n, v) for n, v in debug_modes))
    return args