File: mfxutil.py

package info (click to toggle)
pysolfc 2.6.4-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 31,144 kB
  • sloc: python: 73,008; tcl: 4,529; sh: 339; makefile: 83; perl: 48
file content (326 lines) | stat: -rw-r--r-- 9,018 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
#!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
# ---------------------------------------------------------------------------##
#
#  Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer
#  Copyright (C) 2003 Mt. Hood Playing Card Co.
#  Copyright (C) 2005-2009 Skomoroh
#
#  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/>.
#
# ---------------------------------------------------------------------------##

import locale
import os
import re
import sys
import time
import webbrowser
from pickle import Pickler, Unpickler

from pysollib.settings import PACKAGE, TOOLKIT

import six
from six import print_

Image = ImageTk = ImageOps = None
if TOOLKIT == 'tk':
    try:  # PIL
        from PIL import Image
        from PIL import ImageTk  # noqa: F401
        from PIL import ImageOps  # noqa: F401
    except ImportError:
        Image = None
    else:
        # for py2exe
        from PIL import GifImagePlugin  # noqa: F401
        from PIL import PngImagePlugin  # noqa: F401
        from PIL import JpegImagePlugin  # noqa: F401
        from PIL import BmpImagePlugin  # noqa: F401
        from PIL import PpmImagePlugin  # noqa: F401
        Image._initialized = 2
USE_PIL = False
if TOOLKIT == 'tk' and Image:
    USE_PIL = True

# debug
# Image = None
# USE_PIL = False

# ************************************************************************
# * exceptions
# ************************************************************************


class SubclassResponsibility(Exception):
    pass


# ************************************************************************
# * misc. util
# ************************************************************************


def latin1_to_ascii(n):
    if sys.version_info > (3,):
        return n
    # return n
    n = n.encode('iso8859-1', 'replace')
    # FIXME: rewrite this for better speed
    return (n.replace("\xc4", "Ae")
             .replace("\xd6", "Oe")
             .replace("\xdc", "Ue")
             .replace("\xe4", "ae")
             .replace("\xf6", "oe")
             .replace("\xfc", "ue"))


def latin1_normalize(n):
    return re.sub(r"[^\w]", "", latin1_to_ascii(n).lower())


def format_time(t):
    # print 'format_time:', t
    if t <= 0:
        return "0:00"
    if t < 3600:
        return "%d:%02d" % (t // 60, t % 60)
    return "%d:%02d:%02d" % (t // 3600, (t % 3600) // 60, t % 60)


def print_err(s, level=1):
    if level == 0:
        ss = PACKAGE+': ERROR:'
    elif level == 1:
        ss = PACKAGE+': WARNING:'
    elif level == 2:
        ss = PACKAGE+': DEBUG WARNING:'
    try:
        print_(ss, s.encode(locale.getpreferredencoding()), file=sys.stderr)
    except Exception:
        print_(ss, s, file=sys.stderr)
    sys.stderr.flush()


# ************************************************************************
# * misc. portab stuff
# ************************************************************************

def getusername():
    if os.name == "nt":
        return win32_getusername()
    user = os.environ.get("USER", "").strip()
    if not user:
        user = os.environ.get("LOGNAME", "").strip()
    return user


def getprefdir(package):

    if (TOOLKIT == 'kivy'):
        from pysollib.kivy.LApp import get_platform
        plat = get_platform()
        if plat == 'android':
            os.environ['HOME'] = '/sdcard'

    if os.name == "nt":
        return win32_getprefdir(package)
    home = os.environ.get("HOME", "").strip()
    if not home or not os.path.isdir(home):
        home = os.curdir
    return os.path.join(home, ".pysolfc")


# high resolution clock() and sleep()
try:
    uclock = time.perf_counter
except Exception:
    uclock = time.clock

usleep = time.sleep
if os.name == "posix":
    uclock = time.time

# ************************************************************************
# * MSWin util
# ************************************************************************


def win32_getusername():
    user = os.environ.get('USERNAME', '').strip()
    try:
        user = six.text_type(user, locale.getpreferredencoding())
    except Exception:
        user = ''
    return user


def win32_getprefdir(package):
    portprefdir = 'config'      # portable varsion
    if os.path.isdir(portprefdir):
        return portprefdir
    # %USERPROFILE%, %APPDATA%
    hd = os.environ.get('APPDATA')
    if not hd:
        hd = os.path.expanduser('~')
        if hd == '~':  # win9x
            hd = os.path.abspath('/windows/Application Data')
            if not os.path.exists(hd):
                hd = os.path.abspath('/')
    return os.path.join(hd, 'PySolFC')


# ************************************************************************
# * memory util
# ************************************************************************

def destruct(obj):
    if TOOLKIT == 'kivy':
        return

    # assist in breaking circular references
    if obj is not None:
        for k in obj.__dict__.keys():
            obj.__dict__[k] = None
            # del obj.__dict__[k]


# ************************************************************************
# *
# ************************************************************************

class Struct:
    def __init__(self, **kw):
        self.__dict__.update(kw)

    def __str__(self):
        return str(self.__dict__)

    def __setattr__(self, key, value):
        if key not in self.__dict__:
            raise AttributeError(key)
        self.__dict__[key] = value

    def addattr(self, **kw):
        for key in kw.keys():
            if hasattr(self, key):
                raise AttributeError(key)
        self.__dict__.update(kw)

    def update(self, dict):
        for key in dict.keys():
            if key not in self.__dict__:
                raise AttributeError(key)
        self.__dict__.update(dict)

    def clear(self):
        for key in self.__dict__.keys():
            if isinstance(key, list):
                self.__dict__[key] = []
            elif isinstance(key, tuple):
                self.__dict__[key] = ()
            elif isinstance(key, dict):
                self.__dict__[key] = {}
            else:
                self.__dict__[key] = None

    def copy(self):
        c = self.__class__()
        c.__dict__.update(self.__dict__)
        return c


# ************************************************************************
# * keyword argument util
# ************************************************************************

# update keyword arguments with default arguments
def kwdefault(kw, **defaults):
    for k, v in defaults.items():
        if k not in kw:
            kw[k] = v


class KwStruct:
    def __init__(self, kw={}, **defaults):
        if isinstance(kw, KwStruct):
            kw = kw.__dict__
        if isinstance(defaults, KwStruct):
            defaults = defaults.__dict__
        if defaults:
            kw = kw.copy()
            for k, v in defaults.items():
                if k not in kw:
                    kw[k] = v
        self.__dict__.update(kw)

    def __setattr__(self, key, value):
        if key not in self.__dict__:
            raise AttributeError(key)
        self.__dict__[key] = value

    def __getitem__(self, key):
        return getattr(self, key)

    def get(self, key, default=None):
        return self.__dict__.get(key, default)

    def getKw(self):
        return self.__dict__


# ************************************************************************
# * pickling support
# ************************************************************************

def pickle(obj, filename, protocol=0):
    f = None
    try:
        f = open(filename, "wb")
        Pickler(f, protocol).dump(obj)
        f.close()
        f = None
        # print "Pickled", filename
    finally:
        if f:
            f.close()


def unpickle(filename):
    f, obj = None, None
    try:
        f = open(filename, "rb")
        x = Unpickler(f).load()
        f.close()
        f = None
        obj = x
        # print "Unpickled", filename
    finally:
        if f:
            f.close()
    return obj


# ************************************************************************
# *
# ************************************************************************

def openURL(url):
    try:
        webbrowser.open(url)
    except OSError:                  # raised on windows if link is unreadable
        pass
    except Exception:
        return False
    return True