Skip to content

Instantly share code, notes, and snippets.

@bitoffdev
Created April 4, 2014 00:58
Show Gist options
  • Save bitoffdev/9965978 to your computer and use it in GitHub Desktop.
Save bitoffdev/9965978 to your computer and use it in GitHub Desktop.
In-scene keyboard for Pythonista app
# -*- coding: utf-8 -*-
import scene
keyboard_layouts = (
'''
q w e r t y u i o p del
a s d f g h j k l return
z x c v b n m , . shift
.?123 space .?123
''', '''
Q W E R T Y U I O P del
A S D F G H J K L return
Z X C V B N M , . shift
.?123 space .?123
''', '''
1 2 3 4 5 6 7 8 9 0 del
- / : ; ( ) $ & @ return
#+= undo . , ? ! ' " #+=
ABC space ABC
''', '''
[ ] { } # % ^ * + = del
_ \ | ~ < > € £ ¥ return
123 redo . , ? ! ' " 123
ABC space ABC
''')
def make_keyboards(keyboard_layouts = keyboard_layouts):
keyboards = []
for keyboard_layout in keyboard_layouts:
keyboard = []
for line in keyboard_layout.splitlines():
if line:
keyrow = []
for key in line.split():
keyrow.append(key)
keyboard.append(tuple(keyrow))
keyboard.reverse()
keyboards.append(tuple(keyboard))
return keyboards
class TextButton(scene.Button): # scene.Button is an undocumented class
def __init__(self, inSuperLayer, inRect, inText):
super(self.__class__, self).__init__(inRect, inText)
inSuperLayer.add_layer(self)
self.parent = inSuperLayer # needed to make button_pressed() work
self.text = ' ' if inText == 'space' else inText
self.action = self.button_pressed
def button_pressed(self):
self.parent.button_pressed(self.text)
class Keyboard(scene.Scene):
def __init__(self):
self.text = ''
self.type = 0
scene.run(self)
def setup(self):
# This will be called before the first frame is drawn.
height = 60
self.center = self.bounds.center()
pad = 0 # pixels between buttons
loc = scene.Point(pad, pad)
keyboard = make_keyboards()[self.type]
for keyrow in keyboard:
button_height = 200
loc.x = pad
for key in keyrow:
width = self.bounds.w/len(keyrow)
key_button = TextButton(self, scene.Rect(loc[0], loc[1], width, height), key)
loc.x += key_button.frame.w + pad
loc.y += max(height, key_button.frame.h) + pad
self.center.y += loc.y / 2 # move center up to compensate for keyboard
def button_pressed(self, button_text):
#If single character pressed
if len(button_text) == 1:
self.text += button_text
if self.type == 1:
self.type = 0
self.setup()
#If action pressed
else:
if self.text and button_text == 'del':
self.text = self.text[:-1]
elif button_text == '.?123':
self.type = 2
self.setup()
elif button_text == '#+=':
self.type = 3
self.setup()
elif button_text == 'ABC':
self.type = 0
self.setup()
elif button_text == 'shift':
if self.type == 0: self.type = 1
elif self.type == 1: self.type = 0
self.setup()
def draw(self):
scene.background(0.5, 0.5, 0.5) # grey
self.root_layer.update(self.dt)
self.root_layer.draw()
scene.text(self.text, font_size=40, x=self.center.x, y=self.center.y)
Keyboard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment