code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
'''Testing flat map scrolling.
Press arrow keys to move view focal point (little ball) around map.
You will be able to move "off" the map.
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
import scene2d
from scene2d.debug import gen_rect_map
class FlatScrollingTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_rect_map([[{}]*10]*10, 32, 32))
self.show_focus()
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Base class for rendering tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import *
import pyglet.window
from pyglet.window.event import *
from pyglet.window import key
from pyglet import clock
from scene2d import *
from scene2d.drawable import ScaleEffect
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class RenderBase(unittest.TestCase):
w = None
def init_window(self, vx, vy):
self.w = pyglet.window.Window(width=vx, height=vy)
def set_map(self, m, resize=False):
if resize:
vx, vy = m.pxw, m.pxh
self.w.set_size(vx, vy)
else:
vx = self.w.width
vy = self.w.height
self.view = scene2d.FlatView(0, 0, vx, vy, layers=[m])
self.w.push_handlers(self.view.camera)
self.keyboard = key.KeyStateHandler()
self.w.push_handlers(self.keyboard)
marker = None
def show_focus(self):
# add in a "sprite"
marker = Image2d.load(ball_png)
self.marker = Sprite(0, 0, 16, 16, marker)
self.marker.add_effect(ScaleEffect(.25, .25))
self.view.sprites.append(self.marker)
def run_test(self):
clock.set_fps_limit(30)
while not self.w.has_exit:
clock.tick()
self.w.dispatch_events()
self.view.fx += (self.keyboard[key.RIGHT] - self.keyboard[key.LEFT]) * 5
self.view.fy += (self.keyboard[key.UP] - self.keyboard[key.DOWN]) * 5
if self.marker is not None:
self.marker.x = self.view.fx
self.marker.y = self.view.fy
self.view.clear()
self.view.draw()
self.w.flip()
self.w.close()
| Python |
#!/usr/bin/env python
'''Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pyglet.window.event
from pyglet import clock
from scene2d import Sprite, Image2d, FlatView
from scene2d.image import TintEffect
from scene2d.camera import FlatCamera
ball_png = os.path.join(os.path.dirname(__file__), 'ball.png')
class BouncySprite(Sprite):
def update(self):
# move, check bounds
p = self.properties
self.x += p['dx']; self.y += p['dy']
if self.left < 0: self.left = 0; p['dx'] = -p['dx']
elif self.right > 320: self.right = 320; p['dx'] = -p['dx']
if self.bottom < 0: self.bottom = 0; p['dy'] = -p['dy']
elif self.top > 320: self.top = 320; p['dy'] = -p['dy']
class SpriteOverlapTest(unittest.TestCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
ball1.update()
ball2.update()
if ball1.overlaps(ball2):
if 'overlap' not in ball2.properties:
ball2.properties['overlap'] = e
ball2.add_effect(e)
elif 'overlap' in ball2.properties:
ball2.remove_effect(e)
del ball2.properties['overlap']
view.clear()
view.draw()
w.flip()
w.close()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing rect map debug rendering.
You should see a checkered square grid.
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
import scene2d
from scene2d.debug import gen_rect_map
class RectFlatDebugTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_rect_map([[{}]*10]*10, 32, 32), resize=True)
self.view.allow_oob = False
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing the map model.
This test should just run without failing.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet.window import Window
from scene2d import RectMap, HexMap, RectCell, HexCell
from scene2d.debug import gen_hex_map, gen_rect_map
rmd = [
[ {'meta': x} for x in m ] for m in ['ad', 'be', 'cf']
]
hmd = [
[ {'meta': x} for x in m ] for m in ['ab', 'cd', 'ef', 'gh']
]
class MapModelTest(unittest.TestCase):
def setUp(self):
self.w = Window(width=1, height=1, visible=False)
def tearDown(self):
self.w.close()
def test_rect_neighbor(self):
# test rectangular tile map
# +---+---+---+
# | d | e | f |
# +---+---+---+
# | a | b | c |
# +---+---+---+
m = gen_rect_map(rmd, 10, 16)
t = m.get_cell(0,0)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
assert m.get_neighbor(t, m.DOWN) is None
assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
assert m.get_neighbor(t, m.LEFT) is None
assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'b'
t = m.get_neighbor(t, m.UP)
assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.LEFT) is None
assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'e'
t = m.get_neighbor(t, m.RIGHT)
assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'b'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'f'
assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'd'
t = m.get_neighbor(t, m.RIGHT)
assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'c'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.RIGHT) is None
assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'e'
t = m.get_neighbor(t, m.DOWN)
assert (t.x, t.y) == (2, 0) and t.properties['meta'] == 'c'
assert m.get_neighbor(t, m.DOWN) is None
assert m.get_neighbor(t, m.UP).properties['meta'] == 'f'
assert m.get_neighbor(t, m.RIGHT) is None
assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'b'
def test_rect_coords(self):
# test rectangular tile map
# +---+---+---+
# | d | e | f |
# +---+---+---+
# | a | b | c |
# +---+---+---+
m = gen_rect_map(rmd, 10, 16)
# test tile sides / corners
t = m.get_cell(0,0)
assert t.top == 16
assert t.bottom == 0
assert t.left == 0
assert t.right == 10
assert t.topleft == (0, 16)
assert t.topright == (10, 16)
assert t.bottomleft == (0, 0)
assert t.bottomright == (10, 0)
assert t.midtop == (5, 16)
assert t.midleft == (0, 8)
assert t.midright == (10, 8)
assert t.midbottom == (5, 0)
def test_rect_pixel(self):
# test rectangular tile map
# +---+---+---+
# | d | e | f |
# +---+---+---+
# | a | b | c |
# +---+---+---+
m = gen_rect_map(rmd, 10, 16)
t = m.get(0,0)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
t = m.get(9,15)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
t = m.get(10,15)
assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'b'
t = m.get(9,16)
assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
t = m.get(10,16)
assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'
def test_hex_neighbor(self):
# test hexagonal tile map
# tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
# /d\ /h\
# /b\_/f\_/
# \_/c\_/g\
# /a\_/e\_/
# \_/ \_/
m = gen_hex_map(hmd, 32)
t = m.get_cell(0,0)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
assert m.get_neighbor(t, m.DOWN) is None
assert m.get_neighbor(t, m.UP).properties['meta'] == 'b'
assert m.get_neighbor(t, m.DOWN_LEFT) is None
assert m.get_neighbor(t, m.DOWN_RIGHT) is None
assert m.get_neighbor(t, m.UP_LEFT) is None
assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'c'
t = m.get_neighbor(t, m.UP)
assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'b'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.DOWN_LEFT) is None
assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'c'
assert m.get_neighbor(t, m.UP_LEFT) is None
assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'd'
t = m.get_neighbor(t, m.DOWN_RIGHT)
assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'
assert m.get_neighbor(t, m.DOWN) is None
assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'a'
assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'e'
assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'b'
assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'f'
t = m.get_neighbor(t, m.UP_RIGHT)
assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'e'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'c'
assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'g'
assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'd'
assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'h'
t = m.get_neighbor(t, m.DOWN_RIGHT)
assert (t.x, t.y) == (3, 0) and t.properties['meta'] == 'g'
assert m.get_neighbor(t, m.DOWN) is None
assert m.get_neighbor(t, m.UP).properties['meta'] == 'h'
assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'e'
assert m.get_neighbor(t, m.DOWN_RIGHT) is None
assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'f'
assert m.get_neighbor(t, m.UP_RIGHT) is None
t = m.get_neighbor(t, m.UP)
assert (t.x, t.y) == (3, 1) and t.properties['meta'] == 'h'
assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'g'
assert m.get_neighbor(t, m.UP) is None
assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'f'
assert m.get_neighbor(t, m.DOWN_RIGHT) is None
assert m.get_neighbor(t, m.UP_LEFT) is None
assert m.get_neighbor(t, m.UP_RIGHT) is None
def test_hex_coords(self):
# test hexagonal tile map
# tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
# /d\ /h\
# /b\_/f\_/
# \_/c\_/g\
# /a\_/e\_/
# \_/ \_/
m = gen_hex_map(hmd, 32)
# test tile sides / corners
t00 = m.get_cell(0, 0)
assert t00.top == 32
assert t00.bottom == 0
assert t00.left == (0, 16)
assert t00.right == (36, 16)
assert t00.center == (18, 16)
assert t00.topleft == (9, 32)
assert t00.topright == (27, 32)
assert t00.bottomleft == (9, 0)
assert t00.bottomright == (27, 0)
assert t00.midtop == (18, 32)
assert t00.midbottom == (18, 0)
assert t00.midtopleft == (4, 24)
assert t00.midtopright == (31, 24)
assert t00.midbottomleft == (4, 8)
assert t00.midbottomright == (31, 8)
t10 = m.get_cell(1, 0)
assert t10.top == 48
assert t10.bottom == 16
assert t10.left == t00.topright
assert t10.right == (63, 32)
assert t10.center == (45, 32)
assert t10.topleft == (36, 48)
assert t10.topright == (54, 48)
assert t10.bottomleft == t00.right
assert t10.bottomright == (54, 16)
assert t10.midtop == (45, 48)
assert t10.midbottom == (45, 16)
assert t10.midtopleft == (31, 40)
assert t10.midtopright == (58, 40)
assert t10.midbottomleft == t00.midtopright
assert t10.midbottomright == (58, 24)
t = m.get_cell(2, 0)
assert t.top == 32
assert t.bottom == 0
assert t.left == t10.bottomright
assert t.right == (90, 16)
assert t.center == (72, 16)
assert t.topleft == t10.right
assert t.midtopleft == t10.midbottomright
def test_hex_pixel(self):
# test hexagonal tile map
# tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
# /d\ /h\
# /b\_/f\_/
# \_/c\_/g\
# /a\_/e\_/
# \_/ \_/
m = gen_hex_map(hmd, 32)
t = m.get(0,0)
assert t is None
t = m.get(0,16)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
t = m.get(16,16)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
t = m.get(35,16)
assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
t = m.get(36,16)
assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'
def test_hex_dimensions(self):
m = gen_hex_map([[{'a':'a'}]], 32)
assert m.pxw, m.pxh == (36, 32)
m = gen_hex_map([[{'a':'a'}]*2], 32)
assert m.pxw, m.pxh == (36, 64)
m = gen_hex_map([[{'a':'a'}]]*2, 32)
assert m.pxw, m.pxh == (63, 48)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing hex map debug rendering.
You should see a checkered hex map.
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
import scene2d
from scene2d.debug import gen_hex_map
class HexFlatDebugTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_hex_map([[{}]*10]*10, 32), resize=True)
self.view.allow_oob = False
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''Testing mouse interaction
The cell the mouse is hovering over should highlight in red.
Clicking in a cell should highliht that cell green. Clicking again will
clear the highlighting.
Clicking on the ball sprite should highlight it and not underlying cells.
You may press the arrow keys to scroll the focus around the map (this
will move the map eventually)
Press escape or close the window to finish the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from render_base import RenderBase
from scene2d import Tile, Sprite
from pyglet.event import event
from scene2d.event import for_cells, for_sprites
from scene2d.image import TintEffect
from scene2d.debug import gen_hex_map
class RectFlatMouseTest(RenderBase):
def test_main(self):
self.init_window(256, 256)
self.set_map(gen_hex_map([[{}]*10]*10, 32))
self.w.push_handlers(self.view)
self.view.allow_oob = False
@event(self.view)
@for_cells()
def on_mouse_enter(cells):
for cell in cells:
e = TintEffect((1, .5, .5, 1))
cell.properties['hover'] = e
cell.add_effect(e)
@event(self.view)
@for_cells()
def on_mouse_leave(cells):
for cell in cells:
cell.remove_effect(cell.properties['hover'])
@event(self.view)
@for_cells()
@for_sprites()
def on_mouse_press(objs, x, y, button, modifiers):
for obj in objs:
if 'clicked' in obj.properties:
obj.remove_effect(obj.properties['clicked'])
del obj.properties['clicked']
else:
e = TintEffect((.5, 1, .5, 1))
obj.properties['clicked'] = e
obj.add_effect(e)
return
self.show_focus()
self.run_test()
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: //depot/task/DEV-99/client/tests.py#13 $'
import sys
sys.path.insert(0, '../../')
sys.path.insert(0, '../layout/')
from pyglet.window import *
from pyglet import clock
from pyglet.gl import *
from pyglet import media
import layout
from wydget import GUI
from wydget import event, dialogs, dragndrop, anim, layouts, widgets, loadxml
if len(sys.argv) > 1:
if '--help' in sys.argv:
print '%s [test_file.xml] [--dump] [--once]'%sys.argv[0]
print ' test_file.xml -- a single XML file to display (see tests/)'
print ' --dump -- text dump of constructed GUI objects'
print ' --once -- render the GUI exactly once and exit'
sys.exit(0)
print '-'*75
print 'To exit the test, hit <escape> or close the window'
print '-'*75
else:
print '-'*75
print 'To move on to the next test, hit <escape>.'
print 'Close the window to exit the tests.'
print '-'*75
window = Window(width=800, height=600, vsync=False, resizable=True)
#clock.set_fps_limit(10)
fps = clock.ClockDisplay(color=(1, .5, .5, 1))
window.push_handlers(fps)
class MyEscape(object):
has_exit = False
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.has_exit = True
return event.EVENT_HANDLED
my_escape = MyEscape()
window.push_handlers(my_escape)
def run(xml_file):
gui = GUI(window)
loadxml.fromFile(gui, xml_file)
if '--dump' in sys.argv:
print '-'*75
gui.dump()
print '-'*75
window.push_handlers(gui)
gui.push_handlers(dragndrop.DragHandler('.draggable'))
@gui.select('#press-me')
def on_click(widget, *args):
print 'on_click', widget
return event.EVENT_HANDLED
@gui.select('#enable-other')
def on_click(widget, *args):
w = gui.get('#press-me')
w.setEnabled(not w.isEnabled())
return event.EVENT_HANDLED
@gui.select('button, text-button')
def on_click(widget, *args):
print 'DEBUG', widget, 'PRESSED'
return event.EVENT_UNHANDLED
@gui.select('.show-value')
def on_change(widget, value):
print 'DEBUG', widget, 'VALUE CHANGED', `value`
return event.EVENT_UNHANDLED
@gui.select('frame#menu-test', 'on_click')
def on_menu(w, x, y, button, modifiers, click_count):
if not widgets.PopupMenu.isActivatingClick(button, modifiers):
return event.EVENT_UNHANDLED
gui.get('#test-menu').expose((x, y))
return event.EVENT_HANDLED
@gui.select('.hover')
def on_element_enter(widget, *args):
print 'ENTER ELEMENT', widget.id
return event.EVENT_HANDLED
@gui.select('.hover')
def on_element_leave(widget, *args):
print 'LEAVE ELEMENT', widget.id
return event.EVENT_HANDLED
@gui.select('.drawer-control')
def on_click(widget, *args):
id = widget.id.replace('drawer-control', 'test-drawer')
gui.get('#'+id).toggle_state()
return event.EVENT_HANDLED
@gui.select('#question-dialog-test')
def on_click(widget, *args):
def f(*args):
print 'DIALOG SAYS', args
dialogs.Question(widget.getGUI(), 'Did this appear correctly?',
callback=f).run()
return event.EVENT_HANDLED
@gui.select('#message-dialog-test')
def on_click(widget, *args):
def f(*args):
print 'DIALOG SAYS', args
dialogs.Message(widget.getGUI(), 'Hello, World!', callback=f).run()
return event.EVENT_HANDLED
@gui.select('#music-test')
def on_click(widget, x, y, button, modifiers, click_count):
if not button & mouse.RIGHT:
return event.EVENT_UNHANDLED
def load_music(file=None):
if not file: return
gui.get('#music-test').delete()
m = widgets.Music(gui, file, id='music-test', playing=True)
m.gainFocus()
dialogs.FileOpen(gui, callback=load_music).run()
return event.EVENT_HANDLED
@gui.select('#movie-test')
def on_click(widget, x, y, button, modifiers, click_count):
if not button & mouse.RIGHT:
return event.EVENT_UNHANDLED
def load_movie(file=None):
print 'DIALOG SELECTION:', file
if not file: return
gui.get('#movie-test').delete()
m = widgets.Movie(gui, file, id='movie-test', playing=True)
m.gainFocus()
dialogs.FileOpen(gui, callback=load_movie).run()
return event.EVENT_HANDLED
@gui.select('#movie-test')
def on_text(widget, text):
if text == 'f':
gui.get('#movie-test').video.pause()
anim.Delayed(gui.get('#movie-test').video.play, duration=10)
window.set_fullscreen()
return event.EVENT_HANDLED
@gui.select('.droppable')
def on_drop(widget, x, y, button, modifiers, element):
element.reparent(widget)
widget.bgcolor = (1, 1, 1, 1)
return event.EVENT_HANDLED
@gui.select('.droppable')
def on_drag_enter(widget, x, y, element):
widget.bgcolor = (.8, 1, .8, 1)
return event.EVENT_HANDLED
@gui.select('.droppable')
def on_drag_leave(widget, x, y, element):
widget.bgcolor = (1, 1, 1, 1)
return event.EVENT_HANDLED
try:
sample = gui.get('#xhtml-sample')
except KeyError:
sample = None
if sample:
@layout.select('#click-me')
def on_mouse_press(element, x, y, button, modifiers):
print 'CLICK ON', element
return event.EVENT_HANDLED
sample.label.push_handlers(on_mouse_press)
if gui.has('.progress-me'):
class Progress:
progress = 0
direction = 1
def animate(self, dt):
self.progress += dt * self.direction
if self.progress > 5:
self.progress = 5
self.direction = -1
elif self.progress < 0:
self.progress = 0
self.direction = 1
for e in gui.get('.progress-me'):
e.value = self.progress / 5.
animate_progress = Progress().animate
clock.schedule(animate_progress)
my_escape.has_exit = False
while not (window.has_exit or my_escape.has_exit):
clock.tick()
window.dispatch_events()
media.dispatch_events()
glClearColor(.2, .2, .2, 1)
glClear(GL_COLOR_BUFFER_BIT)
gui.draw()
fps.draw()
window.flip()
if '--once' in sys.argv:
window.close()
sys.exit()
if '--dump' in sys.argv:
print '-'*75
gui.dump()
print '-'*75
if gui.has('.progress-me'):
clock.unschedule(animate_progress)
# reset everything
window.pop_handlers()
gui.delete()
window.set_size(800, 600)
return window.has_exit
if len(sys.argv) > 1:
run(sys.argv[1])
else:
import os
for file in os.listdir('tests'):
if not file.endswith('.xml'): continue
if not os.path.isfile(os.path.join('tests', file)): continue
print 'Running', file
if run(os.path.join('tests', file)): break
window.close()
| Python |
from pyglet.window import mouse
import event
def DragHandler(rule, buttons=mouse.LEFT):
class _DragHandler(object):
original_position = None
mouse_buttons = buttons
@event.select(rule)
def on_drag(self, widget, x, y, dx, dy, buttons, modifiers):
if not buttons & self.mouse_buttons:
return event.EVENT_UNHANDLED
if self.original_position is None:
self.original_position = (widget.x, widget.y, widget.z)
widget.z += 1
widget.x += dx; widget.y += dy
return event.EVENT_HANDLED
@event.select(rule)
def on_drag_complete(self, widget, x, y, buttons, modifiers, ok):
if ok:
widget.z = self.original_position[2]
self.original_position = None
else:
if self.original_position is None: return
widget.x, widget.y, widget.z = self.original_position
self.original_position = None
return event.EVENT_HANDLED
return _DragHandler()
| Python |
'''Define the core `Element` class from which all gui widgets are derived.
All gui elements have:
- the parent widget
- an id, element name and list of classes
- a list of children widgets
- a position in 3D space, relative to their parent's position
- dimensions available as width, height, rect and inner_rect
- scaling factors in x and y
- visibility, enabled and transparent flags
- a border colour, padding and background colour
Display Model
-------------
The basic shape of an element is defined by the x, y, width and height
attributes.
Borders are drawn on the inside of the element's rect as a single pixel
line in the specified border colour. If no padding is specified then the
padding will automatically be set to 1 pixel.
There is an additional rect defined which exists inside the padding, if
there is any. This is available as the ``inner_rect`` attribute.
Finally each element may define a "view clip" which will restrict the
rendering of the item and its children to a limited rectangle.
Sizing
------
Elements may specify one of the following for width and height:
1. a fixed value (in pixels) TODO: allow em sizes?
2. a fixed value in em units using the active style for the element. This
method calculates an *inner* dimension, so padding is added on.
2. a percentage of their parent size (using the inner rect of the parent)
3. no value, thus the element is sized to be the minimum necessary to
display contents correctly
Elements have three properties for each of width and height:
<dimension>_spec -- the specification, one of the above
min_<dimension> -- the minimum size based on element contents and
positioning
<dimension> -- the calculated size
Subclasses if Element define:
intrinsic_<dimension> -- the size of the element contents
If <dimension> depends on parent sizing and that sizing is unknown then it
should be None. This indicates that sizing calculation is needed.
'''
import inspect
import math
from pyglet.gl import *
from wydget import loadxml
from wydget import event
from wydget import util
intceil = lambda i: int(math.ceil(i))
class Element(object):
'''A GUI element.
x, y, z -- position *relative to parent*
width, height -- for hit area
is_transparent -- is this element displayed*?
is_visible -- is this element *and its children* displayed*?
is_enabled -- is this element *and its children* enabled?
is_modal -- is this element capturing all user input?
children -- Elements I hold
parent -- container I belong to
id -- my id (auto-allocated if none given)
border -- Colour of the border around the element. If set,
padding is defaulted to 1 unless otherwise specified.
(see `colour specification`_)
padding --
bgcolor --
*: elements not displayed also do not receive events.
Positioning and Dimension Specification
---------------------------------------
The positioning and dimensions arguments may be specifed as simple numeric
values or as percentages of the parent's *inner* rectangle measurement.
Colour Specification
--------------------
All colours (border and bgcolor here, but other colours on various widgets)
may be specified as a 4-tuple of floats in the 0-1 range for (red, green,
blue, alpha). Alternatively any valid CSS colour specification may be used
("#FFF", "red", etc).
'''
is_focusable = False
# each GUI element (widget, etc) must define its own name attribute
# name
classes = ()
view_clip = None
_x = _y = _width = _height = None
def __init__(self, parent, x, y, z, width, height, padding=0,
border=None, bgcolor=None, is_visible=True, is_enabled=True,
is_transparent=False, children=None, id=None, classes=()):
self.parent = parent
self.id = id or self.allocateID()
self.classes = classes
self.children = children or []
# colors, border and padding
self.bgcolor = util.parse_color(bgcolor)
self.border = util.parse_color(border)
self._padding = util.parse_value(padding)
if border:
# force enough room to see the border
self._padding += 1
# save off the geometry specifications
self.x_spec = util.Position(x, self, parent, 'width')
self.y_spec = util.Position(y, self, parent, 'height')
self._z = util.parse_value(z) or 0
self.width_spec = util.Dimension(width, self, parent, 'width')
self.height_spec = util.Dimension(height, self, parent, 'height')
# attempt to calculate now what we can
if self.x_spec.is_fixed:
self.x = self.x_spec.calculate()
if self.y_spec.is_fixed:
self.y = self.y_spec.calculate()
if self.width_spec.is_fixed:
self.width = self.width_spec.calculate()
if self.height_spec.is_fixed:
self.height = self.height_spec.calculate()
self.is_visible = is_visible
self.is_enabled = is_enabled
self.is_modal = False
self.is_transparent = is_transparent
self._event_handlers = {}
# add this new element to its parent
self.parent.addChild(self)
# indicate we need geometry calculation
self.resetGeometry()
_next_id = 1
def allocateID(self):
id = '%s-%d'%(self.__class__.__name__, Element._next_id)
Element._next_id += 1
return id
def set_x(self, value):
self._x = value
self.setDirty()
x = property(lambda self: self._x and int(self._x), set_x)
def set_y(self, value):
self._y = value
self.setDirty()
y = property(lambda self: self._y and int(self._y), set_y)
def set_z(self, value):
self._z = value
self.setDirty()
z = property(lambda self: self._z and int(self._z), set_z)
def set_width(self, value):
self._width = value
self.setDirty()
width = property(lambda self: self._width and intceil(self._width),
set_width)
def set_height(self, value):
self._height = value
self.setDirty()
height = property(lambda self: self._height and intceil(self._height),
set_height)
def set_padding(self, value):
self._padding = value
self.setDirty()
padding = property(lambda self: self._padding and int(self._padding),
set_padding)
def get_rect(self):
return util.Rect(int(self._x), int(self._y), self.width, self.height)
rect = property(get_rect)
def get_inner_rect(self):
p = self._padding
return util.Rect(int(p), int(p), intceil(self._width - p*2),
intceil(self._height - p*2))
inner_rect = property(get_inner_rect)
def get_inner_width(self):
return intceil(self._width - self._padding*2)
inner_width = property(get_inner_width)
def get_inner_height(self):
return intceil(self._height - self._padding*2)
inner_height = property(get_inner_height)
def get_min_width(self):
'''Return the minimum width required for this element.
If the width relies on some parent element's dimensions, then just
return the intrinsic_width for the element.
'''
if self.width_spec.value is not None:
return self.width_spec.value
width = self.width
if width is None:
width = self.intrinsic_width()
return width
min_width = property(get_min_width)
def intrinsic_width(self):
raise NotImplementedError('intrinsic_width on %r'%self.__class__)
def get_min_height(self):
'''Return the minimum height required for this element.
If the height relies on some parent element's dimensions, then just
return the intrinsic_height for the element.
'''
if self.height_spec.value is not None:
return self.height_spec.value
height = self.height
if height is None:
height = self.intrinsic_height()
return height
min_height = property(get_min_height)
def intrinsic_height(self):
raise NotImplementedError('intrinsic_height on %r'%self.__class__)
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
obj = cls(parent, **kw)
for child in element.getchildren():
loadxml.getConstructor(child.tag)(child, obj)
return obj
def addChild(self, child):
'''Add the child element to this container.
The child is register()ed with the GUI and this element's geometry
is reset (if not fixed) so it will be reshaped upon the next
top-level GUI layout().
'''
self.children.append(child)
child.parent = self
self.getGUI().register(child)
self.resetGeometry()
def getParent(self, selector):
'''Get the first parent selected by the selector.
XXX at the moment, just does name
'''
if isinstance(selector, str):
if selector[0] in '.#':
raise NotImplementedError(
'lookup by id and class not yet supported')
selector = [s.strip() for s in selector.split(',')]
if self.name in selector: return self
return self.parent.getParent(selector)
def holds(self, element):
'''Return True if the element is a child of this element or its
children.
'''
for child in self.children:
if child is element:
return True
if child.holds(element):
return True
return False
def resetGeometry(self):
if not self.width_spec.is_fixed:
self._width = None
if not self.height_spec.is_fixed:
self._height = None
for child in self.children:
child.resetGeometry()
# this is going to be called *a lot*
self.setDirty()
def resize(self):
'''Determine position and dimension.
Return boolean whether we are able to calculate all values or
whether we need parent dimensions to continue.
'''
ok = True
if self._width is None:
w = self.width_spec.calculate()
# if we calculated the value write it through the property so
# that subclasses may react to the altered dimension
if w is None: ok = False
else: self.width = w
if self._height is None:
h = self.height_spec.calculate()
if h is None: ok = False
else: self.height = h
return ok
def getRects(self, view_clip=None, exclude=None):
'''Determine the drawing parameters for this element and its
children.
Returns a list of (element, (x, y, z, clipped)) where:
(x, y, z) is the screen location to render at
clipped is the relative rectangle to render
'''
if not self.is_visible: return []
# figure my rect
r = util.Rect(self._x, self._y, self._width, self._height)
if view_clip is not None:
r = r.intersect(view_clip)
if r is None: return []
x, y, z = self._x, self._y, self._z
# translate the view clip into this element's coordinate space
clipped = self.rect
clipped.x -= x
clipped.y -= y
if view_clip:
view_clip = view_clip.copy()
view_clip.x -= x
view_clip.y -= y
clipped = clipped.intersect(view_clip)
if not clipped:
return []
rects = []
if not self.is_transparent:
rects.append((self, (x, y, z, clipped)))
if not self.children:
return rects
# shift child elements and view clip for left & bottom padding
pad = self._padding
x += pad
y += pad
if view_clip is not None:
view_clip = view_clip.copy()
view_clip.x -= pad
view_clip.y -= pad
# clip by this element's view clip
if self.view_clip is not None:
if view_clip is not None:
view_clip = view_clip.intersect(self.view_clip)
else:
view_clip = self.view_clip
if not view_clip: return rects
for child in self.children:
if exclude is child: continue
for obj, (ox, oy, oz, c) in child.getRects(view_clip,
exclude):
rects.append((obj, (ox+x, oy+y, oz+z, c)))
return rects
def setViewClip(self, rect):
self.view_clip = util.Rect(*rect)
def draw(self, x, y, z, clipped):
'''Draw me given the parameters:
`rect` -- absolute coordinates of the element on screen
taking into account all translation and scaling
`z` -- z position
`clipped` -- recangle to draw in *relative* coordinates
to pass to render()
This method is not invoked if self.is_transparent or
not self.is_visible.
'''
# translate
glPushMatrix()
glTranslatef(int(x), int(y), z)
# render the common Element stuff - border and background
attrib = GL_CURRENT_BIT
bg, border = self.bgcolor, self.border
if (bg and bg[-1] != 1) or (border and border[-1] != 1):
attrib |= GL_ENABLE_BIT
glPushAttrib(attrib)
if attrib & GL_ENABLE_BIT:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
self.renderBackground(clipped)
self.renderBorder(clipped)
glPopAttrib()
# translate padding
if self._padding:
glTranslatef(self._padding, self._padding, 0)
# now render the element
self.render(clipped)
glPopMatrix()
def render(self, clipped):
'''Render the element in relative coordinates clipped to the
indicated view.
'''
pass
def renderBackground(self, clipped):
'''Render the background in relative coordinates clipped to the
indicated view.
'''
if self.bgcolor is None: return
glColor4f(*self.bgcolor)
x2, y2 = clipped.topright
glRectf(clipped.x, clipped.y, x2, y2)
def renderBorder(self, clipped):
'''Render the border in relative coordinates clipped to the
indicated view.
'''
if self.border is None: return
ox, oy = 0, 0
ox2, oy2 = self.width, self.height
cx, cy = clipped.bottomleft
cx2, cy2 = clipped.topright
glColor4f(*self.border)
glBegin(GL_LINES)
# left
if ox == cx:
glVertex2f(ox, cy)
glVertex2f(ox, cy2)
# right
if ox2 == cx2:
glVertex2f(ox2-1, cy)
glVertex2f(ox2-1, cy2)
# bottom
if oy == cy:
glVertex2f(cx, oy)
glVertex2f(cx2, oy)
# top
if oy2 == cy2:
glVertex2f(cx, oy2-1)
glVertex2f(cx2, oy2-1)
glEnd()
def isEnabled(self):
return self.is_enabled and self.parent.isEnabled()
def setEnabled(self, is_enabled):
self.is_enabled = is_enabled
def isVisible(self):
return self.is_visible and self.parent.isVisible()
def setVisible(self, is_visible):
self.is_visible = is_visible
self.getGUI().layoutNeeded()
def setDirty(self):
self.getGUI().setDirty()
def isFocused(self):
return self is self.getGUI().focused_element
def setModal(self, element=None):
'''Have this element capture all user input.
'''
if element is None: element = self
self.parent.setModal(element)
def gainFocus(self):
self.getGUI().setFocus(self, source='code')
def hasFocus(self):
return self.getGUI().focused_element is self
def loseFocus(self):
self.getGUI().setFocus(None, source='code')
def clearSelection(self):
'''The element has previously indicated that it has data for the
clipboard, but it has now been superceded by another element.
'''
pass
def getStyle(self):
return self.parent.getStyle()
def getGUI(self):
return self.parent.getGUI()
def get(self, spec):
return self.getGUI().get(spec)
def calculateAbsoluteCoords(self, x, y):
x += self._x + self.parent.padding; y += self._y + self.parent.padding
return self.parent.calculateAbsoluteCoords(x, y)
def calculateRelativeCoords(self, x, y):
x -= self._x + self.padding; y -= self._y + self.padding
return self.parent.calculateRelativeCoords(x, y)
def reparent(self, new_parent):
x, y = self.parent.calculateAbsoluteCoords(self._x, self._y)
self.x, self.y = new_parent.calculateRelativeCoords(x, y)
self.parent.children.remove(self)
new_parent.children.append(self)
self.parent = new_parent
self.setDirty()
def replace(self, old, new):
'''Replace the "old" widget with the "new" one.
It is assumed that "new" is already a child of this element.
'''
self.children.remove(new)
old_index = self.children.index(old)
old.delete()
self.children.insert(old_index, new)
def clear(self):
for child in list(self.children): child.delete()
self.children = []
def delete(self):
self.resetGeometry()
gui = self.getGUI()
# clear modality?
if self.is_modal: gui.setModal(None)
gui.dispatch_event(self, 'on_delete')
self.parent.children.remove(self)
gui.unregister(self)
self.clear()
def dump(self, s=''):
print s + str(self)
for child in self.children: child.dump(s+' ')
def __repr__(self):
return '<%s %r at (%s, %s, %s) (%sx%s) pad=%s>'%(
self.__class__.__name__, self.id, self._x, self._y, self._z,
self._width, self._height, self._padding)
| Python |
import math
class RestartLayout(Exception):
'''During layout an element has mutated the scene (eg. through adding
scrollbars) and thus layout must be restarted).
'''
def parse_value(value, base_value=0):
'''Parse a numeric value spec which is one of:
NNN integer
NN.MMM float
NN% proportional to base_value
'''
if not isinstance(value, str):
return value
if value[-1] == '%':
value = base_value * float(value[:-1]) / 100
elif '.' in value:
return float(value)
return int(value)
intceil = lambda i: int(math.ceil(i))
class Dimension(object):
def __init__(self, spec, element, parent, attribute):
self.spec = spec
self.element = element
self.parent = parent
self.attribute = attribute
self.percentage = None
self.is_fixed = True
if isinstance(spec, str):
if spec[-1] == '%':
self.value = None
self.percentage = float(spec[:-1]) / 100
self.is_fixed = False
elif spec.endswith('em'):
size = parse_value(spec[:-2], None)
style = element.getStyle()
self.value = size * style.getGlyphString('M').width
self.value += element.padding * 2
elif '.' in spec:
self.value = float(spec)
else:
self.value = int(spec)
elif spec is None:
self.value = None
self.is_fixed = False
else:
self.value = int(spec)
def __repr__(self):
return '<%s %r on %s id %s>'%(self.__class__.__name__, self.spec,
self.parent.__class__.__name__, self.parent.id)
def __hash__(self):
return hash(self.id)
def specified(self):
'''Return the value specified (ie. not using the intrinsic
dimension as a fallback.
'''
if self.percentage is not None:
pv = getattr(self.parent, self.attribute)
if pv is None:
return None
pv = getattr(self.parent, 'inner_' + self.attribute)
return intceil(pv * self.percentage)
return self.value
def calculate(self):
'''Determine this dimension falling back on the element's intrinsic
properties if necessary.
'''
if self.percentage is not None:
pv = getattr(self.parent, self.attribute)
if pv is None:
return None
pv = getattr(self.parent, 'inner_' + self.attribute)
return pv * self.percentage
elif self.value is None:
if self.attribute == 'width':
return self.element.intrinsic_width()
else:
return self.element.intrinsic_height()
return self.value
class Position(Dimension):
def calculate(self):
'''Determine this dimension falling back on the element's intrinsic
properties if necessary.
'''
if self.percentage is not None:
pv = getattr(self.parent, self.attribute)
if pv is None:
return None
pv = getattr(self.parent.inner_rect, self.attribute)
return pv * self.percentage
elif self.value is None:
return 0
return self.value
def parse_color(value):
'''Parse a color value which is one of:
name a color name (CSS 2.1 standard colors)
RGB a three-value hex color
RRGGBB a three-value hex color
'''
from layout.base import Color
if not isinstance(value, str):
return value
if value in Color.names:
return Color.names[value]
return Color.from_hex(value)
has_fbo = None
def renderToTexture(w, h, function):
import ctypes
from pyglet import gl
from pyglet import image
from pyglet.gl import gl_info
global has_fbo
if has_fbo is None:
has_fbo = gl_info.have_extension('GL_EXT_framebuffer_object')
# enforce dimensions are ints
w, h = int(w), int(h)
# set up viewport
gl.glPushAttrib(gl.GL_VIEWPORT_BIT|gl.GL_TRANSFORM_BIT)
gl.glViewport(0, 0, w, h)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, w, 0, h, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
if has_fbo:
# render directly to texture
# create our frame buffer
fbo = gl.GLuint()
gl.glGenFramebuffersEXT(1, ctypes.byref(fbo))
gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, fbo)
# allocate a texture and add to the frame buffer
tex = image.Texture.create_for_size(gl.GL_TEXTURE_2D, w, h, gl.GL_RGBA)
gl.glBindTexture(gl.GL_TEXTURE_2D, tex.id)
gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT,
gl.GL_COLOR_ATTACHMENT0_EXT, gl.GL_TEXTURE_2D, tex.id, 0)
status = gl.glCheckFramebufferStatusEXT(gl.GL_FRAMEBUFFER_EXT)
assert status == gl.GL_FRAMEBUFFER_COMPLETE_EXT
# now render
gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, fbo)
function()
gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, 0)
# clean up
gl.glDeleteFramebuffersEXT(1, ctypes.byref(fbo))
else:
# render and copy to texture
# render
function()
# grab the buffer and copy contents to the texture
buffer = image.get_buffer_manager().get_color_buffer()
tex = image.Texture.create_for_size(gl.GL_TEXTURE_2D, w, h, gl.GL_RGBA)
tex.blit_into(buffer.get_region(0, 0, w, h), 0, 0, 0)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPopMatrix()
gl.glPopAttrib()
# return the region (the whole texture will most likely be larger)
return tex.get_region(0, 0, w, h)
class Rect(object):
def __init__(self, x, y, width, height):
self.x = x; self.y = y
self.width = width; self.height = height
def __nonzero__(self):
return bool(self.width and self.height)
def __repr__(self):
return 'Rect(xy=%.4g,%.4g; wh=%.4g,%.4g)'%(self.x, self.y,
self.width, self.height)
def __eq__(self, other):
'''Compare the two rects.
>>> r1 = Rect(0, 0, 10, 10)
>>> r1 == Rect(0, 0, 10, 10)
True
>>> r1 == Rect(1, 0, 10, 10)
False
>>> r1 == Rect(0, 1, 10, 10)
False
>>> r1 == Rect(0, 0, 11, 10)
False
>>> r1 == Rect(0, 0, 10, 11)
False
'''
return (self.x == other.x and self.y == other.y and
self.width == other.width and self.height == other.height)
def __ne__(self, other):
'''Compare the two rects.
>>> r1 = Rect(0, 0, 10, 10)
>>> r1 != Rect(0, 0, 10, 10)
False
>>> r1 != Rect(1, 0, 10, 10)
True
>>> r1 != Rect(0, 1, 10, 10)
True
>>> r1 != Rect(0, 0, 11, 10)
True
>>> r1 != Rect(0, 0, 10, 11)
True
'''
return not (self == other)
def copy(self):
return self.__class__(self.x, self.y, self.width, self.height)
def clippedBy(self, other):
'''Determine whether this rect is clipped by the other rect.
>>> r1 = Rect(0, 0, 10, 10)
>>> r2 = Rect(1, 1, 9, 9)
>>> r2.clippedBy(r1)
False
>>> r1.clippedBy(r2)
True
>>> r2 = Rect(1, 1, 11, 11)
>>> r1.intersect(r2)
Rect(xy=1,1; wh=9,9)
>>> r1.clippedBy(r2)
True
>>> r2.intersect(r1)
Rect(xy=1,1; wh=9,9)
>>> r2.clippedBy(r1)
True
>>> r2 = Rect(11, 11, 1, 1)
>>> r1.clippedBy(r2)
True
'''
i = self.intersect(other)
if i is None: return True
if i.x > self.x: return True
if i.y > self.y: return True
if i.width < self.width: return True
if i.height < self.height: return True
return False
def intersect(self, other):
'''Find the intersection of two rects defined as tuples (x, y, w, h).
>>> r1 = Rect(0, 51, 200, 17)
>>> r2 = Rect(0, 64, 200, 55)
>>> r1.intersect(r2)
Rect(xy=0,64; wh=200,4)
>>> r1 = Rect(0, 64, 200, 55)
>>> r2 = Rect(0, 0, 200, 17)
>>> print r1.intersect(r2)
None
>>> r1 = Rect(10, 10, 10, 10)
>>> r2 = Rect(20, 20, 10, 10)
>>> print r1.intersect(r2)
None
>>> bool(Rect(0, 0, 1, 1))
True
>>> bool(Rect(0, 0, 1, 0))
False
>>> bool(Rect(0, 0, 0, 1))
False
>>> bool(Rect(0, 0, 0, 0))
False
'''
s_tr_x, s_tr_y = self.topright
o_tr_x, o_tr_y = other.topright
bl_x = max(self.x, other.x)
bl_y = max(self.y, other.y)
tr_x = min(s_tr_x, o_tr_x)
tr_y = min(s_tr_y, o_tr_y)
w, h = max(0, tr_x-bl_x), max(0, tr_y-bl_y)
if not w or not h:
return None
return self.__class__(bl_x, bl_y, w, h)
def get_top(self): return self.y + self.height
def set_top(self, y): self.y = y - self.height
top = property(get_top, set_top)
def get_bottom(self): return self.y
def set_bottom(self, y): self.y = y
bottom = property(get_bottom, set_bottom)
def get_left(self): return self.x
def set_left(self, x): self.x = x
left = property(get_left, set_left)
def get_right(self): return self.x + self.width
def set_right(self, x): self.x = x - self.width
right = property(get_right, set_right)
def get_center(self):
return (self.x + self.width//2, self.y + self.height//2)
def set_center(self, center):
x, y = center
self.x = x - self.width//2
self.y = y - self.height//2
center = property(get_center, set_center)
def get_midtop(self):
return (self.x + self.width//2, self.y + self.height)
def set_midtop(self, midtop):
x, y = midtop
self.x = x - self.width//2
self.y = y - self.height
midtop = property(get_midtop, set_midtop)
def get_midbottom(self):
return (self.x + self.width//2, self.y)
def set_midbottom(self, midbottom):
x, y = midbottom
self.x = x - self.width//2
self.y = y
midbottom = property(get_midbottom, set_midbottom)
def get_midleft(self):
return (self.x, self.y + self.height//2)
def set_midleft(self, midleft):
x, y = midleft
self.x = x
self.y = y - self.height//2
midleft = property(get_midleft, set_midleft)
def get_midright(self):
return (self.x + self.width, self.y + self.height//2)
def set_midright(self, midright):
x, y = midright
self.x = x - self.width
self.y = y - self.height//2
midright = property(get_midright, set_midright)
def get_topleft(self):
return (self.x, self.y + self.height)
def set_topleft(self, pos):
x, y = pos
self.x = x
self.y = y - self.height
topleft = property(get_topleft, set_topleft)
def get_topright(self):
return (self.x + self.width, self.y + self.height)
def set_topright(self, pos):
x, y = pos
self.x = x - self.width
self.y = y - self.height
topright = property(get_topright, set_topright)
def get_bottomright(self):
return (self.x + self.width, self.y)
def set_bottomright(self, pos):
x, y = pos
self.x = x - self.width
self.y = y
bottomright = property(get_bottomright, set_bottomright)
def get_bottomleft(self):
return (self.x, self.y)
def set_bottomleft(self, pos):
self.x, self.y = pos
bottomleft = property(get_bottomleft, set_bottomleft)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python |
import math
from pyglet import clock
linear = lambda t: t
cosine90 = lambda t: 1-math.cos(t * math.pi/2)
cosine180 = lambda t: 1-abs(math.cos(t * math.pi))
exponential = lambda t: (math.exp(t)-1) / (math.exp(1)-1)
half_parabola = lambda t: (1000*t)**2 / 1000**2
inverted_half_parabola = lambda t: 1-((1000*t)**2 / 1000**2)
parabola = lambda t: (2000*(t-.5))**2 / 1000**2
inverted_parabola = lambda t: 1-((2000*(t-.5))**2 / 1000**2)
def tween(v1, v2, t, function=cosine90):
'''Tween the values v1 and v2 by the factor 0 < t < 1 using the supplied
function.
'''
return type(v1)(v1 + (v2-v1)*function(t))
def tween_triple(p1, p2, t, function=cosine90):
'''Tween the triples p1 and p2 by the factor 0 < t < 1 using the supplied
function.
'''
r = function(t)
x1, y1, z1 = p1
x2, y2, z2 = p2
x = type(x1)(x1 + (x2-x1)*r)
y = type(x1)(y1 + (y2-y1)*r)
z = type(x1)(z1 + (z2-z1)*r)
return x, y, z
class Animation(object):
def __init__(self):
self.anim_time = 0
self.is_running = True
clock.schedule(self.animate)
def cancel(self):
if self.is_running:
self.is_running = False
clock.unschedule(self.animate)
class Delayed(Animation):
def __init__(self, *args, **kw):
self.callable = args[0]
self.args = args[1:]
self.duration = kw.pop('delay', 1.)
self.kw = kw
super(Delayed, self).__init__()
def animate(self, dt):
self.anim_time += dt
if self.anim_time > self.duration:
self.cancel()
self.callable(*self.args, **self.kw)
class Called(Animation):
def __init__(self, *args, **kw):
self.callable = args[0]
self.args = args[1:]
self.duration = kw.pop('duration', 1.)
self.kw = kw
super(Called, self).__init__()
def animate(self, dt):
self.anim_time += dt
self.callable(*self.args, **self.kw)
if self.anim_time > self.duration:
self.cancel()
class Translate(Animation):
'''Translate some object that has a .position (x, y, z) property to the
specified x, y, z position.
Duration is the number of seconds to animate over.
Function is the translation function, by default using a cosine curve
between 0 and 90 degrees.
Callback is called once the translation is complete.
'''
def __init__(self, object, x, y, z, duration=1, function=cosine90,
callback=None):
self.object = object
self.source = object.position
self.destination = (x, y, z)
self.duration = duration
self.function = function
self.callback = callback
super(Translate, self).__init__()
def animate(self, dt):
self.anim_time += dt
if self.anim_time > self.duration:
self.cancel()
self_anim_time = self.duration
if self.function in (cosine180, inverted_parabola):
self.object.position = self.source
else:
self.object.position = self.destination
if self.callback: self.callback()
else:
self.object.position = tween_triple(self.source,
self.destination, self.anim_time / self.duration,
self.function)
class Rotate(Animation):
'''Rotate some object that has a .angle (rx, ry, rz) property to the
specified rx, ry, rz angles.
Duration is the number of seconds to animate over.
Function is the translation function, by default using a cosine curve
between 0 and 90 degrees.
'''
def __init__(self, object, rx, ry, rz, duration=1, function=cosine90):
self.object = object
self.source = object.angle
self.destination = (rx, ry, rz)
self.duration = duration
self.function = function
super(Rotate, self).__init__()
def animate(self, dt):
self.anim_time += dt
if self.anim_time >= self.duration:
self.cancel()
self_anim_time = self.duration
if self.function in (cosine180, inverted_parabola):
self.object.angle = self.source
else:
self.object.angle = self.destination
else:
self.object.angle = tween_triple(self.source,
self.destination, self.anim_time / self.duration,
self.function)
class TranslateProperty(Animation):
'''Translate some property on an object.
Duration is the number of seconds to animate over.
Function is the translation function, by default using a cosine curve
between 0 and 90 degrees.
Callback is called once the translation is complete.
'''
def __init__(self, object, property, value, duration=1, function=cosine90,
callback=None):
self.object = object
self.property = property
self.source = getattr(object, property)
self.destination = value
self.duration = duration
self.function = function
self.callback = callback
super(TranslateProperty, self).__init__()
def animate(self, dt):
self.anim_time += dt
if self.anim_time >= self.duration:
self.cancel()
self_anim_time = self.duration
if self.function in (cosine180, inverted_parabola):
setattr(self.object, self.property, self.source)
else:
setattr(self.object, self.property, self.destination)
if self.callback: self.callback()
else:
value = tween(self.source, self.destination,
self.anim_time / self.duration, self.function)
setattr(self.object, self.property, value)
| Python |
from pyglet.gl import *
from pyglet.window import mouse
from pyglet import media, clock
from wydget import element, event, util, data, layouts, anim
from wydget.widgets.frame import Frame
from wydget.widgets.label import Image, Label
from wydget.widgets.button import Button
class Movie(Frame):
name='movie'
def __init__(self, parent, file=None, source=None, playing=False,
x=0, y=0, z=0, width=None, height=None, scale=True, **kw):
self.parent = parent
self.scale = scale
if file is not None:
source = self.source = media.load(file, streaming=True)
else:
assert source is not None, 'one of file or source is required'
self.player = media.Player()
self.player.eos_action = self.player.EOS_PAUSE
self.player.on_eos = self.on_eos
# poke at the video format
if not source.video_format:
raise ValueError("Movie file doesn't contain video")
video_format = source.video_format
if width is None:
width = video_format.width
if video_format.sample_aspect > 1:
width *= video_format.sample_aspect
if height is None:
height = video_format.height
if video_format.sample_aspect < 1:
height /= video_format.sample_aspect
super(Movie, self).__init__(parent, x, y, z, width, height, **kw)
# control frame top-level
c = self.control = Frame(self, bgcolor=(1, 1, 1, .5),
is_visible=False, width='100%', height=64)
# controls underlay
f = Frame(c, is_transparent=True, width='100%', height='100%')
f.layout = layouts.Horizontal(f, valign='center', halign='center',
padding=10)
c.play = Image(f, data.load_gui_image('media-play.png'),
classes=('-play-button',), is_visible=not playing)
c.pause = Image(f, data.load_gui_image('media-pause.png'),
bgcolor=None, classes=('-pause-button',), is_visible=playing)
fi = Frame(f, is_transparent=True)
c.range = Image(fi, data.load_gui_image('media-range.png'))
im = data.load_gui_image('media-position.png')
c.position = Image(fi, im, x=0, y=-2, classes=('-position',))
c.time = Label(f, '00:00', font_size=20)
c.anim = None
# make sure we get at least one frame to display
self.player.queue(source)
clock.schedule(self.update)
self.playing = False
if playing:
self.play()
def update(self, dt):
self.player.dispatch_events()
if self.control is None:
# the player update may have resulted in this element being
# culled
return
if not self.control.isVisible():
return
t = self.player.time
# time display
s = int(t)
m = t // 60
h = m // 60
m %= 60
s = s % 60
if h: text = '%d:%02d:%02d'%(h, m, s)
else: text = '%02d:%02d'%(m, s)
if text != self.control.time.text:
self.control.time.text = text
# slider position
p = (t/self.player.source.duration)
self.control.position.x = int(p * self.control.range.width)
def pause(self):
if not self.playing: return
clock.unschedule(self.update)
self.player.pause()
self.control.play.setVisible(True)
self.control.pause.setVisible(False)
self.playing = False
def play(self):
if self.playing: return
clock.schedule(self.update)
self.player.play()
self.control.play.setVisible(False)
self.control.pause.setVisible(True)
self.playing = True
def render(self, rect):
t = self.player.texture
if not t: return
x = float(self.width) / t.width
y = float(self.height) / t.height
s = min(x, y)
w = int(t.width * s)
h = int(t.height * s)
x = rect.x
y = rect.y
if w < self.width: x += self.width//2 - w//2
if h < self.height: y += self.height//2 - h//2
t.blit(x, y, width=w, height=h)
def on_eos(self):
self.player.seek(0)
self.pause()
self.control.position.x = 0
self.control.time.text = '00:00'
self.getGUI().dispatch_event(self, 'on_eos')
def delete(self):
self.pause()
if self.control.anim is not None:
self.control.anim.cancel()
self.control = None
super(Movie, self).delete()
@event.default('movie')
def on_element_enter(widget, *args):
widget.control.setVisible(True)
widget.control.anim = anim.Delayed(widget.control.setVisible, False,
delay=5)
return event.EVENT_HANDLED
@event.default('movie')
def on_mouse_motion(widget, *args):
if widget.control.anim is not None:
widget.control.anim.cancel()
widget.control.setVisible(True)
widget.control.anim = anim.Delayed(widget.control.setVisible, False,
delay=5)
return event.EVENT_HANDLED
@event.default('movie')
def on_element_leave(widget, *args):
widget.control.setVisible(False)
if widget.control.anim is not None:
widget.control.anim.cancel()
return event.EVENT_HANDLED
@event.default('movie .-play-button')
def on_click(widget, x, y, buttons, modifiers, click_count):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('movie').play()
return event.EVENT_HANDLED
@event.default('movie .-pause-button')
def on_click(widget, x, y, buttons, modifiers, click_count):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('movie').pause()
return event.EVENT_HANDLED
@event.default('movie .-position')
def on_mouse_press(widget, x, y, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('movie').pause()
return event.EVENT_HANDLED
@event.default('movie .-position')
def on_mouse_release(widget, x, y, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('movie').play()
return event.EVENT_HANDLED
@event.default('movie .-position')
def on_drag(widget, x, y, dx, dy, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
movie = widget.getParent('movie')
rw = movie.control.range.width
widget.x = max(0, min(rw, widget.x + dx))
p = float(widget.x) / rw
movie.player.seek(p * movie.player.source.duration)
return event.EVENT_HANDLED
| Python |
from pyglet.gl import *
from wydget import loadxml
from wydget import util
from wydget.widgets.label import Label
class Progress(Label):
name = 'progress'
def __init__(self, parent, value=0.0, show_value=True,
bar_color='gray', bgcolor=(.3, .3, .3, 1), color='white',
width=None, height=16, halign='center', valign='center', **kw):
self._value = util.parse_value(value, 0)
self.show_value = show_value
self.bar_color = util.parse_color(bar_color)
super(Progress, self).__init__(parent, ' ', width=width,
height=height, bgcolor=bgcolor, color=color, halign=halign,
valign=valign, **kw)
if self.show_value:
self.text = '%d%%'%(value * 100)
def set_value(self, value):
self._value = value
if self.show_value:
self.text = '%d%%'%(value * 100)
value = property(lambda self: self._value, set_value)
def renderBackground(self, rect):
super(Progress, self).renderBackground(rect)
r = rect.copy()
r.width *= self._value
b, self.bgcolor = self.bgcolor, self.bar_color
super(Progress, self).renderBackground(r)
self.bgcolor = b
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
obj = cls(parent, **kw)
for child in element.getchildren():
loadxml.getConstructor(element.tag)(child, obj)
return obj
| Python |
import sys
import string
from pyglet.gl import *
from pyglet.window import key, mouse
from wydget import event, anim, util, element
from wydget.widgets.frame import Frame
from wydget.widgets.label import Label
from wydget import clipboard
# for detecting words later
letters = set(string.letters)
class Cursor(element.Element):
name = '-text-cursor'
def __init__(self, color, *args, **kw):
self.color = color
self.alpha = 1
self.animation = None
super(Cursor, self).__init__(*args, **kw)
def draw(self, *args):
pass
def _render(self, rect):
glPushAttrib(GL_ENABLE_BIT|GL_CURRENT_BIT)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
color = self.color[:3] + (self.alpha,)
glColor4f(*color)
glRectf(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height)
glPopAttrib()
def enable(self):
self.setVisible(True)
self.animation = CursorAnimation(self)
def disable(self):
self.setVisible(False)
if self.animation is not None:
self.animation.cancel()
self.animation = None
class CursorAnimation(anim.Animation):
def __init__(self, element):
self.element = element
super(CursorAnimation, self).__init__()
self.paused = 0
def pause(self):
self.element.alpha = 1
self.paused = .5
def animate(self, dt):
if self.paused > 0:
self.paused -= dt
if self.paused < 0:
self.paused = 0
return
self.anim_time += dt
if self.anim_time % 1 < .5:
self.element.alpha = 1
else:
self.element.alpha = 0.2
class TextInputLine(Label):
name = '-text-input-line'
def __init__(self, parent, text, *args, **kw):
self.cursor_index = len(text)
if 'is_password' in kw:
self.is_password = kw.pop('is_password')
else:
self.is_password = False
kw['border'] = None
super(TextInputLine, self).__init__(parent, text, *args, **kw)
self.cursor = Cursor(self.color, self, 1, 0, 0, 1, self.font_size,
is_visible=False)
self.highlight = None
def selectWord(self, pos):
if self.is_password:
return self.selectAll()
# clicks outside the bounds should select the last item in the text
if pos >= len(self.text):
pos = len(self.text) - 1
# determine whether we should select a word, some whitespace or
# just a single char of punctuation
current = self.text[pos]
if current == ' ':
allowed = set(' ')
elif current in letters:
allowed = letters
else:
self.highlight = (pos, pos+1)
return
# scan back to the start of the thing
for start in range(pos, -1, -1):
if self.text[start] not in allowed:
start += 1
break
# scan up to the end of the thing
for end in range(pos, len(self.text)):
if self.text[end] not in allowed:
break
else:
end += 1
self.highlight = (start, end)
def selectAll(self):
self.highlight = (0, len(self.text))
def clearSelection(self):
self.highlight = None
def _render(self):
text = self._text
if self.is_password:
text = u'\u2022' * len(text)
style = self.getStyle()
self.unconstrained = style.text(text, font_size=self.font_size,
halign=self.halign, valign='top')
if self._text:
self.glyphs = style.getGlyphString(text, size=self.font_size)
self.label = style.text(text, font_size=self.font_size,
color=self.color, valign='top')
self.width = self.label.width
self.height = self.label.height
else:
self.glyphs = None
self.label = None
self.width = 0
f = style.getFont(size=self.font_size)
self.height = f.ascent - f.descent
# just quickly force a resize on the parent to fix up its
# dimensions
self.parent.resize()
# move cursor
self.setCursorPosition(self.cursor_index)
def editText(self, text, move=0):
'''Either insert at the current cursor position or replace the
current highlight.
'''
i = self.cursor_index
if self.highlight:
s, e = self.highlight
text = self.text[0:s] + text + self.text[e:]
self.highlight = None
else:
text = self.text[0:i] + text + self.text[i:]
self.text = text
self._render()
self.setCursorPosition(i+move)
self.getGUI().dispatch_event(self, 'on_change', text)
def render(self, rect):
super(TextInputLine, self).render(rect)
if self.cursor.is_visible:
self.cursor._render(self.cursor.rect)
if self.highlight is not None:
start, end = self.highlight
if start:
start = self.glyphs.get_subwidth(0, start)
end = self.glyphs.get_subwidth(0, end)
glPushAttrib(GL_ENABLE_BIT|GL_CURRENT_BIT)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
glColor4f(.8, .8, 1, .5)
glRectf(start, 0, end, rect.height)
glPopAttrib()
def determineIndex(self, x):
if self.glyphs is None:
return 0
diff = abs(x)
index = 0
for advance in self.glyphs.cumulative_advance:
new_diff = abs(x - advance)
if new_diff > diff: break
index += 1
diff = new_diff
return min(len(self.text), index)
def resize(self):
ok = super(TextInputLine, self).resize()
if ok and self.parent.width is not None:
self.setCursorPosition(self.cursor_index)
return ok
def setCursorPosition(self, index):
if self.glyphs is None:
self.cursor.x = 0
self.cursor_index = 0
return
if index >= len(self.text):
index = len(self.text)
direction = index - self.cursor_index
self.cursor_index = index
# determine position in self.glyphs
if not self.text or index == 0:
cursor_text_width = 0
else:
cursor_text_width = self.glyphs.get_subwidth(0, index)
# can't do this yet - parent doesn't know its dimensions
if self.parent.width is None:
return
parent_width = self.parent.inner_rect.width
cursor_x = cursor_text_width + self.x
# offset for current self.label offset
if direction > 0:
if cursor_x > parent_width:
self.x = - (cursor_text_width - parent_width)
else:
if cursor_x < 0:
self.x = -(cursor_text_width)
if hasattr(self, 'cursor'):
self.cursor.x = max(0, cursor_text_width)
class TextInput(Frame):
'''Cursor position indicates which indexed element the cursor is to the
left of.
Note the default padding of 2 (rather than 1) pixels to give some space
from the border.
'''
name='textinput'
is_focusable = True
def __init__(self, parent, text='', font_size=None, size=None,
x=0, y=0, z=0, width=None, height=None, border='black',
padding=2, bgcolor='white', color='black',
focus_border=(.3, .3, .7, 1), **kw):
style = parent.getStyle()
if font_size is None:
font_size = style.font_size
else:
font_size = util.parse_value(font_size, None)
self.font_size = font_size
if size is not None:
size = util.parse_value(size, None)
width = size * style.getGlyphString('M', size=font_size).width
width += padding*2
super(TextInput, self).__init__(parent, x, y, z, width, height,
padding=padding, border=border, bgcolor=bgcolor, **kw)
self.ti = TextInputLine(self, text, font_size=font_size,
bgcolor=bgcolor, color=color)
self.base_border = self.border
self.focus_border = util.parse_color(focus_border)
def renderBorder(self, clipped):
if self.isFocused():
self.border = self.focus_border
else:
self.border = self.base_border
super(TextInput, self).renderBorder(clipped)
def get_text(self):
return self.ti.text
def set_text(self, text):
self.ti.text = text
text = property(get_text, set_text)
value = property(get_text, set_text)
def get_cursor_postion(self):
return self.ti.cursor_index
def set_cursor_postion(self, pos):
self.ti.setCursorPosition(pos)
cursor_postion = property(get_cursor_postion, set_cursor_postion)
def resize(self):
if not super(TextInput, self).resize():
return False
ir = self.inner_rect
self.setViewClip((0, 0, ir.width, ir.height))
return True
class PasswordInput(TextInput):
name='password'
def __init__(self, *args, **kw):
super(PasswordInput, self).__init__(*args, **kw)
self.ti.is_password = True
self.ti.text = self.ti.text
@event.default('textinput, password')
def on_element_enter(widget, x, y):
w = widget.getGUI().window
cursor = w.get_system_mouse_cursor(w.CURSOR_TEXT)
w.set_mouse_cursor(cursor)
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_element_leave(widget, x, y):
w = widget.getGUI().window
cursor = w.get_system_mouse_cursor(w.CURSOR_DEFAULT)
w.set_mouse_cursor(cursor)
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_gain_focus(widget, source):
if widget.ti.text and source != 'mouse':
widget.ti.selectAll()
else:
widget.ti.cursor.enable()
widget.ti.setCursorPosition(0)
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_lose_focus(widget):
widget.ti.cursor.disable()
widget.ti.highlight = None
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_click(widget, x, y, buttons, modifiers, click_count):
widget = widget.ti
x, y = widget.calculateRelativeCoords(x, y)
if not buttons & mouse.LEFT:
return event.EVENT_UNHANDLED
if click_count == 1:
new = widget.determineIndex(x)
if modifiers & key.MOD_SHIFT:
old = widget.cursor_index
if old < new: widget.highlight = (old, new)
else: widget.highlight = (new, old)
widget.getGUI().setSelection(widget)
else:
widget.getGUI().clearSelection(widget)
widget.highlight = None
widget.cursor.enable()
widget.setCursorPosition(new)
elif click_count == 2:
widget.cursor.disable()
pos = widget.determineIndex(x)
widget.selectWord(pos)
widget.getGUI().setSelection(widget)
elif click_count == 3:
widget.cursor.disable()
widget.selectAll()
widget.getGUI().setSelection(widget)
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_mouse_drag(widget, x, y, dx, dy, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget = widget.ti
x, y = widget.calculateRelativeCoords(x, y)
if widget.highlight is None:
start = widget.determineIndex(x)
widget.highlight = (start, start)
widget.getGUI().setSelection(widget)
widget.cursor.disable()
else:
start, end = widget.highlight
now = widget.determineIndex(x)
if now <= start:
widget.highlight = (now, end)
else:
widget.highlight = (start, now)
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_key_press(widget, symbol, modifiers):
if sys.platform == 'darwin':
active_mod = key.MOD_COMMAND
else:
active_mod = key.MOD_CTRL
if modifiers & active_mod:
if symbol == key.A:
widget.ti.selectAll()
return event.EVENT_HANDLED
elif symbol == key.X:
# cut highlighted section
if widget.ti.highlight is None:
return event.EVENT_UNHANDLED
start, end = widget.ti.highlight
clipboard.put_text(widget.ti.text[start:end])
widget.ti.editText('')
return event.EVENT_HANDLED
elif symbol == key.C:
# copy highlighted section
if widget.ti.highlight is None:
return event.EVENT_UNHANDLED
start, end = widget.ti.highlight
clipboard.put_text(widget.ti.text[start:end])
return event.EVENT_HANDLED
elif symbol == key.V:
widget.ti.editText(clipboard.get_text())
return event.EVENT_HANDLED
return event.EVENT_UNHANDLED
@event.default('textinput, password')
def on_text(widget, text):
# special-case newlines - we don't want them
if text == '\r': return event.EVENT_UNHANDLED
widget.ti.editText(text, move=1)
if widget.ti.cursor.animation is not None:
widget.ti.cursor.animation.pause()
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_text_motion(widget, motion):
pos = widget.ti.cursor_index
if motion == key.MOTION_LEFT:
if pos != 0: widget.ti.setCursorPosition(pos-1)
elif motion == key.MOTION_RIGHT:
if pos != len(widget.ti.text): widget.ti.setCursorPosition(pos+1)
elif motion in (key.MOTION_UP, key.MOTION_BEGINNING_OF_LINE,
key.MOTION_BEGINNING_OF_FILE):
widget.ti.setCursorPosition(0)
elif motion in (key.MOTION_DOWN, key.MOTION_END_OF_LINE,
key.MOTION_END_OF_FILE):
widget.ti.setCursorPosition(len(widget.ti.text))
elif motion == key.MOTION_BACKSPACE:
text = widget.ti.text
if widget.ti.highlight is not None:
start, end = widget.ti.highlight
text = text[:start] + text[end:]
widget.ti.highlight = None
widget.ti.cursor_index = start
if pos != 0:
n = pos
widget.ti.cursor_index -= 1
text = text[0:n-1] + text[n:]
if text != widget.ti.text:
widget.ti.text = text
widget.getGUI().dispatch_event(widget, 'on_change', text)
elif motion == key.MOTION_DELETE:
text = widget.ti.text
if widget.ti.highlight is not None:
start, end = widget.ti.highlight
text = text[:start] + text[end:]
widget.ti.highlight = None
widget.ti.cursor_index = start
elif pos != len(text):
n = pos
text = text[0:n] + text[n+1:]
if text != widget.ti.text:
widget.ti.text = text
widget.getGUI().dispatch_event(widget, 'on_change', text)
else:
print 'Unhandled MOTION', key.motion_string(motion)
# hide mouse highlight, show caret
widget.ti.highlight = None
widget.ti.cursor.enable()
widget.ti.cursor.animation.pause()
return event.EVENT_HANDLED
@event.default('textinput, password')
def on_text_motion_select(widget, motion):
pos = widget.ti.cursor_index
if widget.ti.highlight is None:
start = end = pos
widget.getGUI().setSelection(widget.ti)
else:
start, end = widget.ti.highlight
# regular motion
if motion == key.MOTION_LEFT:
if pos != 0: widget.ti.setCursorPosition(pos-1)
elif motion == key.MOTION_RIGHT:
if pos != len(widget.ti.text): widget.ti.setCursorPosition(pos+1)
elif motion in (key.MOTION_UP, key.MOTION_BEGINNING_OF_LINE,
key.MOTION_BEGINNING_OF_FILE):
widget.ti.setCursorPosition(0)
elif motion in (key.MOTION_DOWN, key.MOTION_END_OF_LINE,
key.MOTION_END_OF_FILE):
widget.ti.setCursorPosition(len(widget.ti.text))
else:
print 'Unhandled MOTION SELECT', key.motion_string(motion)
if widget.ti.cursor_index < start:
start = widget.ti.cursor_index
elif widget.ti.cursor_index > end:
end = widget.ti.cursor_index
if start < end: widget.ti.highlight = (start, end)
else: widget.ti.highlight = (end, start)
return event.EVENT_HANDLED
| Python |
import sys
import xml.sax.saxutils
from pyglet.gl import *
from pyglet.window import mouse, key
from wydget import event, layouts, loadxml
from wydget.widgets.frame import Frame
from wydget.widgets.label import Label
class MenuItem(Label):
name = 'menu-item'
@event.default('menu-item')
def on_element_enter(item, x, y):
item._save_bgcolor = item.bgcolor
item.bgcolor = (.9, .9, 1, 1)
return event.EVENT_HANDLED
@event.default('menu-item')
def on_element_leave(item, x, y):
item.bgcolor = item._save_bgcolor
return event.EVENT_HANDLED
@event.default('menu-item')
def on_click(widget, *args):
menu = widget.parent
menu.hide()
return event.EVENT_HANDLED
class PopupMenu(Frame):
'''A menu that should appear under the mouse when activated.
The static method `isActivatingClick(buttons, modifiers)` may be used
to determine whether the menu should be shown.
'''
name = 'popup-menu'
is_focusable = True
def __init__(self, parent, items, **kw):
super(PopupMenu, self).__init__(parent, border="black",
is_visible=False, **kw)
for n, (label, id) in enumerate(items):
MenuItem(self, text=label, id=id, width='100%',
bgcolor=((.95, .95, .95, 1), (1, 1, 1, 1))[n%2])
self.layout = layouts.Vertical(self)
def expose(self, mouse):
w = self.getGUI().window
w, h = w.width, w.height
self.center = map(int, mouse)
if self.x < 0: self.x = 0
if self.y < 0: self.y = 0
if self.x + self.width > w: self.x = w - self.width
if self.y + self.height > h: self.y = h - self.height
self.setVisible(True)
self.gainFocus()
def hide(self):
self.setVisible(False)
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
If scrollable then put all children loaded into a container frame.
'''
kw = loadxml.parseAttributes(element)
items = []
for child in element.getchildren():
text = xml.sax.saxutils.unescape(child.text)
items.append((text, child.attrib['id']))
return cls(parent, items, **kw)
@staticmethod
def isActivatingClick(button, modifiers):
'''Determine whether the mouse button / modifiers combine to be a
popup menu activation click or not.
On all platforms a RMB click is allowed.
On OS X a control-LMB is allowed.
'''
if sys.platform == 'darwin':
if button & mouse.LEFT and modifiers & key.MOD_CTRL:
return True
return button & mouse.RIGHT
@event.default('popup-menu', 'on_gain_focus')
def on_menu_gain_focus(menu, method):
# catch focus
return event.EVENT_HANDLED
@event.default('popup-menu', 'on_lose_focus')
def on_menu_lose_focus(menu, method):
menu.hide()
return event.EVENT_HANDLED
| Python |
import os
from pyglet.gl import *
from pyglet.window import mouse
from pyglet import media, clock
from wydget import element, event, util, data, layouts
from wydget.widgets.frame import Frame
from wydget.widgets.label import Image, Label
from wydget.widgets.button import Button
class Music(Frame):
name='music'
def __init__(self, parent, file=None, source=None, title=None,
playing=False, bgcolor=(1, 1, 1, 1), color=(0, 0, 0, 1),
font_size=20, **kw):
'''Pass in a filename as "file" or a pyglet Source as "source".
'''
self.parent = parent
if file is not None:
source = media.load(file, streaming=True)
else:
assert source is not None, 'one of file or source is required'
self.player = media.Player()
# poke at the audio format
if not source.audio_format:
raise ValueError("File doesn't contain audio")
super(Music, self).__init__(parent, bgcolor=bgcolor, **kw)
# lay it out
# control frame top-level
c = self.control = Frame(self, width='100%', height=64)
ft = Frame(c, is_transparent=True, width='100%', height='100%')
ft.layout = layouts.Vertical(ft)
Label(ft, title or 'unknown', color=color, bgcolor=bgcolor,
padding=2, font_size=font_size)
# controls underlay
f = Frame(ft, is_transparent=True, width='100%', height='100%')
f.layout = layouts.Horizontal(f, valign='center', halign='center',
padding=10)
c.play = Image(f, data.load_gui_image('media-play.png'),
classes=('-play-button',), is_visible=not playing)
c.pause = Image(f, data.load_gui_image('media-pause.png'),
bgcolor=None, classes=('-pause-button',), is_visible=playing)
fi = Frame(f, is_transparent=True)
c.range = Image(fi, data.load_gui_image('media-range.png'))
c.position = Image(fi, data.load_gui_image('media-position.png'),
y=-2, classes=('-position',))
c.time = Label(f, '00:00', font_size=20)
c.anim = None
# make sure we get at least one frame to display
self.player.queue(source)
clock.schedule(self.update)
self.playing = False
if playing:
self.play()
def update(self, dt):
self.player.dispatch_events()
def pause(self):
if not self.playing: return
clock.unschedule(self.time_update)
self.player.pause()
self.control.pause.setVisible(False)
self.control.play.setVisible(True)
self.playing = False
def play(self):
if self.playing: return
clock.schedule(self.time_update)
self.player.play()
self.control.pause.setVisible(True)
self.control.play.setVisible(False)
self.playing = True
def on_eos(self):
self.player.seek(0)
self.pause()
self.control.time.text = '00:00'
self.getGUI().dispatch_event(self, 'on_eos', self)
def time_update(self, ts):
if not self.control.isVisible(): return
t = self.player.time
# time display
s = int(t)
m = t // 60
h = m // 60
m %= 60
s = s % 60
if h: text = '%d:%02d:%02d'%(h, m, s)
else: text = '%02d:%02d'%(m, s)
if text != self.control.time.text:
self.control.time.text = text
# slider position
p = (t/self.player.source.duration)
self.control.position.x = int(p * self.control.range.width)
def delete(self):
self.pause()
super(Music, self).delete()
@event.default('music .-play-button')
def on_click(widget, x, y, buttons, modifiers, click_count):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('music').play()
return event.EVENT_HANDLED
@event.default('music .-pause-button')
def on_click(widget, x, y, buttons, modifiers, click_count):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('music').pause()
return event.EVENT_HANDLED
@event.default('music .-position')
def on_mouse_press(widget, x, y, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('music').pause()
return event.EVENT_HANDLED
@event.default('music .-position')
def on_mouse_release(widget, x, y, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
widget.getParent('music').play()
return event.EVENT_HANDLED
@event.default('music .-position')
def on_drag(widget, x, y, dx, dy, buttons, modifiers):
if not buttons & mouse.LEFT: return event.EVENT_UNHANDLED
music = widget.getParent('music')
rw = music.control.range.width
widget.x = max(0, min(rw, widget.x + dx))
p = float(widget.x) / rw
music.player.seek(p * music.player.source.duration)
return event.EVENT_HANDLED
| Python |
import xml.sax.saxutils
from pyglet.window import mouse, key
from pyglet.gl import *
from wydget import element, event, layouts, loadxml, util, data
from wydget.widgets.frame import Frame
from wydget.widgets.button import TextButton, Button
from wydget.widgets.label import Label, Image
class SelectionCommon(Frame):
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
items = []
for child in element.getchildren():
assert child.tag == 'option'
text = xml.sax.saxutils.unescape(child.text)
childkw = loadxml.parseAttributes(child)
items.append((text, child.attrib.get('id'), childkw))
return cls(parent, items, **kw)
class Selection(SelectionCommon):
name = 'selection'
def __init__(self, parent, items=[], size=None, is_exclusive=False,
color='black', bgcolor='white', is_vertical=True,
alt_bgcolor='eee', active_bgcolor='ffc', item_pad=0,
is_transparent=True, scrollable=True, font_size=None, **kw):
self.is_vertical = is_vertical
self.is_exclusive = is_exclusive
if font_size is None:
font_size = parent.getStyle().font_size
else:
font_size = util.parse_value(font_size, None)
size = util.parse_value(size, None)
if is_vertical:
if size is not None:
kw['height'] = size * font_size
else:
if size is not None:
kw['width'] = size * font_size
super(Selection, self).__init__(parent, bgcolor=bgcolor,
scrollable=scrollable, scrollable_resize=scrollable,
is_transparent=is_transparent, **kw)
if scrollable: f = self.contents
else: f = self
if is_vertical:
f.layout = layouts.Vertical(f, padding=item_pad)
else:
f.layout = layouts.Horizontal(f, padding=item_pad)
# specific attributes for Options
self.color = util.parse_color(color)
self.base_bgcolor = self.bgcolor
self.alt_bgcolor = util.parse_color(alt_bgcolor)
self.active_bgcolor = util.parse_color(active_bgcolor)
self.font_size = font_size
for label, id, kw in items:
self.addOption(label, id, **kw)
def clearOptions(self):
if self.scrollable: self.contents.clear()
else: self.clear()
def addOption(self, label, id=None, **kw):
if self.scrollable: f = self.contents
else: f = self
Option(f, text=label, id=id or label, **kw)
def get_value(self):
if self.scrollable: f = self.contents
else: f = self
return [c.id for c in f.children if c.is_active]
value = property(get_value)
@event.default('selection')
def on_mouse_scroll(widget, x, y, dx, dy):
if not widget.scrollable:
return event.EVENT_UNHANDLED
if widget.v_slider is not None:
widget.v_slider.stepToMaximum(dy)
if widget.h_slider is not None:
widget.h_slider.stepToMaximum(dx)
return event.EVENT_HANDLED
class ComboBox(SelectionCommon):
name = 'combo-box'
is_focusable = True
is_vertical = True
def __init__(self, parent, items, font_size=None, border="black",
color='black', bgcolor='white', alt_bgcolor='eee',
active_bgcolor='ffc', item_pad=0, **kw):
super(ComboBox, self).__init__(parent, **kw)
# specific attributes for Options
self.color = util.parse_color(color)
self.base_bgcolor = self.bgcolor
self.alt_bgcolor = util.parse_color(alt_bgcolor)
self.active_bgcolor = util.parse_color(active_bgcolor)
self.font_size = font_size
lf = Frame(self)
lf.layout = layouts.Horizontal(lf, halign='left', valign='top')
# XXX add a an editable flag, and use a TextInput if it's true
self.label = Label(lf, items[0][0], font_size=font_size,
color=color, bgcolor=bgcolor, border=border)
Image(lf, self.arrow, color=(0, 0, 0, 1), bgcolor=bgcolor,
border=border)
# set up the popup item - try to make it appear in front
self.contents = Frame(self, is_visible=False,
bgcolor=bgcolor, border=border, z=.5)
self.contents.layout = layouts.Vertical(self.contents)
self.layout.ignore = set([self.contents])
# add the options
for label, id, kw in items:
Option(self.contents, text=label, id=id, **kw)
self.value = self.contents.children[0].id
def resize(self):
while self.contents.width is None or self.contents.height is None:
self.contents.resize()
# fix label width so it fits largest selection
self.label.width = self.contents.width
if not super(ComboBox, self).resize(): return False
self.contents.y = -(self.contents.height - self.height)
self.contents.x = 0
return True
@classmethod
def get_arrow(cls):
if not hasattr(cls, 'image_object'):
cls.image_object = data.load_gui_image('slider-arrow-down.png')
return cls.image_object
def _get_arrow(self): return self.get_arrow()
arrow = property(_get_arrow)
def get_value(self):
return self._value
def set_value(self, value):
for item in self.contents.children:
if item.id == value: break
else:
raise ValueError, '%r not a valid child item id'%(value,)
self.label.text = item.text
self._value = value
value = property(get_value, set_value)
def addOption(self, label, id=None, **kw):
Option(self.contents, text=label, id=id or label, **kw)
@event.default('combo-box')
def on_click(widget, x, y, button, modifiers, click_count):
if not button & mouse.LEFT:
return event.EVENT_UNHANDLED
# XXX position contents so the active item is over the label
label = widget.label
contents = widget.contents
if contents.is_visible:
label.setVisible(True)
contents.setVisible(False)
contents.loseFocus()
else:
label.setVisible(False)
contents.setVisible(True)
contents.gainFocus()
# reposition the selection drop down
contents.y = -(contents.height - widget.height)
contents.x = 0
return event.EVENT_HANDLED
@event.default('combo-box', 'on_gain_focus')
def on_gain_focus(widget, source):
if source == 'mouse':
# don't focus on mouse clicks
return event.EVENT_UNHANDLED
# catch focus
return event.EVENT_HANDLED
@event.default('combo-box', 'on_lose_focus')
def on_lose_focus(widget):
widget.contents.setVisible(False)
return event.EVENT_HANDLED
@event.default('combo-box')
def on_text_motion(widget, motion):
options = widget.contents.children
for i, option in enumerate(options):
if option.id == widget.value:
break
if motion == key.MOTION_DOWN and i + 1 != len(options):
widget.value = options[i+1].id
elif motion == key.MOTION_UP and i - 1 != -1:
widget.value = options[i-1].id
return event.EVENT_HANDLED
class Option(TextButton):
name = 'option'
def __init__(self, parent, border=None, color=None, bgcolor=None,
active_bgcolor=None, font_size=None, is_active=False,
alt_bgcolor=None, id=None, width='100%', **kw):
self.is_active = is_active
assert 'text' in kw, 'text required for Option'
# default styling and width to parent settings
select = parent.getParent('selection, combo-box')
if color is None:
color = select.color
if bgcolor is None:
self.bgcolor = select.bgcolor
else:
self.bgcolor = util.parse_color(bgcolor)
if alt_bgcolor is None:
self.alt_bgcolor = select.alt_bgcolor
else:
self.alt_bgcolor = util.parse_color(alt_bgcolor)
if active_bgcolor is None:
self.active_bgcolor = select.active_bgcolor
else:
self.active_bgcolor = util.parse_color(active_bgcolor)
if self.alt_bgcolor:
n = len(parent.children)
bgcolor = (self.bgcolor, self.alt_bgcolor)[n%2]
if font_size is None: font_size = select.font_size
if id is None: id = kw['text']
super(Option, self).__init__(parent, border=border, bgcolor=bgcolor,
font_size=font_size, color=color, id=id, width=width, **kw)
def set_text(self, text):
return super(Option, self).set_text(text, additional=('active', ))
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
kw['text'] = xml.sax.saxutils.unescape(element.text)
obj = cls(parent, **kw)
for child in element.getchildren():
loadxml.getConstructor(element.tag)(child, obj)
return obj
def renderBackground(self, clipped):
'''Select the correct image to render.
'''
if self.is_active and self.active_bgcolor:
self.bgcolor = self.active_bgcolor
else:
self.bgcolor = self.base_bgcolor
super(TextButton, self).renderBackground(clipped)
@event.default('combo-box option')
def on_click(widget, *args):
combo = widget.getParent('combo-box')
combo.value = widget.id
combo.contents.setVisible(False)
combo.label.setVisible(True)
combo.contents.loseFocus()
widget.getGUI().dispatch_event(combo, 'on_change', combo.value)
return event.EVENT_HANDLED
@event.default('selection option')
def on_click(widget, *args):
widget.is_active = not widget.is_active
select = widget.getParent('selection')
if select.scrollable: f = select.contents
else: f = select
if widget.is_active and select.is_exclusive:
for child in f.children:
if child is not widget:
child.is_active = None
widget.getGUI().dispatch_event(select, 'on_change', select.value)
return event.EVENT_HANDLED
| Python |
import operator
import xml.sax.saxutils
from xml.etree import ElementTree
from pyglet.gl import *
import pyglet.image
from wydget import element, event, loadxml, util, data, style
TOP = 'top'
BOTTOM = 'bottom'
LEFT = 'left'
RIGHT = 'right'
CENTER = 'center'
class ImageCommon(element.Element):
image = None
blend_color = False
def __init__(self, parent, x=None, y=None, z=None, width=None,
height=None, is_blended=False, valign='top', halign='left',
**kw):
self.is_blended = is_blended
self.valign = valign
self.halign = halign
super(ImageCommon, self).__init__(parent, x, y, z, width, height, **kw)
def setImage(self, image):
if hasattr(image, 'texture'):
image = image.texture
self.image = image
self.setDirty()
def intrinsic_width(self):
return self.image.width + self.padding * 2
def intrinsic_height(self):
return self.image.height + self.padding * 2
def render(self, rect):
image = self.image
if image is None:
return
ir = util.Rect(image.x, image.y, image.width, image.height)
if ir.clippedBy(rect):
rect = ir.intersect(rect)
if rect is None: return
image = image.get_region(rect.x, rect.y, rect.width, rect.height)
attrib = 0
if not self.isEnabled():
attrib = GL_CURRENT_BIT
elif self.blend_color and self.color is not None:
attrib = GL_CURRENT_BIT
if self.is_blended:
attrib |= GL_ENABLE_BIT
if attrib:
glPushAttrib(attrib)
if attrib & GL_ENABLE_BIT:
# blend with background
glEnable(GL_BLEND)
if attrib & GL_CURRENT_BIT:
if not self.isEnabled():
# blend with gray colour to wash out
glColor4f(.7, .7, .7, 1.)
else:
glColor4f(*self.color)
# XXX alignment
# blit() handles enabling GL_TEXTURE_2D and binding
image.blit(rect.x, rect.y, 0)
if attrib:
glPopAttrib()
class Image(ImageCommon):
name='image'
blend_color = True
def __init__(self, parent, image, is_blended=True, color=None, **kw):
if image is None and file is None:
raise ValueError, 'image or file required'
if isinstance(image, str):
image = data.load_image(image)
elif hasattr(image, 'texture'):
image = image.texture
self.parent = parent
self.color = util.parse_color(color)
super(Image, self).__init__(parent, is_blended=is_blended, **kw)
self.setImage(image)
class LabelCommon(element.Element):
def __init__(self, parent, text, x=None, y=None, z=None, width=None,
height=None, font_size=None, valign='top', halign='left',
color='black', rotate=0, **kw):
self.valign = valign
self.halign = halign
self.font_size = int(font_size or parent.getStyle().font_size)
self.color = util.parse_color(color)
self.rotate = util.parse_value(rotate, 0)
assert self.rotate in (0, 90, 180, 270), \
'rotate must be one of 0, 90, 180, 270, not %r'%(self.rotate, )
# set parent now so style is available
self.parent = parent
super(LabelCommon, self).__init__(parent, x, y, z, width, height, **kw)
self.text = text
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
text = xml.sax.saxutils.unescape(element.text)
obj = cls(parent, text, **kw)
for child in element.getchildren():
loadxml.getConstructor(element.tag)(child, obj)
return obj
class Label(LabelCommon):
name='label'
label = None
unconstrained = None
_text = None
def set_text(self, text):
if text == self._text: return
self._text = text
self.label = None
self.unconstrained = None
if hasattr(self, 'parent'):
self.setDirty()
text = property(lambda self: self._text, set_text)
def resetGeometry(self):
self.label = None
self.unconstrained = None
super(Label, self).resetGeometry()
def _render(self):
# get the unconstrained render first to determine intrinsic dimensions
style = self.getStyle()
self.unconstrained = style.text(self._text, font_size=self.font_size,
halign=self.halign, valign='top')
if self.rotate in (0, 180):
w = self.width or self.width_spec.specified()
if w is not None:
w -= self.padding * 2
else:
w = self.height or self.height_spec.specified()
if w is not None:
w -= self.padding * 2
self.label = style.text(self._text, color=self.color,
font_size=self.font_size, width=w, halign=self.halign,
valign='top')
def set_width(self, width):
# TODO this doesn't cope with the text being wrapped when width <
# self.label.width
self._width = width
if self.rotate in (0, 180) and self.label is not None:
self.label.width = width
self.setDirty()
width = property(lambda self: self._width, set_width)
def set_height(self, height):
# TODO this doesn't cope with the text being wrapped when height <
# self.label.width
self._height = height
if self.rotate in (90, 270) and self.label is not None:
self.label.width = height
self.setDirty()
height = property(lambda self: self._height, set_height)
def intrinsic_width(self):
# determine the width of the text with no width limitation
if self.unconstrained is None:
self._render()
if self.rotate in (90, 270):
return self.unconstrained.height + self.padding * 2
return self.unconstrained.width + self.padding * 2
def intrinsic_height(self):
# determine the height of the text with no width limitation
if self.unconstrained is None:
self._render()
if self.rotate in (90, 270):
return self.unconstrained.width + self.padding * 2
return self.unconstrained.height + self.padding * 2
def getRects(self, *args):
if self.label is None:
self._render()
return super(Label, self).getRects(*args)
def render(self, rect):
if self.label is None:
self._render()
glPushMatrix()
w = self.label.width
h = self.label.height
if self.rotate:
glRotatef(self.rotate, 0, 0, 1)
else:
glTranslatef(0, h, 0)
if self.rotate == 270:
glTranslatef(-w+self.padding, h, 0)
elif self.rotate == 180:
glTranslatef(-w+self.padding, 0, 0)
scissor = not (rect.x == rect.y == 0 and rect.width >= w and
rect.height >= h)
if scissor:
glPushAttrib(GL_SCISSOR_BIT)
glEnable(GL_SCISSOR_TEST)
x, y = self.calculateAbsoluteCoords(rect.x, rect.y)
glScissor(int(x), int(y), int(rect.width), int(rect.height))
self.label.draw()
if scissor:
glPopAttrib()
glPopMatrix()
class XHTML(LabelCommon):
'''Render an XHTML layout.
Note that layouts use a different coordinate system:
Canvas dimensions
layout.canvas_width and layout.canvas_height
Viewport
layout.viewport_x, layout.viewport_y, layout.viewport_width
and layout.viewport_height
The y coordinates start 0 at the *top* of the canvas and increase
*down* the canvas.
'''
name='xhtml'
def __init__(self, parent, text, style=None, **kw):
assert 'width' in kw, 'XHTML requires a width specification'
self.parent = parent
self.style = style
super(XHTML, self).__init__(parent, text, **kw)
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
children = element.getchildren()
if children:
text = ''.join(ElementTree.tostring(child) for child in children)
else:
text = ''
text = element.text + text + element.tail
obj = cls(parent, text, **kw)
return obj
def set_text(self, text):
self._text = text
self._render()
if hasattr(self, 'parent'):
self.setDirty()
text = property(lambda self: self._text, set_text)
def _render(self):
w = self.width
if w is None:
if self.width_spec.is_fixed or self.parent.width is not None:
w = self.width = self.width_spec.calculate()
else:
# use an arbitrary initial value
w = self.width = 512
self._target_width = w
w -= self.padding * 2
self.label = self.getStyle().xhtml('<p>%s</p>'%self._text, width=w,
style=self.style)
self.height = self.label.canvas_height
def intrinsic_width(self):
if not self.width:
if self.label is not None:
self.width = self.label.canvas_width + self.padding * 2
else:
self._render()
return self.width
def intrinsic_height(self):
if not self.height:
if self.label is not None:
self.height = self.label.canvas_height + self.padding * 2
else:
self._render()
return self.height
def resize(self):
# calculate the new width if necessary
if self._width is None:
w = self.width_spec.calculate()
if w is None: return False
self.width = w
# and reshape the XHTML layout if width changed
if w != self._target_width:
self._target_width = w
self.label.viewport_width = self.width
self.label.constrain_viewport()
# always use the canvas height
self.height = self.label.canvas_height
return True
def render(self, rect):
'''To render we need to:
1. Translate the y position from our OpenGL-based y-increases-up
value to the layout y-increases-down value.
2. Set up a scissor to limit display to the pixel rect we specify.
'''
# reposition the viewport based on visible rect
label = self.label
label.viewport_x = rect.x
scrollable_height = label.canvas_height - rect.height
label.viewport_y = int(scrollable_height - rect.y)
label.viewport_width = rect.width
label.viewport_height = rect.height
label.constrain_viewport()
scissor = not (rect.x == rect.y == 0 and rect.width == self.width and
rect.height == self.height)
if scissor:
glPushAttrib(GL_CURRENT_BIT|GL_SCISSOR_BIT)
glEnable(GL_SCISSOR_TEST)
x, y = self.calculateAbsoluteCoords(rect.x, rect.y)
glScissor(int(x), int(y), int(rect.width), int(rect.height))
else:
glPushAttrib(GL_CURRENT_BIT)
glPushMatrix()
glTranslatef(0, int(label.canvas_height - label.viewport_y), 0)
label.view.draw()
glPopMatrix()
glPopAttrib()
# Note with the following that layouts start at y=0 and go negative
@event.default('xhtml')
def on_mouse_press(widget, x, y, button, modifiers):
x, y = widget.calculateRelativeCoords(x, y)
y -= widget.height
return widget.label.on_mouse_press(x, y, button, modifiers)
@event.default('xhtml')
def on_element_leave(widget, x, y):
x, y = widget.calculateRelativeCoords(x, y)
y -= widget.height
return widget.label.on_mouse_leave(x, y)
@event.default('xhtml')
def on_mouse_motion(widget, x, y, button, modifiers):
x, y = widget.calculateRelativeCoords(x, y)
y -= widget.height
return widget.label.on_mouse_motion(x, y, button, modifiers)
| Python |
from pyglet.gl import *
from wydget import element, event, layouts, util, loadxml
from wydget.widgets.label import Label, Image
class FrameCommon(element.Element):
need_layout = True
def setDirty(self):
super(FrameCommon, self).setDirty()
self.need_layout = True
def intrinsic_width(self):
return self.layout.width + self.padding * 2
def intrinsic_height(self):
return self.layout.height + self.padding * 2
scrollable = False
def resize(self):
if not super(FrameCommon, self).resize():
return False
if self.scrollable:
if self.contents.checkForScrollbars():
raise util.RestartLayout()
if not self.need_layout:
return True
# make sure all the children have dimensions before trying
# layout
for c in self.children:
c.resize()
if c.height is None or c.width is None:
return False
self.layout()
self.need_layout = False
return True
def delete(self):
self.layout = None
super(FrameCommon, self).delete()
class Frame(FrameCommon):
name='frame'
h_slider = None
v_slider = None
def __init__(self, parent, x=None, y=None, z=None, width=None,
height=None, scrollable=False, scrollable_resize=False, **kw):
self.layout = layouts.Layout(self)
self.scrollable = scrollable
self.scrollable_resize = scrollable_resize
super(Frame, self).__init__(parent, x, y, z, width, height, **kw)
if self.scrollable:
self.contents = ContainerFrame(self, 0, 0, 0, None, None,
is_transparent=True)
self.contents.layout = layouts.Layout(self.contents)
self.contents.setViewClip((0, 0, self.width, self.height))
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
If scrollable then put all children loaded into a container frame.
'''
kw = loadxml.parseAttributes(element)
obj = cls(parent, **kw)
for child in element.getchildren():
if obj.scrollable:
loadxml.getConstructor(child.tag)(child, obj.contents)
else:
loadxml.getConstructor(child.tag)(child, obj)
return obj
@event.default('frame')
def on_mouse_scroll(widget, x, y, dx, dy):
if widget.scrollable:
if dy and widget.v_slider is not None:
slider = widget.v_slider
slider.set_value(slider.value + dy * slider.step, event=True)
if dx and widget.h_slider is not None:
slider = widget.h_slider
slider.set_value(slider.value + dx * slider.step, event=True)
elif dy and widget.v_slider is None and widget.h_slider is not None:
slider = widget.h_slider
slider.set_value(slider.value + dy * slider.step, event=True)
return event.EVENT_HANDLED
return event.EVENT_UNHANDLED
class ContainerFrame(FrameCommon):
'''A special transparent frame that is used for frames with fixed size
and scrolling contents -- this frame holds those contents.
'''
name = 'container-frame'
def intrinsic_width(self):
return self.layout.width + self.padding * 2
def intrinsic_height(self):
return self.layout.height + self.padding * 2
def checkForScrollbars(self):
# avoid circular import
from wydget.widgets.slider import VerticalSlider, HorizontalSlider
# XXX perhaps this should be on the parent
h = self.layout.height
w = self.layout.width
# check to see whether the parent needs a slider
p = self.parent
pr = self.parent.inner_rect
vc_width, vc_height = pr.width, pr.height
self.y = vc_height - self.layout.height
# see what we need
v_needed = h > vc_height
if v_needed and not self.parent.scrollable_resize:
vc_width -= VerticalSlider.slider_size
h_needed = w > vc_width
if h_needed and not v_needed:
v_needed = h > vc_height
change = False # slider added or removed
# add a vertical slider?
if v_needed:
r = h - vc_height
if h_needed and not self.parent.scrollable_resize:
y = HorizontalSlider.slider_size
h = vc_height - y
r += y
else:
y = 0
h = vc_height
if p.v_slider is not None:
# XXX update the range more sanely
p.v_slider.range = r
else:
p.v_slider = VerticalSlider(p, 0, r, r, x=vc_width, y=y,
height=h, step=16, classes=('-frame-vertical-slider',))
change = True
elif p.v_slider is not None:
p.v_slider.delete()
p.v_slider = None
change = True
# add a horizontal slider?
if h_needed:
r = w - vc_width
if p.h_slider is not None:
p.h_slider.range = r
else:
p.h_slider = HorizontalSlider(p, 0, r, 0, x=0, y=0,
width=vc_width, step=16,
classes=('-frame-horizontal-slider',))
change = True
elif p.h_slider is not None:
p.h_slider.delete()
p.h_slider = None
change = True
#if change:
# XXX really do need to do something here to resize contents
return change
def resize(self):
if not super(ContainerFrame, self).resize():
return False
if self.parent.width is None:
return False
if self.parent.height is None:
return False
self.updateViewClip()
return True
def updateViewClip(self):
p = self.parent
pr = p.inner_rect
vc_width, vc_height = pr.width, pr.height
h_height = 0
if p.v_slider and not self.parent.scrollable_resize:
vc_width -= p.v_slider.width
if p.h_slider and not self.parent.scrollable_resize:
h_height = p.h_slider.height
vc_height -= h_height
self.setViewClip((-self.x, -self.y + h_height, vc_width, vc_height))
def setY(self, value):
self.y = -value
p = self.parent
if p.h_slider and not self.parent.scrollable_resize:
self.y += p.h_slider.height
self.updateViewClip()
def setX(self, value):
self.x = -value
self.updateViewClip()
@event.default('.-frame-vertical-slider')
def on_change(widget, value):
widget.parent.contents.setY(int(value))
return event.EVENT_HANDLED
@event.default('.-frame-horizontal-slider')
def on_change(widget, value):
widget.parent.contents.setX(int(value))
return event.EVENT_HANDLED
class TabFrame(Frame):
'''Special frame for inside a TabbedFrame that renders its border so
it appears merged with the button. Also performs more cleanup on delete().
'''
name = 'tab-frame'
def renderBorder(self, clipped):
if self.border is None: return
glColor4f(*self.border)
# XXX handle clippped better
x2, y2 = clipped.topright
butx1 = self._button.x
butx2 = self._button.x + self._button.width
glBegin(GL_LINE_STRIP)
glVertex2f(butx1, y2)
if butx1 != clipped.x: glVertex2f(clipped.x, y2)
glVertex2f(clipped.x, clipped.y)
glVertex2f(x2, clipped.y)
glVertex2f(x2, y2)
if butx2 != x2: glVertex2f(butx2, y2)
if self.bgcolor is not None:
glColor4f(*self.bgcolor)
glVertex2f(butx2-1, y2)
glVertex2f(butx1+1, y2)
glEnd()
def resize(self):
if self.scrollable:
self.width = self.parent.width
self.height = self.parent.height
return super(TabFrame, self).resize()
def delete(self):
self._button = None
super(TabFrame, self).delete()
class TabButton(Frame):
'''Special button for inside a TabbedFrame that renders its border so
it appears merged with the tab. Also performs more cleanup on delete().
'''
name = 'tab-button'
is_focusable = False
def __init__(self, parent, text=None, image=None, border="black",
padding=1, halign="left", valign="bottom", font_size=None,
**kw):
super(TabButton, self).__init__(parent, border=border,
padding=padding, **kw)
if text is None and image is None:
raise ValueError, 'text or image required'
if image is not None: Image(self, image)
if text is not None: Label(self, text, font_size=font_size)
self.layout = layouts.Horizontal(self, padding=2, halign=halign,
valign=valign)
def renderBorder(self, clipped):
'''Render the border in relative coordinates clipped to the
indicated view.
'''
if self.border is None: return
ox, oy = 0, 0
ox2, oy2 = self.width, self.height
cx, cy = clipped.bottomleft
cx2, cy2 = clipped.topright
glColor4f(*self.border)
glBegin(GL_LINES)
# left
if ox == cx:
glVertex2f(ox, cy)
glVertex2f(ox, cy2)
# right
if ox2 == cx2:
glVertex2f(ox2-1, cy)
glVertex2f(ox2-1, cy2)
# top
if oy2 == cy2:
glVertex2f(cx, oy2-1)
glVertex2f(cx2, oy2-1)
glEnd()
def delete(self):
self._frame = None
self._top = None
super(TabButton, self).delete()
class TabsLayout(layouts.Layout):
'''A special layout that overlaps TabFrames.
'''
name = 'tabs-layout'
def getChildren(self):
'''Don't use scrollable tabs for sizing.
'''
return [c for c in super(TabsLayout, self).getChildren()
if not c.scrollable]
class TabbedFrame(Frame):
'''A collection of frames, one active at a time.
Container frames must be created using the newTab method. It in turn
uses the button_class and frame_class attributes to create the tabs.
'''
name = 'tabbed-frame'
button_class = TabButton
frame_class = TabFrame
def __init__(self, parent, is_transparent=True, halign='left', **kw):
super(TabbedFrame, self).__init__(parent,
is_transparent=is_transparent, **kw)
self.halign = halign
self.top = Frame(self, is_transparent=True)
self.top.layout = layouts.Horizontal(self.top, halign=self.halign,
padding=2)
self.bottom = Frame(self, is_transparent=True)
self.bottom.layout = TabsLayout(self.bottom)
self.layout = layouts.Vertical(self, valign='bottom', padding=0)
self._active_frame = None
def get_active(self):
return self._active_frame._button
active = property(get_active)
default = []
def newTab(self, text=None, image=None, border=default,
bgcolor=default, scrollable=False, font_size=None, **kw):
if border is self.default: border = self.border
if bgcolor is self.default: bgcolor = self.bgcolor
# this will resize the height of the top frame if necessary
b = self.button_class(self.top, text=text, image=image,
border=border, bgcolor=bgcolor, font_size=font_size, **kw)
b._top = self
if scrollable:
f = self.frame_class(self.bottom, scrollable=True, x=0, y=0,
border=border, bgcolor=bgcolor, padding=2,
height='100%', width='100%')
r = f.contents
else:
r = f = self.frame_class(self.bottom, border=border, x=0, y=0,
bgcolor=bgcolor, padding=2, height='100%', width='100%')
b._frame = f
f._button = b
if self._active_frame is None:
self._active_frame = f
else:
f.setVisible(False)
return r
def activate(self, tab):
self._active_frame.setVisible(False)
self._active_frame.setEnabled(False)
self._active_frame = tab
tab.setVisible(True)
tab.setEnabled(True)
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
Create tabs for <tab> child tags.
'''
kw = loadxml.parseAttributes(element)
obj = cls(parent, **kw)
for child in element.getchildren():
assert child.tag == 'tab'
kw = loadxml.parseAttributes(child)
label = kw.pop('label')
tab = obj.newTab(label, **kw)
for content in child.getchildren():
loadxml.getConstructor(content.tag)(content, tab)
return obj
@event.default('tab-button', 'on_click')
def on_tab_click(widget, *args):
widget.getParent('tabbed-frame').activate(widget._frame)
return event.EVENT_HANDLED
| Python |
from wydget import anim
from wydget.widgets.frame import Frame
class Drawer(Frame):
'''A *transparent container* that may hide and expose its contents.
'''
name='drawer'
HIDDEN='hidden'
EXPOSED='exposed'
LEFT='left'
RIGHT='right'
TOP='top'
BOTTOM='bottom'
def __init__(self, parent, state=HIDDEN, side=LEFT,
is_transparent=True, **kw):
super(Drawer, self).__init__(parent, is_transparent=is_transparent,
**kw)
self.state = state
self.side = side
if state == self.HIDDEN:
self.setVisible(False)
def toggle_state(self):
if self.state == self.EXPOSED: self.hide()
else: self.expose()
_anim = None
def expose(self):
if self.state == self.EXPOSED: return
if self._anim is not None and self._anim.is_running:
self._anim.cancel()
self._anim = ExposeAnimation(self)
self.setVisible(True)
self.state = self.EXPOSED
def hide(self):
if self.state == self.HIDDEN: return
if self._anim is not None and self._anim.is_running:
self._anim.cancel()
self._anim = HideAnimation(self)
self.state = self.HIDDEN
class HideAnimation(anim.Animation):
def __init__(self, drawer, duration=.25, function=anim.cosine90):
self.drawer = drawer
self.duration = duration
self.function = function
if drawer.side == Drawer.LEFT:
self.sx = int(drawer.x)
self.ex = int(drawer.x - drawer.width)
self.sw = int(drawer.width)
self.ew = 0
elif drawer.side == Drawer.RIGHT:
self.sx = int(drawer.x)
self.ex = int(drawer.x + drawer.width)
self.sw = int(drawer.width)
self.ew = 0
elif drawer.side == Drawer.TOP:
self.sy = int(drawer.y)
self.ey = int(drawer.y - drawer.height)
self.sh = int(drawer.height)
self.eh = 0
elif drawer.side == Drawer.BOTTOM:
self.sy = int(drawer.y)
self.ey = int(drawer.y + drawer.height)
self.sh = int(drawer.height)
self.eh = 0
super(HideAnimation, self).__init__()
def cancel(self):
self.drawer.setVisible(False)
if self.drawer.side in (Drawer.LEFT, Drawer.RIGHT):
self.drawer.setViewClip((self.sx, 0, self.ew,
self.drawer.height))
self.drawer.x = self.ex
else:
self.drawer.setViewClip((0, self.sy, self.drawer.width,
self.eh))
self.drawer.y = self.ey
super(HideAnimation, self).cancel()
def animate(self, dt):
self.anim_time += dt
if self.anim_time >= self.duration:
self.cancel()
else:
t = self.anim_time / self.duration
if self.drawer.side in (Drawer.LEFT, Drawer.RIGHT):
x = anim.tween(self.sx, self.ex, t, self.function)
w = anim.tween(self.sw, self.ew, t, self.function)
if self.drawer.side == Drawer.LEFT:
vcx = self.sw - w
elif self.drawer.side == Drawer.RIGHT:
vcx = 0
self.drawer.setViewClip((vcx, 0, w, self.drawer.height))
self.drawer.x = x
else:
y = anim.tween(self.sy, self.ey, t, self.function)
h = anim.tween(self.sh, self.eh, t, self.function)
if self.drawer.side == Drawer.TOP:
vcy = self.sh - h
elif self.drawer.side == Drawer.BOTTOM:
vcy = 0
self.drawer.setViewClip((0, vcy, self.drawer.width, h))
self.drawer.y = y
class ExposeAnimation(anim.Animation):
def __init__(self, drawer, duration=.25, function=anim.cosine90):
self.drawer = drawer
self.duration = duration
self.function = function
if drawer.side == Drawer.LEFT:
self.sx = int(drawer.x)
self.ex = int(drawer.x + drawer.width)
self.sw = 0
self.ew = int(drawer.width)
elif drawer.side == Drawer.RIGHT:
self.sx = int(drawer.x)
self.ex = int(drawer.x - drawer.width)
self.sw = 0
self.ew = int(drawer.width)
elif drawer.side == Drawer.TOP:
self.sy = int(drawer.y)
self.ey = int(drawer.y + drawer.height)
self.sh = 0
self.eh = int(drawer.height)
elif drawer.side == Drawer.BOTTOM:
self.sy = int(drawer.y)
self.ey = int(drawer.y - drawer.height)
self.sh = 0
self.eh = int(drawer.height)
super(ExposeAnimation, self).__init__()
def cancel(self):
if self.drawer.side in (Drawer.LEFT, Drawer.RIGHT):
self.drawer.setViewClip((0, 0, self.ew, self.drawer.height))
self.drawer.x = self.ex
else:
self.drawer.setViewClip((0, 0, self.drawer.width, self.eh))
self.drawer.y = self.ey
super(ExposeAnimation, self).cancel()
def animate(self, dt):
self.anim_time += dt
if self.anim_time >= self.duration:
self.cancel()
else:
t = self.anim_time / self.duration
if self.drawer.side in (Drawer.LEFT, Drawer.RIGHT):
x = anim.tween(self.sx, self.ex, t, self.function)
w = anim.tween(self.sw, self.ew, t, self.function)
if self.drawer.side == Drawer.LEFT:
vcx = self.ew - w
elif self.drawer.side == Drawer.RIGHT:
vcx = 0
self.drawer.setViewClip((vcx, 0, w, self.drawer.height))
self.drawer.x = x
else:
y = anim.tween(self.sy, self.ey, t, self.function)
h = anim.tween(self.sh, self.eh, t, self.function)
if self.drawer.side == Drawer.TOP:
vcy = self.eh - h
elif self.drawer.side == Drawer.BOTTOM:
vcy = 0
self.drawer.setViewClip((0, vcy, self.drawer.width, h))
self.drawer.y = y
| Python |
import xml.sax.saxutils
from pyglet.gl import *
from pyglet import clock
from pyglet.window import key, mouse
from wydget import element, event, util, anim, data, loadxml
from wydget.widgets.label import ImageCommon, Label
class ButtonCommon(object):
is_focusable = True
is_pressed = False
is_over = False
class Button(ButtonCommon, ImageCommon):
'''A button represented by one to three images.
image - the normal-state image to be displayed
pressed_image - button is pressed
over_image - the mouse is over the button or the button is focused
If text is supplied, it is rendered over the image, centered.
'''
name = 'button'
def __init__(self, parent, image, text=None, pressed_image=None,
over_image=None, is_blended=True, font_size=None,
color=(0, 0, 0, 1),
x=0, y=0, z=0, width=None, height=None, **kw):
super(Button, self).__init__(parent, x, y, z, width, height,
is_blended=is_blended, **kw)
if image is None:
raise ValueError, 'image argument is required'
self.setImage(image)
self.setPressedImage(pressed_image)
self.setOverImage(over_image)
self.color = util.parse_color(color)
if text:
self.font_size = int(font_size or self.getStyle().font_size)
self.bg = self.base_image
self.over_bg = self.over_image
self.pressed_bg = self.pressed_image
# clear so we don't delete these
self.base_image = self.over_image = self.pressed_image = None
self.text = text
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
if element.text:
text = xml.sax.saxutils.unescape(element.text)
else:
text = None
if 'image' in kw:
kw['text'] = text
obj = Button(parent, **kw)
else:
obj = TextButton(parent, text, **kw)
for child in element.getchildren():
loadxml.getConstructor(child.tag)(child, obj)
return obj
def setImage(self, image, attribute='base_image'):
if isinstance(image, str):
image = data.load_image(image).texture
elif hasattr(image, 'texture'):
image = image.texture
setattr(self, attribute, image)
if attribute == 'base_image':
self.image = self.base_image
self.setDirty()
def setPressedImage(self, image):
self.setImage(image, 'pressed_image')
def setOverImage(self, image):
self.setImage(image, 'over_image')
_text = None
def set_text(self, text):
if text == self._text: return
self._text = text
self.over_image = None
self.pressed_image = None
# XXX restrict text width?
label = self.getStyle().text(text, font_size=self.font_size,
color=self.color, valign='top')
label.width # force clean
num_lines = len(label.lines)
# size of resulting button images
w, h = self.width, self.height = self.bg.width, self.bg.height
# center
tx = self.bg.width // 2 - label.width // 2
ty = self.bg.height // 2 - label.height // 2
def f(bg):
def _inner():
glPushAttrib(GL_CURRENT_BIT|GL_COLOR_BUFFER_BIT)
glClearColor(1, 1, 1, 0)
glClear(GL_COLOR_BUFFER_BIT)
glPushMatrix()
glLoadIdentity()
bg.blit(0, 0, 0)
glTranslatef(tx, ty + label.height, 0)
# prevent the text's alpha channel being written into the new
# texture
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE)
label.draw()
glPopMatrix()
glPopAttrib()
return _inner
self.setImage(util.renderToTexture(w, h, f(self.bg)))
if self.over_bg is not None:
self.setImage(util.renderToTexture(w, h, f(self.over_bg)),
'over_image')
if self.pressed_bg is not None:
self.setImage(util.renderToTexture(w, h, f(self.pressed_bg)),
'pressed_image')
text = property(lambda self: self._text, set_text)
def render(self, rect):
'''Select the correct image to render.
'''
if self.is_pressed and self.is_over and self.pressed_image:
self.image = self.pressed_image
elif self.is_over and self.over_image:
self.image = self.over_image
else:
self.image = self.base_image
# XXX handle isFocused()
super(Button, self).render(rect)
class TextButton(ButtonCommon, Label):
'''A button with text on it.
Will be rendered over the standard Element rendering.
'''
name = 'button'
_default = []
def __init__(self, parent, text, bgcolor='white', color='black',
border='black', focus_border=(.3, .3, .7, 1),
pressed_bgcolor=(1, .9, .9, 1), over_bgcolor=(.9, .9, 1, 1),
**kw):
super(TextButton, self).__init__(parent, text, bgcolor=bgcolor,
color=color, border=border, **kw)
# colouring attributes
self.base_bgcolor = self.bgcolor
self.pressed_bgcolor = util.parse_color(pressed_bgcolor)
self.over_bgcolor = util.parse_color(over_bgcolor)
self.base_border = self.border
self.focus_border = util.parse_color(focus_border)
def renderBorder(self, clipped):
if self.isFocused():
self.border = self.focus_border
else:
self.border = self.base_border
super(TextButton, self).renderBorder(clipped)
def renderBackground(self, clipped):
'''Select the correct image to render.
'''
if not self.isEnabled():
self.bgcolor = (.7, .7, .7, 1)
elif self.is_pressed and self.is_over and self.pressed_bgcolor:
self.bgcolor = self.pressed_bgcolor
elif self.is_over and self.over_bgcolor:
self.bgcolor = self.over_bgcolor
else:
self.bgcolor = self.base_bgcolor
super(TextButton, self).renderBackground(clipped)
class RepeaterButton(Button):
'''Generates on_click events periodically if the mouse button is held
pressed over the button.
on mouse press, schedule a timeout for .5 secs and after that time
schedule a call to the callback every .1 secs.
on mouse release, cancel the timer
on mouse leave, cancel the *second* timer only
on mouse enter, reinstate the second timer
'''
name = 'repeater-button'
is_focusable = False
delay_timer = None
def __init__(self, parent, delay=.5, **kw):
super(RepeaterButton, self).__init__(parent, **kw)
self.delay = delay
repeating = False
def startRepeat(self):
self.delay_timer = None
self.repeat_time = 0
self.repeating = True
clock.schedule(self.repeat)
def repeat(self, dt):
self.repeat_time += dt
if self.repeat_time > .1:
self.repeat_time -= .1
self.getGUI().dispatch_event(self, 'on_click', 0, 0,
self.buttons, self.modifiers, 1)
def stopRepeat(self):
if self.delay_timer is not None:
self.delay_timer.cancel()
self.delay_timer = None
if self.repeating:
clock.unschedule(self.repeat)
self.repeating = False
@event.default('button, text-button')
def on_gain_focus(self, source):
if source == 'mouse':
# mouse clicks should not focus buttons
return event.EVENT_UNHANDLED
return event.EVENT_HANDLED
@event.default('button')
def on_element_enter(self, x, y):
self.is_over = True
return event.EVENT_HANDLED
@event.default('button')
def on_element_leave(self, x, y):
self.is_over = False
return event.EVENT_HANDLED
@event.default('button')
def on_mouse_press(self, x, y, button, modifiers):
self.is_pressed = True
return event.EVENT_UNHANDLED
@event.default('button')
def on_mouse_release(self, x, y, button, modifiers):
self.is_pressed = False
return event.EVENT_UNHANDLED
@event.default('repeater-button')
def on_mouse_press(self, x, y, buttons, modifiers):
self.is_pressed = True
if self.delay:
self.delay_timer = anim.Delayed(self.startRepeat, delay=self.delay)
else:
self.startRepeat()
self.buttons = buttons
self.modifiers = modifiers
self.getGUI().dispatch_event(self, 'on_click', x, y, buttons,
modifiers, 1)
self.is_pressed = True
return event.EVENT_HANDLED
@event.default('repeater-button')
def on_mouse_release(self, x, y, buttons, modifiers):
self.is_pressed = False
self.stopRepeat()
return event.EVENT_HANDLED
@event.default('repeater-button')
def on_element_enter(self, x, y):
if self.is_pressed:
self.startRepeat()
self.is_over = True
return event.EVENT_HANDLED
@event.default('repeater-button')
def on_element_leave(self, x, y):
self.is_over = False
self.stopRepeat()
return event.EVENT_HANDLED
@event.default('button, repeater-button')
def on_text(self, text):
if text in ' \r':
self.getGUI().dispatch_event(self, 'on_click', 0, 0, mouse.LEFT, 0, 1)
return event.EVENT_HANDLED
return event.EVENT_UNHANDLED
| Python |
from pyglet.gl import *
from pyglet import clock
from pyglet.window import key, mouse
from wydget import element, event, util, anim, data
class Checkbox(element.Element):
name='checkbox'
is_focusable = True
def __init__(self, parent, value=False, width=16, height=16, **kw):
self.parent = parent
self.value = value
super(Checkbox, self).__init__(parent, None, None, None, width,
height, **kw)
def intrinsic_width(self):
return self.width or 16
def intrinsic_height(self):
return self.height or 16
def render(self, rect):
# XXX handle rect (and use images...)
glPushAttrib(GL_CURRENT_BIT)
glColor4f(.85, .85, .85, 1)
w, h = 16, 16
glRectf(1, 1, w, h)
if self.value:
glColor4f(0, 0, 0, 1)
w8, h8 = w//8, h//8
glBegin(GL_LINE_STRIP)
glVertex2f(1+w8, 1+4*h8)
glVertex2f(1+3*w8, 1+h8)
glVertex2f(1+7*w8, 1+7*h8)
glEnd()
glPopAttrib()
@event.default('checkbox')
def on_click(widget, *args):
widget.value = not widget.value
return event.EVENT_UNHANDLED
@event.default('checkbox')
def on_text(self, text):
if text in (' \r'):
self.getGUI().dispatch_event(self, 'on_click', 0, 0, mouse.LEFT, 0, 1)
return event.EVENT_HANDLED
return event.EVENT_UNHANDLED
| Python |
from wydget.widgets.button import Button, TextButton, RepeaterButton
from wydget.widgets.frame import Frame, TabbedFrame
from wydget.widgets.drawer import Drawer
from wydget.widgets.label import Image, Label, XHTML
from wydget.widgets.menu import MenuItem, PopupMenu
from wydget.widgets.movie import Movie
from wydget.widgets.music import Music
from wydget.widgets.selection import ComboBox, Selection, Option
from wydget.widgets.slider import VerticalSlider, HorizontalSlider
from wydget.widgets.slider import ArrowButtonUp, ArrowButtonDown
from wydget.widgets.slider import ArrowButtonLeft, ArrowButtonRight
from wydget.widgets.textline import TextInput, PasswordInput
from wydget.widgets.checkbox import Checkbox
from wydget.widgets.table import Table, Heading, Row, Cell
from wydget.widgets.progress import Progress
from wydget import loadxml
for klass in [Frame, TabbedFrame,
Drawer,
Image, Label, XHTML,
Button, RepeaterButton,
TextInput, PasswordInput,
VerticalSlider, HorizontalSlider,
ArrowButtonUp, ArrowButtonDown,
ArrowButtonLeft, ArrowButtonRight,
Checkbox,
Movie, Music,
PopupMenu, MenuItem,
ComboBox, Selection, Option,
Table, Heading, Row, Cell,
Progress]:
loadxml.xml_registry[klass.name] = klass
| Python |
import datetime
import xml.sax.saxutils
from pyglet.gl import *
from wydget import element, event, layouts, loadxml, util
from wydget.widgets.frame import Frame, ContainerFrame
from wydget.widgets.slider import VerticalSlider, HorizontalSlider
from wydget.widgets.label import Label
class Table(element.Element):
name = 'table'
h_slider = None
v_slider = None
def __init__(self, parent, size=None, is_exclusive=False,
color=(0, 0, 0, 1), bgcolor=(1, 1, 1, 1),
alt_bgcolor=(.9, .9, .9, 1), active_bgcolor=(1, .8, .8, 1),
x=0, y=0, z=0, width='100%', height=None, **kw):
font_size = parent.getStyle().font_size
size = util.parse_value(size, None)
if size is not None:
height = (size + 1) * font_size
self.is_exclusive = is_exclusive
super(Table, self).__init__(parent, x, y, z, width, height,
bgcolor=bgcolor, **kw)
# rows go in under the heading
#self.contents = TableContainer(self)
self.contents = ContainerFrame(self)
self.contents.layout = layouts.Layout(self.contents)
self.contents.checkForScrollbars()
# specific attributes for rows
self.color = util.parse_color(color)
self.base_bgcolor = self.bgcolor
self.alt_bgcolor = util.parse_color(alt_bgcolor)
self.active_bgcolor = util.parse_color(active_bgcolor)
def get_inner_rect(self):
p = self.padding
font_size = self.getStyle().font_size
return util.Rect(p, p, self.width - p*2, self.height - p*2 - font_size)
inner_rect = property(get_inner_rect)
def layoutDimensionsChanged(self, layout):
pass
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
If scrollable then put all children loaded into a container frame.
'''
kw = loadxml.parseAttributes(element)
obj = cls(parent, **kw)
for child in element.getchildren():
if child.tag == 'row':
Row.fromXML(child, obj.contents)
elif child.tag == 'heading':
obj.heading = Heading.fromXML(child, obj)
obj.heading.layout.layout()
else:
raise ValueError, 'unexpected tag %r'%child.tag
obj.contents.layout.layout()
return obj
class Heading(Frame):
name = 'heading'
def __init__(self, parent, width='100%', bgcolor='aaa', **kw):
kw['y'] = parent.height - parent.getStyle().font_size
super(Heading, self).__init__(parent, width=width, **kw)
self.layout = layouts.Horizontal(self, valign='top', halign='fill',
padding=2)
class Row(Frame):
name = 'row'
def __init__(self, parent, border=None, color=None, bgcolor=None,
active_bgcolor=None, is_active=False, width='100%', **kw):
self.is_active = is_active
# default styling and width to parent settings
n = len(parent.children)
table = parent.parent
if color is None:
color = table.color
if bgcolor is None:
bgcolor = (table.bgcolor, table.alt_bgcolor)[n%2]
if active_bgcolor is None:
self.active_bgcolor = table.active_bgcolor
else:
self.active_bgcolor = util.parse_color(active_bgcolor)
font_size = parent.getStyle().font_size
kw['y'] = n * font_size
kw['height'] = font_size
super(Row, self).__init__(parent, border=border, bgcolor=bgcolor,
width=width, **kw)
self.base_bgcolor = bgcolor
def renderBackground(self, clipped):
'''Select the correct background color to render.
'''
if self.is_active and self.active_bgcolor:
self.bgcolor = self.active_bgcolor
else:
self.bgcolor = self.base_bgcolor
super(Row, self).renderBackground(clipped)
class Cell(Label):
name = 'cell'
def __init__(self, parent, value, type='string', **kw):
self.value = value
self.type = type
self.column = len(parent.children)
kw['x'] = parent.parent.parent.heading.children[self.column].x
if type == 'time':
if value.hour:
text = '%d:%02d:%02d'%(value.hour, value.minute, value.second)
else:
text = '%d:%02d'%(value.minute, value.second)
else:
text = str(value)
super(Cell, self).__init__(parent, text, **kw)
@classmethod
def fromXML(cls, element, parent):
'''Create the object from the XML element and attach it to the parent.
'''
kw = loadxml.parseAttributes(element)
text = xml.sax.saxutils.unescape(element.text)
t = kw.get('type')
if t == 'integer':
value = int(text)
elif t == 'time':
if ':' in text:
# (h:)m:s value
value = map(int, text.split(':'))
if len(value) == 2: m, s = value[0], value[1]
else: h, m, s = value[0], value[1], value[2]
else:
# seconds value
value = int(text)
s = value % 60
m = (value / 60) % 60
h = value / 360
value = datetime.time(h, m, s)
else:
value = text
obj = cls(parent, value, **kw)
#for child in element.getchildren():
# loadxml.getConstructor(element.tag)(child, obj)
return obj
| Python |
from pyglet.gl import *
from pyglet import clock
from pyglet.window import mouse
from wydget import element, event, data, util, anim
from wydget.widgets.button import Button, RepeaterButton
from wydget.widgets.label import Label
from wydget.widgets.frame import Frame
class SliderCommon(Frame):
slider_size = 16
def resize(self):
if not super(SliderCommon, self).resize(): return False
self.handleSizing()
return True
def get_value(self):
return self._value
def set_value(self, value, event=False, position_bar=True):
self._value = self.type(max(self.minimum, min(self.maximum, value)))
if position_bar:
self.positionBar()
if self.show_value:
self.bar.tect = str(self._value)
if event:
self.getGUI().dispatch_event(self, 'on_change', self._value)
value = property(get_value, set_value)
def stepToMaximum(self, multiplier=1):
self.set_value(self._value + multiplier * self.step, event=True)
def stepToMinimum(self, multiplier=1):
self.set_value(self._value - multiplier * self.step, event=True)
class VerticalSlider(SliderCommon):
'''
The value will be of the same type as the minimum value.
'''
name='vslider'
def __init__(self, parent, minimum, maximum, value, step=1,
bar_size=None, show_value=False, bar_text_color='white',
bar_color=(.3, .3, .3, 1), x=None, y=None, z=None,
width=SliderCommon.slider_size, height='100%',
bgcolor='gray', **kw):
self.minimum = util.parse_value(minimum, 0)
self.type = type(self.minimum)
self.maximum = util.parse_value(maximum, 0)
self.range = self.maximum - self.minimum
self._value = util.parse_value(value, 0)
self.step = util.parse_value(step, 0)
self.show_value = show_value
self.bar_spec = bar_size
self.bar_color = util.parse_color(bar_color)
self.bar_text_color = util.parse_color(bar_text_color)
self.bar = self.dbut = self.ubut = None
super(VerticalSlider, self).__init__(parent, x, y, z, width, height,
bgcolor=bgcolor, **kw)
def handleSizing(self):
try:
# if the bar size spec is a straight integer, use it
min_size = int(self.bar_spec) + self.slider_size
except:
min_size = self.slider_size * 2
height = self.height
if height < min_size:
height = min_size
# assume buttons are same height
bh = ArrowButtonUp.get_arrow().height
# only have buttons if there's enough room (two buttons plus
# scrolling room)
self.have_buttons = height > (bh * 2 + min_size)
if self.have_buttons and self.dbut is None:
# do this after the call to super to allow it to set the parent etc.
self.dbut = ArrowButtonDown(self, classes=('-repeater-button-min',),
color='black')
self.ubut = ArrowButtonUp(self, y=height-bh, color='black',
classes=('-repeater-button-max',))
elif not self.have_buttons and self.dbut is not None:
self.dbut.delete()
self.ubut.delete()
self.dbut = self.ubut = None
# add slider bar
#i_height = self.inner_rect.height
i_height = height
self.bar_size = util.parse_value(self.bar_spec, i_height)
if self.bar_size is None:
self.bar_size = int(max(self.slider_size, i_height /
(self.range+1)))
s = self.show_value and str(self._value) or ' '
# note: dimensions are funny because the bar is rotated 90 degrees
if self.bar is None:
self.bar = SliderBar(self, 'y', s, self.width, self.bar_size,
bgcolor=self.bar_color, color=self.bar_text_color)
else:
self.bar.text = s
self.bar.height = self.bar_size
self.height = height
# fix up sizing and positioning of elements
if self.dbut is not None:
self.dbut.resize()
self.ubut.resize()
self.bar.resize()
self.positionBar()
def get_inner_rect(self):
if self.have_buttons:
bh = ArrowButtonLeft.get_arrow().height
return util.Rect(0, bh, self.width, self.height - bh*2)
else:
return util.Rect(0, 0, self.width, self.height)
inner_rect = property(get_inner_rect)
def positionBar(self):
ir = self.inner_rect
h = ir.height - self.bar.height
self.bar.x = 0
self.bar.y = ir.y + int(self._value / float(self.range) * h)
@event.default('vslider')
def on_mouse_press(self, x, y, buttons, modifiers):
x, y = self.calculateRelativeCoords(x, y)
r = self.bar.rect
if y < r.y: self.stepToMinimum()
elif y > r.top: self.stepToMaximum()
return event.EVENT_HANDLED
@event.default('vslider')
def on_mouse_scroll(self, x, y, dx, dy):
if dy: self.stepToMaximum(dy)
return event.EVENT_HANDLED
@event.default('.-repeater-button-max')
def on_click(widget, *args):
widget.parent.stepToMaximum()
return event.EVENT_HANDLED
@event.default('.-repeater-button-min')
def on_click(widget, *args):
widget.parent.stepToMinimum()
return event.EVENT_HANDLED
class HorizontalSlider(SliderCommon):
'''
The value will be of the same type as the minimum value.
'''
name='hslider'
def __init__(self, parent, minimum, maximum, value, step=1,
bar_size=None, show_value=False, bar_text_color='white',
bar_color=(.3, .3, .3, 1), x=None, y=None, z=None, width='100%',
height=SliderCommon.slider_size, bgcolor='gray', **kw):
self.minimum = util.parse_value(minimum, 0)
self.type = type(self.minimum)
self.maximum = util.parse_value(maximum, 0)
self.range = self.maximum - self.minimum
self._value = util.parse_value(value, 0)
self.step = util.parse_value(step, 0)
self.show_value = show_value
self.bar_spec = bar_size
self.bar_color = util.parse_color(bar_color)
self.bar_text_color = util.parse_color(bar_text_color)
self.bar = self.lbut = self.rbut = None
# for step repeat when clicking in the bar
self.delay_timer = None
super(HorizontalSlider, self).__init__(parent, x, y, z, width, height,
bgcolor=bgcolor, **kw)
def handleSizing(self):
try:
# if the bar size spec is a straight integer, use it
min_size = int(self.bar_spec) + self.slider_size
except:
min_size = self.slider_size * 2
width = self.width
if width < min_size:
width = min_size
# assume buttons are same width
bw = ArrowButtonLeft.get_arrow().width
# only have buttons if there's enough room (two buttons plus
# scrolling room)
self.have_buttons = width > (bw * 2 + min_size)
if self.have_buttons and self.lbut is None:
self.lbut = ArrowButtonLeft(self, classes=('-repeater-button-min',),
color='black')
self.rbut = ArrowButtonRight(self, x=width-bw, color='black',
classes=('-repeater-button-max',))
elif not self.have_buttons and self.lbut is not None:
self.lbut.delete()
self.rbut.delete()
self.lbut = self.rbut = None
# slider bar size
#i_width = self.inner_rect.width
i_width = width
self.bar_size = util.parse_value(self.bar_spec, i_width)
if self.bar_size is None:
self.bar_size = int(max(self.slider_size, i_width / (self.range+1)))
s = self.show_value and str(self._value) or ' '
# we force blending here so we don't generate a bazillion textures
if self.bar is None:
self.bar = SliderBar(self, 'x', s, self.bar_size, self.height,
bgcolor=self.bar_color, color=self.bar_text_color)
else:
self.bar.text = s
self.bar.width = self.bar_size
self.width = width
# fix up sizing and positioning of elements
if self.lbut is not None:
self.lbut.resize()
self.rbut.resize()
self.bar.resize()
self.positionBar()
def get_inner_rect(self):
if self.have_buttons:
bw = ArrowButtonLeft.get_arrow().width
return util.Rect(bw, 0, self.width - bw*2, self.height)
else:
return util.Rect(0, 0, self.width, self.height)
inner_rect = property(get_inner_rect)
def positionBar(self):
ir = self.inner_rect
w = ir.width - self.bar.width
range = self.maximum - self.minimum
self.bar.x = ir.x + int(self._value / float(range) * w)
self.bar.y = 0
repeating = False
def startRepeat(self, direction):
self.delay_timer = None
self.repeat_time = 0
self.repeating = True
self.repeat_direction = direction
clock.schedule(self.repeat)
def repeat(self, dt):
self.repeat_time += dt
if self.repeat_time > .1:
self.repeat_time -= .1
self.repeat_direction()
def stopRepeat(self):
if self.delay_timer is not None:
self.delay_timer.cancel()
self.delay_timer = None
if self.repeating:
clock.unschedule(self.repeat)
self.repeating = False
@event.default('hslider')
def on_mouse_press(self, x, y, buttons, modifiers):
x, y = self.calculateRelativeCoords(x, y)
r = self.bar.rect
if x < r.x:
self.stepToMinimum()
self.delay_timer = anim.Delayed(self.startRepeat,
self.stepToMinimum, delay=.5)
elif x > r.right:
self.stepToMaximum()
self.delay_timer = anim.Delayed(self.startRepeat,
self.stepToMaximum, delay=.5)
return event.EVENT_HANDLED
@event.default('hslider')
def on_mouse_release(self, x, y, buttons, modifiers):
self.stopRepeat()
return event.EVENT_HANDLED
@event.default('hslider')
def on_mouse_scroll(self, x, y, dx, dy):
if dx: self.stepToMaximum(dx)
else: self.stepToMaximum(dy)
return event.EVENT_HANDLED
class SliderBar(Label):
name = 'slider-bar'
def __init__(self, parent, axis, initial, width, height, **kw):
self.axis = axis
rotate = 90 if axis == 'y' else 0
super(SliderBar, self).__init__(parent, str(initial), width=width,
height=height, halign='center', rotate=rotate, **kw)
@event.default('slider-bar')
def on_mouse_drag(widget, x, y, dx, dy, buttons, modifiers):
if not buttons & mouse.LEFT:
return event.EVENT_UNHANDLED
if widget.axis == 'x':
s = widget.getParent('hslider')
x = s.calculateRelativeCoords(x, y)[0]
w = s.inner_rect.width - widget.width
xoff = s.inner_rect.x
if x < xoff:
widget.x = xoff
elif x > (xoff + s.inner_rect.width):
widget.x = w + xoff
else:
widget.x = max(xoff, min(w + xoff, widget.x + dx))
value = (widget.x - xoff) / float(w)
else:
s = widget.getParent('vslider')
y = s.calculateRelativeCoords(x, y)[1]
h = s.inner_rect.height - widget.height
yoff = s.inner_rect.y
if y < yoff:
widget.y = yoff
elif y > (yoff + s.inner_rect.height):
widget.y = h + yoff
else:
widget.y = max(yoff, min(h + yoff, widget.y + dy))
value = (widget.y - yoff) / float(h)
s.set_value(value * s.range + s.minimum, position_bar=False, event=True)
return event.EVENT_HANDLED
class ArrowButton(RepeaterButton):
def __init__(self, parent, **kw):
super(ArrowButton, self).__init__(parent, image=self.arrow, **kw)
@classmethod
def get_arrow(cls):
if not hasattr(cls, 'image_object'):
cls.image_object = data.load_gui_image(cls.image_file)
return cls.image_object
def _get_arrow(self): return self.get_arrow()
arrow = property(_get_arrow)
class ArrowButtonUp(ArrowButton):
image_file = 'slider-arrow-up.png'
class ArrowButtonDown(ArrowButton):
image_file = 'slider-arrow-down.png'
class ArrowButtonLeft(ArrowButton):
image_file = 'slider-arrow-left.png'
class ArrowButtonRight(ArrowButton):
image_file = 'slider-arrow-right.png'
| Python |
'''Implement event handling for wydget GUIs.
The `GUIEventDispatcher` class is automatically mixed into the `wydget.GUI`
class and is activated by pushing the gui onto a window's event handlers
stack::
gui = GUI(window)
window.push_handlers(gui)
Events
------
Standard pyglet events are passed through if handled. The first argument is
always the "active" element (see below `determining the active element`_):
- `on_mouse_motion(element, x, y, dx, dy)`
- `on_mouse_press(element, x, y, button, modifiers)`
- `on_mouse_release(element, x, y, button, modifiers)`
- `on_mouse_drag(element, x, y, dx, dy, buttons, modifiers)`
- `on_mouse_scroll(element, x, y, dx, dy)`
- `on_key_press(element, symbol, modifiers)`
- `on_text(element, text)`
- `on_text_motion(element, motion)`
- `on_text_motion_select(element, motion)`
New events generated by wydget:
`on_change(element, value)`
The element's "value" changed (eg. text in a TextInput, selection
choice for a Selection)
`on_click(element, x, y, buttons, modifiers, click_count)`
The element was clicked. the click_count argument indicates how
many times the element has been clicked in rapid succession.
`on_element_enter(element, x, y)`
The mouse is over the element. Note that this event will be
automatically propogated to all parents of the element directly under
the mouse.
If an element implements the `on_element_enter` handler but does not
wish to receive an `on_element_leave` event when the mouse
departs it should return `EVENT_UNHANDLED`. Returning `EVENT_HANDLED`
implies that `on_element_leave` be generated once the mouse leaves the
element.
`on_element_leave(element, x, y)`
The mouse is no longer over the element.
`on_drag(element, x, y, dx, dy, buttons, modifiers)`
Press on listening element followed by mouse movement. If the handler
returns `EVENT_UNHANDLED` then the element is not considered to be being
dragged, and thus no further `on_drag_*` events will be generated, nor
an `on_drop`.
`on_drag_enter(element, x, y, dragged_element)`
The dragged_element is being dragged over the stationary element.
`on_drag_leave(element, x, y, dragged_element)`
The dragged_element is no longer being dragged over the
stationary element.
`on_drag_complete(element, x, y, buttons, modifiers, ok)`
Release after dragging listening element, ok is return code
from dropped-on element's `on_drop`.
`on_drop(element, x, y, button, modifiers, element)`
Element has been drag-n-dropped on listening element.
`on_gain_focus(element, source)`
Listening element gains focus from "source" ('tab', 'mouse' or 'code').
`on_lose_focus(element)`
Listening element loses focus.
`on_delete(element)`
The element is about to be deleted from the gui.
`on_eos(element)`
The movie or music element has reached the end of the stream it was
playing.
Determining the Active Element
------------------------------
The element passed into the event handlers above is usually the element
directly under the mouse. There are some situations where this is not
the case:
- it's not if ``element.is_transparent == True``
- it's not if ``element.isEnabled() == False``
- `on_text`, `on_text_motion` and `on_text_motion_select` are passed to the
*currently focused element* regardless of the mouse position
- if an `on_drag` or `on_mouse_drag` events are passed to the
`mouse_press_element` (ie. the one identified on an `on_mouse_press` event)
- `on_mouse_release` events are always passed to the `mouse_press_element`
regardless of where the mouse pointer happens to be
- `on_click` is only generated for the `mouse_press_element` if the
`on_mouse_release` event is received over that element
- `on_element_enter` and `on_element_leave` are generated for all elements up
the active element's branch of the element tree
- in all other cases, the event may be propogated (see `event propogation`_
below)
Event Propogation
-----------------
Events are automatically propogated up to element parents if an event
handler either does not exist or the handler returns `EVENT_UNHANDLED`.
Keyboard Focusing
-----------------
Focus events include the source of the focus event:
'tab' -- tab-key cycling through is_focusable elements
'mouse' -- mouse click on an element
'code' -- code called setFocus() to explicitly focus an element
Elements marked is_focusable=True will participate in tab-key focus
movement.
'''
import inspect
import time
from pyglet.event import (EventDispatcher, EVENT_UNHANDLED, EVENT_HANDLED,
EventException)
from pyglet.window import key
from layout.css import Rule, RuleSet, Selector, SimpleSelector
# partially snarfed from layout.gl.event
# Instead of each stack layer being a dictionary mapping event-name to
# event-function, each layer is a dictionary mapping event-name to
# RuleSet
class GUIEventDispatcher(EventDispatcher):
default_event_handlers = {}
def __init__(self):
EventDispatcher.__init__(self)
assert isinstance(self._event_stack, tuple)
self._event_stack = [self.default_event_handlers]
# list of elements that have responded to an on_element_enter event
self.entered_elements = []
@classmethod
def set_default_handler(cls, name, selector, handler):
'''Inspect handler for a selector and apply to the primary-set.
If the handler has no selector, it is assumed to have a universal
selector.
'''
if name not in cls.default_event_handlers:
cls.default_event_handlers[name] = RuleSet()
ruleset = cls.default_event_handlers[name]
ruleset.add_rule(Rule(selector, handler))
def select(self, rule, event_name=None):
# XXX assume passed an element with an id to select on
if not isinstance(rule, str):
rule = '#' + rule.id
def decorate(func):
func.selectors = [Selector.from_string(r.strip())
for r in rule.split(',')]
if event_name is not None:
func.event_name = event_name
self.push_handlers(func)
return func
return decorate
def set_handlers(self, *args, **kwargs):
'''Attach one or more event handlers to the top level of the handler
stack.
See `push_handlers` for the accepted argument types.
'''
# Create event stack if necessary
if type(self._event_stack) is tuple:
self._event_stack = [{}]
for object in args:
if inspect.isroutine(object):
# Single magically named function
name = getattr(object, 'event_name', object.__name__)
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
self.set_handler(name, object)
else:
# Single instance with magically named methods
for name, handler in inspect.getmembers(object):
name = getattr(handler, 'event_name', name)
if name in self.event_types:
self.set_handler(name, handler)
for name, handler in kwargs.items():
# Function for handling given event (no magic)
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
self.set_handler(name, handler)
def set_handler(self, name, handler):
'''Inspect handler for a selector and apply to the primary-set.
If the handler has no selector, it is assumed to have a universal
selector.
'''
if name not in self._event_stack[0]:
self._event_stack[0][name] = RuleSet()
ruleset = self._event_stack[0][name]
#if not hasattr(handler, 'selector'):
#handler.selector = universal_selector
for selector in handler.selectors:
ruleset.add_rule(Rule(selector, handler))
def dispatch_event(self, element, event_type, *args, **kw):
'''Pass the event to the element.
If propogate is True (the default) then events will propogate up
to the element's parent.
Since the event may be handled by a parent of the element passed
in, we pass back the element that handled the event.
'''
propogate=kw.get('propogate', True)
for frame in self._event_stack:
ruleset = frame.get(event_type, None)
if not ruleset: continue
rules = ruleset.get_matching_rules(element)
for rule in rules:
handler = rule.declaration_set
try:
ret = handler(element, *args)
except TypeError, message:
print 'ERROR CALLING %r (%r, *%r)]'%(handler,
element, args)
raise
if ret != EVENT_UNHANDLED:
return element, EVENT_HANDLED
# not handled, so pass the event up to parent element
if propogate and element.parent is not None:
return self.dispatch_event(element.parent, event_type, *args, **kw)
return (None, EVENT_UNHANDLED)
# EVENT HANDLER BEHAVIOR
mouse_press_element = None
drag_element = None
mouse_drag_element = None
drag_over_element = None
cumulative_drag = (0, 0)
focused_element = None
def setModal(self, element):
'''The element will capture all input.
setModal(None) to clear.
'''
if element is None:
for child in self.children:
child.is_enabled = True
child.is_modal = False
else:
found = False
for child in self.children:
if child is not element:
child.is_enabled = False
else:
found = True
child.is_modal = True
assert found, '%r not found in gui children'%(element,)
def setFocus(self, element, source):
'''The "source" has set the focus of keyboard input to "element".
"source" is either 'tab' (key), 'mouse' or 'code'.
All future `on_text`, `on_text_motion` and `on_text_motion_select`
events will be passed to the element.
'''
# gain focus first so some elements are able to detect whether their
# child has been focused
if element is not None and self.focused_element is not element:
element = self.dispatch_event(element, 'on_gain_focus', source)[0]
# if nothing wanted the event, don't switch focus
if element is None:
return
# if we switched focus to a different element, then tell the old
# element it lost focus
if (self.focused_element is not None and
self.focused_element is not element):
self.dispatch_event(self.focused_element, 'on_lose_focus')
self.focused_element = element
def focusNextElement(self, direction=1):
'''Move the focus on to the next element.
'''
if not self._focus_order: return
# determine the index of the next element to possibly focus on
N = len(self._focus_order)
if self.focused_element is None:
if direction == 1: i = 0
else: i = N-1
else:
try:
i = self._focus_order.index(self.focused_element.id) + direction
except ValueError:
# element not in the focus order list
i = 0
if i < 0: i = N-1
if i >= N: i = 0
# now start at that index and work through the focusable elements
# until we find a visible & enabled one to focus on
j = i
while True:
element = self._by_id[self._focus_order[i]]
if element.isEnabled() and element.isVisible():
self.setFocus(element, source='tab')
return
i += direction
if i < 0: i = N-1
if i >= N: i = 0
if i == j: return # no focusable element found
# NOW THE EVENT HANDLERS
def on_resize(self, w, h):
self.width = self.inner_width = w
self.height = self.inner_height = h
self.layout()
# let the window do its resize handling too
return EVENT_UNHANDLED
def generateEnterLeave(self, x, y, element):
# XXX this would possibly be simpler if we could ask whether
# elements handled the on_element_enter event
# see which elements (starting with the one under the mouse and
# moving up the parentage) care about an on_element_enter event
enter = []
over = []
e = element
while e:
if not e.isEnabled():
e = e.parent
continue
if e in self.entered_elements:
# remain over
over.append(e)
else:
enter.append(e)
e = e.parent
# right, now "leave" any elements that aren't in "enter" any more
# (only if they still exist)
all = enter + over
for e in self.entered_elements:
if e not in all and self.has('#'+e.id):
self.dispatch_event(e, 'on_element_leave', x, y,
propogate=False)
# and now generate enter events
for e in enter:
if self.dispatch_event(e, 'on_element_enter', x, y,
propogate=False)[1]:
over.append(e)
#if mouse stable (not moving)? and 1 second has passed
# element.on_element_hover(x, y)
# remember the elements we're over for later _leave events
self.entered_elements = over
def on_mouse_motion(self, x, y, dx, dy):
'''Determine what element(s) the mouse is positioned over and
generate on_element_enter and on_element_leave events. Additionally
generate a new on_mouse_motion event for the element under the
mouse.
'''
element = self.determineHit(x, y)
if self.debug_display is not None:
self.debug_display.text = '%r classes=%r'%(element,
element and element.classes)
self.generateEnterLeave(x, y, element)
if element is not None and element.isEnabled():
return self.dispatch_event(element, 'on_mouse_motion', x, y,
dx, dy)[1]
return EVENT_UNHANDLED
def on_mouse_enter(self, x, y):
'''Translate this into an on_mouse_motion event.
'''
return self.on_mouse_motion(x, y, 0, 0)
def on_mouse_leave(self, x, y):
'''Translate this into an on_element_leave for all
on_element_enter'ed elements.
'''
# leave all entered elements
for e in self.entered_elements:
self.dispatch_event(e, 'on_element_leave', x, y, propogate=False)
self.entered_elements = []
return EVENT_HANDLED
def on_mouse_press(self, x, y, button, modifiers):
'''Pass this event on to the element underneath the mouse.
Additionally, switch keyboard focus to this element through
`self.setFocus(element, source='mouse')`
The element will be registered as potentially interesting for
generating future `on_mouse_release`, `on_click` and `on_drag`
events.
'''
element = self.determineHit(x, y)
# set these now before so we can still generate drag events
# the mouse_press_element may be disabled since it may belong to a
# parent element which is not and should be draggable
self.mouse_press_element = element
self.mouse_drag_element = None
self.drag_element = None
self.cumulative_drag = (0, 0)
# don't do any further processing if there's no element or it's
# disabled
if element is None: return EVENT_UNHANDLED
if not element.isEnabled(): return EVENT_UNHANDLED
# switch focus
self.setFocus(element, source='mouse')
return self.dispatch_event(element, 'on_mouse_press', x, y, button,
modifiers)[1]
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
'''Translate this event into a number of events:
First up, generate enter/leave events (replicating the behaviour of
`on_mouse_move`).
If already dragging (self.drag_element or self.mouse_drag_element
are set) then continue that behaviour.
If the mouse button was pressed while over an element we attempt to
pass an `on_mouse_drag` event to that element. If that event is
handled and the handler returns EVENT_HANDLED then we set
self.mouse_drag_element and the handler returns.
We then check a drag threshold to determine whether an on_drag
should be generated. If the mouse has moved far enough (currently
4 pixels) then we attempt to pass an `on_drag` event to the
element under the pointer. If that event is handled and the
handler returns EVENT_HANDLED we set self.drag_element and them
attempt to pass on_drag_enter and on_drag_leave events on the
element *under* the element being dragged.
'''
element = self.determineHit(x, y)
self.generateEnterLeave(x, y, element)
if self.drag_element is not None:
# continue to feed on_drag events
element, handled = self.dispatch_event(self.drag_element,
'on_drag', x, y, dx, dy, buttons, modifiers)
self.drag_element = element
# tell the element we've dragged over
over = self.determineHit(x, y, exclude=element)
if (over is not self.drag_over_element and
self.drag_over_element is not None):
self.dispatch_event(self.drag_over_element, 'on_drag_leave',
x, y, element)
if over is not None and over.isEnabled():
self.dispatch_event(over, 'on_drag_enter', x, y, element)
self.drag_over_element = over
return handled
elif self.mouse_drag_element is not None:
# continue to feed on_mouse_drag events
element, handled = self.dispatch_event(self.mouse_drag_element,
'on_mouse_drag', x, y, dx, dy, buttons, modifiers)
self.mouse_drag_element = element
return handled
# we didn't actually click on an element
if self.mouse_press_element is None:
return EVENT_UNHANDLED
# try an on_mouse_drag event if the element is enabled
if self.mouse_press_element.isEnabled():
element, handled = self.dispatch_event(self.mouse_press_element,
'on_mouse_drag', x, y, dx, dy, buttons, modifiers)
if handled == EVENT_HANDLED:
self.mouse_drag_element = element
return EVENT_HANDLED
# check drag threshold
cdx, cdy = self.cumulative_drag
cdx += abs(dx); cdy += abs(dy)
self.cumulative_drag = (cdx, cdy)
if cdx + cdy < 4:
# less than 4 pixels, don't drag just yet
return EVENT_UNHANDLED
# if the mouse_press_element is disabled we need to find the first
# enabled parent to try to pass the event to
element = self.mouse_press_element
if not element.isEnabled():
while not element.isEnabled():
element = element.parent
if element is None:
return EVENT_UNHANDLED
# now try an on_drag event
element, handled = self.dispatch_event(element, 'on_drag',
x, y, dx, dy, buttons, modifiers)
if handled == EVENT_UNHANDLED:
return EVENT_UNHANDLED
# the event may have been handled by a parent
self.drag_element = element
# tell the element we've dragged the active element over
element = self.determineHit(x, y, exclude=element)
if element is not self.drag_over_element:
if self.drag_over_element is not None:
self.dispatch_event(self.drag_over_element,
'on_drag_leave', x, y, self.drag_element)
if element is not None and element.isEnabled():
self.dispatch_event(element, 'on_drag_enter', x, y,
self.drag_element)
self.drag_over_element = element
return EVENT_HANDLED
_last_click = 0
def on_mouse_release(self, x, y, button, modifiers):
# send release to the previously-pressed element
if self.mouse_press_element is not None:
if self.mouse_press_element.isEnabled():
self.dispatch_event(self.mouse_press_element,
'on_mouse_release', x, y, button, modifiers)
if self.drag_element is not None:
# the on_drop check will most likely alter the active element
drop = self.determineHit(x, y, exclude=self.drag_element)
# see if the element underneath wants the dragged element
if drop is not None and drop.isEnabled():
ok = self.dispatch_event(drop, 'on_drop', x, y, button,
modifiers, self.drag_element)[1] == EVENT_HANDLED
else:
ok = False
# now tell the dragged element what's going on
handled = self.dispatch_event(self.drag_element,
'on_drag_complete', x, y, button, modifiers, ok)[1]
# clear state - we're done
self.drag_element = self.mouse_press_element = \
self.drag_over_element = None
return handled
# regular mouse press/release click
element = self.determineHit(x, y)
if element is None: return EVENT_UNHANDLED
if not element.isEnabled():
return EVENT_UNHANDLED
# determine multiple clicks
now = time.time()
if now - self._last_click < .25:
self._click_count += 1
else:
self._click_count = 1
self._last_click = now
if element is self.mouse_press_element:
return self.dispatch_event(element, 'on_click', x, y, button,
modifiers, self._click_count)[1]
return EVENT_UNHANDLED
def on_mouse_scroll(self, x, y, dx, dy):
element = self.determineHit(x, y)
if element is None: return EVENT_UNHANDLED
return self.dispatch_event(element, 'on_mouse_scroll', x, y,
dx, dy)[1]
# the following are special -- they will be sent to the currently-focused
# element rather than being dispatched
def on_key_press(self, symbol, modifiers):
handled = EVENT_UNHANDLED
if self.focused_element is not None:
handled = self.dispatch_event(self.focused_element,
'on_key_press', symbol, modifiers)[1]
if handled == EVENT_UNHANDLED and symbol == key.TAB:
if modifiers & key.MOD_SHIFT:
self.focusNextElement(-1)
else:
self.focusNextElement()
return handled
def on_text(self, text):
if self.focused_element is None: return
return self.dispatch_event(self.focused_element, 'on_text', text)[1]
def on_text_motion(self, motion):
if self.focused_element is None: return
return self.dispatch_event(self.focused_element, 'on_text_motion',
motion)[1]
def on_text_motion_select(self, motion):
if self.focused_element is None: return
return self.dispatch_event(self.focused_element,
'on_text_motion_select', motion)[1]
# EVENTS IN and OUT
GUIEventDispatcher.register_event_type('on_mouse_motion')
GUIEventDispatcher.register_event_type('on_mouse_press')
GUIEventDispatcher.register_event_type('on_mouse_release')
GUIEventDispatcher.register_event_type('on_mouse_enter')
GUIEventDispatcher.register_event_type('on_mouse_leave')
GUIEventDispatcher.register_event_type('on_mouse_drag')
GUIEventDispatcher.register_event_type('on_mouse_scroll')
GUIEventDispatcher.register_event_type('on_key_press')
GUIEventDispatcher.register_event_type('on_text')
GUIEventDispatcher.register_event_type('on_text_motion')
GUIEventDispatcher.register_event_type('on_text_motion_select')
# EVENTS OUT
GUIEventDispatcher.register_event_type('on_change')
GUIEventDispatcher.register_event_type('on_click')
GUIEventDispatcher.register_event_type('on_drag')
GUIEventDispatcher.register_event_type('on_drag_enter')
GUIEventDispatcher.register_event_type('on_drag_leave')
GUIEventDispatcher.register_event_type('on_drag_complete')
GUIEventDispatcher.register_event_type('on_drop')
GUIEventDispatcher.register_event_type('on_element_enter')
GUIEventDispatcher.register_event_type('on_element_leave')
GUIEventDispatcher.register_event_type('on_gain_focus')
GUIEventDispatcher.register_event_type('on_lose_focus')
GUIEventDispatcher.register_event_type('on_delete')
GUIEventDispatcher.register_event_type('on_eos')
def select(rule, event_name=None):
# XXX assume passed an element with an id to select on
if not isinstance(rule, str):
rule = '#' + rule.id
def decorate(func):
func.selectors = [Selector.from_string(r.strip())
for r in rule.split(',')]
if event_name is not None:
func.event_name = event_name
return func
return decorate
def default(rule, event_name=None):
def decorate(func):
name = event_name or func.__name__
if name not in GUIEventDispatcher.event_types:
raise EventException('Unknown event "%s"' % name)
for r in rule.split(','):
selector = Selector.from_string(r.strip())
GUIEventDispatcher.set_default_handler(name, selector, func)
return func
return decorate
universal_selector = Selector(SimpleSelector(None, None, (), (), ()), ())
| Python |
from xml.etree import ElementTree
class XMLLoadError(Exception):
pass
xml_registry = {}
def fromFile(parent, file):
'''Load a gui frame and any child elements from the XML file.
The elements will be added as children on "parent" which may be any
other widget or a GUI instance.
'''
try:
element = ElementTree.parse(file).getroot()
except Exception, error:
raise XMLLoadError, '%s (%r)'%(error, file)
assert element.tag == 'frame', 'XML root tag must be <frame>'
return getConstructor(element.tag)(element, parent)
def fromString(parent, string):
'''Load a gui frame and any child elements from the XML string.
The elements will be added as children on "parent" which may be any
other widget or a GUI instance.
'''
try:
element = ElementTree.fromstring(string)
except Exception, error:
raise XMLLoadError, '%s (%r)'%(error, string)
assert element.tag == 'frame', 'XML root tag must be <frame>'
return getConstructor(element.tag)(element, parent)
def getConstructor(name):
'''Wrap the constructor retrieval to present a nicer error message.
'''
try:
return xml_registry[name].fromXML
except KeyError:
raise KeyError, 'No constructor for XML element %r'%name
def parseAttributes(element):
'''Convert various XML element attribute strings into Python values.
'''
kw = {}
for key, value in element.items():
if key == 'class':
value = tuple(value.split(' '))
key = 'classes'
elif key in ('is_exclusive', 'scrollable', 'is_visible', 'is_blended',
'is_enabled', 'is_vertical', 'show_value', 'expand'):
value = { 'true': True, 'false': False, }[value.lower()]
kw[key] = value
return kw
| Python |
import os
from pyglet import image
_data = {}
filename = os.path.join
dirname = os.path.dirname(__file__)
def load_gui_image(filename):
if not os.path.isabs(filename):
filename = os.path.join(dirname, 'data', filename)
return load_image(filename)
def load_image(*filename):
filename = os.path.join(*filename)
if filename not in _data:
_data[filename] = image.load(filename)
return _data[filename]
| Python |
'''wydget is a graphical user interface (GUI) toolkit for pyglet.
This module allows applications to create a user interface comprised of
widgets and attach event handling to those widgets.
GUIs are managed by the top-level GUI class::
from pyglet.window import Window
from wydget import GUI
window = Window(100, 100)
gui = GUI(window)
window.push_handlers(gui)
You may then add components to the GUI by importing them from the
`wydget.widgets` package::
from wydget.widgets import TextButton
b = TextButton(gui, 'Press me!')
To handle click events on the button, create a handler::
@gui.select(b)
def on_click(button, *args):
print 'I was pressed!'
Finally, use a standard pyglet event loop to have the GUI run, and invoke
``gui.draw()`` to render the GUI. The GUI will render to an area the
dimensions of the window and at z = 0::
while not window.has_exit:
window.dispatch_events()
window.clear()
gui.draw()
window.flip()
'''
import sys
import collections
from xml.etree import ElementTree
from pyglet.gl import *
from pyglet import media
import style
import event
import loadxml
import widgets
import util
class GUI(event.GUIEventDispatcher):
'''GUI oganisation and event handling.
'''
id = '-gui'
name = 'gui'
classes = ()
parent = None
def __init__(self, window, x=0, y=0, z=0, width=None, height=None):
super(GUI, self).__init__()
self.window = window
self.style = style.Style()
# element.Element stuff
self.x, self.y, self.z = x, y, z
self.width = self.inner_width = width or window.width
self.height = self.inner_height = height or window.height
self.children = []
# map Element id, class and name to Element
self._by_id = {}
self._by_class = collections.defaultdict(set)
self._by_name = collections.defaultdict(set)
# list Element.ids in the order they're registered for tabbing
self._focus_order = []
self.debug_display = None
self.debug = '--debug' in sys.argv
if self.debug:
self.debug_display = widgets.Label(self, 'dummy',
bgcolor="white", padding=1, width=self.width)
def __repr__(self):
return '<%s at (%s, %s, %s) (%sx%s)>'%(self.__class__.__name__,
self.x, self.y, self.z, self.width, self.height)
def dump(self, s=''):
print s + str(self)
for child in self.children: child.dump(s+' ')
# clipboard support
clipboard_element = None
def setSelection(self, element):
'''The element has some data that may interact with the clipboard.
'''
if self.clipboard_element not in (element, None):
self.clipboard_element.clearSelection()
self.clipboard_element = element
def clearSelection(self, element):
'''The element doesn't want to interact with the clipboard any
longer.
'''
# might already have been bumped for another
if self.clipboard_element is element:
self.clipoard_element = None
# Registration of elements
# XXX I suspect that this is duplicating functionality in layout
def register(self, element):
'''Register the element with the gui.
IDs must be unique.
'''
if element.id in self._by_id:
raise KeyError, 'ID %r already exists as %r (trying to add %r)'%(
element.id, self._by_id[element.id], element)
self._by_id[element.id] = element
self._by_name[element.name].add(element.id)
for klass in element.classes:
self._by_class[klass].add(element.id)
if element.is_focusable:
self._focus_order.append(element.id)
self.setDirty()
self._layout_needed = True
def unregister(self, element):
del self._by_id[element.id]
self._by_name[element.name].remove(element.id)
for klass in element.classes:
self._by_class[klass].remove(element.id)
if self.focused_element is element:
self.focused_element = None
if element.is_focusable:
self._focus_order.remove(element.id)
self.setDirty()
self._layout_needed = True
def has(self, spec):
if spec[0] == '#':
return spec[1:] in self._by_id
elif spec[0] == '.':
return spec[1:] in self._by_class
else:
return spec in self._by_name
def get(self, spec):
if spec[0] == '#':
return self._by_id[spec[1:]]
elif spec[0] == '.':
return (self._by_id[id] for id in self._by_class[spec[1:]])
else:
return (self._by_id[id] for id in self._by_name[spec])
# rendering / hit detection
_rects = None
def setDirty(self):
'''Indicate that one or more of the gui's children have changed
geometry and a new set of child rects is needed.
'''
self._rects = None
_layout_needed = True
def layout(self):
'''Layout the entire GUI in response to its dimensions changing or
the contents changing (in a way that would alter internal layout).
'''
#print '>'*75
#self.dump()
# resize all elements
while True:
for element in self.children:
element.resetGeometry()
ok = False
try:
while not ok:
ok = True
for element in self.children:
ok = ok and element.resize()
except util.RestartLayout:
pass
else:
break
# position top-level elements
for c in self.children:
if c.x is None or c.x_spec.percentage:
c.x = c.x_spec.calculate()
if c.y is None or c.y_spec.percentage:
c.y = c.y_spec.calculate()
self._rects = None
self._layout_needed = False
#print '-'*75
#self.dump()
#print '<'*75
def layoutNeeded(self):
self._layout_needed = True
def getRects(self, exclude=None):
'''Get the rects for all the children to draw & interact with.
Prune the tree at "exclude" if provided.
'''
if self._layout_needed:
try:
self.layout()
except:
print '*'*75
self.dump()
print '*'*75
raise
if self._rects is not None and exclude is None:
return self._rects
# now get their rects
rects = []
clip = self.rect
for element in self.children:
if element is exclude: continue
rects.extend(element.getRects(clip, exclude))
rects.sort(lambda a,b: cmp(a[1][2], b[1][2]))
if exclude is None:
self._rects = rects
return rects
def determineHit(self, x, y, exclude=None):
'''Determine which element is at the absolute (x, y) position.
"exclude" allows us to ignore a single element (eg. an element
under the cursor being dragged - we wish to know which element is
under *that)
'''
for o, (ox, oy, oz, clip) in reversed(self.getRects(exclude)):
ox += clip.x
oy += clip.y
if x < ox or y < oy: continue
if x > ox + clip.width: continue
if y > oy + clip.height: continue
return o
return None
def draw(self):
'''Render all the elements on display.'''
glPushAttrib(GL_ENABLE_BIT)
glDisable(GL_DEPTH_TEST)
# get the rects and sort by Z (yay for stable sort!)
rects = self.getRects()
# draw
oz = 0
for element, (x, y, z, c) in rects:
if element is self.debug_display:
continue
element.draw(x, y, z, c)
if self.debug:
# render the debugging displays
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
for o, (x, y, z, c) in rects:
w, h = c.width, c.height
x += c.x
y += c.y
glColor4f(1, 0, 0, .1)
glRectf(x, y, x+w, y+h)
glColor4f(1, 1, 1, .1)
glBegin(GL_LINE_LOOP)
glVertex2f(x, y)
glVertex2f(x+w, y)
glVertex2f(x+w, y+h)
glVertex2f(x, y+h)
glEnd()
if o.view_clip:
v = o.view_clip
glColor4f(0, 0, 1, .1)
glRectf(x+v.x, y+v.y, x+v.x+v.width, y+v.y+v.height)
glDisable(GL_BLEND)
self.debug_display.draw(0, 0, 0, util.Rect(0, 0,
self.width, self.debug_display.height))
glPopAttrib()
# Element API (mostly terminators)
def getStyle(self): return self.style
def getGUI(self): return self
def isEnabled(self): return True
def isVisible(self): return True
def getParent(self, selector):
if isinstance(selector, str):
selector = [s.strip() for s in selector.split(',')]
if self.name in selector: return self
return None
def calculateAbsoluteCoords(self, x, y):
return (x + self.x, y + self.y)
def calculateRelativeCoords(self, x, y):
return (x - self.x, y - self.y)
def layoutDimensionsChanged(self, layout):
pass
padding = 0
def get_rect(self):
return util.Rect(0, 0, self.width, self.height)
rect = property(get_rect)
inner_rect = property(get_rect)
def addChild(self, child):
self.children.append(child)
self.register(child)
def delete(self):
for child in self.children: child.delete()
self.children = []
| Python |
'''Clipboard implementation for X11 using xlib.
'''
from ctypes import *
from pyglet import window
from pyglet.window.xlib import xlib
XA_PRIMARY = xlib.Atom(1)
XA_STRING = xlib.Atom(31)
CurrentTime = 0
AnyPropertyType = 0
class XlibClipboard(object):
def get_text(self):
display = window.get_platform().get_default_display()._display
owner = xlib.XGetSelectionOwner(display, XA_PRIMARY)
if not owner: return ''
# XXX xa_utf8_string
xlib.XConvertSelection(display, XA_PRIMARY, XA_STRING, 0, owner,
CurrentTime)
xlib.XFlush(display)
# determine what's in the selection buffer
type = xlib.Atom()
format = c_int()
len = c_ulong()
bytes_left = c_ulong()
data = POINTER(c_ubyte)()
xlib.XGetWindowProperty(display, owner, XA_STRING, 0, 0, 0,
AnyPropertyType, byref(type), byref(format), byref(len),
byref(bytes_left), byref(data))
length = int(bytes_left.value)
if not length:
return ''
# get the contents
dummy = c_ulong()
xlib.XGetWindowProperty(display, owner, XA_STRING, 0,
length, 0, AnyPropertyType, byref(type), byref(format),
byref(len), byref(dummy), byref(data))
s = ''.join(chr(c) for c in data[:len.value])
xlib.XFree(data)
return s
def set_text(self, text):
pass
if __name__ == '__main__':
cb = XlibClipboard()
print 'GOT', `cb.get_text()` # display last text clipped
s = "[Clipboard text replaced]"
cb.set_text(s)
assert s == cb.get_text() # replace it
| Python |
'''Clipboard implementation for OS X using Win32
Based on implementation from:
http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1771866
'''
from ctypes import *
from pyglet.window.win32.constants import CF_TEXT, GHND
OpenClipboard = windll.user32.OpenClipboard
EmptyClipboard = windll.user32.EmptyClipboard
GetClipboardData = windll.user32.GetClipboardData
SetClipboardData = windll.user32.SetClipboardData
IsClipboardFormatAvailable = windll.user32.IsClipboardFormatAvailable
CloseClipboard = windll.user32.CloseClipboard
GlobalLock = windll.kernel32.GlobalLock
GlobalAlloc = windll.kernel32.GlobalAlloc
GlobalUnlock = windll.kernel32.GlobalUnlock
memcpy = cdll.msvcrt.memcpy
class Win32Clipboard(object):
def get_text(self):
# XXX Doesn't handle CF_UNICODETEXT yet.
if not IsClipboardFormatAvailable(CF_TEXT):
return ''
if not OpenClipboard(c_int(0)):
return ''
try:
hClipMem = GetClipboardData(c_int(CF_TEXT))
GlobalLock.restype = c_char_p
text = GlobalLock(c_int(hClipMem))
GlobalUnlock(c_int(hClipMem))
finally:
CloseClipboard()
return text.decode('windows-1252')
def put_text(self, text):
# XXX Doesn't handle CF_UNICODETEXT yet.
buffer = c_buffer(text)
bufferSize = sizeof(buffer)
hGlobalMem = GlobalAlloc(c_int(GHND), c_int(bufferSize))
GlobalLock.restype = c_void_p
lpGlobalMem = GlobalLock(c_int(hGlobalMem))
memcpy(lpGlobalMem, addressof(buffer), c_int(bufferSize))
GlobalUnlock(c_int(hGlobalMem))
if OpenClipboard(0):
EmptyClipboard()
SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))
CloseClipboard()
if __name__ == '__main__':
cb = Win32Clipboard()
print 'GOT', `cb.get_text()` # display last text clipped
cb.set_text("[Clipboard text replaced]") # replace it
print 'GOT', `cb.get_text()` # display new clipboard
| Python |
'''Clipboard implementation for OS X using Carbon
Based on information from:
http://developer.apple.com/carbon/pasteboards.html
'''
import sys
from ctypes import *
import pyglet.lib
from pyglet.window.carbon import _create_cfstring, carbon, _oscheck
from pyglet.window.carbon.constants import *
from pyglet.window.carbon.types import *
carbon = pyglet.lib.load_library(
framework='/System/Library/Frameworks/Carbon.framework')
PasteboardRef = c_void_p
PasteboardItemID = c_void_p
CFArrayRef = c_void_p
CFDataRef = c_void_p
ItemCount = c_int32
kPasteboardClipboard = _create_cfstring("com.apple.pasteboard.clipboard")
kPasteboardModified = 1 << 0
kPasteboardClientIsOwner = 1 << 1
utf16_plain_text = _create_cfstring("public.utf16-plain-text")
traditional_mac_plain_text = _create_cfstring("com.apple.traditional-mac-plain-text")
carbon.CFDataGetBytePtr.restype = POINTER(c_char)
class CarbonPasteboard(object):
def __init__(self):
self.pasteboard = PasteboardRef()
carbon.PasteboardCreate(kPasteboardClipboard, byref(self.pasteboard))
def get_text(self):
# get pasteboard item count
item_count = ItemCount()
_oscheck(carbon.PasteboardGetItemCount(self.pasteboard,
byref(item_count)))
item_id = PasteboardItemID()
flavor_type_array = CFArrayRef()
flavor_data = CFDataRef()
for item_index in range(1, item_count.value + 1):
# get pasteboard item
_oscheck(carbon.PasteboardGetItemIdentifier(self.pasteboard,
item_index, byref(item_id)))
# get pasteboard item flavor type array
_oscheck(carbon.PasteboardCopyItemFlavors(self.pasteboard, item_id,
byref(flavor_type_array)))
flavor_count = carbon.CFArrayGetCount(flavor_type_array)
try:
# Look for UTF-16 value first
for flavor_index in range(flavor_count):
flavor_type = carbon.CFArrayGetValueAtIndex(
flavor_type_array, flavor_index)
if carbon.UTTypeConformsTo(flavor_type, utf16_plain_text):
# get flavor data
_oscheck(carbon.PasteboardCopyItemFlavorData(
self.pasteboard, item_id, flavor_type,
byref(flavor_data)))
try:
data = carbon.CFDataGetBytePtr(flavor_data)
length = carbon.CFDataGetLength(flavor_data)
s = str(data[:length])
if sys.byteorder == 'big':
return s.decode('utf_16_be')
else:
return s.decode('utf_16_le') # explicit endian avoids BOM
finally:
carbon.CFRelease (flavor_data)
# Look for TEXT value if no UTF-16 value
for flavor_index in range(flavor_count):
flavor_type = carbon.CFArrayGetValueAtIndex(
flavor_type_array, flavor_index)
if carbon.UTTypeConformsTo(flavor_type,
traditional_mac_plain_text):
# get flavor data
_oscheck(carbon.PasteboardCopyItemFlavorData(
self.pasteboard, item_id, flavor_type,
byref(flavor_data)))
try:
data = carbon.CFDataGetBytePtr(flavor_data)
length = carbon.CFDataGetLength(flavor_data)
return str(data[:length])
finally:
carbon.CFRelease (flavor_data)
finally:
carbon.CFRelease(flavor_type_array)
return None
def put_text(self, text):
if not text: return
# clear pasteboard
_oscheck(carbon.PasteboardClear(self.pasteboard))
sync_flags = carbon.PasteboardSynchronize(self.pasteboard)
if sync_flags & kPasteboardModified:
raise ValueError, "Pasteboard not synchronized after clear"
if not sync_flags & kPasteboardClientIsOwner:
raise ValueError, "Pasteboard not owned after clear"
if sys.byteorder == 'big':
utf16_data = text.encode('utf_16_be')
else:
utf16_data = text.encode('utf_16_le') # explicit endian avoids BOM
data_ref = carbon.CFDataCreate(None, utf16_data, len(utf16_data))
if not data_ref:
raise ValueError, "Can't create unicode data for pasteboard"
# put unicode to pasteboard
try:
_oscheck(carbon.PasteboardPutItemFlavor(self.pasteboard,
1, utf16_plain_text, data_ref, 0))
finally:
carbon.CFRelease(data_ref)
ascii_data = text.encode('ascii', 'replace')
data_ref = carbon.CFDataCreate(None, ascii_data, len(ascii_data))
if not data_ref:
raise ValueError, "Can't create text data for pasteboard"
# put text to pasteboard
try:
_oscheck(carbon.PasteboardPutItemFlavor(self.pasteboard,
1, traditional_mac_plain_text, data_ref, 0))
finally:
carbon.CFRelease(data_ref)
if __name__ == '__main__':
clipboard = CarbonPasteboard()
print `clipboard.get_text()`
if len(sys.argv) > 1:
clipboard.put_text(''.join(sys.argv[1:]).decode('utf8'))
| Python |
'''Interaction with the Operating System text clipboard
'''
import sys
def get_text():
'''Get a string from the clipboard.
'''
return _clipboard.get_text()
def put_text(text):
'''Put the string onto the clipboard.
'''
return _clipboard.put_text(text)
# Try to determine which platform to use.
if sys.platform == 'darwin':
from wydget.clipboard.carbon import CarbonPasteboard
_clipboard = CarbonPasteboard()
elif sys.platform in ('win32', 'cygwin'):
from wydget.clipboard.win32 import Win32Clipboard
_clipboard = Win32Clipboard()
else:
from wydget.clipboard.xlib import XlibClipboard
_clipboard = XlibClipboard()
| Python |
from wydget import widgets, event
class Dialog(widgets.Frame):
def __init__(self, parent, x=0, y=0, z=0, width=None, height=None,
classes=(), border='black', bgcolor='white', padding=2, **kw):
if 'dialog' not in classes:
classes = ('dialog', ) + classes
super(Dialog, self).__init__(parent, x, y, z, width, height,
padding=padding, border=border, classes=classes,
bgcolor=bgcolor, **kw)
def resize(self):
if not super(Dialog, self).resize():
return False
# position dialog to center of parent
new_x = self.parent.width//2 - self.width//2
if new_x != self._x: self.x = new_x
new_y = self.parent.height//2 - self.height//2
if new_y != self._y: self.y = new_y
return True
def run(self):
'''Invoke to position the dialog in the middle of the parent
(presumably the window) and make the dialog become modal.
'''
self.setModal()
@event.default('.dialog > .title')
def on_drag(widget, x, y, dx, dy, buttons, modifiers):
dialog = widget.parent
dialog.x += dx; dialog.y += dy
return event.EVENT_HANDLED
| Python |
import os, sys
from wydget import event, widgets, layouts
from wydget.dialogs import base
if sys.platform == 'darwin':
default_dir = os.path.expanduser('~/Desktop')
elif sys.platform in ('win32', 'cygwin'):
default_dir = 'c:/'
else:
default_dir = os.path.expanduser('~/Desktop')
class FileOpen(base.Dialog):
id = '-file-dialog'
name = 'file-dialog'
classes = ('dialog', )
def __init__(self, parent, path=default_dir, callback=None, **kw):
kw['border'] = 'black'
kw['bgcolor'] = 'white'
kw['padding'] = 2
kw['width'] = 300
super(FileOpen, self).__init__(parent, **kw)
self.callback = callback
self.layout = layouts.Vertical(self, halign='left', padding=2)
label = widgets.Label(self, 'Select File to Open',
classes=('title',), bgcolor="aaa", padding=2, width="100%",
halign="center")
self.path = widgets.TextInput(self, width="100%",
classes=('-file-open-path',))
self.listing = widgets.Selection(self, scrollable=True,
width="100%", is_exclusive=True, size=20,
classes=('-file-open-dialog',))
self.openPath(os.path.abspath(path))
f = widgets.Frame(self, width=296, is_transparent=True)
ok = widgets.TextButton(f, text='Ok', border="black",
classes=('-file-open-dialog-ok', ))
cancel = widgets.TextButton(f, text='Cancel', border="black",
classes=('-file-open-dialog-cancel', ))
f.layout = layouts.Horizontal(f, padding=10, halign='right')
self.selected_file = None
self.selected_widget = None
def addOption(self, label):
FileOption(self.listing.contents, text=label)
def openPath(self, path):
self.current_path = path
self.listing.clearOptions()
self.path.text = path
self.path.cursor_position = -1
if path != '/':
self.addOption('..')
for entry in os.listdir(path):
# XXX real filtering please
if entry.startswith('.'): continue
if os.path.isdir(os.path.join(path, entry)):
entry += '/'
self.addOption(entry)
def on_ok(self):
if self.callback is not None:
self.callback(self.selected_file)
def on_cancel(self):
if self.callback is not None:
self.callback()
class FileOption(widgets.Option):
name = 'file-option'
@event.default('file-option')
def on_click(widget, x, y, buttons, modifiers, click_count):
# copy from regular Option on_click
widget.is_active = not widget.is_active
select = widget.getParent('selection')
if select.scrollable: f = select.contents
else: f = select
if widget.is_active and select.is_exclusive:
for child in f.children:
if child is not widget:
child.is_active = None
widget.getGUI().dispatch_event(select, 'on_change', select.value)
# now the custom file dialog behaviour
dialog = widget.getParent('file-dialog')
if widget.text == '..':
dialog.selected_widget = None
path = dialog.current_path
if path[-1] == '/': path = path[:-1]
dialog.openPath(os.path.split(path)[0])
elif widget.text[-1] == '/':
dialog.selected_widget = None
dialog.openPath(os.path.join(dialog.current_path, widget.text))
else:
file = os.path.join(dialog.current_path, widget.text)
if click_count > 1:
dialog.selected_file = file
dialog.on_ok()
dialog.delete()
elif dialog.selected_file == file:
dialog.selected_widget = None
else:
dialog.selected_file = file
dialog.selected_widget = widget
return event.EVENT_HANDLED
@event.default('.-file-open-dialog-ok')
def on_click(widget, *args):
d = widget.getParent('file-dialog')
d.on_ok()
d.delete()
return event.EVENT_HANDLED
@event.default('.-file-open-dialog-cancel')
def on_click(widget, *args):
d = widget.getParent('file-dialog')
d.on_cancel()
d.delete()
return event.EVENT_HANDLED
@event.default('.-file-open-path')
def on_change(widget, value):
value = os.path.expanduser(os.path.expandvars(value))
if os.path.isdir(value):
widget.parent.openPath(value)
return event.EVENT_HANDLED
| Python |
from wydget.dialogs.question import Question, Message
from wydget.dialogs.file import FileOpen
| Python |
from wydget import event
from wydget import widgets
from wydget import layouts
from wydget.dialogs import base
class Question(base.Dialog):
id = '-question-dialog'
name = 'question-dialog'
classes = ('dialog', )
def __init__(self, parent, text, callback=None, cancel=True,
font_size=None, padding=10, **kw):
super(Question, self).__init__(parent, padding=padding, **kw)
self.callback = callback
self.layout = layouts.Vertical(self, padding=10)
widgets.Label(self, text, font_size=font_size)
buttons = widgets.Frame(self, width='100%')
buttons.layout = layouts.Horizontal(buttons, padding=10,
halign='center')
self.ok = widgets.TextButton(buttons, 'Ok', border='black',
padding=2, classes=('-question-dialog-ok', ),
font_size=font_size)
if cancel:
widgets.TextButton(buttons, 'Cancel', border='black',
classes=('-question-dialog-cancel', ), padding=2,
font_size=font_size)
def run(self):
super(Question, self).run()
self.ok.gainFocus()
def on_ok(self):
if self.callback is not None:
self.callback(True)
def on_cancel(self):
if self.callback is not None:
self.callback(False)
def Message(*args, **kw):
kw['cancel'] = False
return Question(*args, **kw)
@event.default('.-question-dialog-ok')
def on_click(widget, *args):
dialog = widget.getParent('question-dialog')
dialog.on_ok()
dialog.delete()
return event.EVENT_HANDLED
@event.default('.-question-dialog-cancel')
def on_click(widget, *args):
dialog = widget.getParent('question-dialog')
dialog.on_cancel()
dialog.delete()
return event.EVENT_HANDLED
| Python |
import operator
import math
from wydget import util
from wydget.widgets.label import Label
TOP = 'top'
BOTTOM = 'bottom'
LEFT = 'left'
RIGHT = 'right'
CENTER = 'center'
FILL = 'fill'
intceil = lambda i: int(math.ceil(i))
class Layout(object):
'''Absolute positioning layout -- also base class for other layouts.
Elements in the parent are positioined using absolute coordinates in
the parent's coordinate space.
"only_visible" -- limits the layout to only those elements which are
is_visible (note NOT isVisible - parent visibility
obviously makes no sense in this context)
"ignore" -- set of elements to ignore when running layout
Child elements who do not specify their x and y coordinates will be
placed at 0 on the missing axis/axes.
'''
def __init__(self, parent, only_visible=False, ignore=None):
self.parent = parent
self.only_visible = only_visible
self.ignore = ignore
def __repr__(self):
return '<%s %dx%d>'%(self.__class__.__name__, self.width, self.height)
def _default_positions(self):
# determine all the simple default poisitioning, including
# converting None values to 0
for c in self.getChildren():
if c.x is None:
if c.x_spec.spec is None:
c.x = 0
elif c.x_spec.is_fixed:
c.x = c.x_spec.calculate()
if c.y is None:
if c.y_spec.spec is None:
c.y = 0
elif c.y_spec.is_fixed:
c.y = c.y_spec.calculate()
if c.z is None:
c.z = 0
def layout(self):
self._default_positions()
# can't layout if we don't have dimensions to layout *in*
assert self.parent.height is not None and self.parent.width is not None
# position
for c in self.getChildren():
if c.x is None or c.x_spec.percentage is not None:
c.x = c.x_spec.calculate()
if c.y is None or c.y_spec.percentage is not None:
c.y = c.y_spec.calculate()
if c.z is None:
c.z = 0
def __call__(self):
self.layout()
def get_height(self):
if not self.parent.children: return 0
self._default_positions()
return intceil(max(c.y + c.min_height for c in self.getChildren()))
height = property(get_height)
def get_width(self):
if not self.parent.children: return 0
self._default_positions()
return intceil(max(c.x + c.min_width for c in self.getChildren()))
width = property(get_width)
def getChildren(self):
l = []
for c in self.parent.children:
if self.only_visible and not c.is_visible:
continue
if self.ignore is not None and c in self.ignore:
continue
l.append(c)
return l
@classmethod
def fromXML(cls, element, parent):
'''Create the a layout from the XML element and handle children.
'''
kw = loadxml.parseAttributes(element)
parent.layout = layout = cls(parent, **kw)
for child in element.getchildren():
loadxml.getConstructor(child.tag)(child, layout.parent)
return layout
class Vertical(Layout):
name = 'vertical'
def __init__(self, parent, valign=TOP, halign=LEFT, padding=0,
wrap=None, **kw):
self.valign = valign
self.halign = halign
self.padding = util.parse_value(padding)
self.wrap = wrap and util.Dimension(wrap, parent, parent, 'height')
super(Vertical, self).__init__(parent, *kw)
def get_height(self):
if self.valign == FILL:
ph = self.parent.height
if ph is not None:
# fill means using the available height
return int(self.parent.inner_rect.height)
vis = self.getChildren()
if not vis: return 0
if self.wrap:
if self.parent.height_spec:
# parent height or widest child if higher than parent
return intceil(max(self.wrap.specified(),
max(c.min_height for c in vis)))
else:
# height of highest row
return intceil(max(sum(c.min_height for c in column) +
self.padding * (len(column)-1)
for column in self.determineColumns()))
return intceil(sum(c.min_height for c in vis) +
self.padding * (len(vis)-1))
height = property(get_height)
def get_width(self):
vis = self.getChildren()
if not vis: return 0
if self.wrap:
cols = self.determineColumns()
return sum(max(c.min_width for c in col) for col in cols) + \
self.padding * (len(cols)-1)
return intceil(max(c.min_width for c in vis))
width = property(get_width)
def determineColumns(self):
cols = [[]]
ch = 0
wrap = self.wrap and self.wrap.calculate()
for c in self.getChildren():
if wrap and ch and ch + c.min_height > wrap:
ch = 0
cols.append([])
col = cols[-1]
col.append(c)
ch += c.min_height + self.padding
if not cols[-1]: cols.pop()
return cols
def layout(self):
# can't layout if we don't have dimensions to layout *in*
assert self.parent.height is not None and self.parent.width is not None
for child in self.getChildren():
assert child.height is not None and child.width is not None, \
'%r missing dimensions'%child
# now get the area available for our layout
rect = self.parent.inner_rect
# Determine starting X coord
x = 0
if self.halign == CENTER:
x = rect.width//2 - self.width//2
elif self.halign == RIGHT:
x = rect.width - self.width
wrap = self.wrap and self.wrap.calculate()
fill_padding = self.padding
for col in self.determineColumns():
# column width is width of widest child
cw = max(child.width for child in col)
# height of this column
if self.valign == FILL:
h = rect.height
else:
h = sum(c.height for c in col) + self.padding * (len(col)-1)
# vertical align for this column
if self.valign == BOTTOM:
y = h
elif self.valign == TOP:
y = rect.height
elif self.valign == CENTER:
y = rect.height//2 - h//2 + h
elif self.valign == FILL:
y = rect.height
if len(col) == 1:
fill_padding = 0
else:
h = sum(c.height for c in col)
fill_padding = (rect.height - h)/float(len(col)-1)
# now layout the columns
for child in col:
y -= child.height
child.y = int(y)
y -= fill_padding
if self.halign == LEFT:
child.x = int(x)
elif self.halign == CENTER:
child.x = int(x + (cw//2 - child.width//2))
elif self.halign == RIGHT:
child.x = int(x + (cw - child.width))
if wrap:
x += self.padding + cw
class Horizontal(Layout):
name = 'horizontal'
def __init__(self, parent, halign=LEFT, valign=TOP, padding=0,
wrap=None, **kw):
self.halign = halign
self.valign = valign
self.padding = util.parse_value(padding)
self.wrap = wrap and util.Dimension(wrap, parent, parent, 'height')
super(Horizontal, self).__init__(parent, **kw)
def get_width(self):
if self.halign == FILL:
pw = self.parent.width
if pw is not None:
# fill means using the available width
return int(self.parent.inner_rect.width)
vis = self.getChildren()
if not vis: return 0
if self.wrap:
if self.parent.width_spec:
# parent width or widest child if wider than parent
return intceil(max(self.wrap.specified(),
max(c.min_width for c in vis)))
else:
# width of widest row
return max(sum(c.min_width for c in row) +
self.padding * (len(row)-1)
for row in self.determineRows())
return intceil(sum(c.min_width for c in vis) +
self.padding * (len(vis)-1))
width = property(get_width)
def get_height(self):
vis = self.getChildren()
if not vis: return 0
if self.wrap:
rows = self.determineRows()
return intceil(sum(max(c.min_height for c in row) for row in rows) +
self.padding * (len(rows)-1))
return intceil(max(c.min_height for c in vis))
height = property(get_height)
def determineRows(self):
rows = [[]]
rw = 0
wrap = self.wrap and self.wrap.calculate()
for c in self.getChildren():
if wrap and rw and rw + c.min_width > wrap:
rw = 0
rows.append([])
row = rows[-1]
row.append(c)
rw += c.min_width + self.padding
if not rows[-1]: rows.pop()
return rows
def layout(self):
# can't layout if we don't have dimensions to layout *in*
assert self.parent.height is not None and self.parent.width is not None
# now get the area available for our layout
rect = self.parent.inner_rect
# Determine starting y coordinate at top of parent.
if self.valign == BOTTOM:
y = self.height
elif self.valign == CENTER:
y = rect.height//2 - self.height//2 + self.height
elif self.valign == TOP:
y = rect.height
wrap = self.wrap and self.wrap.calculate()
fill_padding = self.padding
for row in self.determineRows():
rh = max(child.height for child in row)
if self.valign is not None:
y -= rh
# width of this row
if self.halign == FILL:
w = rect.width
else:
w = sum(c.width for c in row) + self.padding * (len(row)-1)
# horizontal align for this row
x = 0
if self.halign == RIGHT:
x = int(rect.width - w)
elif self.halign == CENTER:
x = rect.width//2 - w//2
elif self.halign == FILL:
if len(row) == 1:
fill_padding = 0
else:
w = sum(c.width for c in row)
fill_padding = (rect.width - w)/float(len(row)-1)
for i, child in enumerate(row):
if fill_padding and i == len(row) - 1:
child.x = int(rect.width - child.width)
else:
child.x = int(x)
x += int(child.width + fill_padding)
if self.valign == BOTTOM:
child.y = int(y)
elif self.valign == CENTER:
child.y = int(y + (rh//2 - child.height//2))
elif self.valign == TOP:
child.y = int(y + (rh - child.height))
if wrap:
y -= self.padding
class Grid(Layout):
'''A simple table layout that sets column widths in child rows to fit
all child data.
Note that this layout ignores *cell* visibility but honors *row*
visibility for layout purposes.
'''
name = 'grid'
# XXX column alignments
def __init__(self, parent, colpad=0, rowpad=0, colaligns=None, **kw):
self.colaligns = colaligns
self.colpad = util.parse_value(colpad, 0)
self.rowpad = util.parse_value(rowpad, 0)
super(Grid, self).__init__(parent, **kw)
def columnWidths(self):
columns = []
children = self.getChildren()
if not children:
return []
N = len(children[0].children)
for i in range(N):
w = []
for row in children:
pad = i < N-1 and self.colpad or 0
col = row.children[i]
w.append(col.min_width + pad)
columns.append(max(w))
return columns
def get_width(self):
return intceil(sum(self.columnWidths()))
width = property(get_width)
def get_height(self):
children = self.getChildren()
h = intceil(sum(max(e.min_height for e in c.children) + c.padding*2
for c in children))
return intceil(h + (len(children)-1) * self.rowpad)
height = property(get_height)
def layout(self):
children = self.getChildren()
# determine column widths
columns = self.columnWidths()
# column alignments
colaligns = self.colaligns
# right, now position everything
y = self.height
for row in children:
y -= row.height
rp2 = row.padding * 2
row.y = y
row.x = 0
x = 0
for i, elem in enumerate(row.children):
elem.x = x
if colaligns is not None:
if colaligns[i] == 'r':
elem.x += columns[i] - elem.width - rp2
elif colaligns[i] == 'c':
elem.x += (columns[i] - rp2)//2 - elem.width//2
elif colaligns[i] == 'f':
elem.width = columns[i] - rp2
elem.y = row.inner_height - elem.height
x += columns[i]
y -= self.rowpad
class Form(Grid):
name = 'form'
def __init__(self, *args, **kw):
if 'colaligns' not in kw:
kw['colaligns'] = 'rl'
super(Form, self).__init__(*args, **kw)
def addElement(self, label, element, **kw):
from wydget.widgets.frame import Frame
row = Frame(self.parent, is_transparent=True)
if label:
element._label = Label(row, label, **kw)
else:
element._label = None
Frame(row, is_transparent=True, width=0, height=0)
# move the element to the row
element.parent.children.remove(element)
row.children.append(element)
element.parent = row
@classmethod
def fromXML(cls, element, parent):
'''Create the a layout from the XML element and handle children.
'''
kw = loadxml.parseAttributes(element)
parent.layout = layout = cls(parent, **kw)
for child in element.getchildren():
assert child.tag == 'row', '<form> children must be <row>'
ckw = loadxml.parseAttributes(child)
l = child.getchildren()
if not l: return
assert len(l) == 1, '<row> may only have one (or no) child'
content = loadxml.getConstructor(l[0].tag)(l[0], parent)
layout.addElement(ckw['label'], content)
return layout
import loadxml
for klass in [Vertical, Horizontal, Grid, Form]:
loadxml.xml_registry[klass.name] = klass
| Python |
from pyglet.gl import *
from pyglet import font
from layout import *
import util
class Style(object):
font_name = ''
font_size = 14
def getFont(self, name=None, size=None):
if name is None: name = self.font_name
if size is None: size = self.font_size
return font.load(name, size)
def getGlyphString(self, text, name=None, size=None):
glyphs = self.getFont(name=name, size=size).get_glyphs(text)
return font.GlyphString(text, glyphs)
def text(self, text, color=(0, 0, 0, 1), font_size=None,
font_name=None, halign='left', width=None,
valign=font.Text.BOTTOM):
if font_size is None: font_size = self.font_size
if font_name is None: font_name = self.font_name
f = self.getFont(name=font_name, size=font_size)
return font.Text(f, text, color=color, halign=halign, width=width,
valign=valign)
def textAsTexture(self, text, color=(0, 0, 0, 1), bgcolor=(1, 1, 1, 0),
font_size=None, font_name=None, halign='left', width=None,
rotate=0):
label = self.text(text, color=color, font_size=font_size,
font_name=font_name, halign=halign, width=width, valign='top')
label.width
w = int(width or label.width)
h = font_size * len(label.lines) #int(label.height)
x = c_int()
def _f():
glPushAttrib(GL_COLOR_BUFFER_BIT|GL_ENABLE_BIT|GL_CURRENT_BIT)
glEnable(GL_TEXTURE_2D)
glDisable(GL_DEPTH_TEST)
glClearColor(*bgcolor)
glClear(GL_COLOR_BUFFER_BIT)
glPushMatrix()
if rotate == 0:
glTranslatef(0, h, 0)
if rotate:
glRotatef(rotate, 0, 0, 1)
if rotate == 270:
glTranslatef(-w, h, 0)
if rotate == 180:
glTranslatef(-w, 0, 0)
# prevent the text's alpha channel being written into the new
# texture
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE)
label.draw()
glPopMatrix()
glPopAttrib()
if rotate in (0, 180):
return util.renderToTexture(w, h, _f)
else:
return util.renderToTexture(h, w, _f)
stylesheet = '''
body {margin: 0px; background-color: white; font-family: sans-serif;}
div.frame {border: 1px solid #555; background-color: white;}
h1 {font-size: %(font_size)spx; color: black; margin: 2px;}
p {font-size: %(font_size)spx; color: #444; margin: 2px;}
.button {font-size: %(font_size)spx; border: 1px solid black; padding: 2px; margin: 0px;}
a {color: blue;}
'''%locals()
def xhtml(self, text, width=None, height=None, style=None):
layout = Layout()
if style is None:
style = self.stylesheet
layout.set_xhtml('''<?xml version="1.0"?>
<html><head><style>%s</style></head>
<body>%s</body></html>'''%(style, text))
layout.viewport_x = 0
layout.viewport_y = 0
layout.viewport_width = width or 256
layout.viewport_height = height or 200
h = int(layout.view.canvas_height)
w = int(layout.view.canvas_width)
layout.viewport_width = w
layout.viewport_height = h
return layout
def xhtmlAsTexture(self, text, width=None, height=None, style=None):
return xhtmlAsTexture(self.xhtml(text, width, height, style))
def xhtmlAsTexture(layout):
h = int(layout.view.canvas_height)
w = int(layout.view.canvas_width)
def _f():
glPushAttrib(GL_CURRENT_BIT|GL_COLOR_BUFFER_BIT|GL_ENABLE_BIT)
# always draw onto solid white
glClearColor(1, 1, 1, 1)
glClear(GL_COLOR_BUFFER_BIT)
glPushMatrix()
glLoadIdentity()
glTranslatef(0, h, 0)
# ... and blend with solid white
glColor4f(1, 1, 1, 1)
layout.view.draw()
glPopMatrix()
glPopAttrib()
return util.renderToTexture(w, h, _f)
class Gradient(object):
def __init__(self, *corners):
'''Corner colours in order bottomleft, topleft, topright,
bottomright.
'''
self.corners = corners
def __call__(self, rect, clipped):
scissor = clipped != rect
if scissor:
glPushAttrib(GL_ENABLE_BIT|GL_SCISSOR_BIT)
glEnable(GL_SCISSOR_TEST)
glScissor(*map(int, (clipped.x, clipped.y, clipped.width,
clipped.height)))
glBegin(GL_QUADS)
glColor4f(*self.corners[0])
glVertex2f(*rect.bottomleft)
glColor4f(*self.corners[1])
glVertex2f(*rect.topleft)
glColor4f(*self.corners[2])
glVertex2f(*rect.topright)
glColor4f(*self.corners[3])
glVertex2f(*rect.bottomright)
glEnd()
if scissor:
glPopAttrib()
| Python |
import random
import math
from pyglet import window
from pyglet import image
from pyglet import clock
from pyglet import gl
from pyglet import resource
from pyglet.window import key
import spryte
win = window.Window(width=640, height=400,vsync=False)
fps = clock.ClockDisplay(color=(1, 1, 1, 1))
balls = spryte.SpriteBatch()
ball = resource.image('ball.png')
ball.anchor_x = 16
ball.anchor_y = 16
for i in range(200):
spryte.Sprite(ball,
(win.width - 64) * random.random(), (win.height - 64) * random.random(),
batch=balls,
dx=-50 + 100*random.random(), dy=-50 + 100*random.random())
car = resource.image('car.png')
car.anchor_x = 16
car.anchor_y = 20
car = spryte.Sprite(car, win.width/2, win.height/2)
class EffectSprite(spryte.Sprite):
def on_animation_end(self):
self.delete()
explosions = spryte.SpriteBatch()
explosion_images = resource.image('explosion.png')
explosion_images = image.ImageGrid(explosion_images, 2, 8)
explosion_animation = image.Animation.from_image_sequence(explosion_images,
.001, loop=False)
keyboard = key.KeyStateHandler()
win.push_handlers(keyboard)
def animate(dt):
# update car rotation & speed
r = car.rotation
r += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 200 * dt
if r < 0: r += 360
elif r > 360: r -= 360
car.rotation = r
car.speed = (keyboard[key.UP] - keyboard[key.DOWN]) * 200 * dt
# ... and the rest
spryte.update_kinematics(car, dt)
# handle balls
for i, s in enumerate(balls):
# update positions
s.x += s.dx * dt
s.y += s.dy * dt
if s.right > win.width and s.dx > 0: s.dx *= -1; s.right = win.width
elif s.left < 0 and s.dx < 0: s.dx *= -1; s.left = 0
if s.top > win.height and s.dy > 0: s.dy *= -1; s.top = win.height
elif s.bottom < 0 and s.dy < 0: s.dy *= -1; s.bottom = 0
# handle collisions
if not s.intersects(car):
continue
if s.scale > 2:
# pop!
explosion = EffectSprite(explosion_animation, 0, 0,
batch=explosions)
explosion.center = s.center
explosion.push_handlers
s.delete()
spryte.Sprite(ball,
win.width * random.random(), win.height * random.random(),
batch=balls,
dx=-50 + 100*random.random(), dy=-50 + 100*random.random())
else:
s.scale += .1
n = min(1, max(0, 2-s.scale))
s.color = (1, 1, 1, .5+n/2)
clock.schedule(animate)
while not win.has_exit:
clock.tick()
win.dispatch_events()
win.clear()
explosions.draw()
balls.draw()
car.draw()
fps.draw()
win.flip()
win.close()
| Python |
import sys
import random
from pyglet import window
from pyglet import image
from pyglet import clock
from pyglet import resource
import spryte
NUM_BOOMS = 20
if len(sys.argv) > 1:
NUM_BOOMS = int(sys.argv[1])
win = window.Window(vsync=False)
fps = clock.ClockDisplay(color=(1, 1, 1, 1))
explosions = spryte.SpriteBatch()
explosion_images = resource.image('explosion.png')
explosion_images = image.ImageGrid(explosion_images, 2, 8)
explosion_animation = image.Animation.from_image_sequence(explosion_images,
.001, loop=False)
class EffectSprite(spryte.Sprite):
def on_animation_end(self):
self.delete()
again()
booms = spryte.SpriteBatch()
def again():
EffectSprite(explosion_animation,
win.width*random.random(), win.height*random.random(),
batch=booms)
again()
while not win.has_exit:
clock.tick()
win.dispatch_events()
if len(booms) < NUM_BOOMS: again()
win.clear()
booms.draw()
fps.draw()
win.flip()
win.close()
| Python |
# Lots Of Sprites
'''
Results for 2000 sprites:
platform us per sprite per frame
---------------------------------------------------------------------
Intel C2Quad Q6600 (2.4GHz), GeForce 7800 18.2478245656
Intel C2Duo T7500 (2.2GHz), GeForce 8400M GS 19.115903827
AMD 64 3500+ (1.8GHz), GeForce 7800 23.6
EEE PC 75.0
'''
import os
import sys
import random
import time
from pyglet import options
options['debug_gl'] = False
import pyglet
import spryte
w = pyglet.window.Window(600, 600, vsync=False)
class BouncySprite(spryte.Sprite):
def update(self):
# micro-optimisation: only access properties once
x, y = self.x, self.y
# move
self.position = (x + self.dx, y + self.dy)
# check bounds
if x < 0: self.x = 0; self.dx = -self.dx
elif self.right > 600: self.dx = -self.dx; self.right = 600
if y < 0: self.y = 0; self.dy = -self.dy
elif self.top > 600: self.dy = -self.dy; self.top = 600
batch = spryte.SpriteBatch()
numsprites = int(sys.argv[1])
pyglet.resource.path.append('examples/noisy')
ball = pyglet.resource.image('ball.png')
for i in range(numsprites):
x = random.randint(0, w.width - ball.width)
y = random.randint(0, w.height - ball.height)
BouncySprite(ball, x, y, batch=batch,
dx=random.randint(-10, 10), dy=random.randint(-10, 10))
def update(dt):
for s in batch: s.update()
pyglet.clock.schedule(update)
numframes = 0
sum_numframes = 0
best_fps = 0
def update_stats(dt):
global numframes, sum_numframes, best_fps
fps = numframes / dt
best_fps = max(best_fps, fps)
sum_numframes += numframes
numframes = 0
pyglet.clock.schedule_interval(update_stats, 0.5)
@w.event
def on_draw():
global numframes
numframes += 1
w.clear()
batch.draw()
t = time.time()
pyglet.app.run()
print 'best FPS:', best_fps
print 'best us per sprite:', (1. / best_fps) * 1000000 / numsprites
print 'avg us per sprite:', float(time.time()-t) / (numsprites * sum_numframes) * 1000000
| Python |
import os
import math
from pyglet import image, gl, clock, graphics, sprite
class SpriteBatchGroup(graphics.Group):
def __init__(self, x, y, parent=None):
super(SpriteBatchGroup, self).__init__(parent)
self.x, self.y = x, y
def set(self):
if self.x or self.y:
gl.glTranslatef(self.x, self.y, 0)
def unset(self):
if self.x or self.y:
gl.glTranslatef(-self.x, -self.y, 0)
class SpriteBatch(graphics.Batch):
def __init__(self, x=0, y=0):
super(SpriteBatch, self).__init__()
self.state = SpriteBatchGroup(x, y)
self.sprites = []
def __iter__(self): return iter(self.sprites)
def __len__(self): return len(self.sprites)
def hit(self, x, y):
'''See whether there's a Sprite at the pixel location
XXX optimise me
'''
for sprite in self.sprites:
if sprite.contains(x, y):
return sprite
return None
def on_mouse_press(self, x, y, buttons, modifiers):
'''See if the press occurs over a sprite and if it does, invoke the
on_mouse_press handler on the sprite.
XXX optimise me
'''
sprite = self.hit(x, y)
if sprite:
return sprite.on_mouse_press(x, y, buttons, modifiers)
return False
def add_sprite(self, sprite):
self.sprites.append(sprite)
def remove_sprite(self, sprite):
self.sprites.remove(sprite)
def clear(self):
for s in self.sprites: s.delete()
self.sprites = []
class Sprite(sprite.Sprite):
def __init__(self, img, x=0, y=0,
blend_src=gl.GL_SRC_ALPHA, blend_dest=gl.GL_ONE_MINUS_SRC_ALPHA,
batch=None, parent_state=None, **attributes):
'''A sprite is an image at some position with some rotation.
Sprites are blended into the background by default.
If you're going to have many sprites you should consider creating your
own SpriteBatch.
Any additional keyword arguments will be assigned as attributes on the
sprite. This can be useful if you intend to use `update_kinematics`.
'''
# default parent_state to batch state if it has one
if parent_state is None and hasattr(batch, 'state'):
parent_state = batch.state
super(Sprite, self).__init__(img, x, y, blend_src, blend_dest,
batch, parent_state)
# if the parent wants us to register then do so
if self._batch is not None and hasattr(self._batch, 'add_sprite'):
self._batch.add_sprite(self)
# arbitrary attributes
self.__dict__.update(attributes)
def delete(self):
if self._batch is not None and hasattr(self._batch, 'remove_sprite'):
self._batch.remove_sprite(self)
super(Sprite, self).delete()
def contains(self, x, y):
'''Return boolean whether the point defined by x, y is inside the
rect area.
'''
if x < self.left or x > self.right: return False
if y < self.bottom or y > self.top: return False
return True
def intersects(self, other):
'''Return boolean whether the "other" rect (an object with .x, .y,
.width and .height attributes) overlaps this Rect in any way.
'''
if self.right < other.left: return False
if other.right < self.left: return False
if self.top < other.bottom: return False
if other.top < self.bottom: return False
return True
def on_mouse_press(self, x, y, buttons, modifiers):
pass
def get_top(self):
t = self._texture
height = t.height * self._scale
return self._y + height - t.anchor_y
def set_top(self, y):
t = self._texture
height = t.height * self._scale
self._y = y - height + t.anchor_y
self._update_position()
top = property(get_top, set_top)
def get_bottom(self):
return self._y - self._texture.anchor_y
def set_bottom(self, y):
self._y = y + self._texture.anchor_y
self._update_position()
bottom = property(get_bottom, set_bottom)
def get_left(self):
return self._x - self._texture.anchor_x
def set_left(self, x):
self._x = x + self._texture.anchor_x
self._update_position()
left = property(get_left, set_left)
def get_right(self):
t = self._texture
width = t.width * self._scale
return self._x + width - t.anchor_x
def set_right(self, x):
t = self._texture
width = t.width * self._scale
self._x = x - width + t.anchor_x
self._update_position()
right = property(get_right, set_right)
def get_center(self):
t = self._texture
left = self._x - t.anchor_x
bottom = self._y - t.anchor_y
height = t.height * self._scale
width = t.width * self._scale
return (left + width/2, bottom + height/2)
def set_center(self, center):
x, y = center
# XXX optimise this
self.left = x - self.width/2
self.bottom = y - self.height/2
center = property(get_center, set_center)
def update_kinematics(sprite, dt):
'''Update the sprite with simple kinematics for the passage of "dt"
seconds.
The sprite's acceleration (.ddx and .ddy) are added to the sprite's
velocity.
If there's a .speed attribute it's combined with the .rotation to
calculate a new .dx and .dy.
The sprite's veclocity (.dx and .dy) are added to the sprite's
position.
Sprite rotation is included in the calculations. That is, positive dy
is always pointing up from the top of the sprite and positive dx is
always pointing right from the sprite.
'''
if sprite.ddx: sprite.dx += sprite.ddx * dt
if sprite.ddy: sprite.dy += sprite.ddy * dt
# use speed if it's set
if hasattr(sprite, 'speed'):
r = math.radians(sprite._rotation)
sprite.dx = math.cos(r) * sprite.speed
sprite.dy = -math.sin(r) * sprite.speed
if sprite.dx == sprite.dy == 0: return
x, y = sprite._x, sprite._y
sprite.position = sprite._x + sprite.dx, sprite._y + sprite.dy
| Python |
import os
import math
from pyglet import window
from pyglet import resource
from pyglet import image
from pyglet.window import key
from pyglet import clock
import spryte
import view
win = window.Window(vsync=False)
fps = clock.ClockDisplay(color=(1, 1, 1, 1))
map = [
[ 0, 1, 1, 1, 2, 3],
[ 5, 6, 16, 16, 7, 8],
[ 5, 8, 9, 9, 5, 8],
[ 5, 8, 9, 9, 5, 8],
[ 5, 8, 9, 9, 5, 8],
[ 5, 8, 9, 9, 5, 8],
[ 5, 8, 9, 9, 5, 8],
[ 5, 8, 9, 9, 5, 8],
[10, 11, 1, 1, 12, 13],
[15, 16, 16, 16, 17, 18],
]
v = view.View.for_window(win)
tiles = resource.image('road-tiles.png')
tiles = image.ImageGrid(tiles, 4, 5)
v.add_map(tiles, map)
car = resource.image('car.png')
car.anchor_x = 16
car.anchor_y = 20
car = v.add_sprite(car, 64, 64, z=1)
keyboard = key.KeyStateHandler()
win.push_handlers(keyboard)
# mouse picking ... needs to be in a different example
def f(x, y, buttons, modifiers):
print (x, y)
car.on_mouse_press = f
win.push_handlers(v.get_layer(z=1))
def animate(dt):
# update car rotation & speed
r = car.rotation
r += (keyboard[key.RIGHT] - keyboard[key.LEFT]) * 200 * dt
if r < 0: r += 360
elif r > 360: r -= 360
car.rotation = r
car.speed = (keyboard[key.UP] - keyboard[key.DOWN]) * 300 * dt
# ... and the rest
spryte.update_kinematics(car, dt)
v.focus = car.position
clock.schedule(animate)
while not win.has_exit:
dt = clock.tick()
win.dispatch_events()
win.clear()
v.draw()
fps.draw()
win.flip()
win.close()
| Python |
class Rect(object):
'''Define a rectangular area.
Many convenience handles and other properties are also defined - all of
which may be assigned to which will result in altering the position
and sometimes dimensions of the Rect.
The Rect area includes the bottom and left borders but not the top and
right borders.
'''
def __init__(self, x, y, width, height):
'''Create a Rect with the bottom-left corner at (x, y) and
dimensions (width, height).
'''
self._x, self._y = x, y
self._width, self._height = width, height
# the following four properties will most likely be overridden in a
# subclass
def set_x(self, value): self._x = value
x = property(lambda self: self._x, set_x)
def set_y(self, value): self._y = value
y = property(lambda self: self._y, set_y)
def set_width(self, value): self._width = value
width = property(lambda self: self._width, set_width)
def set_height(self, value): self._height = value
height = property(lambda self: self._height, set_height)
def set_pos(self, value): self._x, self._y = value
pos = property(lambda self: (self._x, self._y), set_pos)
def set_size(self, value): self._width, self._height = value
size = property(lambda self: (self._width, self._height), set_size)
def contains(self, x, y):
'''Return boolean whether the point defined by x, y is inside the
rect area.
'''
if x < self._x or x > self._x + self._width: return False
if y < self._y or y > self._y + self._height: return False
return True
def intersects(self, other):
'''Return boolean whether the "other" rect (an object with .x, .y,
.width and .height attributes) overlaps this Rect in any way.
'''
if self._x + self._width < other.x: return False
if other.x + other.width < self._x: return False
if self._y + self._height < other.y: return False
if other.y + other.height < self._y: return False
return True
# r/w, in pixels, y extent
def get_top(self): return self.y + self.height
def set_top(self, y): self.y = y - self.height
top = property(get_top, set_top)
# r/w, in pixels, y extent
def get_bottom(self): return self.y
def set_bottom(self, y): self.y = y
bottom = property(get_bottom, set_bottom)
# r/w, in pixels, x extent
def get_left(self): return self.x
def set_left(self, x): self.x = x
left = property(get_left, set_left)
# r/w, in pixels, x extent
def get_right(self): return self.x + self.width
def set_right(self, x): self.x = x - self.width
right = property(get_right, set_right)
# r/w, in pixels, (x, y)
def get_center(self):
return (self.x + self.width/2, self.y + self.height/2)
def set_center(self, center):
x, y = center
self.pos = (x - self.width/2, y - self.height/2)
center = property(get_center, set_center)
# r/w, in pixels, (x, y)
def get_midtop(self):
return (self.x + self.width/2, self.y + self.height)
def set_midtop(self, midtop):
x, y = midtop
self.pos = (x - self.width/2, y - self.height)
midtop = property(get_midtop, set_midtop)
# r/w, in pixels, (x, y)
def get_midbottom(self):
return (self.x + self.width/2, self.y)
def set_midbottom(self, midbottom):
x, y = midbottom
self.pos = (x - self.width/2, y)
midbottom = property(get_midbottom, set_midbottom)
# r/w, in pixels, (x, y)
def get_midleft(self):
return (self.x, self.y + self.height/2)
def set_midleft(self, midleft):
x, y = midleft
self.pos = (x, y - self.height/2)
midleft = property(get_midleft, set_midleft)
# r/w, in pixels, (x, y)
def get_midright(self):
return (self.x + self.width, self.y + self.height/2)
def set_midright(self, midright):
x, y = midright
self.pos = (x - self.width, y - self.height/2)
midright = property(get_midright, set_midright)
# r/w, in pixels, (x, y)
def get_topleft(self):
return (self.x, self.y + self.height)
def set_topleft(self, pos):
x, y = pos
self.pos = (x, y - self.height)
topleft = property(get_topleft, set_topleft)
# r/w, in pixels, (x, y)
def get_topright(self):
return (self.x + self.width, self.y + self.height)
def set_topright(self, pos):
x, y = pos
self.pos = (x - self.width, y - self.height)
topright = property(get_topright, set_topright)
# r/w, in pixels, (x, y)
def get_bottomright(self):
return (self.x + self.width, self.y)
def set_bottomright(self, pos):
x, y = pos
self.pos = (x - self.width, y)
bottomright = property(get_bottomright, set_bottomright)
# r/w, in pixels, (x, y)
def get_bottomleft(self):
return (self.x, self.y)
def set_bottomleft(self, pos):
self.x, self.y = pos
bottomleft = property(get_bottomleft, set_bottomleft)
| Python |
# desktop tower defense clone
import math
import random
from pyglet import window
from pyglet import image
from pyglet import resource
from pyglet import clock
from pyglet.window import mouse
import view
import tilemap
import spryte
import path
field_cells = '''
+++++++++++EEEEE++++++++++++
+##########.....###########+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
S..........................E
S..........................E
S..........................E
S..........................E
S..........................E
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+#........................#+
+##########.....###########+
+++++++++++SSSSS++++++++++++
'''.strip()
field_rows = [line.strip() for line in field_cells.splitlines()]
cw = ch = 16
hw = hh = 8
map_height = len(field_rows)
map_width = len(field_rows[0])
win = window.Window(map_width*cw, map_height*ch)
# load / create image resources
blank_image = image.create(cw, ch, image.SolidColorImagePattern((200,)*4))
wall_image = image.create(cw, ch, image.SolidColorImagePattern((100,)*4))
highlight_image = image.create(cw, ch,
image.SolidColorImagePattern((255, 255, 255, 100)))
enemy_image = image.create(hw, hh,
image.SolidColorImagePattern((255, 50, 50, 255)))
enemy_image.anchor_x = hw//2
enemy_image.anchor_y = hh//2
turret_image = resource.image('basic-gun.png')
turret_image.anchor_x = 8
turret_image.anchor_y = 8
bullet_image = image.create(3, 3, image.SolidColorImagePattern((0,0,0,255)))
bullet_image.anchor_x = 1
bullet_image.anchor_y = 1
def distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
class Game(object):
def __init__(self):
self.highlight = spryte.Sprite(highlight_image, 0, 0)
self.show_highlight = False
# CREATE THE MAP
self.field = tilemap.Map()
self.play_field = {}
l = []
for y, line in enumerate(field_rows):
m = []
l.append(m)
for x, cell in enumerate(line):
if cell == '#':
m.append(spryte.Sprite(wall_image, x*cw, y*ch,
batch=self.field))
content = path.Blocker
else:
m.append(spryte.Sprite(blank_image, x*cw, y*ch,
batch=self.field))
if cell == 'E':
content = path.End
elif cell == 'S':
content = path.Start
elif cell == '+':
content = path.Blocker
else:
content = None
self.play_field[x*2, y*2] = content
self.play_field[x*2+1, y*2] = content
self.play_field[x*2, y*2+1] = content
self.play_field[x*2+1, y*2+1] = content
self.field.set_cells(cw, ch, l)
# PATH FOR ENEMIES
self.path = path.Path.determine_path(self.play_field, map_width*2,
map_height*2)
#self.path.dump()
self.constructions = spryte.SpriteBatch()
self.enemies = spryte.SpriteBatch()
self.bullets = spryte.SpriteBatch()
def spawn_enemies(self):
# SOME ENEMIES
starts = []
ends = set()
for y, row in enumerate(field_rows):
for x, cell in enumerate(row):
if cell == 'S':
starts.append((x*2, y*2))
elif cell == 'E':
ends.add((x*2, y*2))
def create_enemy(dt):
x, y = random.choice(starts)
Enemy(x, y, self, ends)
for i in range(10):
clock.schedule_once(create_enemy, i+1) # +10
def create_construction(self, x, y):
x, y = (x // hw)*hw, (y // hh)*hh
cx, cy = x//hw, y//hh
cells = (cx, cy), (cx+1, cy), (cx, cy+1), (cx+1, cy+1)
for cell in cells:
if self.play_field[cell]:
return
# check we're not going to block the only path for any enemy
if not self.path.test_mod(cells):
return
# all ok
Turret(x, y, self)
for cell in cells:
self.play_field[cell] = path.Blocker
self.path = path.Path.determine_path(self.play_field, map_width*2,
map_height*2)
#self.path.dump()
self.show_highlight = False
def update(self, dt):
for shooter in self.constructions:
shooter.update(dt)
# build a hash table of enemy positions in the grid
hit_hash = {}
for enemy in self.enemies:
enemy.update(dt)
x, y = enemy.center
hpos = ((x // hw)*hw, (y // hh)*hh)
hit_hash[hpos] = enemy
# hit the enemies with the bullets
for bullet in self.bullets:
bullet.update(dt)
# bullet position is its center
x, y = bullet.position
hpos = ((x // hw)*hw, (y // hh)*hh)
if hpos in hit_hash:
enemy = hit_hash[hpos]
bullet.hit(enemy)
bullet.delete()
def draw(self):
self.field.draw()
self.constructions.draw()
self.enemies.draw()
self.bullets.draw()
if self.show_highlight:
self.highlight.draw()
# CONSTRUCTIONS
def on_mouse_motion(self, x, y, dx, dy):
cx, cy = x//hw, y//hh
try:
if (self.play_field[cx, cy] or self.play_field[cx+1, cy] or
self.play_field[cx, cy+1] or self.play_field[cx+1, cy+1]):
self.show_highlight = False
return True
except KeyError:
self.show_highlight = False
return True
self.show_highlight = True
self.highlight.position = cx*hw, cy*hh
return True
def on_key_press(self, symbol, modifiers):
if symbol == window.key._1:
x, y = win._mouse_x, win._mouse_y
if self.constructions.hit(x, y):
return False
self.create_construction(x, y)
return True
return False
class Turret(spryte.Sprite):
range = 75
reload = 0
target = None
rotation_speed = 5
def __init__(self, x, y, game):
super(Turret, self).__init__(turret_image, x+8, y+8,
game=game, batch=game.constructions)
def update(self, dt):
sx, sy = self.center
self.reload = max(0, self.reload - dt)
if self.target is not None and self.target.health > 0:
# aim again
ex, ey = self.target.center
d = distance(sx, sy, ex, ey)
if d < self.range:
shoot = not self.reload
self.shoot_at(d, self.target, dt, shoot)
return
if self.reload:
return
self.target = None
# find a new target
l = []
for enemy in self.game.enemies:
ex, ey = enemy.center
d = distance(sx, sy, ex, ey)
if d > self.range:
continue
l.append((d, enemy))
if not l:
# nothing to shoot at
return
l.sort()
self.shoot_at(l[0][0], l[0][1], dt)
def shoot_at(self, d, enemy, dt, shoot=True):
self.target = enemy
sx, sy = self.center
ex, ey = enemy.position
edx, edy = enemy.dx, enemy.dy
# figure time to hit target
projectile_speed = 70.
dt = d / projectile_speed
# adjust target spot for target's movement
ex += edx * dt
ey += edy * dt
# ok, now figure the vector to hit that spot
dx = ex - sx
dy = ey - sy
magnitude = math.sqrt(dx**2 + dy**2)
dx = dx * projectile_speed / magnitude
dy = dy * projectile_speed / magnitude
# update self.rotation every tick when we have a target
angle = math.degrees(math.atan2(dx, dy))
diff = angle - self.rotation
mag = abs(diff)
# correct simple calculation's direction if necessary
if mag > 180:
rot = min(self.rotation_speed * dt, 360 - mag)
diff *= -1
else:
rot = min(self.rotation_speed * dt, mag)
# right, now rotate
if diff > 0:
self.rotation += rot
else:
self.rotation -= rot
# and if we're allowed to shoot *and* lined up then BANG!
diff = int(abs(self.rotation - angle))
if shoot and diff in (0, 360):
Bullet(bullet_image, sx, sy, dx=dx, dy=dy, batch=self.game.bullets)
self.reload = 1
class Bullet(spryte.Sprite):
time_to_live = 1
def update(self, dt):
self.time_to_live -= dt
if self.time_to_live < 0:
self.delete()
return
x, y = self.position
x += self.dx * dt
y += self.dy * dt
if x < 0 or x > win.width:
self.delete()
return
if y < 0 or y > win.height:
self.delete()
return
self.position = x, y
def hit(self, enemy):
enemy.damage(1)
class Enemy(spryte.Sprite):
health = 10
def __init__(self, x, y, game, ends):
self.cell_x, self.cell_y = x, y
self.game = game
self.ends = ends
if self.cell_x == 0:
x, y = ((self.cell_x-1) * hw + hw//2, self.cell_y * hh + hh//2)
else:
x, y = (self.cell_x * hw + hw//2, (self.cell_y+1) * hh + hh//2)
self.period = .5
super(Enemy, self).__init__(enemy_image, x, y, batch=game.enemies)
self.position = (x, y)
self.move_to(self.cell_x, self.cell_y)
def damage(self, amount):
self.health -= amount
if self.health <=0 :
self.delete()
def move_to(self, cx, cy):
'''Move to the indicated cell.
'''
if (cx, cy) in self.ends:
self.delete()
return
self.cell_x, self.cell_y = cx, cy
x, y = self.cell_x * hw + hw//2, self.cell_y * hh + hh//2
self.start_x, self.start_y = self.x, self.y
self.dest_x, self.dest_y = x, y
self.anim_time = 0
self.dx = (self.dest_x - self.start_x) / self.period
self.dy = (self.dest_y - self.start_y) / self.period
def update(self, dt):
self.anim_time += dt
s = (self.anim_time / self.period)
self.x = self.start_x + s * (self.dest_x - self.start_x)
self.y = self.start_y + s * (self.dest_y - self.start_y)
if self.anim_time > self.period:
self.x = self.dest_x
self.y = self.dest_y
self.move_to(*self.game.path.next_step(self.cell_x, self.cell_y))
game = Game()
win.push_handlers(game)
game.spawn_enemies()
clock.schedule(game.update)
# MAIN LOOP
fps = clock.ClockDisplay(color=(1, 1, 1, 1))
while not win.has_exit:
clock.tick()
win.dispatch_events()
win.clear()
game.draw()
fps.draw()
win.flip()
| Python |
Blocker = object()
Start = False
End = object()
class Path(dict):
@classmethod
def determine_path(cls, field, width, height):
path = cls()
path.width = width
path.height = height
path.ends = set()
path.starts = []
cells = []
for y in range(height):
m = []
for x in range(width):
cell = field[x, y]
if cell is End:
path[x, y] = 0
cells.append((x, y))
path.ends.add((x, y))
elif cell is Blocker:
path[x, y] = Blocker
elif cell is Start:
path.starts.append((x, y))
#path.dump()
x_extent = path.width-1
y_extent = path.height-1
while cells:
new = []
for x, y in cells:
v = path[x, y]
if x > 0 and (x-1, y) not in path:
path[x-1, y] = v + 1
new.append((x-1, y))
if x < x_extent and (x+1, y) not in path:
path[x+1, y] = v + 1
new.append((x+1, y))
if y > 0 and (x, y-1) not in path:
path[x, y-1] = v + 1
new.append((x, y-1))
if y < y_extent and (x, y+1) not in path:
path[x, y+1] = v + 1
new.append((x, y+1))
cells = new
for k in list(path.keys()):
if path[k] is Blocker or path[k] is None:
del path[k]
return path
def dump(self, mods={}):
import sys
for y in range(self.height):
sys.stdout.write('%02d '%y)
for x in range(self.width):
p = (x, y)
if p in mods:
c = '*'
else:
c = self.get(p)
if c is None:
c = '.'
elif c is Blocker:
c = '#'
else:
c = chr(c + ord('0'))
sys.stdout.write(c)
print
print
print ' ',
for i in range(self.width):
sys.stdout.write('%d'%(i%10))
print
def get_neighbors(self, x, y):
'''May move horizontal, vertical or diagonal as long as there's not
a blocker on both sides of the diagonal.
'''
l = []
# top left
if x > 0 and y < self.height-1:
tx = x - 1; ty = y + 1
if (x, ty) in self and (tx, y) in self and (tx, ty) in self:
l.append((self[tx, ty], (tx, ty)))
# top right
if x < self.width-1 and y < self.height-1:
tx = x + 1; ty = y + 1
if (x, ty) in self and (tx, y) in self and (tx, ty) in self:
l.append((self[tx, ty], (tx, ty)))
# bottom left
if x > 0 and y > 0:
tx = x - 1; ty = y - 1
if (x, ty) in self and (tx, y) in self and (tx, ty) in self:
l.append((self[tx, ty], (tx, ty)))
# bottom right
if x < self.width-1 and y > 0:
tx = x + 1; ty = y - 1
if (x, ty) in self and (tx, y) in self and (tx, ty) in self:
l.append((self[tx, ty], (tx, ty)))
# left
if x > 0:
tx = x - 1
if (tx, y) in self:
l.append((self[tx, y], (tx, y)))
# right
if x < self.width-1:
tx = x + 1
if (tx, y) in self:
l.append((self[tx, y], (tx, y)))
# left
if y > 0:
ty = y - 1
if (x, ty) in self:
l.append((self[x, ty], (x, ty)))
# right
if y < self.height-1:
ty = y + 1
if (x, ty) in self:
l.append((self[x, ty], (x, ty)))
l.sort()
return l
def next_step(self, x, y):
return self.get_neighbors(x, y)[0][1]
def test_mod(self, set_cells):
'''Determine whether the map would be solvable if the cells
provided are blocked.
'''
set_cells = set(set_cells)
current = self.starts
visited = set()
while current:
visited |= set(current)
#print 'TRY', current
#print 'VISITED', visited
next = set()
for x, y in current:
options = self.get_neighbors(x, y)
options.reverse()
#print 'VISIT', (x, y), options
while options:
c = options.pop()
p = c[1]
if p in self.ends:
#print 'END', p
return True
if p not in set_cells and p not in visited:
next.add(p)
break
current = list(next)
return False
if __name__ == '__main__':
field_cells = '''
++++SSS+++++
+####.#####+
+#........#+
S#.......##E
S..........E
S#.......##E
+#..###...#+
+####.#####+
++++EEE+++++
'''.strip()
field_rows = [line.strip() for line in field_cells.splitlines()]
height = len(field_rows)
width = len(field_rows[0])
play_field = {}
for y, line in enumerate(field_rows):
for x, cell in enumerate(line):
if cell == '#':
content = Blocker
else:
if cell == 'E':
content = End
elif cell == 'S':
content = Start
elif cell == '+':
content = Blocker
else:
content = None
play_field[x*2, y*2] = content
play_field[x*2+1, y*2] = content
play_field[x*2, y*2+1] = content
play_field[x*2+1, y*2+1] = content
path = Path.determine_path(play_field, width*2, height*2)
path.dump()
print path.get_neighbors(7, 13)
print 'TEST BLOCKING MODS'
path.dump(set(((18, 8), (19, 8), (18, 9), (19, 9))))
assert path.test_mod(()) == True
assert path.test_mod(((18, 8), (19, 8), (18, 9), (19, 9))) == False
assert path.test_mod(((0, 8), (0, 8), (1, 9), (1, 9))) == True
| Python |
import operator
from pyglet import gl, event
import spryte
import tilemap
class View(object):
'''Render a flat view of a scene2d.Scene.
Attributes:
scene -- a scene2d.Scene instance
allow_oob -- indicates whether the viewport will allow
viewing of out-of-bounds tile positions (ie.
for which there is no tile image). If set to
False then the map will not scroll to attempt
to display oob tiles.
fx, fy | focus -- pixel point to center in the viewport, subject
to OOB checks
'''
def __init__(self, x, y, width, height, allow_oob=False,
fx=0, fy=0, layers=None, near=-50, far=50):
super(View, self).__init__()
self.x, self.y = x, y
self.width, self.height = width, height
self.near, self.far = near, far
self.allow_oob = allow_oob
self.fx, self.fy = fx, fy
if layers is None:
self.layers = []
else:
self.layers = layers
for layer in layers:
if not hasattr(layer, 'z'): layer.z = 0
self.layers.sort(key=operator.attrgetter('z'))
def on_resize(self, width, height):
self.width, self.height = width, height
return event.EVENT_UNHANDLED
@classmethod
def for_window(cls, window, **kw):
'''Create a view which is the same dimensions as the supplied
window.'''
return cls(0, 0, window.width, window.height, **kw)
def __repr__(self):
return '<%s object at 0x%x focus=(%d,%d) oob=%s>'%(
self.__class__.__name__, id(self), self.fx, self.fy,
self.allow_oob)
#
# QUERY INTERFACE
#
def translate_position(self, x, y):
'''Translate the on-screen pixel position to a scene pixel
position.'''
fx, fy = self._determine_focus()
ox, oy = self.width/2-fx, self.height/2-fy
return (int(x - ox), int(y - oy))
def get(self, x, y):
''' Pick whatever is on the top at the position x, y. '''
r = []
for layer in self.layers:
cell = layer.get(x, y)
if cell:
r.append(cell)
return r
def add_layer(self, layer, z):
layer.z = z
self.layers.append(layer)
def remove_layer(self, layer):
self.layers.remove(layer)
def get_layer(self, z):
'''Get a layer for the specified Z depth, adding it if necessary.
'''
for layer in self.layers:
if layer.z == z:
break
else:
layer = spryte.SpriteBatch()
layer.z = z
self.layers.append(layer)
self.layers.sort(key=operator.attrgetter('z'))
return layer
def add_sprite(self, im, x, y, z=0, klass=spryte.Sprite, **kw):
layer = self.get_layer(z)
return klass(im, x, y, batch=layer, **kw)
def add_map(self, im, cells, z=0, **kw):
map = tilemap.Map.from_imagegrid(im, cells, **kw)
map.z = z
self.layers.append(map)
self.layers.sort(key=operator.attrgetter('z'))
return map
def cell_at(self, x, y):
' query for a map cell at given screen pixel position '
raise NotImplemented()
def sprite_at(self, x, y):
' query for sprite at given screen pixel position '
raise NotImplemented()
#
# FOCUS ADJUSTMENT
#
def _determine_focus(self):
'''Determine the focal point of the view based on foxus (fx, fy),
allow_oob and maps.
Note that this method does not actually change the focus attributes
fx and fy.
'''
# enforce int-only positioning of focus
fx = int(self.fx)
fy = int(self.fy)
if self.allow_oob: return (fx, fy)
# check that any layer has bounds
bounded = []
for layer in self.layers:
# XXX isinstance Map instead?
if hasattr(layer, 'pixel_width'):
bounded.append(layer)
if not bounded:
return (fx, fy)
# figure the bounds min/max
m = bounded[0]
b_min_x = m.x
b_min_y = m.y
b_max_x = m.x + m.pixel_width
b_max_y = m.y + m.pixel_height
for m in bounded[1:]:
b_min_x = min(b_min_x, m.x)
b_min_y = min(b_min_y, m.y)
b_max_x = min(b_max_x, m.x + m.pixel_width)
b_max_y = min(b_max_y, m.y + m.pixel_height)
# figure the view min/max based on focus
w2 = self.width/2
h2 = self.height/2
v_min_x = fx - w2
v_min_y = fy - h2
x_moved = y_moved = False
if v_min_x < b_min_x:
fx += b_min_x - v_min_x
x_moved = True
if v_min_y < b_min_y:
fy += b_min_y - v_min_y
y_moved = True
v_max_x = fx + w2
v_max_y = fy + h2
if not x_moved and v_max_x > b_max_x:
fx -= v_max_x - b_max_x
if not y_moved and v_max_y > b_max_y:
fy -= v_max_y - b_max_y
return map(int, (fx, fy))
def set_focus(self, value):
self.fx, self.fy = value
focus = property(lambda self: (self.fx, self.fy), set_focus)
def draw(self):
# set up projection
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glViewport(self.x, self.y, self.width, self.height)
gl.glOrtho(0, self.width, 0, self.height, self.near, self.far)
gl.glMatrixMode(gl.GL_MODELVIEW)
fx, fy = self._determine_focus()
w2 = self.width/2
h2 = self.height/2
x1, y1 = fx - w2, fy - h2
x2, y2 = fx + w2, fy + h2
gl.glPushMatrix()
gl.glTranslatef(self.width/2-fx, self.height/2-fy, 0)
for layer in self.layers:
if hasattr(layer, 'x'):
translate = layer.x or layer.y
else:
translate = False
if translate:
gl.glPushMatrix()
gl.glTranslatef(layer.x, layer.y, 0)
layer.draw()
if translate:
gl.glPopMatrix()
gl.glPopMatrix()
| Python |
import sys
import random
import math
from pyglet import window
from pyglet import clock
from pyglet import resource
import spryte
NUM_CARS = 100
if len(sys.argv) > 1:
NUM_CARS = int(sys.argv[1])
win = window.Window(vsync=False)
fps = clock.ClockDisplay(color=(1, 1, 1, 1))
cars = spryte.SpriteBatch()
car = resource.image('car.png')
car.anchor_x = 16
car.anchor_y = 20
for i in range(NUM_CARS):
s = spryte.Sprite(car,
win.width*random.random(), win.height*random.random(),
batch=cars, dr=-45 + random.random()*90)
while not win.has_exit:
win.dispatch_events()
clock.tick()
win.clear()
for car in cars:
car.rotation = (car.rotation + car.dr) % 360
cars.draw()
fps.draw()
win.flip()
| Python |
from pyglet import image
import spryte
class Map(spryte.SpriteBatch):
'''Rectangular map.
"cells" argument must be a row-major list of lists of Sprite instances.
'''
def set_cells(self, cell_width, cell_height, cells, origin=None):
self.cell_width, self.cell_height = cell_width, cell_height
if origin is None:
origin = (0, 0)
self.x, self.y = origin
self.cells = cells
self.pixel_width = len(cells[0]) * cell_width
self.pixel_height = len(cells) * cell_height
def get_cell(self, x, y):
''' Return Cell at cell pos=(x,y).
Return None if out of bounds.'''
if x < 0 or y < 0:
return None
try:
return self.cells[y][x]
except IndexError:
return None
def get_in_region(self, x1, y1, x2, y2):
'''Return cells that are within the pixel bounds specified by the
bottom-left (x1, y1) and top-right (x2, y2) corners.
'''
x1 = max(0, x1 // self.cell_width)
y1 = max(0, y1 // self.cell_height)
x2 = min(len(self.cells[0]), x2 // self.cell_width + 1)
y2 = min(len(self.cells), y2 // self.cell_height + 1)
return [self.cells[y][x] for x in range(x1, x2) for y in range(y1, y2)]
def get(self, x, y):
''' Return Cell at pixel px=(x,y).
Return None if out of bounds.'''
return self.get_cell(x // self.cell_width, y // self.cell_height)
UP = (0, 1)
DOWN = (0, -1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def get_neighbor(self, cell, direction):
'''Get the neighbor Cell in the given direction (dx, dy) which
is one of self.UP, self.DOWN, self.LEFT or self.RIGHT.
Returns None if out of bounds.
'''
dx, dy = direction
return self.get_cell(cell.x//self.cell_width + dx,
cell.y//self.cell_height + dy)
def delete(self):
for row in self.cells:
for cell in row:
cell.delete()
self.cells = []
@classmethod
def from_imagegrid(cls, im, cells, file=None, origin=None):
'''Initialise the map using an image the image grid.
Both the image grid and the map cells have y=0 at the bottom of
the grid / map.
Return a Map instance.'''
texture_sequence = im.texture_sequence
l = []
cw, ch = texture_sequence.item_width, texture_sequence.item_height
inst = cls()
for y, row in enumerate(cells):
m = []
l.append(m)
for x, num in enumerate(row):
m.append(spryte.Sprite(texture_sequence[num], x*cw, y*ch,
map=inst, batch=inst))
inst.set_cells(cw, ch, l, origin)
return inst
| Python |
import math
import pyglet
from pyglet.gl import *
class SmoothLineGroup(pyglet.graphics.Group):
def set_state(self):
glPushAttrib(GL_ENABLE_BIT)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
glLineWidth(2)
def unset_state(self):
glPopAttrib()
def __hash__(self):
return hash(self.__class__.__name__)
def __eq__(self, other):
return self.__class__ is other.__class__
def add_circle(batch, x, y, radius, color, num_points=20, antialised=True):
l = []
for n in range(num_points):
angle = (math.pi * 2 * n) / num_points
l.append(int(x + radius * math.cos(angle)))
l.append(int(y + radius * math.sin(angle)))
l.append(int(x + radius * 1))
l.append(int(y))
num_points += 3
l[0:0] = l[0:2]
l.extend(l[-2:])
if antialised:
group = SmoothLineGroup()
else:
group = None
return batch.add(num_points, GL_LINE_STRIP, group, ('v2i', l),
('c4B', color*num_points))
| Python |
'''
Code by Richard Jones, released into the public domain.
Inspired by http://screamyguy.net/lines/index.htm
This code uses a single drawing buffer so that successive drawing passes
may be used to create the line fading effect. The fading is achieved
by drawing a translucent black quad over the entire scene before drawing
the next line segment.
Note: when working with a single buffer it is always a good idea to
glFlush() when you've finished your rendering.
'''
import sys
import random
import pyglet
from pyglet.gl import *
# open a single-buffered window so we can do cheap accumulation
config = Config(double_buffer=False)
window = pyglet.window.Window(fullscreen='-fs' in sys.argv, config=config)
class Line(object):
batch = pyglet.graphics.Batch()
lines = batch.add(100, GL_LINES, None, ('v2f', (0.0,) * 200), ('c4B', (255, ) * 400))
unallocated = range(100)
active = []
def __init__(self):
self.n = self.unallocated.pop()
self.active.append(self)
self.x = self.lx = random.randint(0, window.width)
self.y = self.ly = random.randint(0, window.height)
self.dx = random.randint(-70, 70)
self.dy = random.randint(-70, 70)
self.damping = random.random() * .15 + .8
self.power = random.random() * .1 + .05
def update(self, dt):
# calculate my acceleration based on the distance to the mouse
# pointer and my acceleration power
dx2 = (self.x - self.mouse_x) / self.power
dy2 = (self.y - self.mouse_y) / self.power
# now figure my new velocity
self.dx -= dx2 * dt
self.dy -= dy2 * dt
self.dx *= self.damping
self.dy *= self.damping
# calculate new line endpoints
self.lx = self.x
self.ly = self.y
self.x += self.dx * dt
self.y += self.dy * dt
@classmethod
def on_draw(cls):
# darken the existing display a little
glColor4f(0, 0, 0, .05)
glRectf(0, 0, window.width, window.height)
# render the new lines
cls.batch.draw()
glFlush()
mouse_x = mouse_y = 0
@classmethod
def on_mouse_motion(cls, x, y, dx, dy):
cls.mouse_x, cls.mouse_y = x, y
@classmethod
def tick(cls, dt):
if len(cls.active) < 50 and random.random() < .1:
cls()
if len(cls.active) > 10 and random.random() < .01:
line = cls.active.pop(0)
cls.unallocated.append(line.n)
# update line positions
n = len(cls.active)
for n, line in enumerate(cls.active):
line.update(dt)
cls.lines.vertices[n*4:n*4+4] = [line.lx, line.ly, line.x, line.y]
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
# need to set a FPS limit since we're not going to be limited by VSYNC in single-buffer mode
pyglet.clock.set_fps_limit(30)
pyglet.clock.schedule(Line.tick)
window.push_handlers(Line)
pyglet.app.run()
| Python |
'''
Code by Richard Jones, released into the public domain.
Beginnings of something like http://en.wikipedia.org/wiki/Thrust_(video_game)
'''
import sys
import math
import euclid
import primitives
import pyglet
from pyglet.window import key
from pyglet.gl import *
window = pyglet.window.Window(fullscreen='-fs' in sys.argv)
GRAVITY = -200
class Game(object):
def __init__(self):
self.batch = pyglet.graphics.Batch()
self.ship = Ship(window.width//2, window.height//2, self.batch)
self.debug_text = pyglet.text.Label('debug text', x=10, y=window.height-40, batch=self.batch)
def on_draw(self):
window.clear()
self.batch.draw()
def update(self, dt):
self.ship.update(dt)
class Ship(object):
def __init__(self, x, y, batch):
self.position = euclid.Point2(x, y)
self.velocity = euclid.Point2(0, 0)
self.angle = math.pi/2
self.batch = batch
self.lines = batch.add(6, GL_LINES, primitives.SmoothLineGroup(),
('v2f', (0, 0) * 6),
('c4B', (255, 255, 255, 255) * 6))
self.ball_position = euclid.Point2(window.width/2, window.height/4)
self.ball_velocity = euclid.Point2(0, 0)
self.ball_lines = primitives.add_circle(batch, 0, 0, 20, (255, 255, 255, 255), 20)
self._ball_verts = list(self.ball_lines.vertices)
self._update_ball_verts()
self.join_active = False
self.join_line = None
self.joined = False
def update(self, dt):
self.angle += (keyboard[key.LEFT] - keyboard[key.RIGHT]) * math.pi * dt
r = euclid.Matrix3.new_rotate(self.angle)
if keyboard[key.UP]:
thrust = r * euclid.Vector2(600, 0)
else:
thrust = euclid.Vector2(0, 0)
# attempt join on spacebar press
s_b = self.position - self.ball_position
if keyboard[key.SPACE] and abs(s_b) < 100:
self.join_active = True
if not self.joined:
# simulation is just the ship
# apply thrust to the ship directly
thrust.y += GRAVITY
# now figure my new velocity
self.velocity += thrust * dt
# calculate new line endpoints
self.position += self.velocity * dt
else:
# simulation is of a rod with ship and one end and ball at other
n_v = s_b.normalized()
n_t = thrust.normalized()
# figure the linear acceleration, velocity & move
d = abs(n_v.dot(n_t))
lin = thrust * d
lin.y += GRAVITY
self.velocity += lin * dt
self.cog += self.velocity * dt
# now the angular acceleration
r90 = euclid.Matrix3.new_rotate(math.pi/2)
r_n_t = r90 * n_t
rd = n_v.dot(r_n_t)
self.ang_velocity -= abs(abs(thrust)) * rd * 0.0001
self.join_angle += self.ang_velocity * dt
# vector from center of gravity our to either end
ar = euclid.Matrix3.new_rotate(self.join_angle)
a_r = ar * euclid.Vector2(self.join_length/2, 0)
# set the ship & ball positions
self.position = self.cog + a_r
self.ball_position = self.cog - a_r
self._update_ball_verts()
if self.join_active:
if abs(s_b) >= 100 and not self.joined:
self.joined = True
h_s_b = s_b / 2
self.cog = self.position - h_s_b
self.join_angle = math.atan2(s_b.y, s_b.x)
self.join_length = abs(s_b)
# mass just doubled, so slow linear velocity down
self.velocity /= 2
# XXX and generate some initial angular velocity based on
# XXX ship current velocity
self.ang_velocity = 0
# render the join line
l = [
self.position.x, self.position.y,
self.ball_position.x, self.ball_position.y
]
if self.join_line:
self.join_line.vertices[:] = l
else:
self.join_line = self.batch.add(2, GL_LINES, primitives.SmoothLineGroup(),
('v2f', l), ('c4B', (255, 255, 255, 255) * 2))
# update the ship verts
bl = r * euclid.Point2(-25, 25)
t = r * euclid.Point2(25, 0)
br = r * euclid.Point2(-25, -25)
x, y = self.position
self.lines.vertices[:] = [
x+bl.x, y+bl.y, x+t.x, y+t.y,
x+t.x, y+t.y, x+br.x, y+br.y,
x+br.x, y+br.y, x+bl.x, y+bl.y,
]
def _update_ball_verts(self):
# update the ball for its position
l = []
x, y = self.ball_position
for i, v in enumerate(self._ball_verts):
if i % 2:
l.append(int(v + y))
else:
l.append(int(v + x))
self.ball_lines.vertices[:] = l
g = Game()
window.push_handlers(g)
pyglet.clock.schedule(g.update)
keyboard = key.KeyStateHandler()
window.push_handlers(keyboard)
pyglet.app.run()
| Python |
#!/usr/bin/env python
#
# euclid graphics maths module
#
# Copyright (c) 2006 Alex Holkner
# Alex.Holkner@mail.google.com
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
#
# This library 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 Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''euclid graphics maths module
Documentation and tests are included in the file "euclid.txt", or online
at http://code.google.com/p/pyeuclid
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
__revision__ = '$Revision$'
import math
import operator
import types
# Some magic here. If _use_slots is True, the classes will derive from
# object and will define a __slots__ class variable. If _use_slots is
# False, classes will be old-style and will not define __slots__.
#
# _use_slots = True: Memory efficient, probably faster in future versions
# of Python, "better".
# _use_slots = False: Ordinary classes, much faster than slots in current
# versions of Python (2.4 and 2.5).
_use_slots = True
# If True, allows components of Vector2 and Vector3 to be set via swizzling;
# e.g. v.xyz = (1, 2, 3). This is much, much slower than the more verbose
# v.x = 1; v.y = 2; v.z = 3, and slows down ordinary element setting as
# well. Recommended setting is False.
_enable_swizzle_set = False
# Requires class to derive from object.
if _enable_swizzle_set:
_use_slots = True
# Implement _use_slots magic.
class _EuclidMetaclass(type):
def __new__(cls, name, bases, dct):
if '__slots__' in dct:
dct['__getstate__'] = cls._create_getstate(dct['__slots__'])
dct['__setstate__'] = cls._create_setstate(dct['__slots__'])
if _use_slots:
return type.__new__(cls, name, bases + (object,), dct)
else:
if '__slots__' in dct:
del dct['__slots__']
return types.ClassType.__new__(types.ClassType, name, bases, dct)
@classmethod
def _create_getstate(cls, slots):
def __getstate__(self):
d = {}
for slot in slots:
d[slot] = getattr(self, slot)
return d
return __getstate__
@classmethod
def _create_setstate(cls, slots):
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
return __setstate__
__metaclass__ = _EuclidMetaclass
class Vector2:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
def __copy__(self):
return self.__class__(self.x, self.y)
copy = __copy__
def __repr__(self):
return 'Vector2(%.2f, %.2f)' % (self.x, self.y)
def __eq__(self, other):
if isinstance(other, Vector2):
return self.x == other.x and \
self.y == other.y
else:
assert hasattr(other, '__len__') and len(other) == 2
return self.x == other[0] and \
self.y == other[1]
def __ne__(self, other):
return not self.__eq__(other)
def __nonzero__(self):
return self.x != 0 or self.y != 0
def __len__(self):
return 2
def __getitem__(self, key):
return (self.x, self.y)[key]
def __setitem__(self, key, value):
l = [self.x, self.y]
l[key] = value
self.x, self.y = l
def __iter__(self):
return iter((self.x, self.y))
def __getattr__(self, name):
try:
return tuple([(self.x, self.y)['xy'.index(c)] \
for c in name])
except ValueError:
raise AttributeError, name
if _enable_swizzle_set:
# This has detrimental performance on ordinary setattr as well
# if enabled
def __setattr__(self, name, value):
if len(name) == 1:
object.__setattr__(self, name, value)
else:
try:
l = [self.x, self.y]
for c, v in map(None, name, value):
l['xy'.index(c)] = v
self.x, self.y = l
except ValueError:
raise AttributeError, name
def __add__(self, other):
if isinstance(other, Vector2):
return Vector2(self.x + other.x,
self.y + other.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(self.x + other[0],
self.y + other[1])
__radd__ = __add__
def __iadd__(self, other):
if isinstance(other, Vector2):
self.x += other.x
self.y += other.y
else:
self.x += other[0]
self.y += other[1]
return self
def __sub__(self, other):
if isinstance(other, Vector2):
return Vector2(self.x - other.x,
self.y - other.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(self.x - other[0],
self.y - other[1])
def __rsub__(self, other):
if isinstance(other, Vector2):
return Vector2(other.x - self.x,
other.y - self.y)
else:
assert hasattr(other, '__len__') and len(other) == 2
return Vector2(other.x - self[0],
other.y - self[1])
def __mul__(self, other):
assert type(other) in (int, long, float)
return Vector2(self.x * other,
self.y * other)
__rmul__ = __mul__
def __imul__(self, other):
assert type(other) in (int, long, float)
self.x *= other
self.y *= other
return self
def __div__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.div(self.x, other),
operator.div(self.y, other))
def __rdiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.div(other, self.x),
operator.div(other, self.y))
def __floordiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.floordiv(self.x, other),
operator.floordiv(self.y, other))
def __rfloordiv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.floordiv(other, self.x),
operator.floordiv(other, self.y))
def __truediv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.truediv(self.x, other),
operator.truediv(self.y, other))
def __rtruediv__(self, other):
assert type(other) in (int, long, float)
return Vector2(operator.truediv(other, self.x),
operator.truediv(other, self.y))
def __neg__(self):
return Vector2(-self.x,
-self.y)
__pos__ = __copy__
def __abs__(self):
return math.sqrt(self.x ** 2 + \
self.y ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.x ** 2 + \
self.y ** 2
def normalize(self):
d = self.magnitude()
if d:
self.x /= d
self.y /= d
return self
def normalized(self):
d = self.magnitude()
if d:
return Vector2(self.x / d,
self.y / d)
return self.copy()
def dot(self, other):
assert isinstance(other, Vector2)
return self.x * other.x + \
self.y * other.y
def cross(self):
return Vector2(self.y, -self.x)
def reflect(self, normal):
# assume normal is normalized
assert isinstance(normal, Vector2)
d = 2 * (self.x * normal.x + self.y * normal.y)
return Vector2(self.x - d * normal.x,
self.y - d * normal.y)
class Vector3:
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __copy__(self):
return self.__class__(self.x, self.y, self.z)
copy = __copy__
def __repr__(self):
return 'Vector3(%.2f, %.2f, %.2f)' % (self.x,
self.y,
self.z)
def __eq__(self, other):
if isinstance(other, Vector3):
return self.x == other.x and \
self.y == other.y and \
self.z == other.z
else:
assert hasattr(other, '__len__') and len(other) == 3
return self.x == other[0] and \
self.y == other[1] and \
self.z == other[2]
def __ne__(self, other):
return not self.__eq__(other)
def __nonzero__(self):
return self.x != 0 or self.y != 0 or self.z != 0
def __len__(self):
return 3
def __getitem__(self, key):
return (self.x, self.y, self.z)[key]
def __setitem__(self, key, value):
l = [self.x, self.y, self.z]
l[key] = value
self.x, self.y, self.z = l
def __iter__(self):
return iter((self.x, self.y, self.z))
def __getattr__(self, name):
try:
return tuple([(self.x, self.y, self.z)['xyz'.index(c)] \
for c in name])
except ValueError:
raise AttributeError, name
if _enable_swizzle_set:
# This has detrimental performance on ordinary setattr as well
# if enabled
def __setattr__(self, name, value):
if len(name) == 1:
object.__setattr__(self, name, value)
else:
try:
l = [self.x, self.y, self.z]
for c, v in map(None, name, value):
l['xyz'.index(c)] = v
self.x, self.y, self.z = l
except ValueError:
raise AttributeError, name
def __add__(self, other):
if isinstance(other, Vector3):
# Vector + Vector -> Vector
# Vector + Point -> Point
# Point + Point -> Vector
if self.__class__ is other.__class__:
_class = Vector3
else:
_class = Point3
return _class(self.x + other.x,
self.y + other.y,
self.z + other.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(self.x + other[0],
self.y + other[1],
self.z + other[2])
__radd__ = __add__
def __iadd__(self, other):
if isinstance(other, Vector3):
self.x += other.x
self.y += other.y
self.z += other.z
else:
self.x += other[0]
self.y += other[1]
self.z += other[2]
return self
def __sub__(self, other):
if isinstance(other, Vector3):
# Vector - Vector -> Vector
# Vector - Point -> Point
# Point - Point -> Vector
if self.__class__ is other.__class__:
_class = Vector3
else:
_class = Point3
return Vector3(self.x - other.x,
self.y - other.y,
self.z - other.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(self.x - other[0],
self.y - other[1],
self.z - other[2])
def __rsub__(self, other):
if isinstance(other, Vector3):
return Vector3(other.x - self.x,
other.y - self.y,
other.z - self.z)
else:
assert hasattr(other, '__len__') and len(other) == 3
return Vector3(other.x - self[0],
other.y - self[1],
other.z - self[2])
def __mul__(self, other):
if isinstance(other, Vector3):
# TODO component-wise mul/div in-place and on Vector2; docs.
if self.__class__ is Point3 or other.__class__ is Point3:
_class = Point3
else:
_class = Vector3
return _class(self.x * other.x,
self.y * other.y,
self.z * other.z)
else:
assert type(other) in (int, long, float)
return Vector3(self.x * other,
self.y * other,
self.z * other)
__rmul__ = __mul__
def __imul__(self, other):
assert type(other) in (int, long, float)
self.x *= other
self.y *= other
self.z *= other
return self
def __div__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.div(self.x, other),
operator.div(self.y, other),
operator.div(self.z, other))
def __rdiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.div(other, self.x),
operator.div(other, self.y),
operator.div(other, self.z))
def __floordiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.floordiv(self.x, other),
operator.floordiv(self.y, other),
operator.floordiv(self.z, other))
def __rfloordiv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.floordiv(other, self.x),
operator.floordiv(other, self.y),
operator.floordiv(other, self.z))
def __truediv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.truediv(self.x, other),
operator.truediv(self.y, other),
operator.truediv(self.z, other))
def __rtruediv__(self, other):
assert type(other) in (int, long, float)
return Vector3(operator.truediv(other, self.x),
operator.truediv(other, self.y),
operator.truediv(other, self.z))
def __neg__(self):
return Vector3(-self.x,
-self.y,
-self.z)
__pos__ = __copy__
def __abs__(self):
return math.sqrt(self.x ** 2 + \
self.y ** 2 + \
self.z ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.x ** 2 + \
self.y ** 2 + \
self.z ** 2
def normalize(self):
d = self.magnitude()
if d:
self.x /= d
self.y /= d
self.z /= d
return self
def normalized(self):
d = self.magnitude()
if d:
return Vector3(self.x / d,
self.y / d,
self.z / d)
return self.copy()
def dot(self, other):
assert isinstance(other, Vector3)
return self.x * other.x + \
self.y * other.y + \
self.z * other.z
def cross(self, other):
assert isinstance(other, Vector3)
return Vector3(self.y * other.z - self.z * other.y,
-self.x * other.z + self.z * other.x,
self.x * other.y - self.y * other.x)
def reflect(self, normal):
# assume normal is normalized
assert isinstance(normal, Vector3)
d = 2 * (self.x * normal.x + self.y * normal.y + self.z * normal.z)
return Vector3(self.x - d * normal.x,
self.y - d * normal.y,
self.z - d * normal.z)
class AffineVector3(Vector3):
w = 1
def __repr__(self):
return 'Vector3(%.2f, %.2f, %.2f, 1.00)' % (self.x,
self.y,
self.z)
def __len__(self):
return 4
def __getitem__(self, key):
return (self.x, self.y, self.z, 1)[key]
def __iter__(self):
return iter((self.x, self.y, self.z, 1))
# a b c
# e f g
# i j k
class Matrix3:
__slots__ = list('abcefgijk')
def __init__(self):
self.identity()
def __copy__(self):
M = Matrix3()
M.a = self.a
M.b = self.b
M.c = self.c
M.e = self.e
M.f = self.f
M.g = self.g
M.i = self.i
M.j = self.j
M.k = self.k
return M
copy = __copy__
def __repr__(self):
return ('Matrix3([% 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f])') \
% (self.a, self.b, self.c,
self.e, self.f, self.g,
self.i, self.j, self.k)
def __getitem__(self, key):
return [self.a, self.e, self.i,
self.b, self.f, self.j,
self.c, self.g, self.k][key]
def __setitem__(self, key, value):
L = self[:]
L[key] = value
(self.a, self.e, self.i,
self.b, self.f, self.j,
self.c, self.g, self.k) = L
def __mul__(self, other):
if isinstance(other, Matrix3):
# Caching repeatedly accessed attributes in local variables
# apparently increases performance by 20%. Attrib: Will McGugan.
Aa = self.a
Ab = self.b
Ac = self.c
Ae = self.e
Af = self.f
Ag = self.g
Ai = self.i
Aj = self.j
Ak = self.k
Ba = other.a
Bb = other.b
Bc = other.c
Be = other.e
Bf = other.f
Bg = other.g
Bi = other.i
Bj = other.j
Bk = other.k
C = Matrix3()
C.a = Aa * Ba + Ab * Be + Ac * Bi
C.b = Aa * Bb + Ab * Bf + Ac * Bj
C.c = Aa * Bc + Ab * Bg + Ac * Bk
C.e = Ae * Ba + Af * Be + Ag * Bi
C.f = Ae * Bb + Af * Bf + Ag * Bj
C.g = Ae * Bc + Af * Bg + Ag * Bk
C.i = Ai * Ba + Aj * Be + Ak * Bi
C.j = Ai * Bb + Aj * Bf + Ak * Bj
C.k = Ai * Bc + Aj * Bg + Ak * Bk
return C
elif isinstance(other, Point2):
A = self
B = other
P = Point2(0, 0)
P.x = A.a * B.x + A.b * B.y + A.c
P.y = A.e * B.x + A.f * B.y + A.g
return P
elif isinstance(other, Vector2):
A = self
B = other
V = Vector2(0, 0)
V.x = A.a * B.x + A.b * B.y
V.y = A.e * B.x + A.f * B.y
return V
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Matrix3)
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ae = self.e
Af = self.f
Ag = self.g
Ai = self.i
Aj = self.j
Ak = self.k
Ba = other.a
Bb = other.b
Bc = other.c
Be = other.e
Bf = other.f
Bg = other.g
Bi = other.i
Bj = other.j
Bk = other.k
self.a = Aa * Ba + Ab * Be + Ac * Bi
self.b = Aa * Bb + Ab * Bf + Ac * Bj
self.c = Aa * Bc + Ab * Bg + Ac * Bk
self.e = Ae * Ba + Af * Be + Ag * Bi
self.f = Ae * Bb + Af * Bf + Ag * Bj
self.g = Ae * Bc + Af * Bg + Ag * Bk
self.i = Ai * Ba + Aj * Be + Ak * Bi
self.j = Ai * Bb + Aj * Bf + Ak * Bj
self.k = Ai * Bc + Aj * Bg + Ak * Bk
return self
def identity(self):
self.a = self.f = self.k = 1.
self.b = self.c = self.e = self.g = self.i = self.j = 0
return self
def scale(self, x, y):
self *= Matrix3.new_scale(x, y)
return self
def translate(self, x, y):
self *= Matrix3.new_translate(x, y)
return self
def rotate(self, angle):
self *= Matrix3.new_rotate(angle)
return self
# Static constructors
def new_identity(cls):
self = cls()
return self
new_identity = classmethod(new_identity)
def new_scale(cls, x, y):
self = cls()
self.a = x
self.f = y
return self
new_scale = classmethod(new_scale)
def new_translate(cls, x, y):
self = cls()
self.c = x
self.g = y
return self
new_translate = classmethod(new_translate)
def new_rotate(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.f = c
self.b = -s
self.e = s
return self
new_rotate = classmethod(new_rotate)
# a b c d
# e f g h
# i j k l
# m n o p
class Matrix4:
__slots__ = list('abcdefghijklmnop')
def __init__(self):
self.identity()
def __copy__(self):
M = Matrix4()
M.a = self.a
M.b = self.b
M.c = self.c
M.d = self.d
M.e = self.e
M.f = self.f
M.g = self.g
M.h = self.h
M.i = self.i
M.j = self.j
M.k = self.k
M.l = self.l
M.m = self.m
M.n = self.n
M.o = self.o
M.p = self.p
return M
copy = __copy__
def __repr__(self):
return ('Matrix4([% 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
' % 8.2f % 8.2f % 8.2f % 8.2f])') \
% (self.a, self.b, self.c, self.d,
self.e, self.f, self.g, self.h,
self.i, self.j, self.k, self.l,
self.m, self.n, self.o, self.p)
def __getitem__(self, key):
return [self.a, self.e, self.i, self.m,
self.b, self.f, self.j, self.n,
self.c, self.g, self.k, self.o,
self.d, self.h, self.l, self.p][key]
def __setitem__(self, key, value):
assert not isinstance(key, slice) or \
key.stop - key.start == len(value), 'key length != value length'
L = self[:]
L[key] = value
(self.a, self.e, self.i, self.m,
self.b, self.f, self.j, self.n,
self.c, self.g, self.k, self.o,
self.d, self.h, self.l, self.p) = L
def __mul__(self, other):
if isinstance(other, Matrix4):
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ad = self.d
Ae = self.e
Af = self.f
Ag = self.g
Ah = self.h
Ai = self.i
Aj = self.j
Ak = self.k
Al = self.l
Am = self.m
An = self.n
Ao = self.o
Ap = self.p
Ba = other.a
Bb = other.b
Bc = other.c
Bd = other.d
Be = other.e
Bf = other.f
Bg = other.g
Bh = other.h
Bi = other.i
Bj = other.j
Bk = other.k
Bl = other.l
Bm = other.m
Bn = other.n
Bo = other.o
Bp = other.p
C = Matrix4()
C.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
C.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
C.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
C.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
C.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
C.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
C.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
C.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
C.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
C.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
C.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
C.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
C.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
C.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
C.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
C.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
return C
elif isinstance(other, Point3):
A = self
B = other
P = Point3(0, 0, 0)
P.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d
P.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h
P.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l
return P
elif isinstance(other, AffineVector3):
A = self
B = other
V = AffineVector3(0, 0, 0)
V.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d * B.w
V.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h * B.w
V.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l * B.w
return V
elif isinstance(other, Vector3):
A = self
B = other
V = Vector3(0, 0, 0)
V.x = A.a * B.x + A.b * B.y + A.c * B.z
V.y = A.e * B.x + A.f * B.y + A.g * B.z
V.z = A.i * B.x + A.j * B.y + A.k * B.z
return V
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Matrix4)
# Cache attributes in local vars (see Matrix3.__mul__).
Aa = self.a
Ab = self.b
Ac = self.c
Ad = self.d
Ae = self.e
Af = self.f
Ag = self.g
Ah = self.h
Ai = self.i
Aj = self.j
Ak = self.k
Al = self.l
Am = self.m
An = self.n
Ao = self.o
Ap = self.p
Ba = other.a
Bb = other.b
Bc = other.c
Bd = other.d
Be = other.e
Bf = other.f
Bg = other.g
Bh = other.h
Bi = other.i
Bj = other.j
Bk = other.k
Bl = other.l
Bm = other.m
Bn = other.n
Bo = other.o
Bp = other.p
self.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
self.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
self.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
self.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
self.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
self.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
self.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
self.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
self.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
self.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
self.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
self.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
self.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
self.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
self.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
self.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
return self
def identity(self):
self.a = self.f = self.k = self.p = 1.
self.b = self.c = self.d = self.e = self.g = self.h = \
self.i = self.j = self.l = self.m = self.n = self.o = 0
return self
def scale(self, x, y, z):
self *= Matrix4.new_scale(x, y, z)
return self
def translate(self, x, y, z):
self *= Matrix4.new_translate(x, y, z)
return self
def rotatex(self, angle):
self *= Matrix4.new_rotatex(angle)
return self
def rotatey(self, angle):
self *= Matrix4.new_rotatey(angle)
return self
def rotatez(self, angle):
self *= Matrix4.new_rotatez(angle)
return self
def rotate_axis(self, angle, axis):
self *= Matrix4.new_rotate_axis(angle, axis)
return self
def rotate_euler(self, heading, attitude, bank):
self *= Matrix4.new_rotate_euler(heading, attitude, bank)
return self
# Static constructors
def new_identity(cls):
self = cls()
return self
new_identity = classmethod(new_identity)
def new_scale(cls, x, y, z):
self = cls()
self.a = x
self.f = y
self.k = z
return self
new_scale = classmethod(new_scale)
def new_translate(cls, x, y, z):
self = cls()
self.d = x
self.h = y
self.l = z
return self
new_translate = classmethod(new_translate)
def new_rotatex(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.f = self.k = c
self.g = -s
self.j = s
return self
new_rotatex = classmethod(new_rotatex)
def new_rotatey(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.k = c
self.c = s
self.i = -s
return self
new_rotatey = classmethod(new_rotatey)
def new_rotatez(cls, angle):
self = cls()
s = math.sin(angle)
c = math.cos(angle)
self.a = self.f = c
self.b = -s
self.e = s
return self
new_rotatez = classmethod(new_rotatez)
def new_rotate_axis(cls, angle, axis):
assert(isinstance(axis, Vector3))
vector = axis.normalized()
x = vector.x
y = vector.y
z = vector.z
self = cls()
s = math.sin(angle)
c = math.cos(angle)
c1 = 1. - c
# from the glRotate man page
self.a = x * x * c1 + c
self.b = x * y * c1 - z * s
self.c = x * z * c1 + y * s
self.e = y * x * c1 + z * s
self.f = y * y * c1 + c
self.g = y * z * c1 - x * s
self.i = x * z * c1 - y * s
self.j = y * z * c1 + x * s
self.k = z * z * c1 + c
return self
new_rotate_axis = classmethod(new_rotate_axis)
def new_rotate_euler(cls, heading, attitude, bank):
# from http://www.euclideanspace.com/
ch = math.cos(heading)
sh = math.sin(heading)
ca = math.cos(attitude)
sa = math.sin(attitude)
cb = math.cos(bank)
sb = math.sin(bank)
self = cls()
self.a = ch * ca
self.b = sh * sb - ch * sa * cb
self.c = ch * sa * sb + sh * cb
self.e = sa
self.f = ca * cb
self.g = -ca * sb
self.i = -sh * ca
self.j = sh * sa * cb + ch * sb
self.k = -sh * sa * sb + ch * cb
return self
new_rotate_euler = classmethod(new_rotate_euler)
def new_perspective(cls, fov_y, aspect, near, far):
# from the gluPerspective man page
f = 1 / math.tan(fov_y / 2)
self = cls()
assert near != 0.0 and near != far
self.a = f / aspect
self.f = f
self.k = (far + near) / (near - far)
self.l = 2 * far * near / (near - far)
self.o = -1
self.p = 0
return self
new_perspective = classmethod(new_perspective)
class Quaternion:
# All methods and naming conventions based off
# http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions
# w is the real part, (x, y, z) are the imaginary parts
__slots__ = ['w', 'x', 'y', 'z']
def __init__(self):
self.identity()
def __copy__(self):
Q = Quaternion()
Q.w = self.w
Q.x = self.x
Q.y = self.y
Q.z = self.z
copy = __copy__
def __repr__(self):
return 'Quaternion(real=%.2f, imag=<%.2f, %.2f, %.2f>)' % \
(self.w, self.x, self.y, self.z)
def __mul__(self, other):
if isinstance(other, Quaternion):
Ax = self.x
Ay = self.y
Az = self.z
Aw = self.w
Bx = other.x
By = other.y
Bz = other.z
Bw = other.w
Q = Quaternion()
Q.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
Q.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
Q.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
Q.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
return Q
elif isinstance(other, Vector3):
w = self.w
x = self.x
y = self.y
z = self.z
Vx = other.x
Vy = other.y
Vz = other.z
return other.__class__(\
w * w * Vx + 2 * y * w * Vz - 2 * z * w * Vy + \
x * x * Vx + 2 * y * x * Vy + 2 * z * x * Vz - \
z * z * Vx - y * y * Vx,
2 * x * y * Vx + y * y * Vy + 2 * z * y * Vz + \
2 * w * z * Vx - z * z * Vy + w * w * Vy - \
2 * x * w * Vz - x * x * Vy,
2 * x * z * Vx + 2 * y * z * Vy + \
z * z * Vz - 2 * w * y * Vx - y * y * Vz + \
2 * w * x * Vy - x * x * Vz + w * w * Vz)
else:
other = other.copy()
other._apply_transform(self)
return other
def __imul__(self, other):
assert isinstance(other, Quaternion)
Ax = self.x
Ay = self.y
Az = self.z
Aw = self.w
Bx = other.x
By = other.y
Bz = other.z
Bw = other.w
self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
return self
def __abs__(self):
return math.sqrt(self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2)
magnitude = __abs__
def magnitude_squared(self):
return self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2
def identity(self):
self.w = 1
self.x = 0
self.y = 0
self.z = 0
return self
def rotate_axis(self, angle, axis):
self *= Quaternion.new_rotate_axis(angle, axis)
return self
def rotate_euler(self, heading, attitude, bank):
self *= Quaternion.new_rotate_euler(heading, attitude, bank)
return self
def conjugated(self):
Q = Quaternion()
Q.w = self.w
Q.x = -self.x
Q.y = -self.y
Q.z = -self.z
return Q
def normalize(self):
d = self.magnitude()
if d != 0:
self.w /= d
self.x /= d
self.y /= d
self.z /= d
return self
def normalized(self):
d = self.magnitude()
if d != 0:
Q = Quaternion()
Q.w /= d
Q.x /= d
Q.y /= d
Q.z /= d
return Q
else:
return self.copy()
def get_angle_axis(self):
if self.w > 1:
self = self.normalized()
angle = 2 * math.acos(self.w)
s = math.sqrt(1 - self.w ** 2)
if s < 0.001:
return angle, Vector3(1, 0, 0)
else:
return angle, Vector3(self.x / s, self.y / s, self.z / s)
def get_euler(self):
t = self.x * self.y + self.z * self.w
if t > 0.4999:
heading = 2 * math.atan2(self.x, self.w)
attitude = math.pi / 2
bank = 0
elif t < -0.4999:
heading = -2 * math.atan2(self.x, self.w)
attitude = -math.pi / 2
bank = 0
else:
sqx = self.x ** 2
sqy = self.y ** 2
sqz = self.z ** 2
heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
1 - 2 * sqy - 2 * sqz)
attitude = math.asin(2 * t)
bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
1 - 2 * sqx - 2 * sqz)
return heading, attitude, bank
def get_matrix(self):
xx = self.x ** 2
xy = self.x * self.y
xz = self.x * self.z
xw = self.x * self.w
yy = self.y ** 2
yz = self.y * self.z
yw = self.y * self.w
zz = self.z ** 2
zw = self.z * self.w
M = Matrix4()
M.a = 1 - 2 * (yy + zz)
M.b = 2 * (xy - zw)
M.c = 2 * (xz + yw)
M.e = 2 * (xy + zw)
M.f = 1 - 2 * (xx + zz)
M.g = 2 * (yz - xw)
M.i = 2 * (xz - yw)
M.j = 2 * (yz + xw)
M.k = 1 - 2 * (xx + yy)
return M
# Static constructors
def new_identity(cls):
return cls()
new_identity = classmethod(new_identity)
def new_rotate_axis(cls, angle, axis):
assert(isinstance(axis, Vector3))
axis = axis.normalized()
s = math.sin(angle / 2)
Q = cls()
Q.w = math.cos(angle / 2)
Q.x = axis.x * s
Q.y = axis.y * s
Q.z = axis.z * s
return Q
new_rotate_axis = classmethod(new_rotate_axis)
def new_rotate_euler(cls, heading, attitude, bank):
Q = cls()
c1 = math.cos(heading / 2)
s1 = math.sin(heading / 2)
c2 = math.cos(attitude / 2)
s2 = math.sin(attitude / 2)
c3 = math.cos(bank / 2)
s3 = math.sin(bank / 2)
Q.w = c1 * c2 * c3 - s1 * s2 * s3
Q.x = s1 * s2 * c3 + c1 * c2 * s3
Q.y = s1 * c2 * c3 + c1 * s2 * s3
Q.z = c1 * s2 * c3 - s1 * c2 * s3
return Q
new_rotate_euler = classmethod(new_rotate_euler)
def new_interpolate(cls, q1, q2, t):
assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)
Q = cls()
costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z
theta = math.acos(costheta)
if abs(theta) < 0.01:
Q.w = q2.w
Q.x = q2.x
Q.y = q2.y
Q.z = q2.z
return Q
sintheta = math.sqrt(1.0 - costheta * costheta)
if abs(sintheta) < 0.01:
Q.w = (q1.w + q2.w) * 0.5
Q.x = (q1.x + q2.x) * 0.5
Q.y = (q1.y + q2.y) * 0.5
Q.z = (q1.z + q2.z) * 0.5
return Q
ratio1 = math.sin((1 - t) * theta) / sintheta
ratio2 = math.sin(t * theta) / sintheta
Q.w = q1.w * ratio1 + q2.w * ratio2
Q.x = q1.x * ratio1 + q2.x * ratio2
Q.y = q1.y * ratio1 + q2.y * ratio2
Q.z = q1.z * ratio1 + q2.z * ratio2
return Q
new_interpolate = classmethod(new_interpolate)
# Geometry
# Much maths thanks to Paul Bourke, http://astronomy.swin.edu.au/~pbourke
# ---------------------------------------------------------------------------
class Geometry:
def _connect_unimplemented(self, other):
raise AttributeError, 'Cannot connect %s to %s' % \
(self.__class__, other.__class__)
def _intersect_unimplemented(self, other):
raise AttributeError, 'Cannot intersect %s and %s' % \
(self.__class__, other.__class__)
_intersect_point2 = _intersect_unimplemented
_intersect_line2 = _intersect_unimplemented
_intersect_circle = _intersect_unimplemented
_connect_point2 = _connect_unimplemented
_connect_line2 = _connect_unimplemented
_connect_circle = _connect_unimplemented
_intersect_point3 = _intersect_unimplemented
_intersect_line3 = _intersect_unimplemented
_intersect_sphere = _intersect_unimplemented
_intersect_plane = _intersect_unimplemented
_connect_point3 = _connect_unimplemented
_connect_line3 = _connect_unimplemented
_connect_sphere = _connect_unimplemented
_connect_plane = _connect_unimplemented
def intersect(self, other):
raise NotImplementedError
def connect(self, other):
raise NotImplementedError
def distance(self, other):
c = self.connect(other)
if c:
return c.length
return 0.0
def _intersect_point2_circle(P, C):
return abs(P - C.c) <= C.r
def _intersect_line2_line2(A, B):
d = B.v.y * A.v.x - B.v.x * A.v.y
if d == 0:
return None
dy = A.p.y - B.p.y
dx = A.p.x - B.p.x
ua = (B.v.x * dy - B.v.y * dx) / d
if not A._u_in(ua):
return None
ub = (A.v.x * dy - A.v.y * dx) / d
if not B._u_in(ub):
return None
return Point2(A.p.x + ua * A.v.x,
A.p.y + ua * A.v.y)
def _intersect_line2_circle(L, C):
a = L.v.magnitude_squared()
b = 2 * (L.v.x * (L.p.x - C.c.x) + \
L.v.y * (L.p.y - C.c.y))
c = C.c.magnitude_squared() + \
L.p.magnitude_squared() - \
2 * C.c.dot(L.p) - \
C.r ** 2
det = b ** 2 - 4 * a * c
if det < 0:
return None
sq = math.sqrt(det)
u1 = (-b + sq) / (2 * a)
u2 = (-b - sq) / (2 * a)
if not L._u_in(u1):
u1 = max(min(u1, 1.0), 0.0)
if not L._u_in(u2):
u2 = max(min(u2, 1.0), 0.0)
return LineSegment2(Point2(L.p.x + u1 * L.v.x,
L.p.y + u1 * L.v.y),
Point2(L.p.x + u2 * L.v.x,
L.p.y + u2 * L.v.y))
def _connect_point2_line2(P, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((P.x - L.p.x) * L.v.x + \
(P.y - L.p.y) * L.v.y) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
return LineSegment2(P,
Point2(L.p.x + u * L.v.x,
L.p.y + u * L.v.y))
def _connect_point2_circle(P, C):
v = P - C.c
v.normalize()
v *= C.r
return LineSegment2(P, Point2(C.c.x + v.x, C.c.y + v.y))
def _connect_line2_line2(A, B):
d = B.v.y * A.v.x - B.v.x * A.v.y
if d == 0:
# Parallel, connect an endpoint with a line
if isinstance(B, Ray2) or isinstance(B, LineSegment2):
p1, p2 = _connect_point2_line2(B.p, A)
return p2, p1
# No endpoint (or endpoint is on A), possibly choose arbitrary point
# on line.
return _connect_point2_line2(A.p, B)
dy = A.p.y - B.p.y
dx = A.p.x - B.p.x
ua = (B.v.x * dy - B.v.y * dx) / d
if not A._u_in(ua):
ua = max(min(ua, 1.0), 0.0)
ub = (A.v.x * dy - A.v.y * dx) / d
if not B._u_in(ub):
ub = max(min(ub, 1.0), 0.0)
return LineSegment2(Point2(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y),
Point2(B.p.x + ub * B.v.x, B.p.y + ub * B.v.y))
def _connect_circle_line2(C, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((C.c.x - L.p.x) * L.v.x + (C.c.y - L.p.y) * L.v.y) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
point = Point2(L.p.x + u * L.v.x, L.p.y + u * L.v.y)
v = (point - C.c)
v.normalize()
v *= C.r
return LineSegment2(Point2(C.c.x + v.x, C.c.y + v.y), point)
def _connect_circle_circle(A, B):
v = B.c - A.c
v.normalize()
return LineSegment2(Point2(A.c.x + v.x * A.r, A.c.y + v.y * A.r),
Point2(B.c.x - v.x * B.r, B.c.y - v.y * B.r))
class Point2(Vector2, Geometry):
def __repr__(self):
return 'Point2(%.2f, %.2f)' % (self.x, self.y)
def intersect(self, other):
return other._intersect_point2(self)
def _intersect_circle(self, other):
return _intersect_point2_circle(self, other)
def connect(self, other):
return other._connect_point2(self)
def _connect_point2(self, other):
return LineSegment2(other, self)
def _connect_line2(self, other):
c = _connect_point2_line2(self, other)
if c:
return c._swap()
def _connect_circle(self, other):
c = _connect_point2_circle(self, other)
if c:
return c._swap()
class Line2(Geometry):
__slots__ = ['p', 'v']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point2) and \
isinstance(args[1], Vector2) and \
type(args[2]) == float
self.p = args[0].copy()
self.v = args[1] * args[2] / abs(args[1])
elif len(args) == 2:
if isinstance(args[0], Point2) and isinstance(args[1], Point2):
self.p = args[0].copy()
self.v = args[1] - args[0]
elif isinstance(args[0], Point2) and isinstance(args[1], Vector2):
self.p = args[0].copy()
self.v = args[1].copy()
else:
raise AttributeError, '%r' % (args,)
elif len(args) == 1:
if isinstance(args[0], Line2):
self.p = args[0].p.copy()
self.v = args[0].v.copy()
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
if not self.v:
raise AttributeError, 'Line has zero-length vector'
def __copy__(self):
return self.__class__(self.p, self.v)
copy = __copy__
def __repr__(self):
return 'Line2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.v.x, self.v.y)
p1 = property(lambda self: self.p)
p2 = property(lambda self: Point2(self.p.x + self.v.x,
self.p.y + self.v.y))
def _apply_transform(self, t):
self.p = t * self.p
self.v = t * self.v
def _u_in(self, u):
return True
def intersect(self, other):
return other._intersect_line2(self)
def _intersect_line2(self, other):
return _intersect_line2_line2(self, other)
def _intersect_circle(self, other):
return _intersect_line2_circle(self, other)
def connect(self, other):
return other._connect_line2(self)
def _connect_point2(self, other):
return _connect_point2_line2(other, self)
def _connect_line2(self, other):
return _connect_line2_line2(other, self)
def _connect_circle(self, other):
return _connect_circle_line2(other, self)
class Ray2(Line2):
def __repr__(self):
return 'Ray2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.v.x, self.v.y)
def _u_in(self, u):
return u >= 0.0
class LineSegment2(Line2):
def __repr__(self):
return 'LineSegment2(<%.2f, %.2f> to <%.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.x + self.v.x, self.p.y + self.v.y)
def _u_in(self, u):
return u >= 0.0 and u <= 1.0
def __abs__(self):
return abs(self.v)
def magnitude_squared(self):
return self.v.magnitude_squared()
def _swap(self):
# used by connect methods to switch order of points
self.p = self.p2
self.v *= -1
return self
length = property(lambda self: abs(self.v))
class Circle(Geometry):
__slots__ = ['c', 'r']
def __init__(self, center, radius):
assert isinstance(center, Vector2) and type(radius) == float
self.c = center.copy()
self.r = radius
def __copy__(self):
return self.__class__(self.c, self.r)
copy = __copy__
def __repr__(self):
return 'Circle(<%.2f, %.2f>, radius=%.2f)' % \
(self.c.x, self.c.y, self.r)
def _apply_transform(self, t):
self.c = t * self.c
def intersect(self, other):
return other._intersect_circle(self)
def _intersect_point2(self, other):
return _intersect_point2_circle(other, self)
def _intersect_line2(self, other):
return _intersect_line2_circle(other, self)
def connect(self, other):
return other._connect_circle(self)
def _connect_point2(self, other):
return _connect_point2_circle(other, self)
def _connect_line2(self, other):
c = _connect_circle_line2(self, other)
if c:
return c._swap()
def _connect_circle(self, other):
return _connect_circle_circle(other, self)
# 3D Geometry
# -------------------------------------------------------------------------
def _connect_point3_line3(P, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((P.x - L.p.x) * L.v.x + \
(P.y - L.p.y) * L.v.y + \
(P.z - L.p.z) * L.v.z) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
return LineSegment3(P, Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z))
def _connect_point3_sphere(P, S):
v = P - S.c
v.normalize()
v *= S.r
return LineSegment3(P, Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z))
def _connect_point3_plane(p, plane):
n = plane.n.normalized()
d = p.dot(plane.n) - plane.k
return LineSegment3(p, Point3(p.x - n.x * d, p.y - n.y * d, p.z - n.z * d))
def _connect_line3_line3(A, B):
assert A.v and B.v
p13 = A.p - B.p
d1343 = p13.dot(B.v)
d4321 = B.v.dot(A.v)
d1321 = p13.dot(A.v)
d4343 = B.v.magnitude_squared()
denom = A.v.magnitude_squared() * d4343 - d4321 ** 2
if denom == 0:
# Parallel, connect an endpoint with a line
if isinstance(B, Ray3) or isinstance(B, LineSegment3):
return _connect_point3_line3(B.p, A)._swap()
# No endpoint (or endpoint is on A), possibly choose arbitrary
# point on line.
return _connect_point3_line3(A.p, B)
ua = (d1343 * d4321 - d1321 * d4343) / denom
if not A._u_in(ua):
ua = max(min(ua, 1.0), 0.0)
ub = (d1343 + d4321 * ua) / d4343
if not B._u_in(ub):
ub = max(min(ub, 1.0), 0.0)
return LineSegment3(Point3(A.p.x + ua * A.v.x,
A.p.y + ua * A.v.y,
A.p.z + ua * A.v.z),
Point3(B.p.x + ub * B.v.x,
B.p.y + ub * B.v.y,
B.p.z + ub * B.v.z))
def _connect_line3_plane(L, P):
d = P.n.dot(L.v)
if not d:
# Parallel, choose an endpoint
return _connect_point3_plane(L.p, P)
u = (P.k - P.n.dot(L.p)) / d
if not L._u_in(u):
# intersects out of range, choose nearest endpoint
u = max(min(u, 1.0), 0.0)
return _connect_point3_plane(Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z), P)
# Intersection
return None
def _connect_sphere_line3(S, L):
d = L.v.magnitude_squared()
assert d != 0
u = ((S.c.x - L.p.x) * L.v.x + \
(S.c.y - L.p.y) * L.v.y + \
(S.c.z - L.p.z) * L.v.z) / d
if not L._u_in(u):
u = max(min(u, 1.0), 0.0)
point = Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z)
v = (point - S.c)
v.normalize()
v *= S.r
return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
point)
def _connect_sphere_sphere(A, B):
v = B.c - A.c
v.normalize()
return LineSegment3(Point3(A.c.x + v.x * A.r,
A.c.y + v.y * A.r,
A.c.x + v.z * A.r),
Point3(B.c.x + v.x * B.r,
B.c.y + v.y * B.r,
B.c.x + v.z * B.r))
def _connect_sphere_plane(S, P):
c = _connect_point3_plane(S.c, P)
if not c:
return None
p2 = c.p2
v = p2 - S.c
v.normalize()
v *= S.r
return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
p2)
def _connect_plane_plane(A, B):
if A.n.cross(B.n):
# Planes intersect
return None
else:
# Planes are parallel, connect to arbitrary point
return _connect_point3_plane(A._get_point(), B)
def _intersect_point3_sphere(P, S):
return abs(P - S.c) <= S.r
def _intersect_line3_sphere(L, S):
a = L.v.magnitude_squared()
b = 2 * (L.v.x * (L.p.x - S.c.x) + \
L.v.y * (L.p.y - S.c.y) + \
L.v.z * (L.p.z - S.c.z))
c = S.c.magnitude_squared() + \
L.p.magnitude_squared() - \
2 * S.c.dot(L.p) - \
S.r ** 2
det = b ** 2 - 4 * a * c
if det < 0:
return None
sq = math.sqrt(det)
u1 = (-b + sq) / (2 * a)
u2 = (-b - sq) / (2 * a)
if not L._u_in(u1):
u1 = max(min(u1, 1.0), 0.0)
if not L._u_in(u2):
u2 = max(min(u2, 1.0), 0.0)
return LineSegment3(Point3(L.p.x + u1 * L.v.x,
L.p.y + u1 * L.v.y,
L.p.z + u1 * L.v.z),
Point3(L.p.x + u2 * L.v.x,
L.p.y + u2 * L.v.y,
L.p.z + u2 * L.v.z))
def _intersect_line3_plane(L, P):
d = P.n.dot(L.v)
if not d:
# Parallel
return None
u = (P.k - P.n.dot(L.p)) / d
if not L._u_in(u):
return None
return Point3(L.p.x + u * L.v.x,
L.p.y + u * L.v.y,
L.p.z + u * L.v.z)
def _intersect_plane_plane(A, B):
n1_m = A.n.magnitude_squared()
n2_m = B.n.magnitude_squared()
n1d2 = A.n.dot(B.n)
det = n1_m * n2_m - n1d2 ** 2
if det == 0:
# Parallel
return None
c1 = (A.k * n2_m - B.k * n1d2) / det
c2 = (B.k * n1_m - A.k * n1d2) / det
return Line3(Point3(c1 * A.n.x + c2 * B.n.x,
c1 * A.n.y + c2 * B.n.y,
c1 * A.n.z + c2 * B.n.z),
A.n.cross(B.n))
class Point3(Vector3, Geometry):
def __repr__(self):
return 'Point3(%.2f, %.2f, %.2f)' % (self.x, self.y, self.z)
def intersect(self, other):
return other._intersect_point3(self)
def _intersect_sphere(self, other):
return _intersect_point3_sphere(self, other)
def connect(self, other):
return other._connect_point3(self)
def _connect_point3(self, other):
if self != other:
return LineSegment3(other, self)
return None
def _connect_line3(self, other):
c = _connect_point3_line3(self, other)
if c:
return c._swap()
def _connect_sphere(self, other):
c = _connect_point3_sphere(self, other)
if c:
return c._swap()
def _connect_plane(self, other):
c = _connect_point3_plane(self, other)
if c:
return c._swap()
class Line3:
__slots__ = ['p', 'v']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point3) and \
isinstance(args[1], Vector3) and \
type(args[2]) == float
self.p = args[0].copy()
self.v = args[1] * args[2] / abs(args[1])
elif len(args) == 2:
if isinstance(args[0], Point3) and isinstance(args[1], Point3):
self.p = args[0].copy()
self.v = args[1] - args[0]
elif isinstance(args[0], Point3) and isinstance(args[1], Vector3):
self.p = args[0].copy()
self.v = args[1].copy()
else:
raise AttributeError, '%r' % (args,)
elif len(args) == 1:
if isinstance(args[0], Line3):
self.p = args[0].p.copy()
self.v = args[0].v.copy()
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
# XXX This is annoying.
#if not self.v:
# raise AttributeError, 'Line has zero-length vector'
def __copy__(self):
return self.__class__(self.p, self.v)
copy = __copy__
def __repr__(self):
return 'Line3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
p1 = property(lambda self: self.p)
p2 = property(lambda self: Point3(self.p.x + self.v.x,
self.p.y + self.v.y,
self.p.z + self.v.z))
def _apply_transform(self, t):
self.p = t * self.p
self.v = t * self.v
def _u_in(self, u):
return True
def intersect(self, other):
return other._intersect_line3(self)
def _intersect_sphere(self, other):
return _intersect_line3_sphere(self, other)
def _intersect_plane(self, other):
return _intersect_line3_plane(self, other)
def connect(self, other):
return other._connect_line3(self)
def _connect_point3(self, other):
return _connect_point3_line3(other, self)
def _connect_line3(self, other):
return _connect_line3_line3(other, self)
def _connect_sphere(self, other):
return _connect_sphere_line3(other, self)
def _connect_plane(self, other):
c = _connect_line3_plane(self, other)
if c:
return c
class Ray3(Line3):
def __repr__(self):
return 'Ray3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
def _u_in(self, u):
return u >= 0.0
class LineSegment3(Line3):
def __repr__(self):
return 'LineSegment3(<%.2f, %.2f, %.2f> to <%.2f, %.2f, %.2f>)' % \
(self.p.x, self.p.y, self.p.z,
self.p.x + self.v.x, self.p.y + self.v.y, self.p.z + self.v.z)
def _u_in(self, u):
return u >= 0.0 and u <= 1.0
def __abs__(self):
return abs(self.v)
def magnitude_squared(self):
return self.v.magnitude_squared()
def _swap(self):
# used by connect methods to switch order of points
self.p = self.p2
self.v *= -1
return self
length = property(lambda self: abs(self.v))
class Sphere:
__slots__ = ['c', 'r']
def __init__(self, center, radius):
assert isinstance(center, Vector3) and type(radius) == float
self.c = center.copy()
self.r = radius
def __copy__(self):
return self.__class__(self.c, self.r)
copy = __copy__
def __repr__(self):
return 'Sphere(<%.2f, %.2f, %.2f>, radius=%.2f)' % \
(self.c.x, self.c.y, self.c.z, self.r)
def _apply_transform(self, t):
self.c = t * self.c
def intersect(self, other):
return other._intersect_sphere(self)
def _intersect_point3(self, other):
return _intersect_point3_sphere(other, self)
def _intersect_line3(self, other):
return _intersect_line3_sphere(other, self)
def connect(self, other):
return other._connect_sphere(self)
def _connect_point3(self, other):
return _connect_point3_sphere(other, self)
def _connect_line3(self, other):
c = _connect_sphere_line3(self, other)
if c:
return c._swap()
def _connect_sphere(self, other):
return _connect_sphere_sphere(other, self)
def _connect_plane(self, other):
c = _connect_sphere_plane(self, other)
if c:
return c
class Plane:
# n.p = k, where n is normal, p is point on plane, k is constant scalar
__slots__ = ['n', 'k']
def __init__(self, *args):
if len(args) == 3:
assert isinstance(args[0], Point3) and \
isinstance(args[1], Point3) and \
isinstance(args[2], Point3)
self.n = (args[1] - args[0]).cross(args[2] - args[0])
self.n.normalize()
self.k = self.n.dot(args[0])
elif len(args) == 2:
if isinstance(args[0], Point3) and isinstance(args[1], Vector3):
self.n = args[1].normalized()
self.k = self.n.dot(args[0])
elif isinstance(args[0], Vector3) and type(args[1]) == float:
self.n = args[0].normalized()
self.k = args[1]
else:
raise AttributeError, '%r' % (args,)
else:
raise AttributeError, '%r' % (args,)
if not self.n:
raise AttributeError, 'Points on plane are colinear'
def __copy__(self):
return self.__class__(self.n, self.k)
copy = __copy__
def __repr__(self):
return 'Plane(<%.2f, %.2f, %.2f>.p = %.2f)' % \
(self.n.x, self.n.y, self.n.z, self.k)
def _get_point(self):
# Return an arbitrary point on the plane
if self.n.z:
return Point3(0., 0., self.k / self.n.z)
elif self.n.y:
return Point3(0., self.k / self.n.y, 0.)
else:
return Point3(self.k / self.n.x, 0., 0.)
def _apply_transform(self, t):
p = t * self._get_point()
self.n = t * self.n
self.k = self.n.dot(p)
def intersect(self, other):
return other._intersect_plane(self)
def _intersect_line3(self, other):
return _intersect_line3_plane(other, self)
def _intersect_plane(self, other):
return _intersect_plane_plane(self, other)
def connect(self, other):
return other._connect_plane(self)
def _connect_point3(self, other):
return _connect_point3_plane(other, self)
def _connect_line3(self, other):
return _connect_line3_plane(other, self)
def _connect_sphere(self, other):
return _connect_sphere_plane(other, self)
def _connect_plane(self, other):
return _connect_plane_plane(other, self)
| Python |
import os
import sys
import inspect
# Events
from sphinx.ext.autodoc import MethodDocumenter, FunctionDocumenter
from sphinx.ext.autodoc import ModuleDocumenter, ClassDocumenter
class EventDocumenter(MethodDocumenter):
objtype = "event"
member_order = 45
priority = 5
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
if not isinstance(parent, ClassDocumenter):
return False
try:
return member.__name__ in member.im_class.event_types
except:
return False
class FunctionDocumenter2(FunctionDocumenter):
objtype = 'function'
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
can = FunctionDocumenter.can_document_member(
member, membername, isattr, parent)
# bound methods
plus = isinstance(parent, ModuleDocumenter) and inspect.ismethod(member)
return can or plus
def setup(app):
app.add_autodocumenter(EventDocumenter)
app.add_autodocumenter(FunctionDocumenter2)
# Search all submodules
def find_modules(rootpath, skip={}):
"""
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
"""
INITPY = '__init__.py'
rootpath = os.path.normpath(os.path.abspath(rootpath))
if INITPY in os.listdir(rootpath):
root_package = rootpath.split(os.path.sep)[-1]
print "Searching modules in", rootpath
else:
print "No modules in", rootpath
return
def makename(package, module):
"""Join package and module with a dot."""
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
skipall = []
for m in skip.keys():
if skip[m] is None: skipall.append(m)
tree = {}
saved = 0
found = 0
def save(module, submodule):
name = module+ "."+ submodule
for s in skipall:
if name.startswith(s):
return False
if skip.has_key(module):
if submodule in skip[module]:
return False
if not tree.has_key(module):
tree[module] = []
tree[module].append(submodule)
return True
for root, subs, files in os.walk(rootpath):
py_files = sorted([f for f in files if os.path.splitext(f)[1] == '.py'])
if INITPY in py_files:
subpackage = root[len(rootpath):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
full = makename(root_package, subpackage)
part = full.rpartition('.')
base_package, submodule = part[0], part[2]
found += 1
if save(base_package, submodule): saved += 1
py_files.remove(INITPY)
for py_file in py_files:
found += 1
module = os.path.splitext(py_file)[0]
if save(full, module): saved += 1
for item in tree.keys():
tree[item].sort()
print "%s contains %i submodules, %i skipped" % \
(root_package, found, found-saved)
return tree
def find_all_modules(document_modules, skip_modules):
tree = {}
for mod in document_modules:
mod_path = os.path.join('..', mod)
if mod in skip_modules.keys():
tree.update(find_modules(mod_path, skip_modules[mod]))
else:
tree.update(find_modules(mod_path))
return tree
def write_build(data, filename):
with open(os.path.join('internal', filename), 'w') as f:
f.write(".. list-table::\n")
f.write(" :widths: 50 50\n")
f.write("\n")
for var, val in data:
f.write(" * - "+var+"\n - "+val+"\n")
def write_blacklist(pack, filename):
with open(os.path.join('internal', filename), 'w') as f:
modules = pack.keys()
modules.sort()
for mod in modules:
if pack[mod] is None:
f.write("* ``"+mod+"``\n")
else:
pack[mod].sort()
for sub in pack[mod]:
f.write("* ``"+mod+"."+sub+"``\n")
| Python |
# -*- coding: utf-8 -*-
''' pyglet specific docstring transformations.
'''
_debug = False
def debug(lines):
with open('debug.log', 'a') as f:
for line in lines:
f.write(line+"\n")
if _debug:
with open('debug.log', 'w') as f:
f.write("Docstring modifications.\n\n")
def indentation(line):
if line.strip()=="": return 0
return len(line) - len(line.lstrip())
def process_block(converter, lines, start):
''' Apply a transformation to an indented block
'''
first = indentation(lines[start])
current = first
blocks = [[]]
block = 0
for i, line in enumerate(lines[start+1:]):
level = indentation(line)
if level<=first:
try: # allow one blank line in the block
if line.strip()=="" and \
(current == indentation(lines[start + i + 2])):
continue
except: pass
break
if level<current:
blocks.append([line])
block += 1
else:
blocks[block].append(line)
current = level
result = []
for block in blocks:
result += converter(block)
return i, result
def ReST_parameter(lines):
''' Converts :parameters: blocks to :param: markup
'''
indent = indentation(lines[0])
part = lines[0].replace("`","").split(":")
name = part[0].replace(" ", "")
rest = [":param "+name+":"]
for line in lines[1:]:
rest.append(line[indent:])
if len(part)>1:
rest.append(":type "+name+": "+part[1].strip().lstrip())
return rest
def ReST_Ivariable(lines):
''' Converts :Ivariable: blocks to :var: markup
'''
indent = indentation(lines[0])
part = lines[0].replace("`","").split(":")
name = part[0].replace(" ", "")
rest = [":var "+name+":"]
for line in lines[1:]:
rest.append(line[indent:])
if len(part)>1:
rest.append(":type "+name+": "+part[1].strip().lstrip())
return rest
def modify_docstrings(app, what, name, obj, options, lines,
reference_offset=[0]):
original = lines[:]
def convert(converter, start):
affected, result = process_block(converter, lines, start)
for x in range(start, start+affected+1):
del lines[start]
for i, line in enumerate(result):
lines.insert(start+i, line)
i=0
while i<len(lines):
line = lines[i]
if ":parameters:" in line.lower():
convert(ReST_parameter, i)
elif ":Ivariables:" in line:
convert(ReST_Ivariable, i)
elif ":guide:" in line:
lines[i] = lines[i].replace(u':guide:`',
u'.. seealso:: Programming Guide - :ref:`guide_')
elif ":deprecated:" in line:
lines[i] = lines[i].replace(u':deprecated:',
u'.. warning:: Deprecated.')
lines.insert(i,"")
lines.insert(i,"")
elif line.strip().startswith(":since:"):
lines[i] = lines[i].replace(u':since:',
u'.. note:: Since')
lines.insert(i+1,"")
lines.insert(i,"")
elif line.strip().startswith("**since:**"):
lines[i] = lines[i].replace(u'**since:**',
u'.. note:: Since')
lines.insert(i+1,"")
lines.insert(i,"")
elif ":event:" in line.lower():
lines[i] = lines[i].replace(u':event:', u'.. event mark')
i += 1
if _debug and original!=lines:
title = what + " " +name
debug(["\n",title, "-"*len(title)])
debug(["Original:", ""]+original)
debug(["Redacted:", ""]+lines)
def setup(app):
app.connect('autodoc-process-docstring', modify_docstrings)
| Python |
# -*- coding: utf-8 -*-
"""
sphinx.ext.autosummary.generate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usable as a library or script to generate automatic RST source files for
items referred to in autosummary:: directives.
Each generated RST file contains a single auto*:: directive which
extracts the docstring of the referred item.
Example Makefile rule::
generate:
sphinx-autogen -o source/generated source/*.rst
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import sys
import pydoc
import optparse
import inspect
from jinja2 import FileSystemLoader, TemplateNotFound
from jinja2.sandbox import SandboxedEnvironment
from sphinx import package_dir
from ..autosummary import import_by_name, get_documenter
from sphinx.jinja2glue import BuiltinTemplateLoader
from sphinx.util.osutil import ensuredir
from sphinx.util.inspect import safe_getattr
from sphinx.pycode import ModuleAnalyzer
def main(argv=sys.argv):
usage = """%prog [OPTIONS] SOURCEFILE ..."""
p = optparse.OptionParser(usage.strip())
p.add_option("-o", "--output-dir", action="store", type="string",
dest="output_dir", default=None,
help="Directory to place all output in")
p.add_option("-s", "--suffix", action="store", type="string",
dest="suffix", default="rst",
help="Default suffix for files (default: %default)")
p.add_option("-t", "--templates", action="store", type="string",
dest="templates", default=None,
help="Custom template directory (default: %default)")
options, args = p.parse_args(argv[1:])
if len(args) < 1:
p.error('no input files given')
generate_autosummary_docs(args, options.output_dir,
"." + options.suffix,
template_dir=options.templates)
def _simple_info(msg):
print msg
def _simple_warn(msg):
print >> sys.stderr, 'WARNING: ' + msg
# -- Generating output ---------------------------------------------------------
def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
warn=_simple_warn, info=_simple_info,
base_path=None, builder=None, template_dir=None):
showed_sources = list(sorted(sources))
if len(showed_sources) > 20:
showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
info('[autosummary] generating autosummary for: %s' %
', '.join(showed_sources))
if output_dir:
info('[autosummary] writing to %s' % output_dir)
if base_path is not None:
sources = [os.path.join(base_path, filename) for filename in sources]
# create our own templating environment
template_dirs = [os.path.join(package_dir, 'ext',
'autosummary', 'templates')]
if builder is not None:
# allow the user to override the templates
template_loader = BuiltinTemplateLoader()
template_loader.init(builder, dirs=template_dirs)
else:
if template_dir:
template_dirs.insert(0, template_dir)
template_loader = FileSystemLoader(template_dirs)
template_env = SandboxedEnvironment(loader=template_loader)
# read
items = find_autosummary_in_files(sources)
# remove possible duplicates
items = dict([(item, True) for item in items]).keys()
# keep track of new files
new_files = []
# write
for name, path, template_name in sorted(items):
if path is None:
# The corresponding autosummary:: directive did not have
# a :toctree: option
continue
path = output_dir or os.path.abspath(path)
ensuredir(path)
try:
name, obj, parent = import_by_name(name)
except ImportError, e:
warn('[autosummary] failed to import %r: %s' % (name, e))
continue
# skip base modules
if name.endswith(".base"):
continue
fn = os.path.join(path, name + suffix)
# skip it if it exists
if os.path.isfile(fn):
continue
new_files.append(fn)
f = open(fn, 'w')
try:
doc = get_documenter(obj, parent)
if template_name is not None:
template = template_env.get_template(template_name)
else:
try:
template = template_env.get_template('autosummary/%s.rst'
% doc.objtype)
except TemplateNotFound:
template = template_env.get_template('autosummary/base.rst')
def exclude_member(obj, name):
if sys.skip_member(name, obj):
return True
live = getattr(obj, name)
if inspect.isbuiltin(live):
return True
real_module = inspect.getmodule(live)
if real_module is not None:
if real_module.__name__ in ["ctypes",
"unittest"]:
return True
c = getattr(obj, name)
if inspect.isclass(c) or inspect.isfunction(c):
if (c.__module__!=obj.__name__+".base" and
c.__module__!=obj.__name__):
return True
return False
def get_members(obj, typ, include_public=[]):
items = []
for name in dir(obj):
# skip_member
if exclude_member(obj, name):
continue
try:
documenter = get_documenter(safe_getattr(obj, name), obj)
except AttributeError:
continue
if documenter.objtype == typ:
items.append(name)
elif typ=='function' and documenter.objtype=='boundmethod':
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
return public, items
def def_members(obj, typ, include_public=[]):
items = []
try:
obj_dict = safe_getattr(obj, '__dict__')
except AttributeError:
return []
defined = obj_dict.keys()
defined.sort()
for name in defined:
if exclude_member(obj, name):
continue
try:
documenter = get_documenter(safe_getattr(obj, name), obj)
except AttributeError:
continue
if documenter.objtype == typ:
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
return public
def get_iattributes(obj):
items = []
name = obj.__name__
obj_attr = dir(obj)
analyzer = ModuleAnalyzer.for_module(obj.__module__)
attr_docs = analyzer.find_attr_docs()
for pair, doc in attr_docs.iteritems():
if name!=pair[0]:
continue
if not pair[1] in obj_attr:
items.append({"name":pair[1],
"doc":'\n '.join(doc)})
items.sort(key=lambda d: d["name"])
return items
ns = {}
if doc.objtype == 'module':
ns['all_members'] = dir(obj)
ns['classes'], ns['all_classes'] = \
get_members(obj, 'class')
ns['functions'], ns['all_functions'] = \
get_members(obj, 'function')
ns['exceptions'], ns['all_exceptions'] = \
get_members(obj, 'exception')
ns['data'], ns['all_data'] = \
get_members(obj, 'data')
documented = ns['classes']+ns['functions'] +ns['exceptions']+ns['data']
if sys.all_submodules.has_key(obj.__name__):
ns['submodules'] = sys.all_submodules[obj.__name__]
# Hide base submodule
if "base" in ns['submodules']:
ns['submodules'].remove("base")
documented += ns['submodules']
ns['members'] = ns['all_members']
try:
obj_dict = safe_getattr(obj, '__dict__')
except AttributeError:
obj_dict = []
public = [x for x in obj_dict if not x.startswith('_')]
for item in documented:
if item in public:
public.remove(item)
public.sort()
ns['members'] = public
ns['constants'] = [x for x in public
#if not sys.skip_member(x, obj)]
if not exclude_member(obj, x)]
elif doc.objtype == 'class':
ns['members'] = dir(obj)
ns['events'], ns['all_events'] = \
get_members(obj, 'event')
ns['methods'], ns['all_methods'] = \
get_members(obj, 'method', ['__init__'])
ns['attributes'], ns['all_attributes'] = \
get_members(obj, 'attribute')
# Add instance attributes
ns['iattributes'] = get_iattributes(obj)
ns['def_events'] = def_members(obj, 'event')
ns['def_methods'] = def_members(obj, 'method')
ns['def_attributes'] = def_members(obj, 'attribute')
# Constructor method special case
if '__init__' in ns['methods']:
ns['methods'].remove('__init__')
if '__init__' in ns['def_methods']:
ns['def_methods'].remove('__init__')
ns['constructor']=['__init__']
else:
ns['constructor']=[]
ns['inherited'] = []
for t in ['events', 'methods', 'attributes']:
key = 'inh_' + t
ns[key]=[]
for item in ns[t]:
if not item in ns['def_' + t]:
ns['inherited'].append(item)
ns[key].append(item)
parts = name.split('.')
if doc.objtype in ('method', 'attribute'):
mod_name = '.'.join(parts[:-2])
cls_name = parts[-2]
obj_name = '.'.join(parts[-2:])
ns['class'] = cls_name
else:
mod_name, obj_name = '.'.join(parts[:-1]), parts[-1]
ns['fullname'] = name
ns['module'] = mod_name
ns['objname'] = obj_name
ns['name'] = parts[-1]
ns['objtype'] = doc.objtype
ns['underline'] = len(name) * '='
rendered = template.render(**ns)
f.write(rendered)
finally:
f.close()
# descend recursively to new files
if new_files:
generate_autosummary_docs(new_files, output_dir=output_dir,
suffix=suffix, warn=warn, info=info,
base_path=base_path, builder=builder,
template_dir=template_dir)
# -- Finding documented entries in files ---------------------------------------
def find_autosummary_in_files(filenames):
"""Find out what items are documented in source/*.rst.
See `find_autosummary_in_lines`.
"""
documented = []
for filename in filenames:
f = open(filename, 'r')
lines = f.read().splitlines()
documented.extend(find_autosummary_in_lines(lines, filename=filename))
f.close()
return documented
def find_autosummary_in_docstring(name, module=None, filename=None):
"""Find out what items are documented in the given object's docstring.
See `find_autosummary_in_lines`.
"""
try:
real_name, obj, parent = import_by_name(name)
lines = pydoc.getdoc(obj).splitlines()
return find_autosummary_in_lines(lines, module=name, filename=filename)
except AttributeError:
pass
except ImportError, e:
print "Failed to import '%s': %s" % (name, e)
return []
def find_autosummary_in_lines(lines, module=None, filename=None):
"""Find out what items appear in autosummary:: directives in the
given lines.
Returns a list of (name, toctree, template) where *name* is a name
of an object and *toctree* the :toctree: path of the corresponding
autosummary directive (relative to the root of the file name), and
*template* the value of the :template: option. *toctree* and
*template* ``None`` if the directive does not have the
corresponding options set.
"""
autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*')
automodule_re = re.compile(
r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$')
module_re = re.compile(
r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$')
autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?')
toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$')
template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$')
documented = []
toctree = None
template = None
current_module = module
in_autosummary = False
base_indent = ""
for line in lines:
if in_autosummary:
m = toctree_arg_re.match(line)
if m:
toctree = m.group(1)
if filename:
toctree = os.path.join(os.path.dirname(filename),
toctree)
continue
m = template_arg_re.match(line)
if m:
template = m.group(1).strip()
continue
if line.strip().startswith(':'):
continue # skip options
m = autosummary_item_re.match(line)
if m:
name = m.group(1).strip()
if name.startswith('~'):
name = name[1:]
if current_module and \
not name.startswith(current_module + '.'):
name = "%s.%s" % (current_module, name)
documented.append((name, toctree, template))
continue
if not line.strip() or line.startswith(base_indent + " "):
continue
in_autosummary = False
m = autosummary_re.match(line)
if m:
in_autosummary = True
base_indent = m.group(1)
toctree = None
template = None
continue
m = automodule_re.search(line)
if m:
current_module = m.group(1).strip()
# recurse into the automodule docstring
documented.extend(find_autosummary_in_docstring(
current_module, filename=filename))
continue
m = module_re.match(line)
if m:
current_module = m.group(2)
continue
return documented
if __name__ == '__main__':
main()
| Python |
# -*- coding: utf-8 -*-
"""
sphinx.ext.autosummary
~~~~~~~~~~~~~~~~~~~~~~
Sphinx extension that adds an autosummary:: directive, which can be
used to generate function/method/attribute/etc. summary lists, similar
to those output eg. by Epydoc and other API doc generation tools.
An :autolink: role is also provided.
autosummary directive
---------------------
The autosummary directive has the form::
.. autosummary::
:nosignatures:
:toctree: generated/
module.function_1
module.function_2
...
and it generates an output table (containing signatures, optionally)
======================== =============================================
module.function_1(args) Summary line from the docstring of function_1
module.function_2(args) Summary line from the docstring
...
======================== =============================================
If the :toctree: option is specified, files matching the function names
are inserted to the toctree with the given prefix:
generated/module.function_1
generated/module.function_2
...
Note: The file names contain the module:: or currentmodule:: prefixes.
.. seealso:: autosummary_generate.py
autolink role
-------------
The autolink role functions as ``:obj:`` when the name referred can be
resolved to a Python object, and otherwise it becomes simple emphasis.
This can be used as the default role to make links 'smart'.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import sys
import inspect
import posixpath
from docutils.parsers.rst import directives
from docutils.statemachine import ViewList
from docutils import nodes
from sphinx import addnodes
from sphinx.util.compat import Directive
# -- autosummary_toc node ------------------------------------------------------
class autosummary_toc(nodes.comment):
pass
def process_autosummary_toc(app, doctree):
"""Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
env = app.builder.env
crawled = {}
def crawl_toc(node, depth=1):
crawled[node] = True
for j, subnode in enumerate(node):
try:
if (isinstance(subnode, autosummary_toc)
and isinstance(subnode[0], addnodes.toctree)):
env.note_toctree(env.docname, subnode[0])
continue
except IndexError:
continue
if not isinstance(subnode, nodes.section):
continue
if subnode not in crawled:
crawl_toc(subnode, depth+1)
crawl_toc(doctree)
def autosummary_toc_visit_html(self, node):
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self, node):
pass
# -- autosummary_table node ----------------------------------------------------
class autosummary_table(nodes.comment):
pass
def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(subnode, nodes.Text):
new_text = unicode(subnode.astext())
new_text = new_text.replace(u" ", u"\u00a0")
par[j] = nodes.Text(new_text)
except IndexError:
pass
# -- autodoc integration -------------------------------------------------------
class FakeDirective:
env = {}
genopt = {}
def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import AutoDirective, DataDocumenter, \
ModuleDocumenter
if inspect.ismodule(obj):
# ModuleDocumenter.can_document_member always returns False
return ModuleDocumenter
# Construct a fake documenter for *parent*
if parent is not None:
parent_doc_cls = get_documenter(parent, None)
else:
parent_doc_cls = ModuleDocumenter
if hasattr(parent, '__name__'):
parent_doc = parent_doc_cls(FakeDirective(), parent.__name__)
else:
parent_doc = parent_doc_cls(FakeDirective(), "")
# Get the corrent documenter class for *obj*
classes = [cls for cls in AutoDirective._registry.values()
if cls.can_document_member(obj, '', False, parent_doc)]
if classes:
classes.sort(key=lambda cls: cls.priority)
return classes[-1]
else:
return DataDocumenter
# -- .. autosummary:: ----------------------------------------------------------
class Autosummary(Directive):
"""
Pretty table containing short signatures and summaries of functions etc.
autosummary can also optionally generate a hidden toctree:: node.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
option_spec = {
'toctree': directives.unchanged,
'nosignatures': directives.flag,
'template': directives.unchanged,
'hidden': directives.flag,
}
def warn(self, msg):
self.warnings.append(self.state.document.reporter.warning(
msg, line=self.lineno))
def run(self):
self.env = env = self.state.document.settings.env
self.genopt = {}
self.warnings = []
names = [x.strip().split()[0] for x in self.content
if x.strip() and re.search(r'^[~a-zA-Z_]', x.strip()[0])]
items = self.get_items(names)
if 'hidden' in self.options:
nodes = []
else:
nodes = self.get_table(items)
if 'toctree' in self.options:
suffix = env.config.source_suffix
dirname = posixpath.dirname(env.docname)
tree_prefix = self.options['toctree'].strip()
docnames = []
for name, sig, summary, real_name in items:
docname = posixpath.join(tree_prefix, real_name)
if docname.endswith(suffix):
docname = docname[:-len(suffix)]
docname = posixpath.normpath(posixpath.join(dirname, docname))
if docname not in env.found_docs:
self.warn('toctree references unknown document %r'
% docname)
docnames.append(docname)
tocnode = addnodes.toctree()
tocnode['includefiles'] = docnames
tocnode['entries'] = [(None, docname) for docname in docnames]
tocnode['maxdepth'] = -1
tocnode['glob'] = None
tocnode = autosummary_toc('', '', tocnode)
if not 'hidden' in self.options:
nodes.append(tocnode)
return self.warnings + nodes
def get_items(self, names):
"""Try to import the given names, and return a list of
``[(name, signature, summary_string, real_name), ...]``.
"""
env = self.state.document.settings.env
prefixes = get_import_prefixes_from_env(env)
items = []
max_item_chars = 50
for name in names:
display_name = name
if name.startswith('~'):
name = name[1:]
display_name = name.split('.')[-1]
try:
real_name, obj, parent = import_by_name(name, prefixes=prefixes)
except ImportError:
self.warn('failed to import %s' % name)
items.append((name, '', '', name))
continue
# NB. using real_name here is important, since Documenters
# handle module prefixes slightly differently
documenter = get_documenter(obj, parent)(self, real_name)
if not documenter.parse_name():
self.warn('failed to parse name %s' % real_name)
items.append((display_name, '', '', real_name))
continue
if not documenter.import_object():
self.warn('failed to import object %s' % real_name)
items.append((display_name, '', '', real_name))
continue
# -- Grab the signature
sig = documenter.format_signature()
if not sig:
sig = ''
else:
max_chars = max(10, max_item_chars - len(display_name))
sig = mangle_signature(sig, max_chars=max_chars)
sig = sig.replace('*', r'\*')
# -- Grab the summary
doc = list(documenter.process_doc(documenter.get_doc()))
while doc and not doc[0].strip():
doc.pop(0)
m = re.search(r"^([A-Z][^A-Z]*?\.\s)", " ".join(doc).strip())
if m:
summary = m.group(1).strip()
elif doc:
summary = doc[0].strip()
# Clean attribute fake doc
__doc = type(obj).__doc__
if isinstance(__doc, str):
if __doc.startswith(summary):
summary = "Type: "+type(obj).__name__
else:
summary = ''
items.append((display_name, sig, summary, real_name))
return items
def get_table(self, items):
"""Generate a proper list of table nodes for autosummary:: directive.
*items* is a list produced by :meth:`get_items`.
"""
table_spec = addnodes.tabular_col_spec()
table_spec['spec'] = 'll'
table = autosummary_table('')
real_table = nodes.table('', classes=['longtable'])
table.append(real_table)
group = nodes.tgroup('', cols=2)
real_table.append(group)
group.append(nodes.colspec('', colwidth=10))
group.append(nodes.colspec('', colwidth=90))
body = nodes.tbody('')
group.append(body)
def append_row(*column_texts):
row = nodes.row('')
for text in column_texts:
node = nodes.paragraph('')
vl = ViewList()
vl.append(text, '<autosummary>')
self.state.nested_parse(vl, 0, node)
try:
if isinstance(node[0], nodes.paragraph):
node = node[0]
except IndexError:
pass
row.append(nodes.entry('', node))
body.append(row)
for name, sig, summary, real_name in items:
qualifier = 'obj'
if 'nosignatures' not in self.options:
col1 = ':%s:`%s <%s>`\ %s' % (qualifier, name, real_name, sig)
else:
col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name)
col2 = summary
append_row(col1, col2)
return [table_spec, table]
def mangle_signature(sig, max_chars=30):
"""Reformat a function signature to a more compact form."""
s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()
# Strip strings (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", s)
s = re.sub(r"\\'", "", s)
s = re.sub(r"'[^']*'", "", s)
# Parse the signature to arguments + options
args = []
opts = []
opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=")
while s:
m = opt_re.search(s)
if not m:
# The rest are arguments
args = s.split(', ')
break
opts.insert(0, m.group(2))
s = m.group(1)[:-2]
# Produce a more compact signature
sig = limited_join(", ", args, max_chars=max_chars-2)
if opts:
if not sig:
sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars-4)
elif len(sig) < max_chars - 4 - 2 - 3:
sig += "[, %s]" % limited_join(", ", opts,
max_chars=max_chars-len(sig)-4-2)
return u"(%s)" % sig
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(full_str) < max_chars:
return full_str
n_chars = 0
n_items = 0
for j, item in enumerate(items):
n_chars += len(item) + len(sep)
if n_chars < max_chars - len(overflow_marker):
n_items += 1
else:
break
return sep.join(list(items[:n_items]) + [overflow_marker])
# -- Importing items -----------------------------------------------------------
def get_import_prefixes_from_env(env):
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None]
currmodule = env.temp_data.get('py:module')
if currmodule:
prefixes.insert(0, currmodule)
currclass = env.temp_data.get('py:class')
if currclass:
if currmodule:
prefixes.insert(0, currmodule + "." + currclass)
else:
prefixes.insert(0, currclass)
return prefixes
def import_by_name(name, prefixes=[None]):
"""Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name = name
obj, parent = _import_by_name(prefixed_name)
return prefixed_name, obj, parent
except ImportError:
tried.append(prefixed_name)
raise ImportError('no module named %s' % ' or '.join(tried))
def _import_by_name(name):
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return getattr(mod, name_parts[-1]), mod
except (ImportError, IndexError, AttributeError):
pass
# ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ...
last_j = 0
modname = None
for j in reversed(range(1, len(name_parts)+1)):
last_j = j
modname = '.'.join(name_parts[:j])
try:
__import__(modname)
except:# ImportError:
continue
if modname in sys.modules:
break
if last_j < len(name_parts):
parent = None
obj = sys.modules[modname]
for obj_name in name_parts[last_j:]:
parent = obj
obj = getattr(obj, obj_name)
return obj, parent
else:
return sys.modules[modname], None
except (ValueError, ImportError, AttributeError, KeyError), e:
raise ImportError(*e.args)
# -- :autolink: (smart default role) -------------------------------------------
def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('obj')(
'obj', rawtext, etext, lineno, inliner, options, content)
pnode = r[0][0]
prefixes = get_import_prefixes_from_env(env)
try:
name, obj, parent = import_by_name(pnode['reftarget'], prefixes)
except ImportError:
content = pnode[0]
r[0][0] = nodes.emphasis(rawtext, content[0].astext(),
classes=content['classes'])
return r
def process_generate_options(app):
genfiles = app.config.autosummary_generate
ext = app.config.source_suffix
if genfiles and not hasattr(genfiles, '__len__'):
env = app.builder.env
genfiles = [x + ext for x in env.found_docs
if os.path.isfile(env.doc2path(x))]
if not genfiles:
return
from generate import generate_autosummary_docs
genfiles = [genfile + (not genfile.endswith(ext) and ext or '')
for genfile in genfiles]
generate_autosummary_docs(genfiles, builder=app.builder,
warn=app.warn, info=app.info, suffix=ext,
base_path=app.srcdir)
def setup(app):
# I need autodoc
app.setup_extension('sphinx.ext.autodoc')
app.add_node(autosummary_toc,
html=(autosummary_toc_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosummary_noop, autosummary_noop),
man=(autosummary_noop, autosummary_noop),
texinfo=(autosummary_noop, autosummary_noop))
app.add_node(autosummary_table,
html=(autosummary_table_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosummary_noop, autosummary_noop),
man=(autosummary_noop, autosummary_noop),
texinfo=(autosummary_noop, autosummary_noop))
app.add_directive('autosummary', Autosummary)
app.add_role('autolink', autolink_role)
app.connect('doctree-read', process_autosummary_toc)
app.connect('builder-inited', process_generate_options)
app.add_config_value('autosummary_generate', [], True)
| Python |
# -*- coding: utf-8 -*-
#
# pyglet documentation build configuration file.
#
# This file is execfile()d with the current directory set to its containing dir.
import os
import sys
import time
import datetime
sys.is_epydoc = True
document_modules = ["pyglet", "tests"]
# Patched extensions base path.
sys.path.insert(0, os.path.abspath('.'))
from ext.sphinx_mod import find_all_modules, write_build, write_blacklist
# import the pyglet package.
sys.path.insert(0, os.path.abspath('..'))
try:
import pyglet
print "Generating pyglet %s Documentation" % (pyglet.version)
except:
print "ERROR: pyglet not found"
sys.exit(1)
# -- PYGLET DOCUMENTATION CONFIGURATION ----------------------------------------
implementations = ["carbon", "cocoa", "win32", "xlib"]
# For each module, a list of submodules that should not be imported.
# If value is None, do not try to import any submodule.
skip_modules = {"pyglet": {
"pyglet.com": None,
"pyglet.compat": None,
"pyglet.lib": None,
"pyglet.libs": None,
"pyglet.app": implementations,
"pyglet.canvas": implementations + ["xlib_vidmoderestore"],
"pyglet.font": ["carbon",
"quartz",
"win32",
"freetype", "freetype_lib",
"win32query",],
"pyglet.input": ["carbon_hid", "carbon_tablet",
"darwin_hid",
"directinput",
"evdev",
"wintab",
"x11_xinput", "x11_xinput_tablet"],
"pyglet.image.codecs": ["gdiplus",
"gdkpixbuf2",
"pil",
"quartz",
"quicktime"],
"pyglet.gl": implementations + ["agl",
"glext_arb", "glext_nv",
"glx", "glx_info",
"glxext_arb", "glxext_mesa", "glxext_nv",
"lib_agl", "lib_glx", "lib_wgl",
"wgl", "wgl_info", "wglext_arb", "wglext_nv"],
"pyglet.media": ["avbin"],
"pyglet.media.drivers": ["directsound",
"openal",
"pulse"],
"pyglet.window": implementations,
}
}
# Things that should not be documented
def skip_member(member, obj):
module = obj.__name__
if module=="tests.test": return True
if ".win32" in module: return True
if ".carbon" in module: return True
if ".cocoa" in module: return True
if ".xlib" in module: return True
if module=="pyglet.input.evdev_constants": return True
if module=="pyglet.window.key":
if member==member.upper(): return True
if module=="pyglet.gl.glu": return True
if module.startswith("pyglet.gl.glext_"): return True
if module.startswith("pyglet.gl.gl_ext_"): return True
if module.startswith("pyglet.gl.glxext_"): return True
if module.startswith("pyglet.image.codecs."): return True
if module!="pyglet.gl.gl":
if member in ["DEFAULT_MODE", "current_context"]:
return True
if member.startswith("PFN"): return True
if member.startswith("GL_"): return True
if member.startswith("GLU_"): return True
if member.startswith("RTLD_"): return True
if member=="GLvoid": return True
if len(member)>4:
if member.startswith("gl") and member[2]==member[2].upper():
return True
if member.startswith("glu") and member[3]==member[3].upper():
return True
return False
# autosummary generation filter
sys.skip_member = skip_member
# find modules
sys.all_submodules = find_all_modules(document_modules, skip_modules)
# Write dynamic rst text files
write_blacklist(skip_modules["pyglet"], "blacklist.rst")
now = datetime.datetime.fromtimestamp(time.time())
data = (("Date", now.strftime("%Y/%m/%d %H:%M:%S")),
("pyglet version", pyglet.version))
write_build(data, 'build.rst')
# -- SPHINX STANDARD OPTIONS ---------------------------------------------------
autosummary_generate = True
# -- General configuration -----------------------------------------------------
#
# Note that not all possible configuration values are present in this file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
inheritance_graph_attrs = dict(rankdir="LR", size='""')
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.1'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc',
'ext.sphinx_mod',
'ext.docstrings',
'ext.autosummary',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.todo']
autodoc_member_order='groupwise'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyglet'
copyright = u'2006-2013, Alex Holkner'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = pyglet.version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '_templates']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['pyglet.']
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'pyglet'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["ext/theme"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "pyglet v%s" % (pyglet.version)
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = "pyglet v%s documentation " % (pyglet.version)
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/logo.png"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = True
# If false, no index is generated.
html_use_index = True
# If true, the index is split into individual pages for each letter.
html_split_index = True
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pygletdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pyglet.tex', u'pyglet Documentation',
u'Alex Holkner', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pyglet', u'pyglet Documentation',
[u'Alex Holkner'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pyglet', u'pyglet Documentation',
u'Alex Holkner', 'pyglet', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import shutil
import sys
import time
from xml.dom.minidom import parse
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
def get_elem_by_id(doc, name, id):
for element in doc.getElementsByTagName(name):
if element.getAttribute('id') == id:
return element
def element_children(parent, name):
for child in parent.childNodes:
if (child.nodeType == child.ELEMENT_NODE and
child.nodeName == name):
yield child
def element_text(elem):
if elem.nodeType == elem.TEXT_NODE:
return elem.nodeValue
else:
s = ''
for child in elem.childNodes:
s += element_text(child)
return s
if __name__ == '__main__':
input_dir = os.path.normpath(os.path.dirname(__file__))
output_dir = os.path.join(input_dir, 'dist')
template_filename = os.path.join(input_dir, 'template.xhtml')
news_items_filename = os.path.join(input_dir, 'news-items.xml')
exclude_files = ('template.xhtml', 'news-items.xml', 'genwebsite.py',
'upload-website.sh', 'update-all.php')
print 'Writing site to %s/' % output_dir
try:
os.makedirs(output_dir)
except OSError:
pass #exists
print '..read news items'
news_items_doc = parse(news_items_filename)
news_items = [item for item in element_children(
news_items_doc.documentElement, 'item')]
print '..write ATOM feed (news.xml)'
atom_filename = os.path.join(output_dir, 'news.xml')
root = ElementTree.Element('feed', xmlns="http://www.w3.org/2005/Atom")
SE = ElementTree.SubElement
title = SE(root, 'title')
title.text = 'Recent news from the pyglet project'
SE(root, 'link', href='http://www.pyglet.org/')
SE(root, 'link', rel='self', href='http://www.pyglet.org/news.xml')
SE(root, 'id').text = 'http://www.pyglet.org/news/'
date = time.strptime(news_items[0].getAttribute('date'), '%d-%B-%Y')
date = time.strftime('%Y-%m-%d', date)
SE(root, 'updated').text = "%sT00:00:00Z" % date
for item in news_items[:10]:
content = element_text(item)
date = time.strptime(item.getAttribute('date'), '%d-%B-%Y')
date = time.strftime('%Y-%m-%d', date)
entry = SE(root, 'entry')
author = SE(entry, 'author')
SE(author, 'name').text = item.getAttribute('author')
SE(entry, 'title').text = item.getAttribute('title')
SE(entry, 'summary').text = content
SE(entry, 'content').text = content
SE(entry, 'updated').text = "%sT00:00:00Z" % date
SE(entry, 'id').text='http://www.pyglet.org/news/' + date
s = open(atom_filename, 'w')
s.write('<?xml version="1.0" encoding="UTF-8" ?>\n')
ElementTree.ElementTree(root).write(s, 'utf-8')
print '..read template'
template = parse(template_filename)
print '..processing files'
for file in os.listdir(input_dir):
if file in exclude_files:
continue
sys.stdout.write('.')
if not file.endswith('.xml'):
if os.path.isfile(os.path.join(input_dir, file)):
shutil.copy(os.path.join(input_dir, file), output_dir)
continue
input_doc = parse(os.path.join(input_dir, file))
output_doc = template.cloneNode(True)
# Insert news items
for news_elem in element_children(input_doc.documentElement, 'news'):
count = None
if news_elem.hasAttribute('items'):
count = int(news_elem.getAttribute('items'))
for item in news_items[:count]:
author = item.getAttribute('author')
date = item.getAttribute('date')
p = input_doc.createElement('p')
p.setAttribute('class', 'news-item')
title = input_doc.createElement('span')
title.setAttribute('class', 'news-title')
title.appendChild(input_doc.createTextNode(
'%s.' % item.getAttribute('title')))
p.appendChild(title)
for child in item.childNodes:
p.appendChild(child.cloneNode(True))
attribution = input_doc.createElement('span')
attribution.setAttribute('class', 'news-attribution')
attribution.appendChild(input_doc.createTextNode(
'Submitted by %s on %s.' % (author, date)))
p.appendChild(attribution)
news_elem.parentNode.insertBefore(p, news_elem)
news_elem.parentNode.removeChild(news_elem)
# Write body content
output_content = get_elem_by_id(output_doc, 'div', 'content')
for child in input_doc.documentElement.childNodes:
output_content.appendChild(child.cloneNode(True))
# Set class on active tab
banner_tabs = get_elem_by_id(output_doc, 'div', 'banner-tabs')
for child in element_children(banner_tabs, 'span'):
if child.hasAttribute('select'):
if child.getAttribute('select') == file:
child.setAttribute('class', 'selected')
child.removeAttribute('select')
output_filename = os.path.join(output_dir,
'%s.html' % os.path.splitext(file)[0])
output_doc.writexml(open(output_filename, 'w'))
print '\nDone.'
| Python |
#!/user/bin/env python
import os, glob, string
path = './'
for infile in glob.glob(os.path.join(path,'*.*')):
#print infile.lower()[3:]
os.system("mv "+infile+" m_"+infile.lower()[2:])
| Python |
#!/user/bin/env python
import os, glob, string
path = './'
for infile in glob.glob(os.path.join(path,'*.*')):
#print infile.lower()[3:]
os.system("mv "+infile+" m_"+infile.lower()[2:])
| Python |
# -*- coding: utf-8 -*-
# python
# process emacs's command frequency file.
# See: http://xahlee.org/emacs/command-frequency.html
# 2007-08
# Xah Lee
import re
from unicodedata import *
# a list of files to read in
input_files = [
"command-frequency_marc.txt",
"command-frequency_marc2.txt",
"command-frequency_xah.txt",
"command-frequency_rgb.txt",
]
# raw data to be read in. Each element is of the form “command:count”
rawdata={}
# a list of commands that's considered “data entry” commands.
data_entry_cmd = ["self-insert-command", "newline"]
# a list of commands that are not counted
notcmd = ["mwheel-scroll", "nil"]
# commands sharing the same keystrokes.
# also, glyph alias for some commands
cmdgroup = {
"next-line":u"↓",
"dired-next-line":u"↓",
"next-history-element":u"↓",
"previous-line":u"↑",
"dired-previous-line":u"↑",
"previous-history-element":u"↑",
"delete-backward-char":u"⌫",
"backward-delete-char-untabify":u"⌫",
"python-backspace":u"⌫",
"cperl-electric-backspace":u"⌫",
"cua-scroll-up":u"▼",
"scroll-up":u"▼",
"scroll-down":u"▲",
"cua-scroll-down":u"▲",
"isearch-forward":u"isearch-→",
"isearch-repeat-forward":u"isearch-→",
"isearch-backward":u"isearch-←",
"isearch-repeat-backward":u"isearch-←",
"backward-char":u"←",
"forward-char":u"→",
"backward-word":u"←w",
"forward-word":u"→w",
"backward-sentence":u"←s",
"forward-sentence":u"→s",
"backward-paragraph":u"↑¶",
"forward-paragraph":u"↓¶",
"move-beginning-of-line":u"|←",
"move-end-of-line":u"→|",
"beginning-of-buffer":u"|◀",
"end-of-buffer":u"▶|",
"delete-char":u"⌦",
"kill-word":u"⌦w",
"backward-kill-word":u"⌫w",
"kill-line":u"⌦l",
"kill-sentence":u"⌦s",
"kill-ring-save":u"copy",
"kill-region":u"✂",
}
# read in each line, skip those starting with “;”
# put it into a rawdata hash
for item in input_files:
f=open(item,'r')
lines = f.readlines()
lines = filter(lambda x: x[0]!=";",lines)
for li in lines:
if li == "\n": continue
parts=re.split(r'\t',li.rstrip(),re.U)
cnt=int(parts[0])
cmd=parts[1]
if cmd in notcmd: continue
#print cmd,cnt
if cmdgroup.has_key(cmd): cmd=cmdgroup[cmd]
if rawdata.has_key(cmd):
rawdata[cmd] = rawdata[cmd] + cnt
else:
rawdata[cmd] = cnt
#for li in lines:print li.rstrip()
# total number of commands
total_cmds = reduce(lambda x,y: x+y,rawdata.values())
# total number of non-data-entry commands
total_nd_cmds = total_cmds
for cmd in data_entry_cmd:
if rawdata.has_key(cmd):
total_nd_cmds -= rawdata[cmd]
# cmdData is a list, where each element is of the form:
# [command name, frequency]
# this list form is easier for sorting
cmdData=[]
for cmd, cnt in rawdata.iteritems():
cmdData.append([cmd,cnt])
cmdData.sort(key=lambda x:x[0]) # sort the cmd names
cmdData.sort(key=lambda x:x[1], reverse=True ) # sort by frequency
print (u'<p>Total number of command calls: %7s</p>' % (total_cmds)).encode('utf-8')
#print (u'<p>Total number of non-data-entry command calls: %7s</p>' % (total_nd_cmds)).encode('utf-8')
print (u'<p>Percent of non-data-entry command calls: %2.f%%</p>' % (float(total_nd_cmds)/total_cmds*100)).encode('utf-8')
print '<table border="1">'
print u'<tr><th>Command Name</th><th>Count</th><th>% total cmd call</th><th>% non-data-entry cmd call</th></tr>'
for el in cmdData:
cmd=el[0]
cnt=el[1]
percT= float(cnt)/total_cmds*100
percND= float(cnt)/total_nd_cmds*100
if percND > 0.1:
print (u'<tr><td class="l">%3s</td><td>%5d</td><td>%2.2f</td><td>%2.2f</td></tr>' % (cmd,cnt,percT,percND)).encode('utf-8')
print '</table>'
| Python |
#!/usr/bin/env python
# This script reads the auto-properties defined in the
# $HOME/.subversion/config file and applies them recursively to all
# the files and directories in the current working copy. It may
# behave differently than the Subversion command line; where the
# subversion command line may only apply a single matching
# auto-property to a single pathname, this script will apply all
# matching lines to a single pathname.
#
# To do:
# 1) Switch to using the Subversion Python bindings.
# 2) Allow a command line option to specify the configuration file to
# load the auto-properties from.
#
# $HeadURL: http://svn.collab.net/repos/svn/branches/1.6.x/contrib/client-side/svn_apply_autoprops.py $
# $LastChangedRevision$
# $LastChangedDate$
# $LastChangedBy: blair $
#
# Copyright (C) 2005,2006 Blair Zajac <blair@orcaware.com>
#
# This script 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 2 of the License, or
# (at your option) any later version.
#
# This script 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.
#
# A copy of the GNU General Public License can be obtained by writing
# to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA.
import fnmatch
import os
import re
import sys
# The path to the Subversion configuration file.
SVN_CONFIG_FILENAME = '$HOME/.subversion/config'
# The name of Subversion's private directory in working copies.
SVN_WC_ADM_DIR_NAME = '.svn'
def get_autoprop_lines(fd):
lines = []
reading_autoprops = 0
re_start_autoprops = re.compile('^\s*\[auto-props\]\s*')
re_end_autoprops = re.compile('^\s*\[\w+\]\s*')
for line in fd.xreadlines():
if reading_autoprops:
if re_end_autoprops.match(line):
reading_autoprops = 0
continue
else:
if re_start_autoprops.match(line):
reading_autoprops = 1
continue
if reading_autoprops:
lines += [line]
return lines
def process_autoprop_lines(lines):
result = []
for line in lines:
# Split the line on the = separating the fnmatch string from the
# properties.
try:
(fnmatch, props) = line.split('=', 1)
except ValueError:
continue
# Remove leading and trailing whitespace from the fnmatch and
# properties.
fnmatch = fnmatch.strip()
props = props.strip()
# Create a list of property name and property values. Remove all
# leading and trailing whitespce from the propery names and
# values.
props_list = []
for prop in props.split(';'):
prop = prop.strip()
if not len(prop):
continue
try:
(prop_name, prop_value) = prop.split('=', 1)
prop_name = prop_name.strip()
prop_value = prop_value.strip()
except ValueError:
prop_name = prop
prop_value = '*'
if len(prop_name):
props_list += [(prop_name, prop_value)]
result += [(fnmatch, props_list)]
return result
def filter_walk(autoprop_lines, dirname, filenames):
# Do no descend into directories that do not have a .svn directory.
try:
filenames.remove(SVN_WC_ADM_DIR_NAME)
except ValueError:
filenames = []
print "Will not process files in '%s' because it does not have a '%s' " \
"directory." \
% (dirname, SVN_WC_ADM_DIR_NAME)
return
filenames.sort()
# Find those filenames that match each fnmatch.
for autoprops_line in autoprop_lines:
fnmatch_str = autoprops_line[0]
prop_list = autoprops_line[1]
matching_filenames = fnmatch.filter(filenames, fnmatch_str)
if not matching_filenames:
continue
for prop in prop_list:
command = ['svn', 'propset', prop[0], prop[1]]
file_path = ''
for f in matching_filenames:
command += ["%s/%s" % (dirname, f)]
file_path += ("%s/%s" % (dirname, f))
if os.path.isdir(file_path):
continue
status = os.spawnvp(os.P_WAIT, 'svn', command)
if status:
print 'Command "%s" failed with exit status %s' \
% (command, status)
sys.exit(1)
def main():
config_filename = os.path.expandvars(SVN_CONFIG_FILENAME)
try:
fd = file(config_filename)
except IOError:
print "Cannot open svn configuration file '%s' for reading: %s" \
% (config_filename, sys.exc_value.strerror)
autoprop_lines = get_autoprop_lines(fd)
fd.close()
autoprop_lines = process_autoprop_lines(autoprop_lines)
os.path.walk('.', filter_walk, autoprop_lines)
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/usr/bin/env python
# This script reads the auto-properties defined in the
# $HOME/.subversion/config file and applies them recursively to all
# the files and directories in the current working copy. It may
# behave differently than the Subversion command line; where the
# subversion command line may only apply a single matching
# auto-property to a single pathname, this script will apply all
# matching lines to a single pathname.
#
# To do:
# 1) Switch to using the Subversion Python bindings.
# 2) Allow a command line option to specify the configuration file to
# load the auto-properties from.
#
# $HeadURL: http://svn.collab.net/repos/svn/branches/1.6.x/contrib/client-side/svn_apply_autoprops.py $
# $LastChangedRevision$
# $LastChangedDate$
# $LastChangedBy: blair $
#
# Copyright (C) 2005,2006 Blair Zajac <blair@orcaware.com>
#
# This script 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 2 of the License, or
# (at your option) any later version.
#
# This script 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.
#
# A copy of the GNU General Public License can be obtained by writing
# to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA.
import fnmatch
import os
import re
import sys
# The path to the Subversion configuration file.
SVN_CONFIG_FILENAME = '$HOME/.subversion/config'
# The name of Subversion's private directory in working copies.
SVN_WC_ADM_DIR_NAME = '.svn'
def get_autoprop_lines(fd):
lines = []
reading_autoprops = 0
re_start_autoprops = re.compile('^\s*\[auto-props\]\s*')
re_end_autoprops = re.compile('^\s*\[\w+\]\s*')
for line in fd.xreadlines():
if reading_autoprops:
if re_end_autoprops.match(line):
reading_autoprops = 0
continue
else:
if re_start_autoprops.match(line):
reading_autoprops = 1
continue
if reading_autoprops:
lines += [line]
return lines
def process_autoprop_lines(lines):
result = []
for line in lines:
# Split the line on the = separating the fnmatch string from the
# properties.
try:
(fnmatch, props) = line.split('=', 1)
except ValueError:
continue
# Remove leading and trailing whitespace from the fnmatch and
# properties.
fnmatch = fnmatch.strip()
props = props.strip()
# Create a list of property name and property values. Remove all
# leading and trailing whitespce from the propery names and
# values.
props_list = []
for prop in props.split(';'):
prop = prop.strip()
if not len(prop):
continue
try:
(prop_name, prop_value) = prop.split('=', 1)
prop_name = prop_name.strip()
prop_value = prop_value.strip()
except ValueError:
prop_name = prop
prop_value = '*'
if len(prop_name):
props_list += [(prop_name, prop_value)]
result += [(fnmatch, props_list)]
return result
def filter_walk(autoprop_lines, dirname, filenames):
# Do no descend into directories that do not have a .svn directory.
try:
filenames.remove(SVN_WC_ADM_DIR_NAME)
except ValueError:
filenames = []
print "Will not process files in '%s' because it does not have a '%s' " \
"directory." \
% (dirname, SVN_WC_ADM_DIR_NAME)
return
filenames.sort()
# Find those filenames that match each fnmatch.
for autoprops_line in autoprop_lines:
fnmatch_str = autoprops_line[0]
prop_list = autoprops_line[1]
matching_filenames = fnmatch.filter(filenames, fnmatch_str)
if not matching_filenames:
continue
for prop in prop_list:
command = ['svn', 'propset', prop[0], prop[1]]
file_path = ''
for f in matching_filenames:
command += ["%s/%s" % (dirname, f)]
file_path += ("%s/%s" % (dirname, f))
if os.path.isdir(file_path):
continue
status = os.spawnvp(os.P_WAIT, 'svn', command)
if status:
print 'Command "%s" failed with exit status %s' \
% (command, status)
sys.exit(1)
def main():
config_filename = os.path.expandvars(SVN_CONFIG_FILENAME)
try:
fd = file(config_filename)
except IOError:
print "Cannot open svn configuration file '%s' for reading: %s" \
% (config_filename, sys.exc_value.strerror)
autoprop_lines = get_autoprop_lines(fd)
fd.close()
autoprop_lines = process_autoprop_lines(autoprop_lines)
os.path.walk('.', filter_walk, autoprop_lines)
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, signal, os
global_debug = False
if "-d" in sys.argv:
global_debug = True
def debug(msg, fr=None):
if global_debug:
if fr: msg = "[%s] %s" % (fr, msg)
print msg
if global_debug: debug("*** Debug output enabled ***", "app")
# find and create configuration directories
home_dir = os.path.expanduser("~")
config_dir = os.path.join(home_dir, ".flashftp")
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
queues_dir = os.path.join(config_dir, "queues")
if not os.path.isdir(queues_dir):
os.mkdir(queues_dir)
# look for our "data" directory
possibilities = ("data", "../data", "/usr/local/lib/flashftp",
"/usr/lib/flashftp")
data_dir = None
for p in possibilities:
if os.path.isdir(p) or os.path.islink(p):
debug("data directory found: %s" % p, "app")
data_dir = p
break
if not data_dir:
sys.stderr.write("[ERROR] data directory NOT found!\n")
sys.exit(1)
# find files
config_file = os.path.join(config_dir, "flash.conf")
glade_file = os.path.join(data_dir, "flash.glade")
# if the glade file was not found we have nowhere to go
if not os.path.isfile(glade_file):
sys.stderr.write("[ERROR] glade file not found, exiting.\n")
sys.exit(1)
import pygtk
pygtk.require('2.0')
import gtk
from gtk import gdk
try:
import dbus
except ImportError:
dbus = None
import browser
import queue
import config
import ftp
import connectdialog
ftp.debugmsg = lambda m: debug(m, "ftp")
class StatusIcon(gtk.StatusIcon):
def __init__(self, appinst):
gtk.StatusIcon.__init__(self)
self.appinst = appinst
self.config = appinst.config
self.set_from_file(os.path.join(data_dir, "flash-64.png"))
class FlashFTPApp:
def __init__(self):
self.browsers = []
self.queues = []
self.preferences_window = None
self.connect_window = None
self.status_icon = None
self.config = config.Config()
self.config.read()
if self.config.getboolean("app", "statusicon"):
self.status_icon = StatusIcon(self)
gdk.threads_init()
for q in os.listdir(queues_dir):
self.new_queue(name=q, load=True)
def close_window(self, window):
"""Called from a browser or queue to be removed.
The object will be closed and dereferenced, and
hopefully released by the gc. TODO: Look into that."""
if window in self.browsers:
self.browsers.remove(window)
elif window in self.queues:
self.queues.remove(window)
elif window is self.preferences_window:
self.preferences_window = None
elif window is self.connect_window:
self.connect_window = None
else:
debug("Closing unknown window: %s" % window, "app")
window.close()
# exit on no windows
if not (self.browsers or self.queues or self.preferences_window or \
self.connect_window):
self.config.write()
gtk.main_quit()
def new_browser(self, connect_dialog=False):
"""Open a new Browser."""
b = browser.BrowserWindow(self)
if connect_dialog:
b.new_connect_dialog()
self.browsers.append(b)
return b
def new_queue(self, name=None, load=False):
"""Open a new Queue.
If load is True, attempt to load the queue from disk."""
if load:
store = queue.queue_from_disk(name)
else:
store = None
if not name:
if len(self.queues) == 0:
name = "Queue"
else:
name = "Queue " + str(len(self.queues) + 1)
q = queue.QueueWindow(self, name=name, store=store)
self.queues.append(q)
return q
def new_preferences(self):
"""Open the preferences window, if not already open."""
if self.preferences_window:
debug("Preferences window already open!", "app")
debug(str(self.preferences_window), "app")
else:
self.preferences_window = config.PreferencesWindow(self)
return self.preferences_window
def new_connect_dialog(self):
"""Open a Connect Dialog with no browser attached."""
self.connect_window = connectdialog.ConnectDialog(self)
def loop(self):
gdk.threads_enter()
try:
gtk.main()
except KeyboardInterrupt:
print "Leaving on ^C"
gdk.threads_leave()
if __name__ == "__main__":
my = FlashFTPApp()
my.new_connect_dialog()
my.loop()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gtk
from gtk import gdk
def units(bytes):
pref = " KMGT"
bytes = float(bytes)
for x in xrange(5):
d = 10**(x*3)
if bytes < d*1024:
return "%s%sB" % (bytes/d % 1 and round(bytes/d, 1) or int(bytes/d), pref[x])
def unic(string):
"""'Failsafe' unicode."""
# What character should be used here?
try:
return unicode(string, 'utf8')
except UnicodeDecodeError:
return unicode(string, 'iso8859', 'replace')
gtk_fiddle_count = 0
def threads(method):
"""GTK+ lock thread decorator.
To prevent that gtk.gdk.threads_enter and threads_leave
will be called more than twice we use a semaphore-like counter
of threads that are fiddling with the gtk internals.
"""
def add_gdk_calls(*args, **kwargs):
global gtk_fiddle_count
gtk_fiddle_count += 1
if not gtk_fiddle_count > 1:
gdk.threads_enter()
method(*args, **kwargs)
gtk_fiddle_count -= 1
if gtk_fiddle_count == 0:
gdk.threads_leave()
return add_gdk_calls
def iters_selection(selection):
"""Returns a list of all iters selected in gtk.TreeSelection."""
i = []
def a(t, p, it):
i.append(it)
selection.selected_foreach(a)
return i
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import fnmatch
import gtk
icon_theme = gtk.icon_theme_get_default()
default_size = 22
match_mappings = {
'*.r[0-9][0-9]': 'package',
'README*': 'ascii',
}
ending_mappings = {
'video': ['.avi', '.wmv', '.asf', '.ogm', '.mkv', '.mpg', '.mpeg'],
'package': ['.rar', '.gz', '.deb', '.bz2'],
'ascii': ['.sfv', '.nfo', '.md5', '.txt', '.cfg', '.py'],
'image': ['.jpg', '.gif', '.png'],
'sound': ['.mp3', '.flac', '.ogg'],
'binary': ['.exe'],
}
cache = {}
def by_filename(filename, size=default_size):
"""Return a pixbuf of the best guess based on filename."""
filename = filename.lower()
# match_match_match lets go nuts.
match_mapping_matches = [x for x in match_mappings.keys() if fnmatch.fnmatch(filename, x)]
if match_mapping_matches:
if icon_theme.has_icon(match_mappings[match_mapping_matches[0]]):
return icon_theme.load_icon(match_mappings[match_mapping_matches[0]], size, 0)
for key in ending_mappings:
for ending in ending_mappings[key]:
if filename.endswith(ending):
return icon_theme.load_icon(key, size, 0)
if len(filename) > 3 and filename[-4] == "." and icon_theme.has_icon(filename[-3:]):
return icon_theme.load_icon(filename[-3:], size, 0)
return None
def from_theme(i, size=None):
"""Return pixbuf of name."""
if type('') == type(i):
if not size: size = default_size
if (i, size) in cache:
return cache[(i, size)]
else:
pixbuf = icon_theme.load_icon(i, size, 0)
cache[(i, size)] = pixbuf
return pixbuf
elif type(0) == type(i):
if not size: size = gtk.ICON_SIZE_MENU
return gtk.image_new_from_stock(i, size)
else:
raise TypeError, "Unknown type '%s' passed to from_theme()" % type(i)
def folder(open=False, size=default_size):
"""Return the icon for a folder."""
s = 'folder%s' % (open and '-open' or '')
if (s, size) in cache:
return cache[(s, size)]
else:
pixbuf = icon_theme.load_icon(s, size, 0)
cache[(s, size)] = pixbuf
return pixbuf
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from ConfigParser import SafeConfigParser
import app
class Config(SafeConfigParser):
def read(self):
read = SafeConfigParser.read(self,
[os.path.join(app.data_dir, "default.config"), app.config_file])
app.debug("Read: %s"%' '.join(read), "config")
def write(self):
fd = open(app.config_file, 'w')
SafeConfigParser.write(self, fd)
app.debug("Configuration written", "config")
del fd
class PreferencesWindow:
def __init__(self, appinst):
self.appinst = appinst
self.config = appinst.config
wTree = gtk.glade.XML(app.glade_file, "preferences_window")
self.wTree = wTree
self.window = wTree.get_widget("preferences_window")
_signals = {
"button_close_clicked":
lambda w: self.appinst.close_window(self),
"destroy":
lambda w: self.appinst.close_window(self),
}
wTree.signal_autoconnect(_signals)
self.load_config()
self.window.show_all()
def close(self):
self.window.destroy()
def load_config(self):
"""Fill in the preferences dialog."""
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from gtk import glade
import flash
class AboutDialog:
def url(self, dialog, link, user_data):
import webbrowser
webbrowser.open(link, 0, 1)
def __init__(self):
gtk.about_dialog_set_url_hook(self.url, None)
self.wTree = gtk.glade.XML(flash.app.glade_file, "flash_about")
self.window = self.wTree.get_widget("flash_about")
self.window.set_icon_from_file(os.path.join(
flash.app.data_dir, "flash-64.png"))
self.window.set_name(flash.__name__)
self.window.set_version(flash.__version__)
self.window.set_logo(gtk.gdk.pixbuf_new_from_file(
os.path.join(flash.app.data_dir, "flash-b.png")))
self.window.show_all()
def run(self):
self.window.run()
self.window.destroy()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os, os.path
import pango
import gobject
import gtk
from gtk import glade
import ftp
import icons
import connectdialog
import about
import app
from gtkmisc import *
class BrowserStore(gtk.TreeStore):
I_FILENAME = 0
I_SIZE = 1
I_ITEM = 2
I_ACCESSIBLE = 3
def __init__(self):
gtk.TreeStore.__init__(self, str, str, object, bool)
self.iters = {'': None}
def _item_to_row(self, item):
return [unic(item.filename),
item.isfile() and units(item.size) or "",
item, True]
# TODO: We could probably do some checks to see if
# the dir is accessible
def add(self, path, item, overwrite=True):
"""Add item at path."""
if not item.filename:
item.filename = "(not set)"
if path.startswith('/'):
path = path[1:]
if not path in self.iters.keys():
try:
p, n = path.rsplit('/', 1)
except ValueError:
p = ""
n = path
self.add(p, ftp.RemoteFile(filename=n, type='d', dir=p,
server=item.server))
parent_iter = self.iters[path]
i = gtk.TreeStore.append(self, parent_iter,
self._item_to_row(item))
self.iters[(path and path + '/' or '') + item.filename] = i
def dir_exists(self, d):
"""Make sure d exists."""
if d.startswith('/'): d = d[1:]
if not d in self.iters:
if '/' in d:
n, p = d.rsplit('/', 1)
else:
n, p = '', d
diritem = ftp.RemoteFile(filename=p, type='d')
self.add(n, diritem, overwrite=False)
def clear(self, path=None):
"""Clear Store. If path is given, clear all entries under path."""
if path == None:
return gtk.TreeStore.clear(self)
if path.startswith("/"): path = path[1:]
path_iter = self.iters[path]
if path_iter == None:
# same as clearing the whole store
return gtk.TreeStore.clear(self)
else:
for iterkey in self.iters.keys():
if iterkey == '': continue
if self.is_ancestor(path_iter, self.iters[iterkey]):
self.remove(self.iters[iterkey])
del self.iters[iterkey]
def select_dir(title="Select destination directory"):
selected = None
chooser = gtk.FileChooserDialog(title=title,
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
response = chooser.run()
if response == gtk.RESPONSE_OK:
selected = chooser.get_filename()
chooser.destroy()
return selected
class LogWindow:
_widgets = ['textview_log', 'entry_cmd', 'button_clear', 'scroll_log']
def __init__(self, parent_window):
self.parent_window = parent_window
self.wTree = gtk.glade.XML(app.glade_file, "log_window")
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget("log_window")
_signals = {
'entry_cmd_activate': self.entry_cmd_activate,
'button_clear_clicked': self.button_clear_clicked,
}
self.wTree.signal_autoconnect(_signals)
buff = self.textview_log.get_buffer()
buff.create_tag("monospaced", family="Monospace")
buff.create_tag("green", foreground="#00e000")
buff.create_tag("blue", foreground="blue")
buff.create_tag("red", foreground="red")
buff.create_tag("bold", weight=pango.WEIGHT_BOLD)
self.window.show_all()
def entry_cmd_activate(self, widget):
cmd = widget.get_text()
if self.parent_window.ftp:
if cmd.startswith("cd "):
cmd, path = cmd.split(" ", 1)
self.parent_window.cd(path)
else:
self.parent_window.ftp.quote(widget.get_text())
widget.set_text('')
else:
app.debug("No FTP connection", "browser")
def button_clear_clicked(self, button):
self.textview_log.get_buffer().set_text('')
def log(self, message, type=0):
buff = self.textview_log.get_buffer()
scroll = self.scroll_log
message = unic("%s\n" % message)
tags = ["monospaced"]
if type == 1: tags.append("green")
elif type == 2: tags.append("blue")
elif type == 3: tags.append("bold")
elif type == 4:
tags.append("bold")
tags.append("red")
end_iter = buff.get_end_iter()
buff.insert_with_tags_by_name(end_iter, message, *tags)
adj = scroll.get_vadjustment()
adj.value = adj.upper
scroll.set_vadjustment(adj)
class BrowserWindow:
_widgets = ['textview_log', 'statusbar', 'scroll_log', 'scroll_files',
'checkitem_io', 'checkitem_hidden']
def __init__(self, appinst):
self.appinst = appinst
self.config = appinst.config
self.wTree = gtk.glade.XML(app.glade_file, "browser_window")
# get widgets
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget('browser_window')
self.tree = self.wTree.get_widget('tree_files')
# connect signals
_signals = {
'tree_files_row_activated': self.tree_row_activate,
#'tree_files_button_release_event': self.tree_button_event,
'tree_files_button_press_event': self.tree_button_event,
'tree_files_cursor_changed': self.tree_cursor_changed,
'tree_files_drag_data_received': self.drag_data_recv,
'browser_window_destroy':
lambda w: self.appinst.close_window(self),
'imagemenuitem_close_activate':
lambda w: self.window.destroy(),
'imagemenuitem_connect_activate':
lambda w: self.new_connect_dialog(),
'menuitem_new_activate':
lambda w: self.appinst.new_browser(),
'checkitem_hidden_toggled':
lambda w: self.config.set("browser",
"show_hidden_files", str(w.get_active())),
'menuitem_about_activate':
lambda w: about.AboutDialog().run(),
'menuitem_new_queue_activate':
lambda q: self.appinst.new_queue(),
'menuitem_preferences_activate':
lambda w: self.appinst.new_preferences(),
'menuitem_log_activate': self.menuitem_log_activate,
'browser_window_check_resize': self.window_resized,
}
self.wTree.signal_autoconnect(_signals)
self.log_window = None
# enable multi-select in treeview
self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
# set up the treeview
self.store = BrowserStore()
self.tree.set_model(self.store)
cell_icon = gtk.CellRendererPixbuf()
cell_name = gtk.CellRendererText()
column_name = gtk.TreeViewColumn("Name")
column_name.pack_start(cell_icon, False)
column_name.pack_start(cell_name, True)
column_name.set_cell_data_func(cell_icon, self.tree_get_icon)
column_name.set_attributes(cell_icon)
column_name.set_attributes(cell_name, text=BrowserStore.I_FILENAME)
column_name.set_expand(True)
column_name.set_max_width(0)
column_name.set_sort_column_id(BrowserStore.I_FILENAME)
self.column_name = column_name
self.tree.append_column(column_name)
self.tree.set_enable_search(True)
self.tree.set_headers_visible(False)
# set up drag and drop on the tree
self.tree.enable_model_drag_dest([('text/plain', 0, 0)],
gtk.gdk.ACTION_DEFAULT)
# resize window
self.window.set_default_size(
self.config.getint("browser", "width"),
self.config.getint("browser", "height")
)
self.in_auto = False # True will turn off listing and pwding
# in browsers callbacks
self.ftp = None
self.homewd = ""
self.window.set_icon_from_file(os.path.join(
app.data_dir, "flash-64.png"))
self.checkitem_hidden.set_active(
self.config.getboolean("browser", "show_hidden_files"))
self.window.show_all()
self.tree.set_sensitive(False)
def window_resized(self, window):
"""The window has been resized. Save new dimensions."""
width, height = window.get_size()
self.config.set("browser", "width", str(width))
self.config.set("browser", "height", str(height))
def close(self):
"""Close window."""
if self.ftp and self.ftp.sock:
self.disconnect()
self.window.destroy()
def new_connect_dialog(self):
"""Creates a new connect dialog for this browser."""
cd = connectdialog.ConnectDialog(self.appinst, browser=self)
cd.window.run()
def cd(self, location):
"""Change current directory to location."""
self.tree.set_sensitive(False)
self.ftp.cwd(location)
def drag_data_recv(self, widget, dc, x, y, selection, info, ts):
files = []
for ld in selection.data.split("\r\n"):
if ld.startswith("file://"): files.append(ld[7:])
if not files:
app.debug("No files dropped")
return
drop_info = self.tree.get_dest_row_at_pos(x, y)
if drop_info:
path, position = drop_info
i = self.store.get_iter(path)
dropped_on = self.store.get_value(i, BrowserStore.I_ITEM)
if dropped_on.isdir():
dropped_on_dir = dropped_on.abs_location()
elif dropped_on.isfile():
dropped_on_dir = dropped_on.dir
app.debug("%s dropped on %s" % (files, dropped_on_dir))
if not self.appinst.queues:
app.debug("No queues to handle drop")
return
que = self.appinst.queues[0] # XXX
for f in files:
rf = ftp.RemoteFile(dir=dropped_on_dir, server=dropped_on.server,
filename=os.path.split(f)[1], size=os.path.getsize(f))
que.append_item(f, rf)
def tree_get_icon(self, column, cell, model, iter):
"""Data function for the file icon in self.tree."""
item = model.get_value(iter, BrowserStore.I_ITEM)
try:
if item.isdir():
if self.tree.row_expanded(self.store.get_path(iter)):
pixbuf = icons.folder(open=True)
else:
pixbuf = icons.folder()
elif item.islink():
pixbuf = icons.from_theme('emblem-symbolic-link')
else:
pixbuf = icons.by_filename(item.filename)
cell.set_property('pixbuf', pixbuf)
except gobject.GError, e:
app.debug("Could not load pixbuf: " + str(e), "browser")
cell.set_property('pixbuf', None)
def tree_row_activate(self, widget, path, column):
item = self.store.get_value(
self.store.get_iter(path), BrowserStore.I_ITEM
)
# change directories if directory
if item.isdir() or item.islink():
self.set_status("Changing Directory")
self.cd(item.abs_location())
elif item.isfile():
app.debug("No action implemented", "browser")
else:
app.debug("Unknown file", "browser")
def tree_cursor_changed(self, widget):
"""Selection changed, update statusbar info."""
iters = iters_selection(self.tree.get_selection())
items = [self.store.get_value(x, BrowserStore.I_ITEM) for x in iters]
if len(items) == 0: return
elif len(items) == 1:
self.set_status("%s, %s" % (items[0].filename,
items[0].isdir() and "(folder)" or units(items[0].size)))
else:
self.set_status("%s items, %s" % (len(items),
str(units(sum([item.size for item in items])))
))
def tree_button_event(self, widget, event):
"""Mouse button pushed over tree. Unclear code is unclear."""
iters = iters_selection(self.tree.get_selection())
if len(iters) == 0:
return
else:
selected = [self.store.get_value(i, BrowserStore.I_ITEM) for i in iters]
def download(items, queue_index=None, download_dir=''):
"""Add items to a queue. If there are no queues, create a new one."""
if not self.appinst.queues:
self.appinst.new_queue()
if queue_index == None:
queue_index = 0
for item in items:
if item.isfile():
self.appinst.queues[queue_index].append_item(item,
os.path.join(download_dir, item.filename))
elif item.isdir():
self.tree.set_sensitive(False)
self.in_auto = True
self.ftp.walk(
item.abs_location(),
queue_number=queue_index,
started_path=item.dir,
target_dir=download_dir
)
# popup menu in right click (button 3)
if event.button == 3:
menu_popup = gtk.Menu()
if selected[0].isdir() or selected[0].islink():
go = gtk.ImageMenuItem("List Directory")
go.set_image(gtk.image_new_from_stock(
"gtk-open", gtk.ICON_SIZE_MENU))
go.connect('activate', lambda w: self.cd(selected[0].abs_location()))
menu_popup.append(go)
def download_if_selected(w, i, q):
dir = select_dir()
if dir:
download(i, download_dir=dir, queue_index=q)
if len(self.appinst.queues) == 0:
it = gtk.ImageMenuItem("Add to new Queue")
it.connect('activate', lambda w:
(self.appinst.new_queue(name=self.server.hostname),
download_if_selected(None, selected, 0)))
if len(self.appinst.queues) == 1:
it = gtk.ImageMenuItem("Add to Queue")
it.connect('activate', download_if_selected, selected, 0)
elif len(self.appinst.queues) > 1:
it = gtk.ImageMenuItem("Add to Queue")
menu_queues = gtk.Menu()
for i, q in enumerate(self.appinst.queues):
foo = gtk.MenuItem(q.name)
foo.connect('activate', download_if_selected, selected, i)
menu_queues.append(foo)
it.set_submenu(menu_queues)
it.set_image(gtk.image_new_from_stock("gtk-save-as", gtk.ICON_SIZE_MENU))
menu_popup.append(it)
d = gtk.ImageMenuItem("Delete")
d.set_image(gtk.image_new_from_stock("gtk-delete", gtk.ICON_SIZE_MENU))
d.connect("activate", lambda w: [self.ftp.delete(x) for x in selected])
menu_popup.append(d)
r = gtk.ImageMenuItem("Rename")
r.set_image(gtk.image_new_from_stock("gtk-rename", gtk.ICON_SIZE_MENU))
menu_popup.append(r)
menu_popup.show_all()
menu_popup.popup(None, None, None, event.button, event.time)
def log(self, *args, **kwargs):
if self.log_window:
self.log_window.log(*args, **kwargs)
def connect(self, server):
"""Connect to FTP server."""
if self.ftp and self.ftp.sock:
self.disconnect()
self.ftp = ftp.FTPThread(daemon=True)
_callbacks = {}
for cb in ftp.FTPThread._all_callbacks:
if hasattr(self, "ftp_%s" % cb):
_callbacks[cb] = getattr(self, "ftp_"+cb)
self.ftp.add_callbacks(_callbacks)
self.set_status("Connecting")
self.log("Connecting to ftp://%s:%s@%s:%s" % \
(server.username,
len(server.password)*"*",
server.hostname,
server.port or "21"))
self.ftp.connect(server)
self.server = server
def disconnect(self):
if self.ftp and self.ftp.sock:
self.ftp.quit()
self.ftp.join()
else:
app.debug("disconnect() called, spite no connection.", "browser")
def set_status(self, message):
context_id = self.statusbar.get_context_id("status")
self.statusbar.pop(context_id)
self.statusbar.push(context_id, message)
def menuitem_log_activate(self, widget):
if not self.log_window:
self.log_window = LogWindow(self)
@threads
def ftp_connected(self, welcomemsg):
self.set_status("Connected to %s" % self.server.hostname)
self.window.set_title("Flash! %s" % self.server.hostname)
self.ftp.login()
@threads
def ftp_connect_error(self, msg):
try:
if len(msg[1]) > 1:
# in many cases, we get a typle with
# errorid, and explaination string
msg = msg[1]
except: pass
self.set_status("Could not connect to %s: %s" % \
(self.server.hostname, str(msg)))
self.log("Could not connect: %s" % str(msg), type=4)
@threads
def ftp_sending(self, data):
app.debug(data, "browser-ftp")
if data.startswith("PASS"):
data = "PASS <hidden>"
self.log(data, type=2)
@threads
def ftp_received(self, data):
app.debug(data, "browser-ftp")
self.log(data, type=1)
@threads
def ftp_authenticated(self, r):
self.set_status("Connected, Authenticated")
self.in_auto = True
self.ftp.pwd() # the ftp session know about current directory
self.ftp.list_parents() # go down and list
@threads
def ftp_authentication_error(self, e):
self.set_status("Not Authenticated")
self.log("Could not authenticate: " + str(e), type=4)
@threads
def ftp_disconnected(self, msg):
self.store.clear()
self.tree.set_sensitive(False)
@threads
def ftp_pwd(self, wd):
app.debug("wd=" + wd + ", listing.", "browser")
self.set_status("Current directory: %s"%wd)
self.store.dir_exists(wd)
if not self.in_auto:
self.set_status("Retreiving Directory Listing")
self.ftp.ls()
if wd[1:]:
# activate this row
store_path = self.store.get_path(self.store.iters[wd[1:]])
self.tree.set_cursor(store_path)
def ftp_cwd(self, msg):
if self.in_auto: return
self.ftp.pwd()
@threads
def ftp_cwd_error(self, msg):
self.tree.set_sensitive(True)
self.set_status("Could not change directory: %s" % msg)
@threads
def ftp_listing(self, listing):
show_hidden = self.config.getboolean('browser', 'show_hidden_files')
self.store.clear(self.ftp.wd)
for item in listing:
if item.ishidden() and not show_hidden: continue
self.store.add(self.ftp.wd, item)
if self.ftp.wd[1:]:
store_path = self.store.get_path(self.store.iters[self.ftp.wd[1:]])
self.tree.expand_row(store_path, True)
if not self.in_auto:
self.tree.set_sensitive(True)
@threads
def ftp_timeout(self, e):
self.log("Timeout: " + str(e), type=4)
@threads
def ftp_unhandled_exception(self, job, exception):
self.log("Unhandled exception in FTP thread: Job: %s Exception: %s" %
(job, exception), type=4)
@threads
def ftp_ssl_enabled(self, server, issuer):
self.log("SSL has been enabled")
@threads
def ftp_deleted(self, filename):
self.set_status("%s deleted" % filename)
# XXX: Remove correct row!
def ftp_walk_end(self):
self.in_auto = False
@threads
def ftp_ssl_not_availible(self, s):
self.log("SSL not availible.", type=4)
self.set_status("No SSL")
@threads
def ftp_list_parents_finished(self):
self.in_auto = False
self.tree.set_sensitive(True)
@threads
def ftp_walk(self, i, queue_number=None, started_path=None, target_dir=None):
target = os.path.join(target_dir, i.filename)
app.debug("Walked %s" % i, "browser")
if started_path:
target = os.path.join(target_dir, i.abs_location()[len(started_path)+1:])
app.debug("Putting in %s" % target, "browser")
if i.isfile():
self.appinst.queues[queue_number].append_item(i, target)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gtk
from gtk import gdk
def units(bytes):
pref = " KMGT"
bytes = float(bytes)
for x in xrange(5):
d = 10**(x*3)
if bytes < d*1024:
return "%s%sB" % (bytes/d % 1 and round(bytes/d, 1) or int(bytes/d), pref[x])
def unic(string):
"""'Failsafe' unicode."""
# What character should be used here?
try:
return unicode(string, 'utf8')
except UnicodeDecodeError:
return unicode(string, 'iso8859', 'replace')
gtk_fiddle_count = 0
def threads(method):
"""GTK+ lock thread decorator.
To prevent that gtk.gdk.threads_enter and threads_leave
will be called more than twice we use a semaphore-like counter
of threads that are fiddling with the gtk internals.
"""
def add_gdk_calls(*args, **kwargs):
global gtk_fiddle_count
gtk_fiddle_count += 1
if not gtk_fiddle_count > 1:
gdk.threads_enter()
method(*args, **kwargs)
gtk_fiddle_count -= 1
if gtk_fiddle_count == 0:
gdk.threads_leave()
return add_gdk_calls
def iters_selection(selection):
"""Returns a list of all iters selected in gtk.TreeSelection."""
i = []
def a(t, p, it):
i.append(it)
selection.selected_foreach(a)
return i
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
__name__ = "Flash!"
__version__ = "0.1"
__version_str__ = '.'.join([str(x) for x in __version__])
__author__ = "Tumi Steingrímsson <tumi.st@gmail.com>"
__licence__ = "GPL"
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gobject
import pango
import time
import gtk
import ftp
import about
import icons
import app
from gtkmisc import *
def nullifnegative(n):
if n < 0:
return 0
else: return n
def get_status_icon(column, cell, model, iter):
direction = model.get_value(iter, QueueStore.I_DIRECTION)
status = model.get_value(iter, QueueStore.I_STATUS)
filename = model.get_value(iter, QueueStore.I_FILENAME)
pixbuf = None
if status == QueueStore.ST_TRANSFERING:
pixbuf = icons.from_theme('player_play', size=16)
elif status == QueueStore.ST_WAITING:
pixbuf = icons.by_filename(filename, size=16)
elif status == QueueStore.ST_ERROR:
pixbuf = icons.from_theme('error', size=16)
elif status == QueueStore.ST_FINISHED:
pixbuf = None
cell.set_property('pixbuf', pixbuf)
return pixbuf
class QueueStore(gtk.ListStore):
I_DIRECTION = 0
I_STATUS = 1
I_FILENAME = 2
I_SIZE = 3
I_STRSIZE = 4
I_TRANSFERRED = 5
I_REMOTE = 6
I_LOCAL = 7
I_ERROR = 8
DR_DOWN = 0
DR_UP = 1
ST_WAITING = 0
ST_TRANSFERING = 1
ST_FINISHED = 2
ST_ERROR = 3
def __init__(self):
gtk.ListStore.__init__(self,
int, int, str, int, str, int, object, str, str)
self.update_size()
def update_size(self, add=None):
"""Sets self.total_size. If add is set, just add it to total_size."""
if add:
self.total_size += add
else:
c = 0
for it in self.iters():
c += self.get_value(it, self.I_SIZE)
self.total_size = c
app.debug(
"Total queue size: %s" % units(self.total_size),
"queue"
)
return self.total_size
def transferred(self):
"""Returns how many bytes in the queues are transferred."""
total = 0
for i in self.iters():
total += self.get_value(i, self.I_TRANSFERRED)
return total
def append(self, item, local, direction=DR_DOWN, status=ST_WAITING):
"""Append a FileItem."""
size = item.isfile() and units(item.size) or ""
list = [direction, status, unic(item.filename),
item.size, size, 0, item, local, '']
if direction == self.DR_DOWN:
if os.path.isfile(local):
transferred = os.path.getsize(local)
list[QueueStore.I_TRANSFERRED] = transferred
if transferred == list[QueueStore.I_SIZE]:
list[QueueStore.I_STATUS] = QueueStore.ST_FINISHED
try:
gtk.ListStore.append(self, list)
except TypeError, e:
print "ERROR! list was:"
print list
return False
self.update_size(add=item.size)
def iters(self):
"""Yield iterators, top-down."""
iter = self.get_iter_first()
while 1:
if not iter:
break
next = self.iter_next(iter)
yield iter
iter = next
def liters(self):
return list(self.iters())
def get_waiting_iter(self):
"""Returns iterator to next waiting item."""
for i in self.iters():
if self.get_value(i, self.I_STATUS) == self.ST_WAITING:
return i
def clear_finished(self):
"""Removes finished transfers."""
for i in self.iters():
if self.get_value(i, self.I_STATUS) == self.ST_FINISHED:
self.remove(i)
self.update_size()
def clear(self):
gtk.ListStore.clear(self)
self.update_size()
def queue_from_disk(fn):
"""Creates a QueueStore from disc.
fn is the name of the queue in queues_dir.
"""
fd = open(app.queues_dir + os.path.sep + fn, 'r')
q = QueueStore()
for i in fd.readlines():
i = i.strip()
list = i.split(';')
list[QueueStore.I_DIRECTION] = int(list[QueueStore.I_DIRECTION])
list[QueueStore.I_STATUS] = int(list[QueueStore.I_STATUS])
list[QueueStore.I_SIZE] = int(list[QueueStore.I_SIZE])
list[QueueStore.I_TRANSFERRED] = int(list[QueueStore.I_TRANSFERRED])
list[QueueStore.I_REMOTE] = ftp.remotefile_from_str(list[QueueStore.I_REMOTE])
gtk.ListStore.append(q, list)
fd.close()
q.update_size()
return q
def serialize(store):
"""Creates multi-line text of a queue. Each line is I_*
separated by the ; character."""
items = []
for i in store.iters():
ml = [str(store.get_value(i, k)) for k in xrange(9)]
ml[QueueStore.I_REMOTE] = store.get_value(i, QueueStore.I_REMOTE).allstr()
items.append(";".join(ml))
return "\n".join(items)
class QueueWindow:
_widgets = ['tree', 'statusbar', 'expander', 'menuitem_run', 'progressbar']
def __init__(self, appinst, name="Queue", store=None):
self.appinst = appinst
self.config = appinst.config
self.name = name
# get widgets
self.wTree = gtk.glade.XML(app.glade_file, "queue_window")
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget('queue_window')
# connect signals
_signals = {
'imagemenuitem_about_activate':
lambda w: about.AboutDialog().run(),
'menuitem_close_activate':
lambda w: self.window.destroy(),
'queue_window_destroy':
lambda w: self.appinst.close_window(self),
'menuitem_run_toggled': self.toggle_run,
'menuitem_clear_activate':
lambda w: (self.store.clear_finished(), self.save()),
'menuitem_clear_all_activate':
lambda w: (self.store.clear(), self.save()),
'menuitem_connect_activate':
lambda w: self.appinst.new_connect_dialog(),
'queue_window_resized': self.window_resized,
'queue_tree_button_press_event':
self.queue_button_event,
'menuitem_rename_activate': lambda w: self.get_new_name(),
}
self.wTree.signal_autoconnect(_signals)
if store:
self.store = store
else:
self.store = QueueStore()
self.tree.set_model(self.store)
# enable multi-selection
self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
for t in ("name", "transferred", "size", "from", "to", "error"):
c = gtk.CellRendererText()
setattr(self, "cell_%s" % t, c)
self.cell_progress = gtk.CellRendererProgress()
self.cell_status = gtk.CellRendererPixbuf()
column_name = gtk.TreeViewColumn("Name")
column_name.pack_start(self.cell_status, False)
column_name.pack_start(self.cell_name, True)
column_size = gtk.TreeViewColumn("Progress")
column_size.pack_start(self.cell_transferred, False)
column_size.pack_start(self.cell_progress, False)
column_size.pack_start(self.cell_size, False)
column_from = gtk.TreeViewColumn("From")
column_from.pack_start(self.cell_from, True)
column_to = gtk.TreeViewColumn("To")
column_to.pack_start(self.cell_to, True)
column_error = gtk.TreeViewColumn("Error")
column_error.pack_start(self.cell_error, False)
column_name.set_attributes(self.cell_name, text=QueueStore.I_FILENAME)
column_name.set_cell_data_func(self.cell_status, get_status_icon)
column_name.set_expand(True)
column_size.set_attributes(self.cell_size, text=QueueStore.I_STRSIZE)
column_size.set_cell_data_func(self.cell_transferred,
lambda c, ce, m, i: ce.set_property('text',
unic(units(m.get_value(i, QueueStore.I_TRANSFERRED)))
)
)
column_size.set_expand(False)
column_from.set_cell_data_func(self.cell_from,
lambda c, ce, m, i: ce.set_property('text', m.get_value(i, m.I_DIRECTION) == m.DR_DOWN and str(m.get_value(i, m.I_REMOTE)) or str(m.get_value(i, m.I_LOCAL))))
column_from.set_expand(True)
column_to.set_cell_data_func(self.cell_to,
lambda c, ce, m, i: ce.set_property('text', m.get_value(i, m.I_DIRECTION) == m.DR_DOWN and str(m.get_value(i, m.I_LOCAL)) or str(m.get_value(i, m.I_REMOTE))))
column_to.set_expand(True)
column_size.set_cell_data_func(self.cell_progress,
lambda c, ce, m, i: ce.set_property('value',
100*m.get_value(i, m.I_TRANSFERRED)/m.get_value(i, m.I_SIZE))
)
column_error.set_attributes(self.cell_error, text=QueueStore.I_ERROR)
self.tree.append_column(column_name)
self.tree.append_column(column_size)
self.tree.append_column(column_from)
self.tree.append_column(column_to)
self.tree.append_column(column_error)
# set window size
self.window.set_default_size(
self.config.getint("queue", "width"),
self.config.getint("queue", "height")
)
# Initialize FTP Thread
self.ftp = ftp.FTPThread(daemon=True)
_callbacks = {}
for cb in ftp.FTPThread._all_callbacks:
if hasattr(self, "ftp_"+cb):
_callbacks[cb] = getattr(self, "ftp_"+cb)
self.ftp.add_callbacks(_callbacks)
# These contain the item and iter of which is currently being processed
self._item = None
self._iter = None
self.window.set_icon_from_file(os.path.join(app.data_dir, "flash-64.png"))
self.window.set_title(self.name)
self.window.show_all()
def close(self):
"""Finish up, destroy window. Called by app."""
if self.ftp.busy():
self.ftp.abor = True
self.ftp.quit()
self.ftp.join()
self.window.destroy()
def save(self):
if self.store.total_size == 0:
if os.path.isfile(os.path.join(app.queues_dir, self.name)):
os.remove(os.path.join(app.queues_dir, self.name))
else:
fd = open("%s%s%s" % (app.queues_dir, os.path.sep, self.name), "w")
fd.write(serialize(self.store))
fd.close()
def toggle_run(self, checkitem):
if checkitem.get_active():
self.pop()
else:
self.stop_queue()
def window_resized(self, window):
width, height = window.get_size()
self.config.set("queue", "width", str(width))
self.config.set("queue", "height", str(height))
def stop_queue(self):
"""Stops the queue."""
if self.ftp.busy():
self.ftp.abor = True
self.ftp.jobs = []
if self._iter: # set current file to 'waiting'
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_WAITING)
self._iter, self._item = None, None
def append_item(self, fr, to, status=0):
"""Appends one item to the queue."""
if isinstance(fr, ftp.RemoteFile) and isinstance(to, str): # a download
self.store.append(fr, to, direction=0, status=status)
app.debug("Adding download item: %s to %s" % (fr, to), "queue")
elif isinstance(to, ftp.RemoteFile) and isinstance(fr, str): # upload
self.store.append(to, fr, direction=1, status=status)
app.debug("Adding upload from %s to %s" % (fr, to), "queue")
else:
raise ValueError, "Unknown from/to types. fr: %s to: %s" % \
(type(fr), type(to))
self.save()
if self.menuitem_run.get_active() and not self.ftp.busy():
app.debug("Popping item since queue is not running.", "queue")
self.pop()
def pop(self, *args):
"""Pop an item.
Should probably not be started while queue is running.
Returns True if there queue was started, False if there were no
items to be transferred.
"""
iter = self.store.get_waiting_iter()
if iter:
# set status to 'transfering'
self.store.set_value(iter, QueueStore.I_STATUS, 1)
# remember item and iter locally
self._item = self.store.get_value(iter, QueueStore.I_REMOTE)
self._iter = iter
# get local path
local = self.store.get_value(iter, QueueStore.I_LOCAL)
direction = self.store.get_value(iter, QueueStore.I_DIRECTION)
if direction == QueueStore.DR_DOWN:
# create dir if it doesn't exist
if os.path.sep in local and not os.path.isdir(os.path.dirname(local)):
os.makedirs(os.path.dirname(local))
# now transfer it
app.debug("Downloading %s to %s" % (self._item.filename, local), "queue")
self.set_statusbar("Downloading")
self.ftp.download(self._item, local, rest=True)
elif direction == QueueStore.DR_UP:
app.debug("Uplading %s to %s" % (local, self._item.filename))
self.set_statusbar("Uploading")
self.ftp.upload(local, self._item)
return True
else:
return False
def queue_button_event(self, widget, event):
iters = iters_selection(self.tree.get_selection())
if len(iters) == 0:
return
def move_to_top(iters):
for iter in iters[::-1]:
self.store.move_before(iter, self.store.liters()[0])
self.save()
def move_to_bottom(iters):
for iter in iters:
self.store.move_after(iter, self.store.liters()[-1])
self.save()
def remove(iters):
for iter in iters:
self.store.remove(iter)
self.save()
if event.button == 3:
menu = gtk.Menu()
mt = gtk.ImageMenuItem(stock_id=gtk.STOCK_GOTO_TOP)
mt.connect('activate', lambda w: move_to_top(iters))
mb = gtk.ImageMenuItem(stock_id=gtk.STOCK_GOTO_BOTTOM)
mb.connect('activate', lambda w: move_to_bottom(iters))
mr = gtk.ImageMenuItem(stock_id=gtk.STOCK_REMOVE)
mr.connect('activate', lambda w: remove(iters))
menu.append(mt)
menu.append(mb)
menu.append(mr)
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
def set_statusbar(self, message):
context_id = self.statusbar.get_context_id("status")
self.statusbar.pop(context_id)
self.statusbar.push(context_id, message)
def set_progress(self):
"""Update window title and progressbar with values from self.store"""
done = self.store.transferred() * 1.0 / self.store.total_size
self.progressbar.set_fraction(done)
self.window.set_title("%s - %i%%" % (self.name, done*100))
def get_new_name(self):
"""Open a dialog for new name."""
dtree = gtk.glade.XML(app.glade_file, 'dialog_rename_queue')
w = dtree.get_widget('dialog_rename_queue')
cancel = dtree.get_widget('button_cancel')
ok = dtree.get_widget('button_ok')
entry = dtree.get_widget('entry_name')
entry.set_text(self.name)
cancel.connect('clicked', lambda i: w.destroy())
def set_name():
self.name = entry.get_text()
self.window.set_title(self.name)
ok.connect('clicked', lambda i: (set_name(), w.destroy()))
w.show_all()
w.run()
def ftp_received(self, data):
app.debug(data, "queue-ftp")
def ftp_sending(self, data):
app.debug(data, "queue-ftp")
@threads
def ftp_ssl_enabled(self, server, issuer):
self.set_statusbar("SSL has been enabled")
@threads
def ftp_authenticated(self, r):
self.set_statusbar("Connected, Authenticated")
self.ftp.cwd(self._item.dir)
@threads
def ftp_connected(self, msg):
self.set_statusbar("Connected")
@threads
def ftp_authentication_error(self, e):
self.set_statusbar("Authentication err: " + str(e))
@threads
def ftp_cwd_error(self, msg):
app.debug("Could not CWD to directory!", "queue")
@threads
def ftp_transfer_finished(self, cmd):
self.set_statusbar("Transfer finished")
# update transferred in store
self.store.set_value(self._iter, QueueStore.I_TRANSFERRED,
self.store.get_value(self._iter, QueueStore.I_SIZE))
self._item = None
# change item to finished in the liststore
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_FINISHED)
# move it to bottom
if self.config.getboolean("queue", "finished_files_to_bottom"):
self.store.move_after(self._iter, list(self.store.iters())[-1])
self._iter = None
self.set_progress()
self.save()
self.pop()
def ftp_unhandled_exception(self, job, exception):
app.debug("Unhandled exception in FTP thread: Job: %s Exception: %s" % \
(job, exception), "queue")
@threads
def ftp_transfer_aborted(self, cmd):
self.set_statusbar("Transfer aborted")
self.set_progress()
last_t = time.time()
last_p = 0
@threads
def ftp_retr_pos(self, pos, cmd):
t = time.time()
if t-self.last_t < 1 or pos == -1: return
else:
self.set_statusbar("Downloading %s/s" % (
units((nullifnegative(pos-self.last_p))/(t-self.last_t)))
)
self.last_t = t
self.last_p = pos
# update transferred bytes in store
self.store.set_value(self._iter, QueueStore.I_TRANSFERRED, pos)
self.set_progress()
@threads
def ftp_download_error(self, error):
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_ERROR)
self.store.set_value(self._iter, QueueStore.I_ERROR, error)
@threads
def ftp_stor_error(self, error):
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_ERROR)
self.store.set_value(self._iter, QueueStore.I_ERROR, error)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from gtk import glade
import app
import ftp
import icons
class ConnectDialog:
def __init__(self, appinst, browser=None):
self.appinst = appinst
self.config = appinst.config
self.browser = browser
self.wTree = glade.XML(app.glade_file, "dialog_connect")
self.window = self.wTree.get_widget('dialog_connect')
self.combobox_sites = self.wTree.get_widget('combobox_sites')
self.entry_host = self.wTree.get_widget('entry_host')
self.entry_user = self.wTree.get_widget('entry_user')
self.entry_password = self.wTree.get_widget('entry_password')
self.checkbutton_use_ssl = self.wTree.get_widget('checkbutton_use_ssl')
self.checkbutton_force_ssl = self.wTree.get_widget('checkbutton_force_ssl')
self.checkbutton_passive = self.wTree.get_widget('checkbutton_passive')
_signals = {'close': lambda w: self.appinst.close_window(self),
'cancel_clicked': lambda w: self.appinst.close_window(self),
'save_clicked': self.save,
'connect_clicked': lambda w: self.connect(),
'combobox_sites_changed': self.select_site,
'button_delete_clicked': self.delete_selected,
'entry_user_activate': lambda w: self.connect(),
'entry_host_activate': lambda w: self.connect(),
'entry_password_activate': lambda w: self.connect(),
}
self.wTree.signal_autoconnect(_signals)
self.window.set_icon(icons.from_theme("gtk-network", 16))
self.store = gtk.ListStore(str)
self.combobox_sites.set_model(self.store)
self.fill_site_menu()
self.window.show_all()
def close(self, *w):
# destroy reference to this object, if browser has that is
if self.browser:
self.browser.connect_dialog = None
self.window.destroy()
def fill_site_menu(self):
"""Fills the combobox with the saved sites."""
self.store.clear()
for x in self.config.sections():
if x.startswith("site:"):
self.store.append([x[5:]])
def delete_selected(self, w):
"""Delete selected site from config."""
iter = self.combobox_sites.get_active_iter()
if not iter: return
site = self.store.get_value(iter, 0)
self.config.remove_section('site:'+site)
self.fill_site_menu()
def save(self, w):
dTree = glade.XML(app.glade_file, "dialog_site_name")
dwindow = dTree.get_widget('dialog_site_name')
dentry = dTree.get_widget('entry_name')
dpass = dTree.get_widget('checkbutton_password')
if self.entry_user.get_text():
dentry.set_text('@'.join([
self.entry_user.get_text(),
self.entry_host.get_text()
]))
else:
dentry.set_text(self.entry_host.get_text())
def doEnd(*args):
dwindow.destroy()
def doSave(*args):
cfgstr = 'site:'+dentry.get_text()
if not self.config.has_section(cfgstr):
self.config.add_section(cfgstr)
self.config.set(cfgstr, 'hostname', self.entry_host.get_text())
self.config.set(cfgstr, 'username', self.entry_user.get_text())
if dpass.get_active():
self.config.set(cfgstr, 'password', self.entry_password.get_text())
self.config.set(cfgstr, 'use_ssl',
str(self.checkbutton_use_ssl.get_active()))
self.config.set(cfgstr, 'force_ssl',
str(self.checkbutton_force_ssl.get_active()))
self.config.set(cfgstr, 'passive',
str(self.checkbutton_passive.get_active()))
doEnd()
_signals = {'button_save_clicked': doSave,
'button_cancel_clicked': doEnd}
dTree.signal_autoconnect(_signals)
dwindow.show_all()
def connect(self):
"""Connect with the information given.
Create a FTPServer object and tell parent to use it."""
host = self.entry_host.get_text()
if ':' in host:
host, port = host.split(':', 1)
port = int(port)
else:
port = 21
s = dict(
username = self.entry_user.get_text() or "anonymous",
password = self.entry_password.get_text() or
self.config.get("ftp", "anonymous_password"),
port = port,
protocol = self.checkbutton_use_ssl.get_active() and "ftp+ssl" or "ftp",
passive = self.checkbutton_passive.get_active(),
)
server = ftp.Server(host, **s)
self.window.hide_all()
if self.browser:
self.browser.connect(server)
else:
self.appinst.new_browser().connect(server)
self.appinst.close_window(self)
def select_site(self, cb):
site = cb.get_active_text()
app.debug("Site selected: " + site, "connectdialog")
cfgstr = 'site:'+site
host = self.config.get(cfgstr, 'hostname')
if self.config.has_option(cfgstr, 'port'):
port = self.config.getint(cfgstr, 'port')
if port != 21:
host += ":%s"%str(port)
user = self.config.get(cfgstr, 'username')
self.entry_host.set_text(host)
self.entry_user.set_text(user)
if self.config.has_option(cfgstr, 'password'):
p = self.config.get(cfgstr, 'password')
self.entry_password.set_text(p)
else:
self.entry_password.set_text('')
# de-activate checkbutton_use_ssl if False
if self.config.has_option(cfgstr, 'use_ssl'):
self.checkbutton_use_ssl.set_active(
self.config.getboolean(cfgstr, 'use_ssl'))
# activate checbutton_force_ssl if set
if self.config.has_option(cfgstr, 'force_ssl'):
self.checkbutton_force_ssl.set_active(
self.config.getboolean(cfgstr, 'force_ssl'))
# set passive
if self.config.has_option(cfgstr, 'passive'):
self.checkbutton_passive.set_active(
self.config.getboolean(cfgstr, 'passive'))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, signal, os
global_debug = False
if "-d" in sys.argv:
global_debug = True
def debug(msg, fr=None):
if global_debug:
if fr: msg = "[%s] %s" % (fr, msg)
print msg
if global_debug: debug("*** Debug output enabled ***", "app")
# find and create configuration directories
home_dir = os.path.expanduser("~")
config_dir = os.path.join(home_dir, ".flashftp")
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
queues_dir = os.path.join(config_dir, "queues")
if not os.path.isdir(queues_dir):
os.mkdir(queues_dir)
# look for our "data" directory
possibilities = ("data", "../data", "/usr/local/lib/flashftp",
"/usr/lib/flashftp")
data_dir = None
for p in possibilities:
if os.path.isdir(p) or os.path.islink(p):
debug("data directory found: %s" % p, "app")
data_dir = p
break
if not data_dir:
sys.stderr.write("[ERROR] data directory NOT found!\n")
sys.exit(1)
# find files
config_file = os.path.join(config_dir, "flash.conf")
glade_file = os.path.join(data_dir, "flash.glade")
# if the glade file was not found we have nowhere to go
if not os.path.isfile(glade_file):
sys.stderr.write("[ERROR] glade file not found, exiting.\n")
sys.exit(1)
import pygtk
pygtk.require('2.0')
import gtk
from gtk import gdk
try:
import dbus
except ImportError:
dbus = None
import browser
import queue
import config
import ftp
import connectdialog
ftp.debugmsg = lambda m: debug(m, "ftp")
class StatusIcon(gtk.StatusIcon):
def __init__(self, appinst):
gtk.StatusIcon.__init__(self)
self.appinst = appinst
self.config = appinst.config
self.set_from_file(os.path.join(data_dir, "flash-64.png"))
class FlashFTPApp:
def __init__(self):
self.browsers = []
self.queues = []
self.preferences_window = None
self.connect_window = None
self.status_icon = None
self.config = config.Config()
self.config.read()
if self.config.getboolean("app", "statusicon"):
self.status_icon = StatusIcon(self)
gdk.threads_init()
for q in os.listdir(queues_dir):
self.new_queue(name=q, load=True)
def close_window(self, window):
"""Called from a browser or queue to be removed.
The object will be closed and dereferenced, and
hopefully released by the gc. TODO: Look into that."""
if window in self.browsers:
self.browsers.remove(window)
elif window in self.queues:
self.queues.remove(window)
elif window is self.preferences_window:
self.preferences_window = None
elif window is self.connect_window:
self.connect_window = None
else:
debug("Closing unknown window: %s" % window, "app")
window.close()
# exit on no windows
if not (self.browsers or self.queues or self.preferences_window or \
self.connect_window):
self.config.write()
gtk.main_quit()
def new_browser(self, connect_dialog=False):
"""Open a new Browser."""
b = browser.BrowserWindow(self)
if connect_dialog:
b.new_connect_dialog()
self.browsers.append(b)
return b
def new_queue(self, name=None, load=False):
"""Open a new Queue.
If load is True, attempt to load the queue from disk."""
if load:
store = queue.queue_from_disk(name)
else:
store = None
if not name:
if len(self.queues) == 0:
name = "Queue"
else:
name = "Queue " + str(len(self.queues) + 1)
q = queue.QueueWindow(self, name=name, store=store)
self.queues.append(q)
return q
def new_preferences(self):
"""Open the preferences window, if not already open."""
if self.preferences_window:
debug("Preferences window already open!", "app")
debug(str(self.preferences_window), "app")
else:
self.preferences_window = config.PreferencesWindow(self)
return self.preferences_window
def new_connect_dialog(self):
"""Open a Connect Dialog with no browser attached."""
self.connect_window = connectdialog.ConnectDialog(self)
def loop(self):
gdk.threads_enter()
try:
gtk.main()
except KeyboardInterrupt:
print "Leaving on ^C"
gdk.threads_leave()
if __name__ == "__main__":
my = FlashFTPApp()
my.new_connect_dialog()
my.loop()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import fnmatch
import gtk
icon_theme = gtk.icon_theme_get_default()
default_size = 22
match_mappings = {
'*.r[0-9][0-9]': 'package',
'README*': 'ascii',
}
ending_mappings = {
'video': ['.avi', '.wmv', '.asf', '.ogm', '.mkv', '.mpg', '.mpeg'],
'package': ['.rar', '.gz', '.deb', '.bz2'],
'ascii': ['.sfv', '.nfo', '.md5', '.txt', '.cfg', '.py'],
'image': ['.jpg', '.gif', '.png'],
'sound': ['.mp3', '.flac', '.ogg'],
'binary': ['.exe'],
}
cache = {}
def by_filename(filename, size=default_size):
"""Return a pixbuf of the best guess based on filename."""
filename = filename.lower()
# match_match_match lets go nuts.
match_mapping_matches = [x for x in match_mappings.keys() if fnmatch.fnmatch(filename, x)]
if match_mapping_matches:
if icon_theme.has_icon(match_mappings[match_mapping_matches[0]]):
return icon_theme.load_icon(match_mappings[match_mapping_matches[0]], size, 0)
for key in ending_mappings:
for ending in ending_mappings[key]:
if filename.endswith(ending):
return icon_theme.load_icon(key, size, 0)
if len(filename) > 3 and filename[-4] == "." and icon_theme.has_icon(filename[-3:]):
return icon_theme.load_icon(filename[-3:], size, 0)
return None
def from_theme(i, size=None):
"""Return pixbuf of name."""
if type('') == type(i):
if not size: size = default_size
if (i, size) in cache:
return cache[(i, size)]
else:
pixbuf = icon_theme.load_icon(i, size, 0)
cache[(i, size)] = pixbuf
return pixbuf
elif type(0) == type(i):
if not size: size = gtk.ICON_SIZE_MENU
return gtk.image_new_from_stock(i, size)
else:
raise TypeError, "Unknown type '%s' passed to from_theme()" % type(i)
def folder(open=False, size=default_size):
"""Return the icon for a folder."""
s = 'folder%s' % (open and '-open' or '')
if (s, size) in cache:
return cache[(s, size)]
else:
pixbuf = icon_theme.load_icon(s, size, 0)
cache[(s, size)] = pixbuf
return pixbuf
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import socket
import threading
import ftplib
import os
def debugmsg(msg):
"""Override as fits."""
CRLF = ftplib.CRLF
def clearwhites(s):
"""This is not a racist function. I takes all
multiple whitespaces away."""
return ' '.join([x for x in s.split(' ') if x])
class Server:
"""A representation of an FTP server."""
protocols = ['ftp', 'ftp+ssl'] # accepted protocols
def __init__(self, hostname, **kwargs):
self.hostname = hostname
self.username = kwargs.get("username", None)
self.password = kwargs.get("password", None)
self.port = kwargs.get("port", 21)
self.protocol = kwargs.get("protocol", "ftp")
self.directory = kwargs.get("directory", None)
self.passive = kwargs.get("passive", True)
self.force_ssl = kwargs.get("force_ssl", False)
self.validate()
def __str__(self):
port = ''
if self.port != 21:
port = ":%s" % self.port
return "%s://%s%s" % (self.protocol, self.hostname, port)
def allstr(self):
return "%s://%s:%s@%s:%s" % (self.protocol, self.username,
self.password, self.hostname, self.port)
def validate(self):
if not self.protocol in self.protocols:
raise ValueError, "%s is unknown protocol" % self.protocol
class RemoteFile:
"""Represents a file on an FTP server."""
def __init__(self, **kwargs):
self.filename = kwargs.get("filename", None)
# the containing directory of this file
self.dir = kwargs.get("dir", None)
# the type of this file: f, d or l
self.type = kwargs.get("type", None)
# size in bytes
self.size = int(kwargs.get("size", 0))
# permissions on this file
self.unix_perm = kwargs.get("unix_perm", None)
# owner on server
self.owner = kwargs.get("owner", None)
# group on server
self.group = kwargs.get("group", None)
# changed date
self.ctime = kwargs.get("ctime", None)
# if this is a symbolic link, specify target file
self.linkto = kwargs.get("linkto", None)
# a Server object
self.server = kwargs.get("server")
def __repr__(self):
return "<RemoteFile %s type: %s>" % \
(self.filename, self.type)
def __str__(self):
"""Return URL for this file.
Without username and password and stuff."""
return "%s%s/%s" % (self.server, self.dir, self.filename)
def allstr(self):
"""Return URL with all information."""
return "%s%s/%s?%s" % (self.server.allstr(), self.dir, self.filename,
"&".join(["type=%s"%self.type and self.type]))
def __int__(self):
return self.size
def ishidden(self):
if self.filename.startswith('.') or self.filename.endswith('~'):
return True
else:
return False
def islink(self):
return self.type == 'l'
def isfile(self):
return self.type == 'f'
def isdir(self):
return self.type == 'd'
def abs_location(self):
"""Absolute location on server."""
if self.dir == "/":
return "/%s" % self.filename
else:
return "%s/%s" % (self.dir, self.filename)
def remotefile_from_str(s):
import urllib
protocol, rest = s.split("://")
host, rest = urllib.splithost("//" + rest)
host, port = urllib.splitnport(host, defport=21)
file, t = urllib.splitquery(rest)
s = Server(host, port=port)
dir, fn = os.path.split(file)
rf = RemoteFile(filename=fn, dir=dir, type="f", server=s)
return rf
def parse_LIST(list_output, dir, server):
"""Interpret LIST output and return RemoteFiles.
list_output should be in a list format (each line from
server a string in the list).
dir is the directory for witch the files are in."""
for line in list_output:
line = clearwhites(line)
if line.startswith('total'):
continue
tokens = line.split(' ', 8)
# item will be yielded later
item = RemoteFile(server=server)
item.type = line[0]
item.size = int(tokens[4])
item.filename = tokens[-1]
item.unix_perm = tokens[0][1:]
item.owner = tokens[2]
item.group = tokens[3],
item.ctime = ''.join(tokens[5:8])
item.dir = dir
# correct symbolic link issues
if line[0] == "l":
item.filename, item.linkto = item.filename.split(" -> ")
elif line[0] == "-":
item.type = "f"
yield item
def parse_MLSD(mlsd_output, dir, server):
"""Interpret MLSD output."""
for line in mlsd_output:
attrs = line.split(';')
kwargs = {}
for attr in attrs[:-1]:
option, value = attr.split('=')
if option == 'type':
kwargs[option] = value[0]
continue
if option == 'size':
kwargs[option] = int(value)
continue
kwargs[option] = value
kwargs['filename'] = attrs[-1][1:]
kwargs['dir'] = dir
item = RemoteFile(server=server, **kwargs)
yield item
class FTP(ftplib.FTP):
"""Improvements to ftplib.FTP"""
class FTPThread(FTP, threading.Thread):
"""FTP Thread built on ftplib.FTP, but with significant
improvements to the standard function, SSL, MLST and
MLSD commands to name a few.
Current job will be in self.current_job
Waiting jobs in self.jobs, clear with jobs = []
Some jobs can be aborted:
* retrbinary can be stopped by switching self.abor to true
ABOR will be sent and data connection closed.
Callbacks: (Arguments...)
* connected: Socket connected to host (welcome_msg)
* connect_error: Socket could not connect to host (exception)
* authenticated: Authentication was successful (response)
* authentication_error: Authentication error (error_str)
* sending: About to send this (data)
* received: Received line (data)
* disconnected: Disconnected from server (reason)
* pwd: Workin directory (directory)
* cwd: Current directory changed (msg)
* cwd_error: Error on changing directories (reason)
* dir: Output from LIST (list)
* timeout: General timeout (exception)
* retr_pos: Bytes read of current receiving file (stream position, cmd)
cmd = the original line sent to server to initiate the transfer
* transfer_finished: This transfer has finished (cmd)
* transfer_aborted: This transfer was aborted (cmd)
* unhandled_exception: Unhandled exception occured (job, exception)
* ssl_enabled: Data-connection has engaged encryption (server, issuer)
* ssl_not_availible: Called when we find out that there is no SSL support (str)
* mlsd: the output from this command ()
* deleted: File was deleted (filename)
* delete_error: File was not deleted (filename, error_string)
* walk: Items in one directory from walk (item, **kwargs)
* walk_end: ()
* walk_error:
* list_parents_finished: ()
* downloaded: File downloaded (remote, to)
* download_error: Error in download() (e)
* stor_pos: Sent bytes via STOR.
* stor_error: Error in upload (e)
"""
_all_callbacks = ['connected', 'connect_error', 'authenticated',
'authentication_error', 'sending', 'received', 'disconnected', 'pwd',
'cwd', 'cwd_error', 'dir', 'timeout', 'retr_pos', 'transfer_finished',
'transfer_aborted', 'unhandled_exception', 'ssl_enabled', 'mlsd',
'listing', 'walk', 'deleted', 'delete_error', 'ssl_not_availible', 'walk_end',
'list_parents_finished', 'stor_pos', 'stor_error']
def __init__(self, socket_timeout=0, data_socket_timeout=0,
daemon=False, server=None):
"""
Arguments:
socket_timeout => The timeout in the control-connection
data_socket_timeout => Timeout for data-connection
daemon => whether to daemonize thread
server => Server object to use
"""
threading.Thread.__init__(self)
self.socket_timeout = socket_timeout
self.data_socket_timeout = data_socket_timeout
self.feats = []
self.ssl_buffer = ''
self.ssl_sock = None
self.abor = False
self.callbacks = {}
self.jobs = []
self.current_job = None
self.wd = ""
self.list_cache = {}
# Server object (not needed until connect())
self.server = server
self.lock = threading.Semaphore()
self.lock.acquire(True) # a new lock can be released once
self.setDaemon(daemon)
if not self.isAlive():
self.start()
def getline(self):
""" Internal: Reads one line from (ssl)socket """
if self.ssl_sock:
while not self.ssl_buffer.count(CRLF):
self.ssl_buffer += self.ssl_sock.read()
pos = self.ssl_buffer.find(CRLF) + 2
line = self.ssl_buffer[:pos]
self.ssl_buffer = self.ssl_buffer[pos:]
else:
line = self.file.readline()
if line:
if line[-2:] == CRLF: line = line[:-2]
elif line[-1:] in CRLF: line = line[:-1]
self.callback('received', line)
else:
self.callback('disconnected', line)
return line
def putline(self, line):
""" Internal: Write line to (ssl)socket """
self.callback('sending', line)
line = line + CRLF
if self.ssl_sock:
self.ssl_sock.write(line)
else:
self.sock.sendall(line)
def parse_feat_response(self, r):
"""Internal:
Parse response from FEAT.
FEATs will be stored in self.feats."""
if r.count(CRLF):
r = r.split(CRLF)
else:
r = r.split("\n")
for l in r:
if not len(l) > 1:
continue
if l[1] == "1":
continue
self.feats.append(l[1:])
def connect(self, server=None):
"""Connect to host."""
if server:
self.server = server
self.add_job("_connect")
def _connect(self):
"""Internal."""
self.set_pasv(self.server.passive)
msg = "getaddrinfo returns an empty list"
try:
foo = socket.getaddrinfo(self.server.hostname,
self.server.port, 0, socket.SOCK_STREAM)
except Exception, e:
self.callback('connect_error', e)
return
for res in foo:
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.socket_timeout:
self.sock.settimeout(self.socket_timeout)
self.sock.connect(sa)
except socket.error, msg:
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
self.callback('connect_error', msg)
return
self.af = af
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
try:
self.parse_feat_response(self.voidcmd("FEAT"))
except ftplib.error_perm:
pass
if "ssl" in self.server.protocol and "AUTH TLS" in self.feats:
try:
self.make_ssl()
except Exception, e:
self.callback('ssl_not_availible', str(e))
elif self.server.force_ssl:
try:
self.make_ssl()
except Exception, e:
self.callback('ssl_not_availible', str(e))
# jump ship!
self._quit()
return
self.callback("connected", self.welcome)
return self.welcome
def makeport(self):
"""
Internal: Create a new socket and send a PORT command for it.
"""
msg = "getaddrinfo returns an empty list"
sock = None
for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
sock = socket.socket(af, socktype, proto)
if self.data_socket_timeout:
sock.settimeout(self.data_socket_timeout)
sock.bind(sa)
except socket.error, msg:
if sock:
sock.close()
sock = None
continue
break
if not sock:
raise socket.error, msg
sock.listen(1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockname()[0] # Get proper host
if self.af == socket.AF_INET:
resp = self.sendport(host, port)
else:
resp = self.sendeprt(host, port)
return sock
def ntransfercmd(self, cmd, rest=None):
"""
Internal:
Initiate a transfer over the data connection.
If the transfer is active, send a port command and the
transfer command, and accept the connection. If the server is
passive, send a pasv command, connect to it, and start the
transfer command. Either way, return the socket for the
connection and the expected size of the transfer. The
expected size may be None if it could not be determined.
Optional `rest' argument can be a string that is sent as the
argument to a RESTART command. This is essentially a server
marker used to tell the server to skip over any data up to the
given marker.
"""
size = None
if self.passiveserver:
host, port = self.makepasv()
af, socktype, proto, canon, sa = socket.getaddrinfo(host, port,
0, socket.SOCK_STREAM)[0]
conn = socket.socket(af, socktype, proto)
if self.data_socket_timeout:
conn.settimeout(self.data_socket_timeout)
conn.connect(sa)
if rest is not None:
self.sendcmd("REST %s" % rest)
resp = self.sendcmd(cmd)
if resp[0] != '1':
raise error_reply, resp
else:
sock = self.makeport()
if rest is not None:
self.sendcmd("REST %s" % rest)
resp = self.sendcmd(cmd)
if resp[0] != '1':
raise error_reply, resp
conn, sockaddr = sock.accept()
if resp[:3] == '150':
# this is conditional in case we received a 125
size = ftplib.parse150(resp)
return conn, size
def login(self):
"""Send login commands."""
self.add_job("_login")
def _login(self):
try:
resp = ftplib.FTP.login(self,
user=self.server.username, passwd=self.server.password)
except ftplib.error_reply, e:
self.callback("authentication_error", e)
except Exception, e:
self.callback("authentication_error", e)
else:
if not self.feats:
self.parse_feat_response(self.voidcmd("FEAT"))
self.callback("authenticated", resp)
def mlsd(self, argument=''):
""" Send MLSD command (use self.ls instead!) """
self.add_job("_mlsd", argument=argument)
def _mlsd(self, argument='', hidden=False):
output = []
try:
resp = self.retrlines(argument and "MLSD %s" % argument \
or "MLSD", output.append)
except socket.timeout, e:
self.callback("timeout", e)
return
self.callback('mlsd', output)
return resp, output
def make_ssl(self):
""" Creates self.ssl_sock socket. Returns AUTH TLS reply. """
debugmsg("Creating SSL socket")
resp = self.voidcmd("AUTH TLS")
self.ssl_sock = socket.ssl(self.sock)
self.ssl_initialized = True
return resp
def callback(self, callback_key, *args, **kwargs):
"""Internal"""
if self.callbacks.has_key(callback_key):
for func in self.callbacks[callback_key]:
try:
func(*args, **kwargs)
except Exception, e:
import traceback, sys
print "Fatal error in callback, trace:"
traceback.print_exc(file=sys.stdout)
def add_job(self, jobname, *args, **kwargs):
"""Internal: Adds a job to the queue"""
self.jobs.append((jobname, args, kwargs))
self.lock.release()
def quit(self):
self.add_job("_quit")
def _quit(self):
resp = ftplib.FTP.quit(self)
self.callback("disconnected", str(resp))
def pwd(self):
""" Print working directory """
self.add_job("_pwd")
def _pwd(self):
resp = ftplib.FTP.pwd(self)
self.wd = resp
self.callback("pwd", resp)
return resp
def cwd(self, d):
""" Change working directory """
self.add_job("_cwd", d)
def _cwd(self, d):
try:
resp = ftplib.FTP.cwd(self, d)
except (ftplib.error_reply, ftplib.error_perm), e:
self.callback("cwd_error", str(e))
return False
else:
self.callback("cwd", resp)
return True
def dir(self):
""" Send LIST command (use self.ls instead!) """
self.add_job("_dir")
def _dir(self, hidden=False, *args):
output = []
try:
if hidden:
resp = ftplib.FTP.dir(self, '-l', output.append)
else:
resp = ftplib.FTP.dir(self, output.append)
except socket.timeout, e:
self.callback("timeout", e)
return
return resp, output
def retrbinary(self, *args, **kwargs):
self.add_job("_retrbinary", *args, **kwargs)
def _retrbinary(self, cmd, callback, blocksize=8192, rest=None):
"""Internal: Retrieve data in binary mode.
`cmd' is a RETR command. `callback' is a callback function is
called for each block. No more than `blocksize' number of
bytes will be read from the socket. Optional `rest' is passed
to transfercmd().
A new port is created for you. Return the response code.
ThreadFTP: Add a position callback, returns -1 once complete.
Checks for self.abor
Calls callback with finish=True once no more callbacks
to this method will be done.
"""
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd, rest)
pos = 0
if rest:
pos = rest
while not self.abor:
data = conn.recv(blocksize)
if not data:
self.callback('retr_pos', -1, cmd)
self.callback('transfer_finished', cmd)
callback('', finish=True)
break
pos += len(data)
self.callback('retr_pos', pos, cmd)
callback(data)
conn.close()
if self.abor:
try:
self.getmultiline()
except EOFError: pass
self.callback('transfer_aborted', cmd)
self.abor = False
return
return self.voidresp()
def storbinary(self, *args, **kwargs):
self.add_job("_storbinary", *args, **kwargs)
def _storbinary(self, cmd, fp, blocksize=8192):
'''Store a file in binary mode.'''
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd)
while not self.abor:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if self.abor:
self.abor = False
conn.close()
return self.voidresp()
def quote(self, line):
""" Send a line """
self.add_job("sendcmd", line)
def sendcmd(self, *args, **kwargs):
""" Internal: Added timeout handling. """
try:
return ftplib.FTP.sendcmd(self, *args, **kwargs)
except socket.timeout, e:
self.callback("timeout", e)
def run(self):
""" Internal: Thread loop """
while 1:
# Wait for a job to enter
self.lock.acquire(True)
try:
job, args, kwargs = self.jobs.pop(0)
self.current_job = (job, args, kwargs)
except IndexError:
debugmsg("Lock released, no job.")
continue
else:
debugmsg("Lock released, job: %s %s %s" %(job, args, kwargs))
if job == "join":
break # Break out of loop, join thread
try:
getattr(self, job)(*args, **kwargs)
except Exception, e:
self.callback('unhandled_exception', (job, args, kwargs), e)
print "Non-fatal exception in job, traceback:"
import traceback, sys
traceback.print_exc(file=sys.stdout)
self.current_job = None
def add_callbacks(self, c_map):
"""
Use map to add callbacks.
"""
for key in c_map.keys():
if self.callbacks.has_key(key):
self.callbacks[key].append(c_map[key])
else:
self.callbacks[key] = [c_map[key]]
def remove_callbacks(self, c_map):
"""
Remove functions from callbacks
"""
for key in c_map:
self.callbacks[key].remove(c_map[key])
def flush_cache(self):
""" Flushes the directory listing cache """
self.list_cache = {}
def ls(self, **kw):
""" List files in current directory. """
self.add_job("_ls")
def _ls(self, **kw):
if self.wd in self.list_cache.keys():
# Use cache
listing = self.list_cache[self.wd]
resp = None
elif "MLSD" in self.feats:
resp, output = self._mlsd(**kw)
listing = list(parse_MLSD(output, self.wd, self.server))
self.list_cache[self.wd] = listing
else:
resp, output = self._dir(**kw)
listing = list(parse_LIST(output, self.wd, self.server))
self.list_cache[self.wd] = listing
self.callback("listing", listing)
return resp, listing
def delete(self, item):
self.add_job("_delete", item)
def _delete(self, item):
if self.wd == item.dir:
fs = item.filename
else:
fs = item.abs_location()
try:
if item.type == 'f':
ftplib.FTP.delete(self, fs)
elif item.type == 'd':
ftplib.FTP.rmd(self, fs)
except ftplib.error_perm, e:
self.callback('delete_error', fs, str(e))
else:
self.callback('deleted', fs)
def join(self):
self.add_job("join")
def busy(self):
"""Return True if this thread is doing a job or has waiting jobs."""
return bool(self.current_job or self.jobs)
def walk(self, d, **kwargs):
self.add_job("_walk", d, **kwargs)
def _walk(self, d, **kwargs):
def cwd(h):
r = self._cwd(h)
self._pwd()
return r
def dodir():
resp, listing = self._ls()
for item in listing:
self.callback('walk', item, **kwargs)
if item.isdir():
if cwd(item.filename):
dodir()
cwd('..')
if cwd(d):
dodir()
cwd('..')
self.callback('walk_end')
self._ls()
def list_parents(self):
self.add_job("_list_parents")
def _list_parents(self):
"""Go to root, list, next, list, repeat."""
wdsplit = [x for x in self.wd.split("/") if x]
for i in xrange(len(wdsplit)+1):
path = "/" + "/".join(wdsplit[:i])
self._cwd(path)
self._pwd()
self._ls()
self.callback('list_parents_finished')
def download(self, remote, to, rest=False):
self.add_job("_download", remote, to, rest)
def _download(self, remote, to, rest):
"""Download a RemoteFile."""
# check if we're already on the correct server
if not remote.server is self.server:
self.server = remote.server
if self.sock: self._quit()
# TODO: this does not handle errors.
self._connect()
self._login()
if not self.wd == remote.dir:
self._cwd(remote.dir)
seek = 0
if rest and os.path.isfile(to):
seek = os.path.getsize(to)
try:
fd = open(to, seek and "a" or "w")
except:
self.callback('download_error',
"Could not open file for writing: %s" % to)
return
def cb(d, finish=False):
fd.write(d)
if finish:
fd.close()
try:
self._retrbinary("RETR %s" % remote.filename, cb,
rest=(seek and str(seek) or None))
except ftplib.error_perm:
self.callback('download_error', "Permission denied")
except Exception, e:
self.callback('download_error', str(e))
def upload(self, local, remote):
self.add_job("_upload", local, remote)
def _upload(self, local, remote):
if not remote.server is self.server:
self.server = remote.server
if self.sock: self._quit()
self._connect()
self._login()
if not self.wd == remote.dir:
self._cwd(remote.dir)
try:
fd = open(local, "r")
self._storbinary("STOR %s" % remote.filename, fd)
except ftplib.error_perm:
self.callback('stor_error', "Permission denied")
except Exception, e:
self.callback('stor_error', str(e))
if __name__ == "__main__":
print "This is a library."
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from ConfigParser import SafeConfigParser
import app
class Config(SafeConfigParser):
def read(self):
read = SafeConfigParser.read(self,
[os.path.join(app.data_dir, "default.config"), app.config_file])
app.debug("Read: %s"%' '.join(read), "config")
def write(self):
fd = open(app.config_file, 'w')
SafeConfigParser.write(self, fd)
app.debug("Configuration written", "config")
del fd
class PreferencesWindow:
def __init__(self, appinst):
self.appinst = appinst
self.config = appinst.config
wTree = gtk.glade.XML(app.glade_file, "preferences_window")
self.wTree = wTree
self.window = wTree.get_widget("preferences_window")
_signals = {
"button_close_clicked":
lambda w: self.appinst.close_window(self),
"destroy":
lambda w: self.appinst.close_window(self),
}
wTree.signal_autoconnect(_signals)
self.load_config()
self.window.show_all()
def close(self):
self.window.destroy()
def load_config(self):
"""Fill in the preferences dialog."""
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os, os.path
import pango
import gobject
import gtk
from gtk import glade
import ftp
import icons
import connectdialog
import about
import app
from gtkmisc import *
class BrowserStore(gtk.TreeStore):
I_FILENAME = 0
I_SIZE = 1
I_ITEM = 2
I_ACCESSIBLE = 3
def __init__(self):
gtk.TreeStore.__init__(self, str, str, object, bool)
self.iters = {'': None}
def _item_to_row(self, item):
return [unic(item.filename),
item.isfile() and units(item.size) or "",
item, True]
# TODO: We could probably do some checks to see if
# the dir is accessible
def add(self, path, item, overwrite=True):
"""Add item at path."""
if not item.filename:
item.filename = "(not set)"
if path.startswith('/'):
path = path[1:]
if not path in self.iters.keys():
try:
p, n = path.rsplit('/', 1)
except ValueError:
p = ""
n = path
self.add(p, ftp.RemoteFile(filename=n, type='d', dir=p,
server=item.server))
parent_iter = self.iters[path]
i = gtk.TreeStore.append(self, parent_iter,
self._item_to_row(item))
self.iters[(path and path + '/' or '') + item.filename] = i
def dir_exists(self, d):
"""Make sure d exists."""
if d.startswith('/'): d = d[1:]
if not d in self.iters:
if '/' in d:
n, p = d.rsplit('/', 1)
else:
n, p = '', d
diritem = ftp.RemoteFile(filename=p, type='d')
self.add(n, diritem, overwrite=False)
def clear(self, path=None):
"""Clear Store. If path is given, clear all entries under path."""
if path == None:
return gtk.TreeStore.clear(self)
if path.startswith("/"): path = path[1:]
path_iter = self.iters[path]
if path_iter == None:
# same as clearing the whole store
return gtk.TreeStore.clear(self)
else:
for iterkey in self.iters.keys():
if iterkey == '': continue
if self.is_ancestor(path_iter, self.iters[iterkey]):
self.remove(self.iters[iterkey])
del self.iters[iterkey]
def select_dir(title="Select destination directory"):
selected = None
chooser = gtk.FileChooserDialog(title=title,
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
response = chooser.run()
if response == gtk.RESPONSE_OK:
selected = chooser.get_filename()
chooser.destroy()
return selected
class LogWindow:
_widgets = ['textview_log', 'entry_cmd', 'button_clear', 'scroll_log']
def __init__(self, parent_window):
self.parent_window = parent_window
self.wTree = gtk.glade.XML(app.glade_file, "log_window")
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget("log_window")
_signals = {
'entry_cmd_activate': self.entry_cmd_activate,
'button_clear_clicked': self.button_clear_clicked,
}
self.wTree.signal_autoconnect(_signals)
buff = self.textview_log.get_buffer()
buff.create_tag("monospaced", family="Monospace")
buff.create_tag("green", foreground="#00e000")
buff.create_tag("blue", foreground="blue")
buff.create_tag("red", foreground="red")
buff.create_tag("bold", weight=pango.WEIGHT_BOLD)
self.window.show_all()
def entry_cmd_activate(self, widget):
cmd = widget.get_text()
if self.parent_window.ftp:
if cmd.startswith("cd "):
cmd, path = cmd.split(" ", 1)
self.parent_window.cd(path)
else:
self.parent_window.ftp.quote(widget.get_text())
widget.set_text('')
else:
app.debug("No FTP connection", "browser")
def button_clear_clicked(self, button):
self.textview_log.get_buffer().set_text('')
def log(self, message, type=0):
buff = self.textview_log.get_buffer()
scroll = self.scroll_log
message = unic("%s\n" % message)
tags = ["monospaced"]
if type == 1: tags.append("green")
elif type == 2: tags.append("blue")
elif type == 3: tags.append("bold")
elif type == 4:
tags.append("bold")
tags.append("red")
end_iter = buff.get_end_iter()
buff.insert_with_tags_by_name(end_iter, message, *tags)
adj = scroll.get_vadjustment()
adj.value = adj.upper
scroll.set_vadjustment(adj)
class BrowserWindow:
_widgets = ['textview_log', 'statusbar', 'scroll_log', 'scroll_files',
'checkitem_io', 'checkitem_hidden']
def __init__(self, appinst):
self.appinst = appinst
self.config = appinst.config
self.wTree = gtk.glade.XML(app.glade_file, "browser_window")
# get widgets
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget('browser_window')
self.tree = self.wTree.get_widget('tree_files')
# connect signals
_signals = {
'tree_files_row_activated': self.tree_row_activate,
#'tree_files_button_release_event': self.tree_button_event,
'tree_files_button_press_event': self.tree_button_event,
'tree_files_cursor_changed': self.tree_cursor_changed,
'tree_files_drag_data_received': self.drag_data_recv,
'browser_window_destroy':
lambda w: self.appinst.close_window(self),
'imagemenuitem_close_activate':
lambda w: self.window.destroy(),
'imagemenuitem_connect_activate':
lambda w: self.new_connect_dialog(),
'menuitem_new_activate':
lambda w: self.appinst.new_browser(),
'checkitem_hidden_toggled':
lambda w: self.config.set("browser",
"show_hidden_files", str(w.get_active())),
'menuitem_about_activate':
lambda w: about.AboutDialog().run(),
'menuitem_new_queue_activate':
lambda q: self.appinst.new_queue(),
'menuitem_preferences_activate':
lambda w: self.appinst.new_preferences(),
'menuitem_log_activate': self.menuitem_log_activate,
'browser_window_check_resize': self.window_resized,
}
self.wTree.signal_autoconnect(_signals)
self.log_window = None
# enable multi-select in treeview
self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
# set up the treeview
self.store = BrowserStore()
self.tree.set_model(self.store)
cell_icon = gtk.CellRendererPixbuf()
cell_name = gtk.CellRendererText()
column_name = gtk.TreeViewColumn("Name")
column_name.pack_start(cell_icon, False)
column_name.pack_start(cell_name, True)
column_name.set_cell_data_func(cell_icon, self.tree_get_icon)
column_name.set_attributes(cell_icon)
column_name.set_attributes(cell_name, text=BrowserStore.I_FILENAME)
column_name.set_expand(True)
column_name.set_max_width(0)
column_name.set_sort_column_id(BrowserStore.I_FILENAME)
self.column_name = column_name
self.tree.append_column(column_name)
self.tree.set_enable_search(True)
self.tree.set_headers_visible(False)
# set up drag and drop on the tree
self.tree.enable_model_drag_dest([('text/plain', 0, 0)],
gtk.gdk.ACTION_DEFAULT)
# resize window
self.window.set_default_size(
self.config.getint("browser", "width"),
self.config.getint("browser", "height")
)
self.in_auto = False # True will turn off listing and pwding
# in browsers callbacks
self.ftp = None
self.homewd = ""
self.window.set_icon_from_file(os.path.join(
app.data_dir, "flash-64.png"))
self.checkitem_hidden.set_active(
self.config.getboolean("browser", "show_hidden_files"))
self.window.show_all()
self.tree.set_sensitive(False)
def window_resized(self, window):
"""The window has been resized. Save new dimensions."""
width, height = window.get_size()
self.config.set("browser", "width", str(width))
self.config.set("browser", "height", str(height))
def close(self):
"""Close window."""
if self.ftp and self.ftp.sock:
self.disconnect()
self.window.destroy()
def new_connect_dialog(self):
"""Creates a new connect dialog for this browser."""
cd = connectdialog.ConnectDialog(self.appinst, browser=self)
cd.window.run()
def cd(self, location):
"""Change current directory to location."""
self.tree.set_sensitive(False)
self.ftp.cwd(location)
def drag_data_recv(self, widget, dc, x, y, selection, info, ts):
files = []
for ld in selection.data.split("\r\n"):
if ld.startswith("file://"): files.append(ld[7:])
if not files:
app.debug("No files dropped")
return
drop_info = self.tree.get_dest_row_at_pos(x, y)
if drop_info:
path, position = drop_info
i = self.store.get_iter(path)
dropped_on = self.store.get_value(i, BrowserStore.I_ITEM)
if dropped_on.isdir():
dropped_on_dir = dropped_on.abs_location()
elif dropped_on.isfile():
dropped_on_dir = dropped_on.dir
app.debug("%s dropped on %s" % (files, dropped_on_dir))
if not self.appinst.queues:
app.debug("No queues to handle drop")
return
que = self.appinst.queues[0] # XXX
for f in files:
rf = ftp.RemoteFile(dir=dropped_on_dir, server=dropped_on.server,
filename=os.path.split(f)[1], size=os.path.getsize(f))
que.append_item(f, rf)
def tree_get_icon(self, column, cell, model, iter):
"""Data function for the file icon in self.tree."""
item = model.get_value(iter, BrowserStore.I_ITEM)
try:
if item.isdir():
if self.tree.row_expanded(self.store.get_path(iter)):
pixbuf = icons.folder(open=True)
else:
pixbuf = icons.folder()
elif item.islink():
pixbuf = icons.from_theme('emblem-symbolic-link')
else:
pixbuf = icons.by_filename(item.filename)
cell.set_property('pixbuf', pixbuf)
except gobject.GError, e:
app.debug("Could not load pixbuf: " + str(e), "browser")
cell.set_property('pixbuf', None)
def tree_row_activate(self, widget, path, column):
item = self.store.get_value(
self.store.get_iter(path), BrowserStore.I_ITEM
)
# change directories if directory
if item.isdir() or item.islink():
self.set_status("Changing Directory")
self.cd(item.abs_location())
elif item.isfile():
app.debug("No action implemented", "browser")
else:
app.debug("Unknown file", "browser")
def tree_cursor_changed(self, widget):
"""Selection changed, update statusbar info."""
iters = iters_selection(self.tree.get_selection())
items = [self.store.get_value(x, BrowserStore.I_ITEM) for x in iters]
if len(items) == 0: return
elif len(items) == 1:
self.set_status("%s, %s" % (items[0].filename,
items[0].isdir() and "(folder)" or units(items[0].size)))
else:
self.set_status("%s items, %s" % (len(items),
str(units(sum([item.size for item in items])))
))
def tree_button_event(self, widget, event):
"""Mouse button pushed over tree. Unclear code is unclear."""
iters = iters_selection(self.tree.get_selection())
if len(iters) == 0:
return
else:
selected = [self.store.get_value(i, BrowserStore.I_ITEM) for i in iters]
def download(items, queue_index=None, download_dir=''):
"""Add items to a queue. If there are no queues, create a new one."""
if not self.appinst.queues:
self.appinst.new_queue()
if queue_index == None:
queue_index = 0
for item in items:
if item.isfile():
self.appinst.queues[queue_index].append_item(item,
os.path.join(download_dir, item.filename))
elif item.isdir():
self.tree.set_sensitive(False)
self.in_auto = True
self.ftp.walk(
item.abs_location(),
queue_number=queue_index,
started_path=item.dir,
target_dir=download_dir
)
# popup menu in right click (button 3)
if event.button == 3:
menu_popup = gtk.Menu()
if selected[0].isdir() or selected[0].islink():
go = gtk.ImageMenuItem("List Directory")
go.set_image(gtk.image_new_from_stock(
"gtk-open", gtk.ICON_SIZE_MENU))
go.connect('activate', lambda w: self.cd(selected[0].abs_location()))
menu_popup.append(go)
def download_if_selected(w, i, q):
dir = select_dir()
if dir:
download(i, download_dir=dir, queue_index=q)
if len(self.appinst.queues) == 0:
it = gtk.ImageMenuItem("Add to new Queue")
it.connect('activate', lambda w:
(self.appinst.new_queue(name=self.server.hostname),
download_if_selected(None, selected, 0)))
if len(self.appinst.queues) == 1:
it = gtk.ImageMenuItem("Add to Queue")
it.connect('activate', download_if_selected, selected, 0)
elif len(self.appinst.queues) > 1:
it = gtk.ImageMenuItem("Add to Queue")
menu_queues = gtk.Menu()
for i, q in enumerate(self.appinst.queues):
foo = gtk.MenuItem(q.name)
foo.connect('activate', download_if_selected, selected, i)
menu_queues.append(foo)
it.set_submenu(menu_queues)
it.set_image(gtk.image_new_from_stock("gtk-save-as", gtk.ICON_SIZE_MENU))
menu_popup.append(it)
d = gtk.ImageMenuItem("Delete")
d.set_image(gtk.image_new_from_stock("gtk-delete", gtk.ICON_SIZE_MENU))
d.connect("activate", lambda w: [self.ftp.delete(x) for x in selected])
menu_popup.append(d)
r = gtk.ImageMenuItem("Rename")
r.set_image(gtk.image_new_from_stock("gtk-rename", gtk.ICON_SIZE_MENU))
menu_popup.append(r)
menu_popup.show_all()
menu_popup.popup(None, None, None, event.button, event.time)
def log(self, *args, **kwargs):
if self.log_window:
self.log_window.log(*args, **kwargs)
def connect(self, server):
"""Connect to FTP server."""
if self.ftp and self.ftp.sock:
self.disconnect()
self.ftp = ftp.FTPThread(daemon=True)
_callbacks = {}
for cb in ftp.FTPThread._all_callbacks:
if hasattr(self, "ftp_%s" % cb):
_callbacks[cb] = getattr(self, "ftp_"+cb)
self.ftp.add_callbacks(_callbacks)
self.set_status("Connecting")
self.log("Connecting to ftp://%s:%s@%s:%s" % \
(server.username,
len(server.password)*"*",
server.hostname,
server.port or "21"))
self.ftp.connect(server)
self.server = server
def disconnect(self):
if self.ftp and self.ftp.sock:
self.ftp.quit()
self.ftp.join()
else:
app.debug("disconnect() called, spite no connection.", "browser")
def set_status(self, message):
context_id = self.statusbar.get_context_id("status")
self.statusbar.pop(context_id)
self.statusbar.push(context_id, message)
def menuitem_log_activate(self, widget):
if not self.log_window:
self.log_window = LogWindow(self)
@threads
def ftp_connected(self, welcomemsg):
self.set_status("Connected to %s" % self.server.hostname)
self.window.set_title("Flash! %s" % self.server.hostname)
self.ftp.login()
@threads
def ftp_connect_error(self, msg):
try:
if len(msg[1]) > 1:
# in many cases, we get a typle with
# errorid, and explaination string
msg = msg[1]
except: pass
self.set_status("Could not connect to %s: %s" % \
(self.server.hostname, str(msg)))
self.log("Could not connect: %s" % str(msg), type=4)
@threads
def ftp_sending(self, data):
app.debug(data, "browser-ftp")
if data.startswith("PASS"):
data = "PASS <hidden>"
self.log(data, type=2)
@threads
def ftp_received(self, data):
app.debug(data, "browser-ftp")
self.log(data, type=1)
@threads
def ftp_authenticated(self, r):
self.set_status("Connected, Authenticated")
self.in_auto = True
self.ftp.pwd() # the ftp session know about current directory
self.ftp.list_parents() # go down and list
@threads
def ftp_authentication_error(self, e):
self.set_status("Not Authenticated")
self.log("Could not authenticate: " + str(e), type=4)
@threads
def ftp_disconnected(self, msg):
self.store.clear()
self.tree.set_sensitive(False)
@threads
def ftp_pwd(self, wd):
app.debug("wd=" + wd + ", listing.", "browser")
self.set_status("Current directory: %s"%wd)
self.store.dir_exists(wd)
if not self.in_auto:
self.set_status("Retreiving Directory Listing")
self.ftp.ls()
if wd[1:]:
# activate this row
store_path = self.store.get_path(self.store.iters[wd[1:]])
self.tree.set_cursor(store_path)
def ftp_cwd(self, msg):
if self.in_auto: return
self.ftp.pwd()
@threads
def ftp_cwd_error(self, msg):
self.tree.set_sensitive(True)
self.set_status("Could not change directory: %s" % msg)
@threads
def ftp_listing(self, listing):
show_hidden = self.config.getboolean('browser', 'show_hidden_files')
self.store.clear(self.ftp.wd)
for item in listing:
if item.ishidden() and not show_hidden: continue
self.store.add(self.ftp.wd, item)
if self.ftp.wd[1:]:
store_path = self.store.get_path(self.store.iters[self.ftp.wd[1:]])
self.tree.expand_row(store_path, True)
if not self.in_auto:
self.tree.set_sensitive(True)
@threads
def ftp_timeout(self, e):
self.log("Timeout: " + str(e), type=4)
@threads
def ftp_unhandled_exception(self, job, exception):
self.log("Unhandled exception in FTP thread: Job: %s Exception: %s" %
(job, exception), type=4)
@threads
def ftp_ssl_enabled(self, server, issuer):
self.log("SSL has been enabled")
@threads
def ftp_deleted(self, filename):
self.set_status("%s deleted" % filename)
# XXX: Remove correct row!
def ftp_walk_end(self):
self.in_auto = False
@threads
def ftp_ssl_not_availible(self, s):
self.log("SSL not availible.", type=4)
self.set_status("No SSL")
@threads
def ftp_list_parents_finished(self):
self.in_auto = False
self.tree.set_sensitive(True)
@threads
def ftp_walk(self, i, queue_number=None, started_path=None, target_dir=None):
target = os.path.join(target_dir, i.filename)
app.debug("Walked %s" % i, "browser")
if started_path:
target = os.path.join(target_dir, i.abs_location()[len(started_path)+1:])
app.debug("Putting in %s" % target, "browser")
if i.isfile():
self.appinst.queues[queue_number].append_item(i, target)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from gtk import glade
import app
import ftp
import icons
class ConnectDialog:
def __init__(self, appinst, browser=None):
self.appinst = appinst
self.config = appinst.config
self.browser = browser
self.wTree = glade.XML(app.glade_file, "dialog_connect")
self.window = self.wTree.get_widget('dialog_connect')
self.combobox_sites = self.wTree.get_widget('combobox_sites')
self.entry_host = self.wTree.get_widget('entry_host')
self.entry_user = self.wTree.get_widget('entry_user')
self.entry_password = self.wTree.get_widget('entry_password')
self.checkbutton_use_ssl = self.wTree.get_widget('checkbutton_use_ssl')
self.checkbutton_force_ssl = self.wTree.get_widget('checkbutton_force_ssl')
self.checkbutton_passive = self.wTree.get_widget('checkbutton_passive')
_signals = {'close': lambda w: self.appinst.close_window(self),
'cancel_clicked': lambda w: self.appinst.close_window(self),
'save_clicked': self.save,
'connect_clicked': lambda w: self.connect(),
'combobox_sites_changed': self.select_site,
'button_delete_clicked': self.delete_selected,
'entry_user_activate': lambda w: self.connect(),
'entry_host_activate': lambda w: self.connect(),
'entry_password_activate': lambda w: self.connect(),
}
self.wTree.signal_autoconnect(_signals)
self.window.set_icon(icons.from_theme("gtk-network", 16))
self.store = gtk.ListStore(str)
self.combobox_sites.set_model(self.store)
self.fill_site_menu()
self.window.show_all()
def close(self, *w):
# destroy reference to this object, if browser has that is
if self.browser:
self.browser.connect_dialog = None
self.window.destroy()
def fill_site_menu(self):
"""Fills the combobox with the saved sites."""
self.store.clear()
for x in self.config.sections():
if x.startswith("site:"):
self.store.append([x[5:]])
def delete_selected(self, w):
"""Delete selected site from config."""
iter = self.combobox_sites.get_active_iter()
if not iter: return
site = self.store.get_value(iter, 0)
self.config.remove_section('site:'+site)
self.fill_site_menu()
def save(self, w):
dTree = glade.XML(app.glade_file, "dialog_site_name")
dwindow = dTree.get_widget('dialog_site_name')
dentry = dTree.get_widget('entry_name')
dpass = dTree.get_widget('checkbutton_password')
if self.entry_user.get_text():
dentry.set_text('@'.join([
self.entry_user.get_text(),
self.entry_host.get_text()
]))
else:
dentry.set_text(self.entry_host.get_text())
def doEnd(*args):
dwindow.destroy()
def doSave(*args):
cfgstr = 'site:'+dentry.get_text()
if not self.config.has_section(cfgstr):
self.config.add_section(cfgstr)
self.config.set(cfgstr, 'hostname', self.entry_host.get_text())
self.config.set(cfgstr, 'username', self.entry_user.get_text())
if dpass.get_active():
self.config.set(cfgstr, 'password', self.entry_password.get_text())
self.config.set(cfgstr, 'use_ssl',
str(self.checkbutton_use_ssl.get_active()))
self.config.set(cfgstr, 'force_ssl',
str(self.checkbutton_force_ssl.get_active()))
self.config.set(cfgstr, 'passive',
str(self.checkbutton_passive.get_active()))
doEnd()
_signals = {'button_save_clicked': doSave,
'button_cancel_clicked': doEnd}
dTree.signal_autoconnect(_signals)
dwindow.show_all()
def connect(self):
"""Connect with the information given.
Create a FTPServer object and tell parent to use it."""
host = self.entry_host.get_text()
if ':' in host:
host, port = host.split(':', 1)
port = int(port)
else:
port = 21
s = dict(
username = self.entry_user.get_text() or "anonymous",
password = self.entry_password.get_text() or
self.config.get("ftp", "anonymous_password"),
port = port,
protocol = self.checkbutton_use_ssl.get_active() and "ftp+ssl" or "ftp",
passive = self.checkbutton_passive.get_active(),
)
server = ftp.Server(host, **s)
self.window.hide_all()
if self.browser:
self.browser.connect(server)
else:
self.appinst.new_browser().connect(server)
self.appinst.close_window(self)
def select_site(self, cb):
site = cb.get_active_text()
app.debug("Site selected: " + site, "connectdialog")
cfgstr = 'site:'+site
host = self.config.get(cfgstr, 'hostname')
if self.config.has_option(cfgstr, 'port'):
port = self.config.getint(cfgstr, 'port')
if port != 21:
host += ":%s"%str(port)
user = self.config.get(cfgstr, 'username')
self.entry_host.set_text(host)
self.entry_user.set_text(user)
if self.config.has_option(cfgstr, 'password'):
p = self.config.get(cfgstr, 'password')
self.entry_password.set_text(p)
else:
self.entry_password.set_text('')
# de-activate checkbutton_use_ssl if False
if self.config.has_option(cfgstr, 'use_ssl'):
self.checkbutton_use_ssl.set_active(
self.config.getboolean(cfgstr, 'use_ssl'))
# activate checbutton_force_ssl if set
if self.config.has_option(cfgstr, 'force_ssl'):
self.checkbutton_force_ssl.set_active(
self.config.getboolean(cfgstr, 'force_ssl'))
# set passive
if self.config.has_option(cfgstr, 'passive'):
self.checkbutton_passive.set_active(
self.config.getboolean(cfgstr, 'passive'))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gobject
import pango
import time
import gtk
import ftp
import about
import icons
import app
from gtkmisc import *
def nullifnegative(n):
if n < 0:
return 0
else: return n
def get_status_icon(column, cell, model, iter):
direction = model.get_value(iter, QueueStore.I_DIRECTION)
status = model.get_value(iter, QueueStore.I_STATUS)
filename = model.get_value(iter, QueueStore.I_FILENAME)
pixbuf = None
if status == QueueStore.ST_TRANSFERING:
pixbuf = icons.from_theme('player_play', size=16)
elif status == QueueStore.ST_WAITING:
pixbuf = icons.by_filename(filename, size=16)
elif status == QueueStore.ST_ERROR:
pixbuf = icons.from_theme('error', size=16)
elif status == QueueStore.ST_FINISHED:
pixbuf = None
cell.set_property('pixbuf', pixbuf)
return pixbuf
class QueueStore(gtk.ListStore):
I_DIRECTION = 0
I_STATUS = 1
I_FILENAME = 2
I_SIZE = 3
I_STRSIZE = 4
I_TRANSFERRED = 5
I_REMOTE = 6
I_LOCAL = 7
I_ERROR = 8
DR_DOWN = 0
DR_UP = 1
ST_WAITING = 0
ST_TRANSFERING = 1
ST_FINISHED = 2
ST_ERROR = 3
def __init__(self):
gtk.ListStore.__init__(self,
int, int, str, int, str, int, object, str, str)
self.update_size()
def update_size(self, add=None):
"""Sets self.total_size. If add is set, just add it to total_size."""
if add:
self.total_size += add
else:
c = 0
for it in self.iters():
c += self.get_value(it, self.I_SIZE)
self.total_size = c
app.debug(
"Total queue size: %s" % units(self.total_size),
"queue"
)
return self.total_size
def transferred(self):
"""Returns how many bytes in the queues are transferred."""
total = 0
for i in self.iters():
total += self.get_value(i, self.I_TRANSFERRED)
return total
def append(self, item, local, direction=DR_DOWN, status=ST_WAITING):
"""Append a FileItem."""
size = item.isfile() and units(item.size) or ""
list = [direction, status, unic(item.filename),
item.size, size, 0, item, local, '']
if direction == self.DR_DOWN:
if os.path.isfile(local):
transferred = os.path.getsize(local)
list[QueueStore.I_TRANSFERRED] = transferred
if transferred == list[QueueStore.I_SIZE]:
list[QueueStore.I_STATUS] = QueueStore.ST_FINISHED
try:
gtk.ListStore.append(self, list)
except TypeError, e:
print "ERROR! list was:"
print list
return False
self.update_size(add=item.size)
def iters(self):
"""Yield iterators, top-down."""
iter = self.get_iter_first()
while 1:
if not iter:
break
next = self.iter_next(iter)
yield iter
iter = next
def liters(self):
return list(self.iters())
def get_waiting_iter(self):
"""Returns iterator to next waiting item."""
for i in self.iters():
if self.get_value(i, self.I_STATUS) == self.ST_WAITING:
return i
def clear_finished(self):
"""Removes finished transfers."""
for i in self.iters():
if self.get_value(i, self.I_STATUS) == self.ST_FINISHED:
self.remove(i)
self.update_size()
def clear(self):
gtk.ListStore.clear(self)
self.update_size()
def queue_from_disk(fn):
"""Creates a QueueStore from disc.
fn is the name of the queue in queues_dir.
"""
fd = open(app.queues_dir + os.path.sep + fn, 'r')
q = QueueStore()
for i in fd.readlines():
i = i.strip()
list = i.split(';')
list[QueueStore.I_DIRECTION] = int(list[QueueStore.I_DIRECTION])
list[QueueStore.I_STATUS] = int(list[QueueStore.I_STATUS])
list[QueueStore.I_SIZE] = int(list[QueueStore.I_SIZE])
list[QueueStore.I_TRANSFERRED] = int(list[QueueStore.I_TRANSFERRED])
list[QueueStore.I_REMOTE] = ftp.remotefile_from_str(list[QueueStore.I_REMOTE])
gtk.ListStore.append(q, list)
fd.close()
q.update_size()
return q
def serialize(store):
"""Creates multi-line text of a queue. Each line is I_*
separated by the ; character."""
items = []
for i in store.iters():
ml = [str(store.get_value(i, k)) for k in xrange(9)]
ml[QueueStore.I_REMOTE] = store.get_value(i, QueueStore.I_REMOTE).allstr()
items.append(";".join(ml))
return "\n".join(items)
class QueueWindow:
_widgets = ['tree', 'statusbar', 'expander', 'menuitem_run', 'progressbar']
def __init__(self, appinst, name="Queue", store=None):
self.appinst = appinst
self.config = appinst.config
self.name = name
# get widgets
self.wTree = gtk.glade.XML(app.glade_file, "queue_window")
for widget in self._widgets:
setattr(self, widget, self.wTree.get_widget(widget))
self.window = self.wTree.get_widget('queue_window')
# connect signals
_signals = {
'imagemenuitem_about_activate':
lambda w: about.AboutDialog().run(),
'menuitem_close_activate':
lambda w: self.window.destroy(),
'queue_window_destroy':
lambda w: self.appinst.close_window(self),
'menuitem_run_toggled': self.toggle_run,
'menuitem_clear_activate':
lambda w: (self.store.clear_finished(), self.save()),
'menuitem_clear_all_activate':
lambda w: (self.store.clear(), self.save()),
'menuitem_connect_activate':
lambda w: self.appinst.new_connect_dialog(),
'queue_window_resized': self.window_resized,
'queue_tree_button_press_event':
self.queue_button_event,
'menuitem_rename_activate': lambda w: self.get_new_name(),
}
self.wTree.signal_autoconnect(_signals)
if store:
self.store = store
else:
self.store = QueueStore()
self.tree.set_model(self.store)
# enable multi-selection
self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
for t in ("name", "transferred", "size", "from", "to", "error"):
c = gtk.CellRendererText()
setattr(self, "cell_%s" % t, c)
self.cell_progress = gtk.CellRendererProgress()
self.cell_status = gtk.CellRendererPixbuf()
column_name = gtk.TreeViewColumn("Name")
column_name.pack_start(self.cell_status, False)
column_name.pack_start(self.cell_name, True)
column_size = gtk.TreeViewColumn("Progress")
column_size.pack_start(self.cell_transferred, False)
column_size.pack_start(self.cell_progress, False)
column_size.pack_start(self.cell_size, False)
column_from = gtk.TreeViewColumn("From")
column_from.pack_start(self.cell_from, True)
column_to = gtk.TreeViewColumn("To")
column_to.pack_start(self.cell_to, True)
column_error = gtk.TreeViewColumn("Error")
column_error.pack_start(self.cell_error, False)
column_name.set_attributes(self.cell_name, text=QueueStore.I_FILENAME)
column_name.set_cell_data_func(self.cell_status, get_status_icon)
column_name.set_expand(True)
column_size.set_attributes(self.cell_size, text=QueueStore.I_STRSIZE)
column_size.set_cell_data_func(self.cell_transferred,
lambda c, ce, m, i: ce.set_property('text',
unic(units(m.get_value(i, QueueStore.I_TRANSFERRED)))
)
)
column_size.set_expand(False)
column_from.set_cell_data_func(self.cell_from,
lambda c, ce, m, i: ce.set_property('text', m.get_value(i, m.I_DIRECTION) == m.DR_DOWN and str(m.get_value(i, m.I_REMOTE)) or str(m.get_value(i, m.I_LOCAL))))
column_from.set_expand(True)
column_to.set_cell_data_func(self.cell_to,
lambda c, ce, m, i: ce.set_property('text', m.get_value(i, m.I_DIRECTION) == m.DR_DOWN and str(m.get_value(i, m.I_LOCAL)) or str(m.get_value(i, m.I_REMOTE))))
column_to.set_expand(True)
column_size.set_cell_data_func(self.cell_progress,
lambda c, ce, m, i: ce.set_property('value',
100*m.get_value(i, m.I_TRANSFERRED)/m.get_value(i, m.I_SIZE))
)
column_error.set_attributes(self.cell_error, text=QueueStore.I_ERROR)
self.tree.append_column(column_name)
self.tree.append_column(column_size)
self.tree.append_column(column_from)
self.tree.append_column(column_to)
self.tree.append_column(column_error)
# set window size
self.window.set_default_size(
self.config.getint("queue", "width"),
self.config.getint("queue", "height")
)
# Initialize FTP Thread
self.ftp = ftp.FTPThread(daemon=True)
_callbacks = {}
for cb in ftp.FTPThread._all_callbacks:
if hasattr(self, "ftp_"+cb):
_callbacks[cb] = getattr(self, "ftp_"+cb)
self.ftp.add_callbacks(_callbacks)
# These contain the item and iter of which is currently being processed
self._item = None
self._iter = None
self.window.set_icon_from_file(os.path.join(app.data_dir, "flash-64.png"))
self.window.set_title(self.name)
self.window.show_all()
def close(self):
"""Finish up, destroy window. Called by app."""
if self.ftp.busy():
self.ftp.abor = True
self.ftp.quit()
self.ftp.join()
self.window.destroy()
def save(self):
if self.store.total_size == 0:
if os.path.isfile(os.path.join(app.queues_dir, self.name)):
os.remove(os.path.join(app.queues_dir, self.name))
else:
fd = open("%s%s%s" % (app.queues_dir, os.path.sep, self.name), "w")
fd.write(serialize(self.store))
fd.close()
def toggle_run(self, checkitem):
if checkitem.get_active():
self.pop()
else:
self.stop_queue()
def window_resized(self, window):
width, height = window.get_size()
self.config.set("queue", "width", str(width))
self.config.set("queue", "height", str(height))
def stop_queue(self):
"""Stops the queue."""
if self.ftp.busy():
self.ftp.abor = True
self.ftp.jobs = []
if self._iter: # set current file to 'waiting'
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_WAITING)
self._iter, self._item = None, None
def append_item(self, fr, to, status=0):
"""Appends one item to the queue."""
if isinstance(fr, ftp.RemoteFile) and isinstance(to, str): # a download
self.store.append(fr, to, direction=0, status=status)
app.debug("Adding download item: %s to %s" % (fr, to), "queue")
elif isinstance(to, ftp.RemoteFile) and isinstance(fr, str): # upload
self.store.append(to, fr, direction=1, status=status)
app.debug("Adding upload from %s to %s" % (fr, to), "queue")
else:
raise ValueError, "Unknown from/to types. fr: %s to: %s" % \
(type(fr), type(to))
self.save()
if self.menuitem_run.get_active() and not self.ftp.busy():
app.debug("Popping item since queue is not running.", "queue")
self.pop()
def pop(self, *args):
"""Pop an item.
Should probably not be started while queue is running.
Returns True if there queue was started, False if there were no
items to be transferred.
"""
iter = self.store.get_waiting_iter()
if iter:
# set status to 'transfering'
self.store.set_value(iter, QueueStore.I_STATUS, 1)
# remember item and iter locally
self._item = self.store.get_value(iter, QueueStore.I_REMOTE)
self._iter = iter
# get local path
local = self.store.get_value(iter, QueueStore.I_LOCAL)
direction = self.store.get_value(iter, QueueStore.I_DIRECTION)
if direction == QueueStore.DR_DOWN:
# create dir if it doesn't exist
if os.path.sep in local and not os.path.isdir(os.path.dirname(local)):
os.makedirs(os.path.dirname(local))
# now transfer it
app.debug("Downloading %s to %s" % (self._item.filename, local), "queue")
self.set_statusbar("Downloading")
self.ftp.download(self._item, local, rest=True)
elif direction == QueueStore.DR_UP:
app.debug("Uplading %s to %s" % (local, self._item.filename))
self.set_statusbar("Uploading")
self.ftp.upload(local, self._item)
return True
else:
return False
def queue_button_event(self, widget, event):
iters = iters_selection(self.tree.get_selection())
if len(iters) == 0:
return
def move_to_top(iters):
for iter in iters[::-1]:
self.store.move_before(iter, self.store.liters()[0])
self.save()
def move_to_bottom(iters):
for iter in iters:
self.store.move_after(iter, self.store.liters()[-1])
self.save()
def remove(iters):
for iter in iters:
self.store.remove(iter)
self.save()
if event.button == 3:
menu = gtk.Menu()
mt = gtk.ImageMenuItem(stock_id=gtk.STOCK_GOTO_TOP)
mt.connect('activate', lambda w: move_to_top(iters))
mb = gtk.ImageMenuItem(stock_id=gtk.STOCK_GOTO_BOTTOM)
mb.connect('activate', lambda w: move_to_bottom(iters))
mr = gtk.ImageMenuItem(stock_id=gtk.STOCK_REMOVE)
mr.connect('activate', lambda w: remove(iters))
menu.append(mt)
menu.append(mb)
menu.append(mr)
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
def set_statusbar(self, message):
context_id = self.statusbar.get_context_id("status")
self.statusbar.pop(context_id)
self.statusbar.push(context_id, message)
def set_progress(self):
"""Update window title and progressbar with values from self.store"""
done = self.store.transferred() * 1.0 / self.store.total_size
self.progressbar.set_fraction(done)
self.window.set_title("%s - %i%%" % (self.name, done*100))
def get_new_name(self):
"""Open a dialog for new name."""
dtree = gtk.glade.XML(app.glade_file, 'dialog_rename_queue')
w = dtree.get_widget('dialog_rename_queue')
cancel = dtree.get_widget('button_cancel')
ok = dtree.get_widget('button_ok')
entry = dtree.get_widget('entry_name')
entry.set_text(self.name)
cancel.connect('clicked', lambda i: w.destroy())
def set_name():
self.name = entry.get_text()
self.window.set_title(self.name)
ok.connect('clicked', lambda i: (set_name(), w.destroy()))
w.show_all()
w.run()
def ftp_received(self, data):
app.debug(data, "queue-ftp")
def ftp_sending(self, data):
app.debug(data, "queue-ftp")
@threads
def ftp_ssl_enabled(self, server, issuer):
self.set_statusbar("SSL has been enabled")
@threads
def ftp_authenticated(self, r):
self.set_statusbar("Connected, Authenticated")
self.ftp.cwd(self._item.dir)
@threads
def ftp_connected(self, msg):
self.set_statusbar("Connected")
@threads
def ftp_authentication_error(self, e):
self.set_statusbar("Authentication err: " + str(e))
@threads
def ftp_cwd_error(self, msg):
app.debug("Could not CWD to directory!", "queue")
@threads
def ftp_transfer_finished(self, cmd):
self.set_statusbar("Transfer finished")
# update transferred in store
self.store.set_value(self._iter, QueueStore.I_TRANSFERRED,
self.store.get_value(self._iter, QueueStore.I_SIZE))
self._item = None
# change item to finished in the liststore
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_FINISHED)
# move it to bottom
if self.config.getboolean("queue", "finished_files_to_bottom"):
self.store.move_after(self._iter, list(self.store.iters())[-1])
self._iter = None
self.set_progress()
self.save()
self.pop()
def ftp_unhandled_exception(self, job, exception):
app.debug("Unhandled exception in FTP thread: Job: %s Exception: %s" % \
(job, exception), "queue")
@threads
def ftp_transfer_aborted(self, cmd):
self.set_statusbar("Transfer aborted")
self.set_progress()
last_t = time.time()
last_p = 0
@threads
def ftp_retr_pos(self, pos, cmd):
t = time.time()
if t-self.last_t < 1 or pos == -1: return
else:
self.set_statusbar("Downloading %s/s" % (
units((nullifnegative(pos-self.last_p))/(t-self.last_t)))
)
self.last_t = t
self.last_p = pos
# update transferred bytes in store
self.store.set_value(self._iter, QueueStore.I_TRANSFERRED, pos)
self.set_progress()
@threads
def ftp_download_error(self, error):
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_ERROR)
self.store.set_value(self._iter, QueueStore.I_ERROR, error)
@threads
def ftp_stor_error(self, error):
self.store.set_value(self._iter, QueueStore.I_STATUS, QueueStore.ST_ERROR)
self.store.set_value(self._iter, QueueStore.I_ERROR, error)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from gtk import glade
import flash
class AboutDialog:
def url(self, dialog, link, user_data):
import webbrowser
webbrowser.open(link, 0, 1)
def __init__(self):
gtk.about_dialog_set_url_hook(self.url, None)
self.wTree = gtk.glade.XML(flash.app.glade_file, "flash_about")
self.window = self.wTree.get_widget("flash_about")
self.window.set_icon_from_file(os.path.join(
flash.app.data_dir, "flash-64.png"))
self.window.set_name(flash.__name__)
self.window.set_version(flash.__version__)
self.window.set_logo(gtk.gdk.pixbuf_new_from_file(
os.path.join(flash.app.data_dir, "flash-b.png")))
self.window.show_all()
def run(self):
self.window.run()
self.window.destroy()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
__name__ = "Flash!"
__version__ = "0.1"
__version_str__ = '.'.join([str(x) for x in __version__])
__author__ = "Tumi Steingrímsson <tumi.st@gmail.com>"
__licence__ = "GPL"
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import socket
import threading
import ftplib
import os
def debugmsg(msg):
"""Override as fits."""
CRLF = ftplib.CRLF
def clearwhites(s):
"""This is not a racist function. I takes all
multiple whitespaces away."""
return ' '.join([x for x in s.split(' ') if x])
class Server:
"""A representation of an FTP server."""
protocols = ['ftp', 'ftp+ssl'] # accepted protocols
def __init__(self, hostname, **kwargs):
self.hostname = hostname
self.username = kwargs.get("username", None)
self.password = kwargs.get("password", None)
self.port = kwargs.get("port", 21)
self.protocol = kwargs.get("protocol", "ftp")
self.directory = kwargs.get("directory", None)
self.passive = kwargs.get("passive", True)
self.force_ssl = kwargs.get("force_ssl", False)
self.validate()
def __str__(self):
port = ''
if self.port != 21:
port = ":%s" % self.port
return "%s://%s%s" % (self.protocol, self.hostname, port)
def allstr(self):
return "%s://%s:%s@%s:%s" % (self.protocol, self.username,
self.password, self.hostname, self.port)
def validate(self):
if not self.protocol in self.protocols:
raise ValueError, "%s is unknown protocol" % self.protocol
class RemoteFile:
"""Represents a file on an FTP server."""
def __init__(self, **kwargs):
self.filename = kwargs.get("filename", None)
# the containing directory of this file
self.dir = kwargs.get("dir", None)
# the type of this file: f, d or l
self.type = kwargs.get("type", None)
# size in bytes
self.size = int(kwargs.get("size", 0))
# permissions on this file
self.unix_perm = kwargs.get("unix_perm", None)
# owner on server
self.owner = kwargs.get("owner", None)
# group on server
self.group = kwargs.get("group", None)
# changed date
self.ctime = kwargs.get("ctime", None)
# if this is a symbolic link, specify target file
self.linkto = kwargs.get("linkto", None)
# a Server object
self.server = kwargs.get("server")
def __repr__(self):
return "<RemoteFile %s type: %s>" % \
(self.filename, self.type)
def __str__(self):
"""Return URL for this file.
Without username and password and stuff."""
return "%s%s/%s" % (self.server, self.dir, self.filename)
def allstr(self):
"""Return URL with all information."""
return "%s%s/%s?%s" % (self.server.allstr(), self.dir, self.filename,
"&".join(["type=%s"%self.type and self.type]))
def __int__(self):
return self.size
def ishidden(self):
if self.filename.startswith('.') or self.filename.endswith('~'):
return True
else:
return False
def islink(self):
return self.type == 'l'
def isfile(self):
return self.type == 'f'
def isdir(self):
return self.type == 'd'
def abs_location(self):
"""Absolute location on server."""
if self.dir == "/":
return "/%s" % self.filename
else:
return "%s/%s" % (self.dir, self.filename)
def remotefile_from_str(s):
import urllib
protocol, rest = s.split("://")
host, rest = urllib.splithost("//" + rest)
host, port = urllib.splitnport(host, defport=21)
file, t = urllib.splitquery(rest)
s = Server(host, port=port)
dir, fn = os.path.split(file)
rf = RemoteFile(filename=fn, dir=dir, type="f", server=s)
return rf
def parse_LIST(list_output, dir, server):
"""Interpret LIST output and return RemoteFiles.
list_output should be in a list format (each line from
server a string in the list).
dir is the directory for witch the files are in."""
for line in list_output:
line = clearwhites(line)
if line.startswith('total'):
continue
tokens = line.split(' ', 8)
# item will be yielded later
item = RemoteFile(server=server)
item.type = line[0]
item.size = int(tokens[4])
item.filename = tokens[-1]
item.unix_perm = tokens[0][1:]
item.owner = tokens[2]
item.group = tokens[3],
item.ctime = ''.join(tokens[5:8])
item.dir = dir
# correct symbolic link issues
if line[0] == "l":
item.filename, item.linkto = item.filename.split(" -> ")
elif line[0] == "-":
item.type = "f"
yield item
def parse_MLSD(mlsd_output, dir, server):
"""Interpret MLSD output."""
for line in mlsd_output:
attrs = line.split(';')
kwargs = {}
for attr in attrs[:-1]:
option, value = attr.split('=')
if option == 'type':
kwargs[option] = value[0]
continue
if option == 'size':
kwargs[option] = int(value)
continue
kwargs[option] = value
kwargs['filename'] = attrs[-1][1:]
kwargs['dir'] = dir
item = RemoteFile(server=server, **kwargs)
yield item
class FTP(ftplib.FTP):
"""Improvements to ftplib.FTP"""
class FTPThread(FTP, threading.Thread):
"""FTP Thread built on ftplib.FTP, but with significant
improvements to the standard function, SSL, MLST and
MLSD commands to name a few.
Current job will be in self.current_job
Waiting jobs in self.jobs, clear with jobs = []
Some jobs can be aborted:
* retrbinary can be stopped by switching self.abor to true
ABOR will be sent and data connection closed.
Callbacks: (Arguments...)
* connected: Socket connected to host (welcome_msg)
* connect_error: Socket could not connect to host (exception)
* authenticated: Authentication was successful (response)
* authentication_error: Authentication error (error_str)
* sending: About to send this (data)
* received: Received line (data)
* disconnected: Disconnected from server (reason)
* pwd: Workin directory (directory)
* cwd: Current directory changed (msg)
* cwd_error: Error on changing directories (reason)
* dir: Output from LIST (list)
* timeout: General timeout (exception)
* retr_pos: Bytes read of current receiving file (stream position, cmd)
cmd = the original line sent to server to initiate the transfer
* transfer_finished: This transfer has finished (cmd)
* transfer_aborted: This transfer was aborted (cmd)
* unhandled_exception: Unhandled exception occured (job, exception)
* ssl_enabled: Data-connection has engaged encryption (server, issuer)
* ssl_not_availible: Called when we find out that there is no SSL support (str)
* mlsd: the output from this command ()
* deleted: File was deleted (filename)
* delete_error: File was not deleted (filename, error_string)
* walk: Items in one directory from walk (item, **kwargs)
* walk_end: ()
* walk_error:
* list_parents_finished: ()
* downloaded: File downloaded (remote, to)
* download_error: Error in download() (e)
* stor_pos: Sent bytes via STOR.
* stor_error: Error in upload (e)
"""
_all_callbacks = ['connected', 'connect_error', 'authenticated',
'authentication_error', 'sending', 'received', 'disconnected', 'pwd',
'cwd', 'cwd_error', 'dir', 'timeout', 'retr_pos', 'transfer_finished',
'transfer_aborted', 'unhandled_exception', 'ssl_enabled', 'mlsd',
'listing', 'walk', 'deleted', 'delete_error', 'ssl_not_availible', 'walk_end',
'list_parents_finished', 'stor_pos', 'stor_error']
def __init__(self, socket_timeout=0, data_socket_timeout=0,
daemon=False, server=None):
"""
Arguments:
socket_timeout => The timeout in the control-connection
data_socket_timeout => Timeout for data-connection
daemon => whether to daemonize thread
server => Server object to use
"""
threading.Thread.__init__(self)
self.socket_timeout = socket_timeout
self.data_socket_timeout = data_socket_timeout
self.feats = []
self.ssl_buffer = ''
self.ssl_sock = None
self.abor = False
self.callbacks = {}
self.jobs = []
self.current_job = None
self.wd = ""
self.list_cache = {}
# Server object (not needed until connect())
self.server = server
self.lock = threading.Semaphore()
self.lock.acquire(True) # a new lock can be released once
self.setDaemon(daemon)
if not self.isAlive():
self.start()
def getline(self):
""" Internal: Reads one line from (ssl)socket """
if self.ssl_sock:
while not self.ssl_buffer.count(CRLF):
self.ssl_buffer += self.ssl_sock.read()
pos = self.ssl_buffer.find(CRLF) + 2
line = self.ssl_buffer[:pos]
self.ssl_buffer = self.ssl_buffer[pos:]
else:
line = self.file.readline()
if line:
if line[-2:] == CRLF: line = line[:-2]
elif line[-1:] in CRLF: line = line[:-1]
self.callback('received', line)
else:
self.callback('disconnected', line)
return line
def putline(self, line):
""" Internal: Write line to (ssl)socket """
self.callback('sending', line)
line = line + CRLF
if self.ssl_sock:
self.ssl_sock.write(line)
else:
self.sock.sendall(line)
def parse_feat_response(self, r):
"""Internal:
Parse response from FEAT.
FEATs will be stored in self.feats."""
if r.count(CRLF):
r = r.split(CRLF)
else:
r = r.split("\n")
for l in r:
if not len(l) > 1:
continue
if l[1] == "1":
continue
self.feats.append(l[1:])
def connect(self, server=None):
"""Connect to host."""
if server:
self.server = server
self.add_job("_connect")
def _connect(self):
"""Internal."""
self.set_pasv(self.server.passive)
msg = "getaddrinfo returns an empty list"
try:
foo = socket.getaddrinfo(self.server.hostname,
self.server.port, 0, socket.SOCK_STREAM)
except Exception, e:
self.callback('connect_error', e)
return
for res in foo:
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.socket_timeout:
self.sock.settimeout(self.socket_timeout)
self.sock.connect(sa)
except socket.error, msg:
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
self.callback('connect_error', msg)
return
self.af = af
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
try:
self.parse_feat_response(self.voidcmd("FEAT"))
except ftplib.error_perm:
pass
if "ssl" in self.server.protocol and "AUTH TLS" in self.feats:
try:
self.make_ssl()
except Exception, e:
self.callback('ssl_not_availible', str(e))
elif self.server.force_ssl:
try:
self.make_ssl()
except Exception, e:
self.callback('ssl_not_availible', str(e))
# jump ship!
self._quit()
return
self.callback("connected", self.welcome)
return self.welcome
def makeport(self):
"""
Internal: Create a new socket and send a PORT command for it.
"""
msg = "getaddrinfo returns an empty list"
sock = None
for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
sock = socket.socket(af, socktype, proto)
if self.data_socket_timeout:
sock.settimeout(self.data_socket_timeout)
sock.bind(sa)
except socket.error, msg:
if sock:
sock.close()
sock = None
continue
break
if not sock:
raise socket.error, msg
sock.listen(1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockname()[0] # Get proper host
if self.af == socket.AF_INET:
resp = self.sendport(host, port)
else:
resp = self.sendeprt(host, port)
return sock
def ntransfercmd(self, cmd, rest=None):
"""
Internal:
Initiate a transfer over the data connection.
If the transfer is active, send a port command and the
transfer command, and accept the connection. If the server is
passive, send a pasv command, connect to it, and start the
transfer command. Either way, return the socket for the
connection and the expected size of the transfer. The
expected size may be None if it could not be determined.
Optional `rest' argument can be a string that is sent as the
argument to a RESTART command. This is essentially a server
marker used to tell the server to skip over any data up to the
given marker.
"""
size = None
if self.passiveserver:
host, port = self.makepasv()
af, socktype, proto, canon, sa = socket.getaddrinfo(host, port,
0, socket.SOCK_STREAM)[0]
conn = socket.socket(af, socktype, proto)
if self.data_socket_timeout:
conn.settimeout(self.data_socket_timeout)
conn.connect(sa)
if rest is not None:
self.sendcmd("REST %s" % rest)
resp = self.sendcmd(cmd)
if resp[0] != '1':
raise error_reply, resp
else:
sock = self.makeport()
if rest is not None:
self.sendcmd("REST %s" % rest)
resp = self.sendcmd(cmd)
if resp[0] != '1':
raise error_reply, resp
conn, sockaddr = sock.accept()
if resp[:3] == '150':
# this is conditional in case we received a 125
size = ftplib.parse150(resp)
return conn, size
def login(self):
"""Send login commands."""
self.add_job("_login")
def _login(self):
try:
resp = ftplib.FTP.login(self,
user=self.server.username, passwd=self.server.password)
except ftplib.error_reply, e:
self.callback("authentication_error", e)
except Exception, e:
self.callback("authentication_error", e)
else:
if not self.feats:
self.parse_feat_response(self.voidcmd("FEAT"))
self.callback("authenticated", resp)
def mlsd(self, argument=''):
""" Send MLSD command (use self.ls instead!) """
self.add_job("_mlsd", argument=argument)
def _mlsd(self, argument='', hidden=False):
output = []
try:
resp = self.retrlines(argument and "MLSD %s" % argument \
or "MLSD", output.append)
except socket.timeout, e:
self.callback("timeout", e)
return
self.callback('mlsd', output)
return resp, output
def make_ssl(self):
""" Creates self.ssl_sock socket. Returns AUTH TLS reply. """
debugmsg("Creating SSL socket")
resp = self.voidcmd("AUTH TLS")
self.ssl_sock = socket.ssl(self.sock)
self.ssl_initialized = True
return resp
def callback(self, callback_key, *args, **kwargs):
"""Internal"""
if self.callbacks.has_key(callback_key):
for func in self.callbacks[callback_key]:
try:
func(*args, **kwargs)
except Exception, e:
import traceback, sys
print "Fatal error in callback, trace:"
traceback.print_exc(file=sys.stdout)
def add_job(self, jobname, *args, **kwargs):
"""Internal: Adds a job to the queue"""
self.jobs.append((jobname, args, kwargs))
self.lock.release()
def quit(self):
self.add_job("_quit")
def _quit(self):
resp = ftplib.FTP.quit(self)
self.callback("disconnected", str(resp))
def pwd(self):
""" Print working directory """
self.add_job("_pwd")
def _pwd(self):
resp = ftplib.FTP.pwd(self)
self.wd = resp
self.callback("pwd", resp)
return resp
def cwd(self, d):
""" Change working directory """
self.add_job("_cwd", d)
def _cwd(self, d):
try:
resp = ftplib.FTP.cwd(self, d)
except (ftplib.error_reply, ftplib.error_perm), e:
self.callback("cwd_error", str(e))
return False
else:
self.callback("cwd", resp)
return True
def dir(self):
""" Send LIST command (use self.ls instead!) """
self.add_job("_dir")
def _dir(self, hidden=False, *args):
output = []
try:
if hidden:
resp = ftplib.FTP.dir(self, '-l', output.append)
else:
resp = ftplib.FTP.dir(self, output.append)
except socket.timeout, e:
self.callback("timeout", e)
return
return resp, output
def retrbinary(self, *args, **kwargs):
self.add_job("_retrbinary", *args, **kwargs)
def _retrbinary(self, cmd, callback, blocksize=8192, rest=None):
"""Internal: Retrieve data in binary mode.
`cmd' is a RETR command. `callback' is a callback function is
called for each block. No more than `blocksize' number of
bytes will be read from the socket. Optional `rest' is passed
to transfercmd().
A new port is created for you. Return the response code.
ThreadFTP: Add a position callback, returns -1 once complete.
Checks for self.abor
Calls callback with finish=True once no more callbacks
to this method will be done.
"""
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd, rest)
pos = 0
if rest:
pos = rest
while not self.abor:
data = conn.recv(blocksize)
if not data:
self.callback('retr_pos', -1, cmd)
self.callback('transfer_finished', cmd)
callback('', finish=True)
break
pos += len(data)
self.callback('retr_pos', pos, cmd)
callback(data)
conn.close()
if self.abor:
try:
self.getmultiline()
except EOFError: pass
self.callback('transfer_aborted', cmd)
self.abor = False
return
return self.voidresp()
def storbinary(self, *args, **kwargs):
self.add_job("_storbinary", *args, **kwargs)
def _storbinary(self, cmd, fp, blocksize=8192):
'''Store a file in binary mode.'''
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd)
while not self.abor:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if self.abor:
self.abor = False
conn.close()
return self.voidresp()
def quote(self, line):
""" Send a line """
self.add_job("sendcmd", line)
def sendcmd(self, *args, **kwargs):
""" Internal: Added timeout handling. """
try:
return ftplib.FTP.sendcmd(self, *args, **kwargs)
except socket.timeout, e:
self.callback("timeout", e)
def run(self):
""" Internal: Thread loop """
while 1:
# Wait for a job to enter
self.lock.acquire(True)
try:
job, args, kwargs = self.jobs.pop(0)
self.current_job = (job, args, kwargs)
except IndexError:
debugmsg("Lock released, no job.")
continue
else:
debugmsg("Lock released, job: %s %s %s" %(job, args, kwargs))
if job == "join":
break # Break out of loop, join thread
try:
getattr(self, job)(*args, **kwargs)
except Exception, e:
self.callback('unhandled_exception', (job, args, kwargs), e)
print "Non-fatal exception in job, traceback:"
import traceback, sys
traceback.print_exc(file=sys.stdout)
self.current_job = None
def add_callbacks(self, c_map):
"""
Use map to add callbacks.
"""
for key in c_map.keys():
if self.callbacks.has_key(key):
self.callbacks[key].append(c_map[key])
else:
self.callbacks[key] = [c_map[key]]
def remove_callbacks(self, c_map):
"""
Remove functions from callbacks
"""
for key in c_map:
self.callbacks[key].remove(c_map[key])
def flush_cache(self):
""" Flushes the directory listing cache """
self.list_cache = {}
def ls(self, **kw):
""" List files in current directory. """
self.add_job("_ls")
def _ls(self, **kw):
if self.wd in self.list_cache.keys():
# Use cache
listing = self.list_cache[self.wd]
resp = None
elif "MLSD" in self.feats:
resp, output = self._mlsd(**kw)
listing = list(parse_MLSD(output, self.wd, self.server))
self.list_cache[self.wd] = listing
else:
resp, output = self._dir(**kw)
listing = list(parse_LIST(output, self.wd, self.server))
self.list_cache[self.wd] = listing
self.callback("listing", listing)
return resp, listing
def delete(self, item):
self.add_job("_delete", item)
def _delete(self, item):
if self.wd == item.dir:
fs = item.filename
else:
fs = item.abs_location()
try:
if item.type == 'f':
ftplib.FTP.delete(self, fs)
elif item.type == 'd':
ftplib.FTP.rmd(self, fs)
except ftplib.error_perm, e:
self.callback('delete_error', fs, str(e))
else:
self.callback('deleted', fs)
def join(self):
self.add_job("join")
def busy(self):
"""Return True if this thread is doing a job or has waiting jobs."""
return bool(self.current_job or self.jobs)
def walk(self, d, **kwargs):
self.add_job("_walk", d, **kwargs)
def _walk(self, d, **kwargs):
def cwd(h):
r = self._cwd(h)
self._pwd()
return r
def dodir():
resp, listing = self._ls()
for item in listing:
self.callback('walk', item, **kwargs)
if item.isdir():
if cwd(item.filename):
dodir()
cwd('..')
if cwd(d):
dodir()
cwd('..')
self.callback('walk_end')
self._ls()
def list_parents(self):
self.add_job("_list_parents")
def _list_parents(self):
"""Go to root, list, next, list, repeat."""
wdsplit = [x for x in self.wd.split("/") if x]
for i in xrange(len(wdsplit)+1):
path = "/" + "/".join(wdsplit[:i])
self._cwd(path)
self._pwd()
self._ls()
self.callback('list_parents_finished')
def download(self, remote, to, rest=False):
self.add_job("_download", remote, to, rest)
def _download(self, remote, to, rest):
"""Download a RemoteFile."""
# check if we're already on the correct server
if not remote.server is self.server:
self.server = remote.server
if self.sock: self._quit()
# TODO: this does not handle errors.
self._connect()
self._login()
if not self.wd == remote.dir:
self._cwd(remote.dir)
seek = 0
if rest and os.path.isfile(to):
seek = os.path.getsize(to)
try:
fd = open(to, seek and "a" or "w")
except:
self.callback('download_error',
"Could not open file for writing: %s" % to)
return
def cb(d, finish=False):
fd.write(d)
if finish:
fd.close()
try:
self._retrbinary("RETR %s" % remote.filename, cb,
rest=(seek and str(seek) or None))
except ftplib.error_perm:
self.callback('download_error', "Permission denied")
except Exception, e:
self.callback('download_error', str(e))
def upload(self, local, remote):
self.add_job("_upload", local, remote)
def _upload(self, local, remote):
if not remote.server is self.server:
self.server = remote.server
if self.sock: self._quit()
self._connect()
self._login()
if not self.wd == remote.dir:
self._cwd(remote.dir)
try:
fd = open(local, "r")
self._storbinary("STOR %s" % remote.filename, fd)
except ftplib.error_perm:
self.callback('stor_error', "Permission denied")
except Exception, e:
self.callback('stor_error', str(e))
if __name__ == "__main__":
print "This is a library."
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A startup file for FlashFTP.
Signals an already running flashftp to start
a Browser if running, else imports flash.app
and creates a new Application.
"""
import sys
try:
import dbus
except ImportError:
dbus = None
def isrunning():
return False
if isrunning():
pass
else:
from flash import app
myapp = app.FlashFTPApp()
myapp.new_connect_dialog()
myapp.loop()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A startup file for FlashFTP.
Signals an already running flashftp to start
a Browser if running, else imports flash.app
and creates a new Application.
"""
import sys
try:
import dbus
except ImportError:
dbus = None
def isrunning():
return False
if isrunning():
pass
else:
from flash import app
myapp = app.FlashFTPApp()
myapp.new_connect_dialog()
myapp.loop()
| Python |
#!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start("HelloWorldActivity")
except ImportError:
import os
os.system("find ./ | sed 's,^./,HelloWorldActivity.activity/,g' > MANIFEST")
os.system('rm HelloWorldActivity.xo')
os.chdir('..')
os.system('zip -r HelloWorldActivity.xo HelloWorldActivity.activity')
os.system('mv HelloWorldActivity.xo ./HelloWorldActivity.activity')
os.chdir('HelloWorldActivity.activity')
| Python |
#!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start("HelloWorldActivity")
except ImportError:
import os
os.system("find ./ | sed 's,^./,HelloWorldActivity.activity/,g' > MANIFEST")
os.system('rm HelloWorldActivity.xo')
os.chdir('..')
os.system('zip -r HelloWorldActivity.xo HelloWorldActivity.activity')
os.system('mv HelloWorldActivity.xo ./HelloWorldActivity.activity')
os.chdir('HelloWorldActivity.activity')
| Python |
#! /usr/bin/env python
# scriptedfun.com 1945
# http://www.scriptedfun.com/
# June 5, 2006
# MIT License
# 1945.bmp
# taken from the Spritelib by Ari Feldman
# http://www.flyingyogi.com/fun/spritelib.html
# Common Public License
import math, os, pygame, random, sys#, olpcgames
from pygame.locals import *
# game constants
SCREENRECT = Rect(0, 0, 1200, 900)
def load_sound(filename):
filename = os.path.join('data', filename)
return pygame.mixer.Sound(filename)
def imgcolorkey(image, colorkey):
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image
def load_image(filename, colorkey = None):
filename = os.path.join('data', filename)
image = pygame.image.load(filename).convert()
return imgcolorkey(image, colorkey)
class SpriteSheet:
def __init__(self, filename):
self.sheet = load_image(filename)
def imgat(self, rect, colorkey = None):
rect = Rect(rect)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
return imgcolorkey(image, colorkey)
def imgsat(self, rects, colorkey = None):
imgs = []
for rect in rects:
imgs.append(self.imgat(rect, colorkey))
return imgs
class Arena:
speed = 1
enemyprob = 22
enemycount = 0
def __init__(self, enemies, shots):
w = SCREENRECT.width
h = SCREENRECT.height
self.tileside = self.oceantile.get_height()
self.counter = 0
self.ocean = pygame.Surface((w, h + self.tileside)).convert()
for x in range(w/self.tileside):
for y in range(h/self.tileside + 1):
self.ocean.blit(self.oceantile, (x*self.tileside, y*self.tileside))
self.enemies = enemies
self.shots = shots
def offset(self):
self.counter = (self.counter - self.speed) % self.tileside
return (0, self.counter, SCREENRECT.width, SCREENRECT.height)
def update(self):
# decreasing enemyprob increases the
# probability of new enemies appearing
#if not random.randrange(self.enemyprob):
# Enemy()
for enemy in pygame.sprite.groupcollide(self.shots, self.enemies, 1, 1).keys():
Explosion(enemy)
self.enemycount -= 1
#print self.enemycount
if self.enemycount <= 0:
# create 10 enemies
for i in range(0, 10):
Enemy()
self.enemycount += 1
#self.enemycount = 10
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change its current position and state
class Plane(pygame.sprite.Sprite):
crect = (14, 1, 29, 39)
guns = [(17, 19), (39, 19)]
animcycle = 1
reloadtime = 15
speed = 4
def __init__(self, arena, bombs, enemies):
pygame.sprite.Sprite.__init__(self, self.containers)
self.oninvincible()
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.arena = arena
self.bombs = bombs
self.enemies = enemies
self.justfired = 0
self.reloadtimer = 0
def oninvincible(self):
self.images = self.transparents
self.invincible = True
def offinvincible(self):
self.images = self.opaques
self.invincible = False
def update(self):
#self.rect.center = pygame.mouse.get_pos()
keystate = pygame.key.get_pressed()
if keystate[K_KP2] or keystate[K_DOWN]:
self.rect.move_ip(0, self.speed)
if keystate[K_KP4] or keystate[K_LEFT]:
self.rect.move_ip(-self.speed, 0)
if keystate[K_KP6] or keystate[K_RIGHT]:
self.rect.move_ip(self.speed, 0)
if keystate[K_KP8] or keystate[K_UP]:
self.rect.move_ip(0, -self.speed)
self.rect = self.rect.clamp(SCREENRECT)
self.counter = (self.counter + 1) % self.maxcount
self.image = self.images[self.counter/self.animcycle]
if self.reloadtimer > 0:
self.reloadtimer = self.reloadtimer -1
#firing = pygame.mouse.get_pressed()[0]
firing = keystate[K_KP1] or keystate[K_KP3] or \
keystate[K_KP7] or keystate[K_KP9]
if firing and (not self.justfired or self.reloadtimer == 0):
if self.invincible:
self.offinvincible()
self.reloadtimer = self.reloadtime
for gun in self.guns:
Shot((self.rect.left + gun[0], self.rect.top + gun[1]))
self.justfired = firing
# shrink rect for collision detection
if not self.invincible:
oldrect = self.rect
self.rect = Rect(*self.crect)
self.rect.topleft = (oldrect.left + self.crect[0], oldrect.top + self.crect[1])
if pygame.sprite.spritecollide(self, self.bombs, 1):
self.oninvincible()
Planeexplosion(self)
if pygame.sprite.spritecollide(self, self.enemies, 1):
self.oninvincible()
Planeexplosion(self)
arena.enemycount -= 1
self.rect = oldrect
self.arena.update()
class Shot(pygame.sprite.Sprite):
speed = 9
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self, self.containers)
self.rect = self.image.get_rect()
self.rect.center = pos
def update(self):
self.rect.move_ip(0, -self.speed)
if self.rect.top < 0:
self.kill()
class Bomb(pygame.sprite.Sprite):
speed = 5
def __init__(self, gun):
pygame.sprite.Sprite.__init__(self, self.containers)
self.rect = self.image.get_rect()
self.rect.centerx = gun[0]
self.rect.centery = gun[1]
self.setfp()
angle = math.atan2(self.plane.rect.centery - gun[1], self.plane.rect.centerx - gun[0])
self.fpdy = self.speed * math.sin(angle)
self.fpdx = self.speed * math.cos(angle)
def setfp(self):
"""use whenever usual integer rect values are adjusted"""
self.fpx = self.rect.centerx
self.fpy = self.rect.centery
def setint(self):
"""use whenever floating point rect values are adjusted"""
self.rect.centerx = self.fpx
self.rect.centery = self.fpy
def update(self):
self.fpx = self.fpx + self.fpdx
self.fpy = self.fpy + self.fpdy
self.setint()
if not SCREENRECT.contains(self.rect):
self.kill()
class Enemy(pygame.sprite.Sprite):
gun = (16, 19)
animcycle = 2
speed = 3
hspeed = 1
turnprob = 200
increasespeedprob = 300
maxspeed = 10
decreasespeedprob = 301
shotprob = 350
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.containers)
self.images = random.choice(self.imagesets)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.left = random.randrange(SCREENRECT.width - self.rect.width)
self.rect.bottom = SCREENRECT.top
def update(self):
self.rect.move_ip(self.hspeed, self.speed)
self.counter = (self.counter + 1) % self.maxcount
self.image = self.images[self.counter/self.animcycle]
#if self.rect.top > SCREENRECT.bottom:
if self.rect.bottom >= SCREENRECT.bottom:
#self.kill()
self.speed = -self.speed
if self.rect.top <= SCREENRECT.top and self.speed < 0:
self.speed = -self.speed
if not random.randrange(self.turnprob):
self.hspeed = -self.hspeed
if not random.randrange(self.shotprob):
Bomb((self.rect.left + self.gun[0], self.rect.top + self.gun[1]))
if self.rect.right >= SCREENRECT.right and self.hspeed > 0:
self.hspeed = -self.hspeed
if self.rect.left <= SCREENRECT.left and self.hspeed < 0:
self.hspeed = -self.hspeed
if not random.randrange(self.increasespeedprob) and self.speed < self.maxspeed:
self.speed += 1
if not random.randrange(self.decreasespeedprob) and self.speed > 0:
self.speed += 1
class Explosion(pygame.sprite.Sprite):
animcycle = 4
def __init__(self, enemy):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.center = enemy.rect.center
def update(self):
self.image = self.images[self.counter/self.animcycle]
self.counter = self.counter + 1
if self.counter == self.maxcount:
self.kill()
class Planeexplosion(pygame.sprite.Sprite):
animcycle = 4
def __init__(self, plane):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.center = plane.rect.center
def update(self):
self.image = self.images[self.counter/self.animcycle]
self.counter = self.counter + 1
if self.counter == self.maxcount:
# this destroys the enemy or bomb
self.kill()
def main():
pygame.init()
global arena
# set the display mode
winstyle = 0
bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
# load images, assign to sprite classes
# (do this before the classes are used, after screen setup)
spritesheet = SpriteSheet('1945.bmp')
Arena.oceantile = spritesheet.imgat((268, 367, 32, 32))
Shot.image = spritesheet.imgat((48, 176, 9, 20), -1)
Bomb.image = spritesheet.imgat((278, 113, 13, 13), -1)
Plane.opaques = spritesheet.imgsat([(305, 113, 61, 49),
(305, 179, 61, 49),
(305, 245, 61, 49)],
-1)
Plane.transparents = spritesheet.imgsat([(305, 113, 61, 49),
(305, 179, 61, 49),
(305, 245, 61, 49)],
-1)
for image in Plane.transparents:
image.set_alpha(85)
Explosion.images = spritesheet.imgsat([(70, 169, 32, 32),
(103, 169, 32, 32),
(136, 169, 32, 32),
(169, 169, 32, 32),
(202, 169, 32, 32),
(235, 169, 32, 32)],
-1)
Planeexplosion.images = spritesheet.imgsat([(4, 301, 65, 65),
(70, 301, 65, 65),
(136, 301, 65, 65),
(202, 301, 65, 65),
(268, 301, 65, 65),
(334, 301, 65, 65),
(400, 301, 65, 65)],
-1)
# 0 - "dark" green
# 1 - white
# 2 - "light" green
# 3 - blue
# 4 - orange
Enemy.imagesets = [
spritesheet.imgsat([(4, 466, 32, 32), (37, 466, 32, 32), (70, 466, 32, 32)], -1),
spritesheet.imgsat([(103, 466, 32, 32), (136, 466, 32, 32), (169, 466, 32, 32)], -1),
spritesheet.imgsat([(202, 466, 32, 32), (235, 466, 32, 32), (268, 466, 32, 32)], -1),
spritesheet.imgsat([(301, 466, 32, 32), (334, 466, 32, 32), (367, 466, 32, 32)], -1),
spritesheet.imgsat([(4, 499, 32, 32), (37, 499, 32, 32), (70, 499, 32, 32)], -1)
]
# decorate the game window
pygame.display.set_caption('scriptedfun.com 1945')
# initialize game groups
shots = pygame.sprite.Group()
bombs = pygame.sprite.Group()
enemies = pygame.sprite.Group()
obstacles = pygame.sprite.Group()
islands = pygame.sprite.RenderPlain()
all = pygame.sprite.RenderPlain()
# assign default groups to each sprite class
Plane.containers = all
Shot.containers = shots, all
Enemy.containers = enemies, obstacles, all
Bomb.containers = bombs, obstacles, all
Explosion.containers = all
Planeexplosion.containers = all
clock = pygame.time.Clock()
# initialize our starting sprites
arena = Arena(enemies, shots)
plane = Plane(arena, bombs, enemies)
Bomb.plane = plane
# eliminate mouse-move events
pygame.event.set_blocked(MOUSEMOTION)
# make the player's plane start at the bottom middle
plane.rect.bottom = SCREENRECT.bottom
plane.rect.left = SCREENRECT.right / 2 - plane.rect.width / 2
while 1:
# get input
for event in pygame.event.get():
# via http://wiki.laptop.org/go/Game_development_HOWTO
#events = pausescreen.get_events()
#for event in events:
if event.type == QUIT or \
(event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
#sys.exit(0)
#keystate = pygame.key.get_pressed()
# draw the scene
screen.blit(arena.ocean, (0, 0), arena.offset())
islands.draw(screen)
all.draw(screen)
pygame.display.flip()
# update all the sprites
all.update()
# cap the framerate
clock.tick(60)
if __name__ == '__main__': main()
| Python |
#! /usr/bin/env python
# scriptedfun.com 1945
# http://www.scriptedfun.com/
# June 5, 2006
# MIT License
# 1945.bmp
# taken from the Spritelib by Ari Feldman
# http://www.flyingyogi.com/fun/spritelib.html
# Common Public License
import math, os, pygame, random, sys#, olpcgames
from pygame.locals import *
# game constants
SCREENRECT = Rect(0, 0, 1200, 900)
def load_sound(filename):
filename = os.path.join('data', filename)
return pygame.mixer.Sound(filename)
def imgcolorkey(image, colorkey):
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image
def load_image(filename, colorkey = None):
filename = os.path.join('data', filename)
image = pygame.image.load(filename).convert()
return imgcolorkey(image, colorkey)
class SpriteSheet:
def __init__(self, filename):
self.sheet = load_image(filename)
def imgat(self, rect, colorkey = None):
rect = Rect(rect)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
return imgcolorkey(image, colorkey)
def imgsat(self, rects, colorkey = None):
imgs = []
for rect in rects:
imgs.append(self.imgat(rect, colorkey))
return imgs
class Arena:
speed = 1
enemyprob = 22
enemycount = 0
def __init__(self, enemies, shots):
w = SCREENRECT.width
h = SCREENRECT.height
self.tileside = self.oceantile.get_height()
self.counter = 0
self.ocean = pygame.Surface((w, h + self.tileside)).convert()
for x in range(w/self.tileside):
for y in range(h/self.tileside + 1):
self.ocean.blit(self.oceantile, (x*self.tileside, y*self.tileside))
self.enemies = enemies
self.shots = shots
def offset(self):
self.counter = (self.counter - self.speed) % self.tileside
return (0, self.counter, SCREENRECT.width, SCREENRECT.height)
def update(self):
# decreasing enemyprob increases the
# probability of new enemies appearing
#if not random.randrange(self.enemyprob):
# Enemy()
for enemy in pygame.sprite.groupcollide(self.shots, self.enemies, 1, 1).keys():
Explosion(enemy)
self.enemycount -= 1
#print self.enemycount
if self.enemycount <= 0:
# create 10 enemies
for i in range(0, 10):
Enemy()
self.enemycount += 1
#self.enemycount = 10
# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change its current position and state
class Plane(pygame.sprite.Sprite):
crect = (14, 1, 29, 39)
guns = [(17, 19), (39, 19)]
animcycle = 1
reloadtime = 15
speed = 4
def __init__(self, arena, bombs, enemies):
pygame.sprite.Sprite.__init__(self, self.containers)
self.oninvincible()
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.arena = arena
self.bombs = bombs
self.enemies = enemies
self.justfired = 0
self.reloadtimer = 0
def oninvincible(self):
self.images = self.transparents
self.invincible = True
def offinvincible(self):
self.images = self.opaques
self.invincible = False
def update(self):
#self.rect.center = pygame.mouse.get_pos()
keystate = pygame.key.get_pressed()
if keystate[K_KP2] or keystate[K_DOWN]:
self.rect.move_ip(0, self.speed)
if keystate[K_KP4] or keystate[K_LEFT]:
self.rect.move_ip(-self.speed, 0)
if keystate[K_KP6] or keystate[K_RIGHT]:
self.rect.move_ip(self.speed, 0)
if keystate[K_KP8] or keystate[K_UP]:
self.rect.move_ip(0, -self.speed)
self.rect = self.rect.clamp(SCREENRECT)
self.counter = (self.counter + 1) % self.maxcount
self.image = self.images[self.counter/self.animcycle]
if self.reloadtimer > 0:
self.reloadtimer = self.reloadtimer -1
#firing = pygame.mouse.get_pressed()[0]
firing = keystate[K_KP1] or keystate[K_KP3] or \
keystate[K_KP7] or keystate[K_KP9]
if firing and (not self.justfired or self.reloadtimer == 0):
if self.invincible:
self.offinvincible()
self.reloadtimer = self.reloadtime
for gun in self.guns:
Shot((self.rect.left + gun[0], self.rect.top + gun[1]))
self.justfired = firing
# shrink rect for collision detection
if not self.invincible:
oldrect = self.rect
self.rect = Rect(*self.crect)
self.rect.topleft = (oldrect.left + self.crect[0], oldrect.top + self.crect[1])
if pygame.sprite.spritecollide(self, self.bombs, 1):
self.oninvincible()
Planeexplosion(self)
if pygame.sprite.spritecollide(self, self.enemies, 1):
self.oninvincible()
Planeexplosion(self)
arena.enemycount -= 1
self.rect = oldrect
self.arena.update()
class Shot(pygame.sprite.Sprite):
speed = 9
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self, self.containers)
self.rect = self.image.get_rect()
self.rect.center = pos
def update(self):
self.rect.move_ip(0, -self.speed)
if self.rect.top < 0:
self.kill()
class Bomb(pygame.sprite.Sprite):
speed = 5
def __init__(self, gun):
pygame.sprite.Sprite.__init__(self, self.containers)
self.rect = self.image.get_rect()
self.rect.centerx = gun[0]
self.rect.centery = gun[1]
self.setfp()
angle = math.atan2(self.plane.rect.centery - gun[1], self.plane.rect.centerx - gun[0])
self.fpdy = self.speed * math.sin(angle)
self.fpdx = self.speed * math.cos(angle)
def setfp(self):
"""use whenever usual integer rect values are adjusted"""
self.fpx = self.rect.centerx
self.fpy = self.rect.centery
def setint(self):
"""use whenever floating point rect values are adjusted"""
self.rect.centerx = self.fpx
self.rect.centery = self.fpy
def update(self):
self.fpx = self.fpx + self.fpdx
self.fpy = self.fpy + self.fpdy
self.setint()
if not SCREENRECT.contains(self.rect):
self.kill()
class Enemy(pygame.sprite.Sprite):
gun = (16, 19)
animcycle = 2
speed = 3
hspeed = 1
turnprob = 200
increasespeedprob = 300
maxspeed = 10
decreasespeedprob = 301
shotprob = 350
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.containers)
self.images = random.choice(self.imagesets)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.left = random.randrange(SCREENRECT.width - self.rect.width)
self.rect.bottom = SCREENRECT.top
def update(self):
self.rect.move_ip(self.hspeed, self.speed)
self.counter = (self.counter + 1) % self.maxcount
self.image = self.images[self.counter/self.animcycle]
#if self.rect.top > SCREENRECT.bottom:
if self.rect.bottom >= SCREENRECT.bottom:
#self.kill()
self.speed = -self.speed
if self.rect.top <= SCREENRECT.top and self.speed < 0:
self.speed = -self.speed
if not random.randrange(self.turnprob):
self.hspeed = -self.hspeed
if not random.randrange(self.shotprob):
Bomb((self.rect.left + self.gun[0], self.rect.top + self.gun[1]))
if self.rect.right >= SCREENRECT.right and self.hspeed > 0:
self.hspeed = -self.hspeed
if self.rect.left <= SCREENRECT.left and self.hspeed < 0:
self.hspeed = -self.hspeed
if not random.randrange(self.increasespeedprob) and self.speed < self.maxspeed:
self.speed += 1
if not random.randrange(self.decreasespeedprob) and self.speed > 0:
self.speed += 1
class Explosion(pygame.sprite.Sprite):
animcycle = 4
def __init__(self, enemy):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.center = enemy.rect.center
def update(self):
self.image = self.images[self.counter/self.animcycle]
self.counter = self.counter + 1
if self.counter == self.maxcount:
self.kill()
class Planeexplosion(pygame.sprite.Sprite):
animcycle = 4
def __init__(self, plane):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.counter = 0
self.maxcount = len(self.images)*self.animcycle
self.rect = self.image.get_rect()
self.rect.center = plane.rect.center
def update(self):
self.image = self.images[self.counter/self.animcycle]
self.counter = self.counter + 1
if self.counter == self.maxcount:
# this destroys the enemy or bomb
self.kill()
def main():
pygame.init()
global arena
# set the display mode
winstyle = 0
bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
# load images, assign to sprite classes
# (do this before the classes are used, after screen setup)
spritesheet = SpriteSheet('1945.bmp')
Arena.oceantile = spritesheet.imgat((268, 367, 32, 32))
Shot.image = spritesheet.imgat((48, 176, 9, 20), -1)
Bomb.image = spritesheet.imgat((278, 113, 13, 13), -1)
Plane.opaques = spritesheet.imgsat([(305, 113, 61, 49),
(305, 179, 61, 49),
(305, 245, 61, 49)],
-1)
Plane.transparents = spritesheet.imgsat([(305, 113, 61, 49),
(305, 179, 61, 49),
(305, 245, 61, 49)],
-1)
for image in Plane.transparents:
image.set_alpha(85)
Explosion.images = spritesheet.imgsat([(70, 169, 32, 32),
(103, 169, 32, 32),
(136, 169, 32, 32),
(169, 169, 32, 32),
(202, 169, 32, 32),
(235, 169, 32, 32)],
-1)
Planeexplosion.images = spritesheet.imgsat([(4, 301, 65, 65),
(70, 301, 65, 65),
(136, 301, 65, 65),
(202, 301, 65, 65),
(268, 301, 65, 65),
(334, 301, 65, 65),
(400, 301, 65, 65)],
-1)
# 0 - "dark" green
# 1 - white
# 2 - "light" green
# 3 - blue
# 4 - orange
Enemy.imagesets = [
spritesheet.imgsat([(4, 466, 32, 32), (37, 466, 32, 32), (70, 466, 32, 32)], -1),
spritesheet.imgsat([(103, 466, 32, 32), (136, 466, 32, 32), (169, 466, 32, 32)], -1),
spritesheet.imgsat([(202, 466, 32, 32), (235, 466, 32, 32), (268, 466, 32, 32)], -1),
spritesheet.imgsat([(301, 466, 32, 32), (334, 466, 32, 32), (367, 466, 32, 32)], -1),
spritesheet.imgsat([(4, 499, 32, 32), (37, 499, 32, 32), (70, 499, 32, 32)], -1)
]
# decorate the game window
pygame.display.set_caption('scriptedfun.com 1945')
# initialize game groups
shots = pygame.sprite.Group()
bombs = pygame.sprite.Group()
enemies = pygame.sprite.Group()
obstacles = pygame.sprite.Group()
islands = pygame.sprite.RenderPlain()
all = pygame.sprite.RenderPlain()
# assign default groups to each sprite class
Plane.containers = all
Shot.containers = shots, all
Enemy.containers = enemies, obstacles, all
Bomb.containers = bombs, obstacles, all
Explosion.containers = all
Planeexplosion.containers = all
clock = pygame.time.Clock()
# initialize our starting sprites
arena = Arena(enemies, shots)
plane = Plane(arena, bombs, enemies)
Bomb.plane = plane
# eliminate mouse-move events
pygame.event.set_blocked(MOUSEMOTION)
# make the player's plane start at the bottom middle
plane.rect.bottom = SCREENRECT.bottom
plane.rect.left = SCREENRECT.right / 2 - plane.rect.width / 2
while 1:
# get input
for event in pygame.event.get():
# via http://wiki.laptop.org/go/Game_development_HOWTO
#events = pausescreen.get_events()
#for event in events:
if event.type == QUIT or \
(event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
#sys.exit(0)
#keystate = pygame.key.get_pressed()
# draw the scene
screen.blit(arena.ocean, (0, 0), arena.offset())
islands.draw(screen)
all.draw(screen)
pygame.display.flip()
# update all the sprites
all.update()
# cap the framerate
clock.tick(60)
if __name__ == '__main__': main()
| Python |
from sugar.activity import activity
import logging
import sys, os
import gtk
class HelloWorldActivity(activity.Activity):
def hello(self, widget, data=None):
logging.info('Hello World')
def __init__(self, handle):
print "running activity init", handle
activity.Activity.__init__(self, handle)
print "activity running"
# Creates the Toolbox. It contains the Activity Toolbar, which is the
# bar that appears on every Sugar window and contains essential
# functionalities, such as the 'Collaborate' and 'Close' buttons.
toolbox = activity.ActivityToolbox(self)
self.set_toolbox(toolbox)
toolbox.show()
# Creates a new button with the label "Hello World".
self.button = gtk.Button("Flashcards Brazil")
# When the button receives the "clicked" signal, it will call the
# function hello() passing it None as its argument. The hello()
# function is defined above.
self.button.connect("clicked", self.hello, None)
# Set the button to be our canvas. The canvas is the main section of
# every Sugar Window. It fills all the area below the toolbox.
self.set_canvas(self.button)
# The final step is to display this newly created widget.
self.button.show()
print "AT END OF THE CLASS"
| Python |
#!/usr/bin/python2
'''
Copyright (c) 2013, Andrew Klaus <andrewklaus@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
__version__ = "1.1"
import os
import time
import shutil
import shlex
import sys
import subprocess
import threading
import multiprocessing # for cpu count
import argparse
try:
import mutagen # ID3 Tags, Imported if selected from command line
except ImportError:
pass
import audio_codecs
import logging
class LosslessToLossyConverter:
def __init__(self,source_dir,dest_dir,Decoder,Encoder, \
thread_count,disable_id3=False):
assert(Decoder.found_exe)
assert(Encoder.found_exe)
# Remove trailing slashes
self.source_dir = source_dir.rstrip('/')
self.dest_dir = dest_dir.rstrip('/')
self._set_thread_count(thread_count)
self.Decoder = Decoder
self.Encoder = Encoder
self.to_convert = [] # Music to convert
self.success = 0 # Successful conversions
self.error_conv = [] # List of error conversions
self.error_id3 = [] # List of error id3 tags
self.disable_id3 = disable_id3
def _set_thread_count(self,thread_count):
if thread_count == 0:
# Auto based on cpu count
self.thread_count = multiprocessing.cpu_count()
else:
self.thread_count = thread_count
def get_convert_list(self):
"""Populates list with files needing conversion."""
logging.debug('Get convert list starting')
try:
for dirpath, dirnames, filenames in os.walk(self.source_dir):
for filename in filenames:
if os.path.splitext(filename)[1] in self.Decoder.ext \
and os.path.splitext(filename)[1] != '':
#logging.debug('filename extension: ' + os.path.splitext(filename)[1])
#logging.debug('comparing extension: ' + self.source_ext)
if self.does_lossy_file_exist(os.path.join(dirpath,filename)) == False:
logging.debug('***Adding to_convert: ' + os.path.join(dirpath,filename))
# Lossy song does not exist
self.to_convert.append(os.path.join(dirpath,filename))
except Exception, ex:
logging.exception('Something happened in get_convert_list')
raise SystemExit
def translate_src_to_dest(self,lossless_file_path):
"""Provides translation between the source file and destination file"""
# Remove "src_path" from path
logging.debug('translate got: '+ lossless_file_path)
dest = os.path.join(self.dest_dir, lossless_file_path[1+len(self.source_dir):])
# Add extension
dest = os.path.splitext(dest)[0] + self.Encoder.ext
logging.debug('translate changed dest to: '+ dest)
return dest
def does_lossy_file_exist(self, source_file_path):
""" Checks if .lossless -> .lossy file already exists """
#logging.debug('does_lossy_file_exist received: '+ source_file_path)
dest = self.translate_src_to_dest(source_file_path)
# Remove ext and add .mp3 extension
dest = os.path.splitext(dest)[0] + self.Encoder.ext
#logging.debug('does_lossy_file_exist dest: '+ dest)
return os.path.exists(dest)
def create_dest_folders(self):
""" This creates an identical folder structure as the source directory
It attempts to create a folder (even if it exists), but catches any
FolderAlreadyExists exceptions that may arise.
"""
logging.debug('Creating folder structure')
for dirpath, dirnames, filenames in os.walk(self.source_dir):
try:
os.makedirs(os.path.join(self.dest_dir,dirpath[1+len(self.source_dir):]))
except:
pass
def get_running_thread_count(self):
"""Returns number of non-main Python threads"""
main_thread = threading.currentThread()
count = 0
# Count all threads except the main thread
for t in threading.enumerate():
if t is main_thread:
continue
count += 1
return count
def encode_and_tagging(self,lossless_file,lossy_file):
logging.debug('Starting encode_and_tagging. Received: ' \
+' ' + lossless_file + ' ' + lossy_file)
conv_result = self.convert_to_lossy(lossless_file,lossy_file)
# Only ID3 tag if conversion successful and if not disabled
if conv_result == 0 and self.disable_id3 == False:
self.update_lossy_tags(lossless_file,lossy_file)
def convert_to_lossy(self,lossless_file,lossy_file):
try:
# avconv complains when .m4a.tmp files are used as output.
# Therefore we need to make extension: .tmp.m4a
#lossy_file_tmp = lossy_file + '.tmp'
lossy_file_tmp = os.path.splitext(lossy_file)[0] + \
'.tmp' + self.Encoder.ext
exe = self.Decoder.found_exe
input_file = lossless_file
flags = self.Decoder.flags
source_cmd = self.Decoder.cmd_seq.format( \
exe = exe, \
input_file = input_file, \
flags = flags)
logging.debug('INPUT command: ' + source_cmd)
exe = self.Encoder.found_exe
output_file = lossy_file_tmp
flags = self.Encoder.flags
dest_cmd = self.Encoder.cmd_seq.format( \
exe= exe,
output_file = output_file,
flags = flags)
logging.debug('OUTPUT command: ' + dest_cmd)
src_args = shlex.split(source_cmd)
dest_args = shlex.split(dest_cmd)
p1 = subprocess.Popen(src_args,stdout=subprocess.PIPE)
p2 = subprocess.Popen(dest_args, stdin=p1.stdout)
output = p2.communicate()[0]
logging.debug('Encode output: ' + str(output))
# Move .tmp after conversion
shutil.move(lossy_file_tmp, lossy_file)
except Exception, ex:
logging.exception('Could not encode')
self.error_conv.append(lossless_file)
return 1
else:
self.success += 1
return 0
def update_lossy_tags(self,lossless_file,lossy_file):
""" Copies ID3 tags from lossless file to lossy file. """
try:
lossless_tags = mutagen.File(lossless_file, easy=True)
lossy_tags = mutagen.File(lossy_file, easy=True)
for k in lossless_tags:
if k in ('album','artist','title','performer','tracknumber','date','genre',):
lossy_tags[k] = lossless_tags[k]
lossy_tags.save()
except:
self.error_id3.append(lossy_file)
def print_results(self):
""" Print a final summary of successful and/or failed conversions"""
output = ''
count_failed_conv = len(self.error_conv)
count_failed_id3 = len(self.error_id3)
if count_failed_conv > 0:
output += '{} songs failed to convert\n'.format(count_failed_conv)
else:
output += '0 conversion errors\n'
if count_failed_id3 > 0:
output += '{} ID3 tags failed to write\n'.format(count_failed_id3)
else:
output += '0 ID3 tag errors\n'
if self.success > 0:
output += '{} songs successfully converted'.format(self.success)
else:
output += '0 songs converted'
print(output)
def start(self):
"""
Start the full conversion process
"""
logging.debug('Starting Conversion')
# Build directory structure
self.create_dest_folders()
self.get_convert_list()
logging.debug('Number of items in convert list: ' + str(len(self.to_convert)))
# Start Threaded Converting
while len(self.to_convert) > 0:
# Get file from list and remove
lossless_file = self.to_convert.pop()
lossy_file = self.translate_src_to_dest(lossless_file)
t = threading.Thread(target=self.encode_and_tagging, \
args=(lossless_file,lossy_file))
t.start()
# Don't allow more than max_cpu threads to run
while self.get_running_thread_count() >= self.thread_count:
# Check every second if more threads are needed
time.sleep(1)
# Wait for threads to complete
main_thread = threading.current_thread()
for t in threading.enumerate():
if t is main_thread:
continue
t.join()
def setup_parsing(decoders, encoders):
parser = argparse.ArgumentParser()
parser.add_argument('source_dir',
help='Input (lossless) directory')
parser.add_argument('dest_dir',
help='Output (lossy) directory')
parser.add_argument('-i',
'--input_codec',
default='flac',
choices=decoders,
help='Input (lossless) codec (default: flac)')
parser.add_argument('-o',
'--output_codec',
default='mp3',
choices=encoders,
help='Output (lossy) codec (default: mp3)')
parser.add_argument('-t',
'--threads',
type=int,
default=0,
help='Force specific number of threads (default: auto)')
parser.add_argument('--noid3',
action='store_true',
default=False, \
help = 'Disable ID3 file tagging (remove requirement for Mutagen)')
parser.add_argument('--debug',
help='Enable debugging',
action='store_true')
return parser
def setup_logging(debug=False):
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("main")
if debug:
logger.setLevel(logging.DEBUG)
logging.getLogger("audio_codecs").setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
logging.getLogger("audio_codecs").setLevel(logging.INFO)
return logger
def main():
print("flacthis {version} Copyright (c) 2012-2013 Andrew Klaus (andrewklaus@gmail.com)\n"\
.format(version=__version__))
try:
CodecMgr = audio_codecs.CodecManager()
except Exception as e:
print("an unknown error has occurred: {}".format(str(e)))
decoders = CodecMgr.list_all_decoders()
encoders = CodecMgr.list_all_encoders()
args = setup_parsing(decoders,encoders).parse_args()
logger = setup_logging(args.debug)
logger.debug('Arguments: ' + str(args))
source_dir = args.source_dir
dest_dir = args.dest_dir
thread_count = args.threads
try:
CodecMgr.discover_codecs()
except audio_codecs.NoSystemDecodersFound:
print("Please install a valid decoder before running")
sys.exit(1)
except audio_codecs.NoSystemEncodersFound:
print("Please install a valid encoder before running")
sys.exit(1)
# Setup codecs
try:
Decoder = CodecMgr.get_decoder(args.input_codec)
print("Using Decoder version: {}".format(Decoder.version))
except audio_codecs.SelectedCodecNotValid:
# This should never trigger as parser will force a valid codec
print("Selected decoder not available")
sys.exit(1)
try:
Encoder = CodecMgr.get_encoder(args.output_codec)
print("Using Encoder version: {}".format(Encoder.version))
except audio_codecs.SelectedCodecNotValid:
# This should never trigger as parser will force a valid codec
print("Selected encoder not available")
sys.exit(1)
if args.noid3 == True:
disable_id3 = args.noid3
else:
disable_id3 = args.noid3
try:
import mutagen
except ImportError:
sys.exit("""You require the Mutagen Python module
install it from http://code.google.com/p/mutagen/""")
logger.debug("""Source Directory: {}
Dest Directory: {}
Decoder: {}
Encoder: {}
""".format(source_dir,
dest_dir,
str(Decoder),
str(Encoder)))
Converter = LosslessToLossyConverter(source_dir,
dest_dir,
Decoder,
Encoder,
thread_count,
disable_id3)
Converter.start()
Converter.print_results()
return(0)
if __name__ == "__main__":
sys.exit(main())
| Python |
'''
Copyright (c) 2013, Andrew Klaus <andrewklaus@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import os
import logging
import sys
import subprocess
logger = logging.getLogger(__name__)
class Codec(object):
"""
Superclass for all encoders and decoders
name is the name of the encoder (ex. FLAC, Wav, etc.)
exe_file is the executable name that runs the codec (ex flac)
ext is the file extension that's used for files (ex .flac)
cmd_seq is the stdin/stdout command line arguments for exe_file:
in the format like : "{exe} -c -d "{input_file}" {flags}"
flags is the desired flags to append to the cmd_seq
Must run .find_exe() to initiate the locate
"""
def __init__(self, name, exec_file, ext, cmd_seq, flags):
self.name = name
self.exec_file = exec_file
self.ext = ext
self.cmd_seq = cmd_seq
self.flags = flags
self.version = None
self.found_exe = None
# Append .exe if running windows
if self._is_windows_os() \
and self.exec_file[-4:] != ".exe":
self.exec_file += ".exe"
def __str__(self, *args, **kwargs):
if self.found_exe:
r_str = "{name} : {found_exe}".format(name=self.name,found_exe=self.found_exe)
else:
r_str = "{name} : Not Found".format(name=self.name)
return r_str
def _check_paths_for_exe(self):
"""
Checks for the executable in the OS default path
Returns string of path+exe if found.
"""
logger.debug("Checking through default path for {}".format(self.exec_file))
found_exe = None
def_paths = []
def_paths.append(os.getcwd()) # Check current directory FIRST
if self._is_windows_os():
logger.debug("Running win32 environment")
def_paths.extend(os.environ["PATH"].split(';'))
else:
logger.debug("Running non-win32 environment")
def_paths.extend(os.environ["PATH"].split(':'))
if len(def_paths) == 0:
raise NoDefaultPaths
logger.debug("Checking paths: {}".format(str(def_paths)))
# Check through default paths
for path in def_paths:
if self._is_exe_in_path(path):
# Found
found_exe = os.path.join(path,self.exec_file)
break
if found_exe is not None:
logger.debug("Found executable: {}".format(found_exe))
else:
logger.debug("No {} executable found".format(self.exec_file))
return found_exe
def _is_exe_in_path(self,path=None):
"""
Checks if executable name is in the provided path.
If no path provided, currect working directory is checked
Returns True if it is, False if not.
"""
found = False
if path is None:
file_path = self.exec_file
else:
file_path = os.path.join(path,self.exec_file)
if os.path.isfile(file_path):
found = True
return found
def _is_exe_executable(self):
assert(self.found_exe)
executable = os.access(self.found_exe,os.X_OK)
return executable
def _is_windows_os(self):
w = False
if sys.platform in ("win32",
"cygwin"):
w = True
return w
def _find_exe_version(self):
"""
Must be implemented at the subclass level
"""
pass
def _check_exe_codec_support(self):
"""
Must be implemented at the subclass level.
Some projects don't implement certain codecs by default.
(i.e. ffmpeg doesn't compile libfdk-aac in by default)
We need a method that will check the exe for this support
"""
pass
def find_exe(self):
"""
Attempts to locate executable for codec starting with the
current directory, then looks in the default path
Raises CodecNotFound if file was not found
Raises CodecNotExecutable if file not executable
"""
logger.debug("Finding executable {}".format(self.exec_file))
self.found_exe = self._check_paths_for_exe()
if not self.found_exe:
raise CodecNotFound
if not self._is_exe_executable():
raise CodecNotExecutable
# Won't do anything unless subclass creates a function for it
self._check_exe_codec_support()
self._find_exe_version()
def override_codec_flags(self,flags):
self.flags = flags
#### DECODERS ####
class FLACDecoder(Codec):
def __init__(self,
name="flac",
exec_file="flac",
ext=".flac",
flags="",
cmd_seq = """{exe} -s -c -d "{input_file}" {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
def _find_exe_version(self):
version = subprocess.check_output([self.found_exe,"-v"])
if len(version) > 0:
self.version = version.strip()
class WAVDecoder(Codec):
def __init__(self,
name="wav",
exec_file="cat",
ext=".wav",
flags="",
cmd_seq = """{exe} "{input_file}" {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
# Wave file support for windows (UNTESTED)
class WINWAVDecoder(Codec):
def __init__(self,
name="winwav",
exec_file="type.exe",
ext=".wav",
flags="",
cmd_seq = """{exe} "{input_file}" {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
#### ENCODERS ####
class AACEncoder(Codec):
def __init__(self,
name="aac",
exec_file="faac",
ext=".m4a",
flags="-q 170",
cmd_seq = """{exe} - -w -o "{output_file}" {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
class AVConvLibFdkAACEncoder(Codec):
def __init__(self,
name="avconv-fdkaac",
exec_file="avconv",
ext=".m4a",
flags="+qscale -global_quality 5 -afterburner 1",
cmd_seq = """{exe} -i - -c:a libfdk_aac -flags {flags} "{output_file}" """):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
class FfmpegLibFdkEncoder(Codec):
def __init__(self,
name="ffmpeg-fdkaac",
exec_file="ffmpeg",
ext=".m4a",
flags="-vbr 3",
cmd_seq = """{exe} -v 0 -i - -c:a libfdk_aac {flags} "{output_file}" """):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
def _check_exe_codec_support(self):
# the -v 0 suppresses verbose output
o = subprocess.check_output([self.found_exe,"-v","0","-encoders"])
if "libfdk_aac" not in o.split(" "):
raise NotCompiledWithCodecSupport
def _find_exe_version(self):
version = subprocess.check_output([self.found_exe,"-v","0","-version"])
# Lame has a lot of output.. we only want the first line
version = version.split("\n")[0]
if len(version) > 0:
self.version = version.strip()
class MP3Encoder(Codec):
def __init__(self,
name="mp3",
exec_file="lame",
ext=".mp3",
flags="-V 0",
cmd_seq = """{exe} - "{output_file}" --silent {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
def _find_exe_version(self):
version = subprocess.check_output([self.found_exe,"--version"])
# Lame has a lot of output.. we only want the first line
version = version.split("\n")[0]
if len(version) > 0:
self.version = version.strip()
class OGGEncoder(Codec):
def __init__(self,
name="ogg",
exec_file="oggenc",
ext=".ogg",
flags="-q 6",
cmd_seq = """{exe} - -o "{output_file}" {flags}"""):
Codec.__init__(self, name, exec_file, ext, cmd_seq, flags)
def _find_exe_version(self):
version = subprocess.check_output([self.found_exe,"--version"])
if len(version) > 0:
self.version = version.strip()
class CodecManager(object):
"""
Manager for all supported codecs.
discover_codecs() must be run before trying to select a codec
"""
__decoders__ = (FLACDecoder,
WAVDecoder,
WINWAVDecoder)
__encoders__ = (MP3Encoder,
OGGEncoder,
AACEncoder,
AVConvLibFdkAACEncoder,
FfmpegLibFdkEncoder,)
def __init__(self):
self._avail_decoders = []
self._avail_encoders = []
def discover_codecs(self):
"""
Looks through all codecs at which are available
to the system
"""
for codec in self.__decoders__:
t_obj = codec()
try:
t_obj.find_exe()
except CodecNotFound:
# Don't add to list
logger.debug("Decoder {} not found".format(t_obj.name))
except CodecNotExecutable:
logger.debug("Decoder {} not executable".format(t_obj.name))
except NotCompiledWithCodecSupport:
logger.debug("Decoder {} not compiled with codec support".format(t_obj.name))
else:
self._avail_decoders.append(t_obj)
for codec in self.__encoders__:
t_obj = codec()
try:
t_obj.find_exe()
except CodecNotFound:
# Don't add to list
logger.debug("Encoder {} not found".format(t_obj.name))
except CodecNotExecutable:
logger.debug("Encoder {} not executable".format(t_obj.name))
except NotCompiledWithCodecSupport:
logger.debug("Encoder {} not compiled with codec support".format(t_obj.name))
else:
self._avail_encoders.append(t_obj)
if len(self._avail_decoders) < 1:
raise NoSystemDecodersFound
elif len(self._avail_decoders) < 1:
raise NoSystemEncodersFound
def get_decoder(self,codec_name):
"""
Accepts a name of a codec, and returns codec object
"""
decoder = None
# Loop through list finding the name
for d in self._avail_decoders:
if codec_name in d.name:
decoder = d
break
if decoder is None:
raise SelectedCodecNotValid
logger.debug("Returning {}".format(str(decoder)))
return decoder
def get_encoder(self,codec_name):
"""
Accepts a name of a codec, and returns codec object
"""
encoder = None
# Loop through list finding the name
for e in self._avail_encoders:
if codec_name in e.name:
encoder = e
break
if encoder is None:
raise SelectedCodecNotValid
logger.debug("Returning {}".format(str(encoder)))
return encoder
def list_all_decoders(self):
"""
Returns list of all decoder names
that are supported
"""
d = []
# Go through full list and get names
for c in self.__decoders__:
d.append(c().name)
return d
def list_all_encoders(self):
"""
Returns list of all encoder names
that are supported
"""
d = []
for c in self.__encoders__:
d.append(c().name)
return d
def get_avail_decoders(self):
"""
Returns a list of decoders available
to the script
"""
r_list = []
for d in self._avail_decoders:
r_list.append(d.name)
return r_list
def get_avail_encoders(self):
"""
Returns a list of encoders available
to the script
"""
r_list = []
for e in self._avail_encoders:
r_list.append(e.name)
return r_list
class SelectedCodecNotValid(Exception):
"""
Used if a codec is selected by the user, but not available
to the system
"""
pass
class NoSystemDecodersFound(Exception):
pass
class NoSystemEncodersFound(Exception):
pass
class NoDefaultPaths(Exception):
pass
class CodecNotFound(Exception):
pass
class CodecNotExecutable(Exception):
pass
class NotCompiledWithCodecSupport(Exception):
pass
if __name__ == "__main__":
print("This module must be imported")
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys
from optparse import OptionParser
from androguard.core.bytecodes import apk, dvm
from androguard.core.analysis import analysis
from androguard.core import androconf
sys.path.append("./elsim")
from elsim import elsim
from elsim.elsim_dalvik import ProxyDalvik, FILTERS_DALVIK_SIM, ProxyDalvikMethod, FILTERS_DALVIK_BB
from elsim.elsim_dalvik import ProxyDalvikBasicBlock, FILTERS_DALVIK_DIFF_BB
from elsim.elsim_dalvik import DiffDalvikMethod
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 2 }
option_1 = { 'name' : ('-t', '--threshold'), 'help' : 'define the threshold', 'nargs' : 1 }
option_2 = { 'name' : ('-c', '--compressor'), 'help' : 'define the compressor', 'nargs' : 1 }
option_3 = { 'name' : ('-d', '--display'), 'help' : 'display the file in human readable format', 'action' : 'count' }
#option_4 = { 'name' : ('-e', '--exclude'), 'help' : 'exclude specific blocks (0 : orig, 1 : diff, 2 : new)', 'nargs' : 1 }
option_5 = { 'name' : ('-e', '--exclude'), 'help' : 'exclude specific class name (python regexp)', 'nargs' : 1 }
option_6 = { 'name' : ('-s', '--size'), 'help' : 'exclude specific method below the specific size', 'nargs' : 1 }
option_7 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_5, option_6, option_7]
def main(options, arguments) :
details = False
if options.display != None :
details = True
if options.input != None :
ret_type = androconf.is_android( options.input[0] )
if ret_type == "APK" :
a = apk.APK( options.input[0] )
d1 = dvm.DalvikVMFormat( a.get_dex() )
elif ret_type == "DEX" :
d1 = dvm.DalvikVMFormat( open(options.input[0], "rb").read() )
dx1 = analysis.VMAnalysis( d1 )
ret_type = androconf.is_android( options.input[1] )
if ret_type == "APK" :
a = apk.APK( options.input[1] )
d2 = dvm.DalvikVMFormat( a.get_dex() )
elif ret_type == "DEX" :
d2 = dvm.DalvikVMFormat( open(options.input[1], "rb").read() )
dx2 = analysis.VMAnalysis( d2 )
print d1, dx1, d2, dx2
sys.stdout.flush()
threshold = None
if options.threshold != None :
threshold = float(options.threshold)
FS = FILTERS_DALVIK_SIM
FS[elsim.FILTER_SKIPPED_METH].set_regexp( options.exclude )
FS[elsim.FILTER_SKIPPED_METH].set_size( options.size )
el = elsim.Elsim( ProxyDalvik(d1, dx1), ProxyDalvik(d2, dx2), FS, threshold, options.compressor )
el.show()
e1 = elsim.split_elements( el, el.get_similar_elements() )
for i in e1 :
j = e1[ i ]
elb = elsim.Elsim( ProxyDalvikMethod(i), ProxyDalvikMethod(j), FILTERS_DALVIK_BB, threshold, options.compressor )
#elb.show()
eld = elsim.Eldiff( ProxyDalvikBasicBlock(elb), FILTERS_DALVIK_DIFF_BB )
#eld.show()
ddm = DiffDalvikMethod( i, j, elb, eld )
ddm.show()
print "NEW METHODS"
enew = el.get_new_elements()
for i in enew :
el.show_element( i, False )
print "DELETED METHODS"
edel = el.get_deleted_elements()
for i in edel :
el.show_element( i )
elif options.version != None :
print "Androdiff version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
from xml.sax.saxutils import escape, unescape
import sys, hashlib, os
from optparse import OptionParser
from androguard.core.bytecodes import apk, dvm
from androguard.core.analysis import analysis, ganalysis
from androguard.core import androconf
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input (dex, apk)', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'filename output of the gexf', 'nargs' : 1 }
options = [option_0, option_1]
def main(options, arguments) :
if options.input != None and options.output != None :
ret_type = androconf.is_android( options.input )
vm = None
a = None
if ret_type == "APK" :
a = apk.APK( options.input )
if a.is_valid_APK() :
vm = dvm.DalvikVMFormat( a.get_dex() )
else :
print "INVALID APK"
elif ret_type == "DEX" :
try :
vm = dvm.DalvikVMFormat( open(options.input, "rb").read() )
except Exception, e :
print "INVALID DEX", e
vmx = analysis.VMAnalysis( vm )
gvmx = ganalysis.GVMAnalysis( vmx, a )
b = gvmx.export_to_gexf()
androconf.save_to_disk( b, options.output )
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012/2013, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import shutil
import sys
import os
import re
from optparse import OptionParser
from androguard.core.androgen import Androguard
from androguard.core import androconf
from androguard.core.analysis import analysis
from androguard.core.bytecodes import dvm
from androguard.core.bytecode import method2dot, method2format
from androguard.decompiler import decompiler
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'base directory to output all files', 'nargs' : 1 }
option_2 = { 'name' : ('-d', '--decompiler'), 'help' : 'choose a decompiler', 'nargs' : 1 }
option_3 = { 'name' : ('-j', '--jar'), 'help' : 'output jar file', 'action' : 'count' }
option_4 = { 'name' : ('-f', '--format'), 'help' : 'write the method in specific format (png, ...)', 'nargs' : 1 }
option_5 = { 'name' : ('-l', '--limit'), 'help' : 'limit analysis to specific methods/classes by using a regexp', 'nargs' : 1}
option_6 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4, option_5, option_6]
def valid_class_name(class_name):
if class_name[-1] == ";":
return class_name[1:-1]
return class_name
def create_directory(class_name, output):
output_name = output
if output_name[-1] != "/":
output_name = output_name + "/"
pathdir = output_name + class_name
try:
if not os.path.exists(pathdir):
os.makedirs(pathdir)
except OSError:
# FIXME
pass
def export_apps_to_format(filename, a, output, methods_filter=None, jar=None, decompiler_type=None, format=None):
print "Dump information %s in %s" % (filename, output)
if not os.path.exists(output):
print "Create directory %s" % output
os.makedirs(output)
else:
print "Clean directory %s" % output
androconf.rrmdir(output)
os.makedirs(output)
methods_filter_expr = None
if methods_filter:
methods_filter_expr = re.compile(methods_filter)
output_name = output
if output_name[-1] != "/":
output_name = output_name + "/"
dump_classes = []
for vm in a.get_vms():
print "Analysis ...",
sys.stdout.flush()
vmx = analysis.VMAnalysis(vm)
print "End"
print "Decompilation ...",
sys.stdout.flush()
if not decompiler_type:
vm.set_decompiler(decompiler.DecompilerDAD(vm, vmx))
elif decompiler_type == "dex2jad":
vm.set_decompiler(decompiler.DecompilerDex2Jad(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_JAD"],
androconf.CONF["BIN_JAD"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "dex2winejad":
vm.set_decompiler(decompiler.DecompilerDex2WineJad(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_JAD"],
androconf.CONF["BIN_WINEJAD"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "ded":
vm.set_decompiler(decompiler.DecompilerDed(vm,
androconf.CONF["PATH_DED"],
androconf.CONF["BIN_DED"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "dex2fernflower":
vm.set_decompiler(decompiler.DecompilerDex2Fernflower(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_FERNFLOWER"],
androconf.CONF["BIN_FERNFLOWER"],
androconf.CONF["OPTIONS_FERNFLOWER"],
androconf.CONF["TMP_DIRECTORY"]))
else:
raise("invalid decompiler !")
print "End"
if options.jar:
print "jar ...",
filenamejar = decompiler.Dex2Jar(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["TMP_DIRECTORY"]).get_jar()
shutil.move(filenamejar, output + "classes.jar")
print "End"
for method in vm.get_methods():
if methods_filter_expr:
msig = "%s%s%s" % (method.get_class_name(),
method.get_name(),
method.get_descriptor())
if not methods_filter_expr.search(msig):
continue
filename_class = valid_class_name(method.get_class_name())
create_directory(filename_class, output)
print "Dump %s %s %s ..." % (method.get_class_name(),
method.get_name(),
method.get_descriptor()),
filename_class = output_name + filename_class
if filename_class[-1] != "/":
filename_class = filename_class + "/"
descriptor = method.get_descriptor()
descriptor = descriptor.replace(";", "")
descriptor = descriptor.replace(" ", "")
descriptor = descriptor.replace("(", "-")
descriptor = descriptor.replace(")", "-")
descriptor = descriptor.replace("/", "_")
filename = filename_class + method.get_name() + descriptor
if len(method.get_name() + descriptor) > 250:
all_identical_name_methods = vm.get_methods_descriptor(method.get_class_name(), method.get_name())
pos = 0
for i in all_identical_name_methods:
if i.get_descriptor() == method.get_descriptor():
break
pos += 1
filename = filename_class + method.get_name() + "_%d" % pos
buff = method2dot(vmx.get_method(method))
if format:
print "%s ..." % format,
method2format(filename + "." + format, format, None, buff)
if method.get_class_name() not in dump_classes:
print "source codes ...",
current_class = vm.get_class(method.get_class_name())
current_filename_class = valid_class_name(current_class.get_name())
create_directory(filename_class, output)
current_filename_class = output_name + current_filename_class + ".java"
fd = open(current_filename_class, "w")
fd.write(current_class.get_source())
fd.close()
dump_classes.append(method.get_class_name())
print "bytecodes ...",
bytecode_buff = dvm.get_bytecodes_method(vm, vmx, method)
fd = open(filename + ".ag", "w")
fd.write(bytecode_buff)
fd.close()
print
def main(options, arguments):
if options.input != None and options.output != None:
a = Androguard([options.input])
export_apps_to_format(options.input, a, options.output, options.limit, options.jar, options.decompiler, options.format)
elif options.version != None:
print "Androdd version %s" % androconf.ANDROGUARD_VERSION
else:
print "Please, specify an input file and an output directory"
if __name__ == "__main__":
parser = OptionParser()
for option in options:
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core import androconf
from androguard.core.bytecodes import apk
from androguard.core.bytecodes import dvm
from androguard.core.analysis import analysis
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename (APK)', 'nargs' : 1 }
option_1 = { 'name' : ('-d', '--directory'), 'help' : 'directory : use this directory', 'nargs' : 1 }
option_2 = { 'name' : ('-t', '--tag'), 'help' : 'display tags', 'action' : 'count' }
option_3 = { 'name' : ('-v', '--version'), 'help' : 'version', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3]
def display_dvm_info(apk):
vm = dvm.DalvikVMFormat(apk.get_dex())
vmx = analysis.uVMAnalysis(vm)
print "Native code:", analysis.is_native_code(vmx)
print "Dynamic code:", analysis.is_dyn_code(vmx)
print "Reflection code:", analysis.is_reflection_code(vmx)
print "Ascii Obfuscation:", analysis.is_ascii_obfuscation(vm)
for i in vmx.get_methods():
i.create_tags()
if not i.tags.empty():
print i.method.get_class_name(), i.method.get_name(), i.tags
def main(options, arguments) :
if options.input != None :
ret_type = androconf.is_android( options.input )
print os.path.basename(options.input), ":"
if ret_type == "APK" :
try :
a = apk.APK(options.input, zipmodule=2)
if a.is_valid_APK() :
a.show()
display_dvm_info( a )
else :
print "INVALID"
except Exception, e :
print "ERROR", e
import traceback
traceback.print_exc()
elif options.directory != None :
for root, dirs, files in os.walk( options.directory, followlinks=True ) :
if files != [] :
for f in files :
real_filename = root
if real_filename[-1] != "/" :
real_filename += "/"
real_filename += f
ret_type = androconf.is_android( real_filename )
if ret_type == "APK" :
print os.path.basename( real_filename ), ":"
try :
a = apk.APK( real_filename )
if a.is_valid_APK() :
a.show()
display_dvm_info( a )
else :
print "INVALID APK"
raise("ooos")
except Exception, e :
print "ERROR", e
raise("ooos")
elif options.version != None :
print "Androapkinfo version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core.bytecodes import apk, dvm
from androguard.core.data import data
from androguard.core.analysis import analysis, ganalysis
from androguard.core import androconf
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input (dex, apk)', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'directory output', 'nargs' : 1 }
options = [option_0, option_1]
def create_directory( class_name, output ) :
output_name = output
if output_name[-1] != "/" :
output_name = output_name + "/"
try :
os.makedirs( output_name + class_name )
except OSError :
pass
def create_directories( vm, output ) :
for class_name in vm.get_classes_names() :
z = os.path.split( class_name )[0]
create_directory( z[1:], output )
def main(options, arguments) :
if options.input != None and options.output != None :
ret_type = androconf.is_android( options.input )
vm = None
a = None
if ret_type == "APK" :
a = apk.APK( options.input )
if a.is_valid_APK() :
vm = dvm.DalvikVMFormat( a.get_dex() )
else :
print "INVALID APK"
elif ret_type == "DEX" :
try :
vm = dvm.DalvikVMFormat( open(options.input, "rb").read() )
except Exception, e :
print "INVALID DEX", e
vmx = analysis.VMAnalysis( vm )
gvmx = ganalysis.GVMAnalysis( vmx, a )
create_directories( vm, options.output )
# dv.export_to_gml( options.output )
dd = data.Data(vm, vmx, gvmx, a)
buff = dd.export_apk_to_gml()
androconf.save_to_disk( buff, options.output + "/" + "apk.graphml" )
buff = dd.export_methodcalls_to_gml()
androconf.save_to_disk( buff, options.output + "/" + "methodcalls.graphml" )
buff = dd.export_dex_to_gml()
for i in buff :
androconf.save_to_disk( buff[i], options.output + "/" + i + ".graphml" )
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.