-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
executable file
·443 lines (325 loc) · 12.2 KB
/
utils.py
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
###############################################################################
# Copyright (c) 2009-2013 Guillaume Roguez
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
###############################################################################
import os, sys
import puremvc.interfaces
import puremvc.patterns.mediator
import puremvc.patterns.proxy
import puremvc.patterns.command
from functools import wraps, partial
from time import time
from string import Template
from math import atan, pi
__all__ = [ 'VirtualCalledError', 'virtualmethod',
'Mediator', 'mvcHandler',
'MetaSingleton', 'idle_cb', '_T', 'delayedmethod' ]
NON_RECORDABLE_COMMAND = "NonRecordableCommand"
idle_cb = lambda *a, **k: None
def _T(s):
# TODO: auto translation function
return s
if os.environ.get('GB_DEBUG'):
def dbg_log(*a):
sys.stderr.write(*a)
sys.stderr.flush()
else:
def dbg_log(*a):
pass
class VirtualCalledError(SyntaxError):
def __init__(self, instance, func):
self.__cls_name = instance.__class__.__name__
self.__func_name = func.__name__
def __str__(self):
return "class %s doesn't implement virtual method %s" % (self.__cls_name, self.__func_name)
def virtualmethod(wrapped_func):
@wraps(wrapped_func)
def wrapper(self, *args, **kwds):
raise VirtualCalledError(self, wrapped_func)
return wrapper
def delayedmethod(delay):
def wrapper(func):
func.__delay = delay
func.__lastcall = 0.
@wraps(func)
def _func(*a, **k):
t = time()
if t-func.__lastcall >= func.__delay:
func.__lastcall = t
return func(*a, **k)
return _func
return wrapper
class MetaMediator(type):
def __new__(metacls, name, bases, dct):
d = {}
dct['_mvc_handlers'] = d
# Added decorated functions, then cleanup
for v in dct.itervalues():
if hasattr(v, '_mvc_signals'):
for sig in v._mvc_signals:
d[sig] = v
del v._mvc_signals
return type.__new__(metacls, name, bases, dct)
class MetaSingleton(type):
def __init__(cls, name, bases, dict):
type.__init__(cls, name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = type.__call__(cls, *args, **kw)
return cls.instance
class Mediator(puremvc.patterns.mediator.Mediator, puremvc.interfaces.IMediator):
"""Mediator
Base class to create MVC Mediator classes.
This class exists because it's better to use mapping design pattern
in Python than the classical C one "if ... elif ...".
Moreover this class detectes methods decorated with 'mvcHandler'.
"""
__metaclass__ = MetaMediator
@classmethod
def listNotificationInterests(cls):
return cls._mvc_handlers.keys()
def handleNotification(self, note):
func = self.__class__._mvc_handlers[note.getName()]
data = note.getBody()
if isinstance(data, (tuple, list)):
func(self, *data)
else:
func(self, data)
def mvcHandler(signal):
"""Decorated function will be called when given MVC signal is trigged.
Note: be aware that there is no way to control the calls order!
"""
def mvcHandlerDecorate(func):
if hasattr(func, '_mvc_signals'):
func._mvc_signals.append(signal)
else:
func._mvc_signals = [signal]
return func
return mvcHandlerDecorate
class _MyTemplate(Template):
idpattern = '[_a-z][_a-z0-9\-]*'
def resolve_path(path):
from model import prefs
path = path.replace('/', os.path.sep)
old_path = None
while path != old_path:
old_path = path
path = _MyTemplate(path).safe_substitute(prefs)
return path
def compute_angle(x, y):
# (x,y) in view coordinates
if y >= 0:
r = 0.
else:
r = pi
y = -y
x = -x
if x > 0:
r += atan(float(y) / x)
elif x < 0:
r += pi - atan(float(y) / -x)
else:
r += pi / 2.
return r
##
## PureMVC extention implemented from "PureMVC AS3 Utility - Undo"
##
__all__ += ["CommandsHistoryProxy",
"IUndoableCommand",
"UndoableCommand",
"NON_RECORDABLE_COMMAND"]
class CommandsHistoryProxy(puremvc.patterns.proxy.Proxy, puremvc.interfaces.IProxy):
"""The model that keeps track of the commands.
It provides methods to get the next or the previous command from the history.
In order to record a command into the history, you must set the type of its notification
to C{RECORDABLE_COMMAND}
@author dragos
"""
# The name of the proxy.
NAME = "CommandsHistoryProxy"
CMD_HIST_ADD = 'hist-add'
CMD_HIST_FLUSHED = 'hist-flushed'
CMD_HIST_UNDO = 'undo-done'
CMD_HIST_REDO = 'redo-done'
__instances = []
__active = None
def __init__(self, name, data=None):
super(CommandsHistoryProxy, self).__init__( name, data )
self.__undoStack = []
self.__redoStack = []
#### Public API ####
def onRegister(self):
CommandsHistoryProxy.__instances.append(self)
if CommandsHistoryProxy.__active is None:
CommandsHistoryProxy.__active = self
def onRemove(self):
# Unregistering the proxy flushes it.
self.__undoStack = []
self.__redoStack = []
CommandsHistoryProxy.__instances.remove(self)
if CommandsHistoryProxy.__active is self:
CommandsHistoryProxy.__active = None
def getPrevious(self):
"""Returns the UNDO command.
Returns the latest command within the undo commands stack
@return The undoable command of type C{IUndoableCommand}
@see IUndoableCommand
"""
if self.__undoStack:
cmd = self.__undoStack.pop(-1)
self.__redoStack.append(cmd)
self.sendNotification( CommandsHistoryProxy.CMD_HIST_UNDO, (self, cmd) )
return cmd
def canUndo(self):
"""Indicates if there is an undo command into the history
@return Return a Boolean value indication if there is an undo command into the history
"""
return bool(self.__undoStack)
def getNext(self):
"""Returns the REDO command
@return The instance of the command
"""
if self.__redoStack:
cmd = self.__redoStack.pop(-1)
self.__undoStack.append(cmd)
self.sendNotification( CommandsHistoryProxy.CMD_HIST_REDO, (self, cmd) )
return cmd
def canRedo(self):
"""Indicates if there is a redo command in the history
@return True if you can redo, false otherwise
"""
return bool(self.__redoStack)
def putCommand(self, cmd):
"""Saves a command into the history.
UndoableCommand calls this method to save its instance into the history,
if the type of the notification is C{RECORDABLE_COMMAND}
@param cmd The instance of the command of type C{IUndoableCommand}
@see IUndoableCommand
"""
self.__redoStack = []
self.__undoStack.append( cmd )
self.sendNotification( CommandsHistoryProxy.CMD_HIST_ADD, (self, cmd))
def flush(self):
# Flush redo stack first
for cmd in self.__redoStack:
cmd.flush()
self.__redoStack = []
# Then undo stack
for cmd in self.__undoStack:
cmd.flush()
self.__undoStack = []
# Notify listeners
self.sendNotification( CommandsHistoryProxy.CMD_HIST_FLUSHED, self)
def activate(self):
self.active = self
@staticmethod
def get_active():
return CommandsHistoryProxy.__active
@staticmethod
def set_active(proxy):
assert isinstance(proxy, CommandsHistoryProxy)
assert proxy in CommandsHistoryProxy.__instances
CommandsHistoryProxy.__active = proxy
### Properties ###
active = property(fget=lambda self: self.get_active(),
fset=lambda self, v: self.set_active(v))
@property
def undo_stack(self): return tuple(self.__undoStack)
@property
def redo_stack(self): return tuple(self.__redoStack)
class IUndoableCommand(puremvc.interfaces.ICommand, puremvc.interfaces.INotification):
def getNote(self):
raise NotImplemented
def undo(self):
raise NotImplemented
def redo(self):
raise NotImplemented
def flush(self):
raise NotImplemented
def executeCommand(self):
raise NotImplemented
class UndoableCommand(puremvc.patterns.command.SimpleCommand, IUndoableCommand):
_note = None
__undoCmdClass = None
def execute(self, note):
"""Saves the command into the C{CommandHistoryProxy} class
and calls the C{executeCommand} method.
@param note: The C{Notification} instance
"""
self._note = note
self.executeCommand()
# default is recorded
if note.getType() != NON_RECORDABLE_COMMAND:
CommandsHistoryProxy.get_active().putCommand(self)
def registerUndoCommand(self, cmdClass):
"""Registers the undo command
@param cmdClass: The class to be executed on undo
"""
self.__undoCmdClass = cmdClass
def getNote(self):
"""Returns the notification sent to this command
@return The notification
"""
return self._note
def setNote(self, value):
"""Sets the value for the note
@param value: The notification of type C{Notification}
"""
self._note = value
def executeCommand(self):
"""This method must be overriden in the super class.
Place here the code for the command to execute.
"""
raise NotImplemented
def redo(self):
"""Calls C{executeCommand}
"""
self.executeCommand()
def undo(self):
"""Calls the undo command setting its note type to
C{NON_RECORDABLE_COMMAND} so that it won't get recorded into the history
since it is already in the history
"""
if self.__undoCmdClass is None:
raise RuntimeError("Undo command not set. Could not undo. Use 'registerUndoCommand' to register an undo command")
##
# The type of the notification is used as a flag,
# indicating wheather to save the command into the history, or not.
# The undo command, should not be recorded into the history,
# and its notification type is set to C{NON_RECORDABLE_COMMAND}
##
oldType = self._note.getType()
self._note.setType( NON_RECORDABLE_COMMAND )
commandInstance = self.__undoCmdClass()
commandInstance.execute( self._note )
self._note.setType( oldType )
def flush(self):
pass
def getCommandName(self):
"""Returns a display name for the undoable command.
By default, the name of the command is the name of the notification.
You must override this method when ever you want to set a different name.
@return The name of the undoable command
"""
return self.getNote().getName()