xybuttons.py 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# This file is part of the Printrun suite.
# 
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Printrun.  If not, see <http://www.gnu.org/licenses/>.

16 17 18 19
import wx, os, math
from bufferedcanvas import *


20 21 22 23 24 25
def imagefile(filename):
    if os.path.exists(os.path.join(os.path.dirname(__file__), "images", filename)):
        return os.path.join(os.path.dirname(__file__), "images", filename)
    else:
        return os.path.join(os.path.split(os.path.split(__file__)[0])[0], "images", filename)
    
26 27 28 29 30 31 32
def sign(n):
    if n < 0: return -1
    elif n > 0: return 1
    else: return 0

class XYButtons(BufferedCanvas):
    keypad_positions = {
33 34 35 36
        0: (105, 102),
        1: (86, 83),
        2: (68, 65),
        3: (53, 50)
37
    }
38 39
    corner_size = (49, 49)
    corner_inset = (8, 6)
40 41 42 43 44 45
    label_overlay_positions = {
        0: (142, 105, 11),
        1: (160, 85, 13),
        2: (179, 65, 15),
        3: (201, 42, 16)
    }
46 47 48
    concentric_circle_radii = [11, 45, 69, 94, 115]
    center = (124, 121)
    spacer = 7
49

50
    def __init__(self, parent, moveCallback=None, cornerCallback=None, ID=-1):
51 52
        self.bg_bmp = wx.Image(imagefile("control_xy.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.keypad_bmp = wx.Image(imagefile("arrow_keys.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
53
        self.keypad_idx = -1
54 55
        self.quadrant = None
        self.concentric = None
56
        self.corner = None
57
        self.moveCallback = moveCallback
58
        self.cornerCallback = cornerCallback
59
        self.enabled = False
60
    
61
        BufferedCanvas.__init__(self, parent, ID)
62
        self.SetSize(self.bg_bmp.GetSize())
63 64 65 66 67

        # Set up mouse and keyboard event capture
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
68
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
69 70
        self.Bind(wx.EVT_KEY_UP, self.OnKey)
        wx.GetTopLevelParent(self).Bind(wx.EVT_CHAR_HOOK, self.OnTopLevelKey)
71
    
72 73
    def disable(self):
        self.enabled = False
74
        self.update()
75 76 77
    
    def enable(self):
        self.enabled = True
78
        self.update()
79
    
80 81 82 83 84 85 86 87 88 89 90
    def distanceToLine(self, pos, x1, y1, x2, y2):
        xlen = x2 - x1
        ylen = y2 - y1
        pxlen = x1 - pos.x
        pylen = y1 - pos.y
        return abs(xlen*pylen-ylen*pxlen)/math.sqrt(xlen**2+ylen**2)
    
    def distanceToPoint(self, x1, y1, x2, y2):
        return math.sqrt((x1-x2)**2 + (y1-y2)**2)

    def cycleKeypadIndex(self):
91 92 93 94
        idx = self.keypad_idx + 1
        if idx > 2: idx = 0
        return idx
    
95 96 97 98 99 100 101 102 103 104
    def setKeypadIndex(self, idx):
        self.keypad_idx = idx
        self.update()
    
    def getMovement(self):
        xdir = [1, 0, -1, 0][self.quadrant]
        ydir = [0, 1, 0, -1][self.quadrant]
        magnitude = math.pow(10, self.concentric-1)
        return (magnitude * xdir, magnitude * ydir)
    
105
    def lookupConcentric(self, radius):
106 107
        idx = 0
        for r in XYButtons.concentric_circle_radii[1:]:
108 109 110
            if radius < r:
                return idx
            idx += 1
111
        return len(XYButtons.concentric_circle_radii)
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    def getQuadrantConcentricFromPosition(self, pos):
        rel_x = pos[0] - XYButtons.center[0]
        rel_y = pos[1] - XYButtons.center[1]
        radius = math.sqrt(rel_x**2 + rel_y**2)
        if rel_x > rel_y and rel_x > -rel_y:
            quadrant = 0 # Right
        elif rel_x <= rel_y and rel_x > -rel_y:
            quadrant = 3 # Down
        elif rel_x > rel_y and rel_x < -rel_y:
            quadrant = 1 # Up
        else:
            quadrant = 2 # Left
        
        idx = self.lookupConcentric(radius)
        return (quadrant, idx)
    
    def mouseOverKeypad(self, mpos):
        for idx, kpos in XYButtons.keypad_positions.items():
131 132
            radius = self.distanceToPoint(mpos[0], mpos[1], kpos[0], kpos[1])
            if radius < 9:
133 134
                return idx
        return None
135
    
136
    def drawPartialPie(self, gc, center, r1, r2, angle1, angle2):
137 138
        p1 = wx.Point(center.x + r1*math.cos(angle1), center.y + r1*math.sin(angle1))
        
139 140 141 142 143 144
        path = gc.CreatePath()
        path.MoveToPoint(p1.x, p1.y)
        path.AddArc(center.x, center.y, r1, angle1, angle2, True)
        path.AddArc(center.x, center.y, r2, angle2, angle1, False)
        path.AddLineToPoint(p1.x, p1.y)
        gc.DrawPath(path)
145
    
146
    def highlightQuadrant(self, gc, quadrant, concentric):
147
        assert(quadrant >= 0 and quadrant <= 3)
148
        assert(concentric >= 0 and concentric <= 3)
149 150 151

        inner_ring_radius = XYButtons.concentric_circle_radii[0]
        # fudge = math.pi*0.002
152
        fudge = -0.02
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        center = wx.Point(XYButtons.center[0], XYButtons.center[1])
        if quadrant == 0:
            a1, a2 = (-math.pi*0.25, math.pi*0.25)
            center.x += inner_ring_radius
        elif quadrant == 1:
            a1, a2 = (math.pi*1.25, math.pi*1.75)
            center.y -= inner_ring_radius
        elif quadrant == 2:
            a1, a2 = (math.pi*0.75, math.pi*1.25)
            center.x -= inner_ring_radius
        elif quadrant == 3:
            a1, a2 = (math.pi*0.25, math.pi*0.75)
            center.y += inner_ring_radius
        
        r1 = XYButtons.concentric_circle_radii[concentric]
        r2 = XYButtons.concentric_circle_radii[concentric+1]

170
        self.drawPartialPie(gc, center, r1-inner_ring_radius, r2-inner_ring_radius, a1+fudge, a2-fudge)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    
    def drawCorner(self, gc, x, y, angle=0.0):
        w, h = XYButtons.corner_size

        gc.PushState()
        gc.Translate(x, y)
        gc.Rotate(angle)
        path = gc.CreatePath()
        path.MoveToPoint(-w/2, -h/2)
        path.AddLineToPoint(w/2, -h/2)
        path.AddLineToPoint(w/2, -h/2+h/3)
        path.AddLineToPoint(-w/2+w/3, h/2)
        path.AddLineToPoint(-w/2, h/2)
        path.AddLineToPoint(-w/2, -h/2)
        gc.DrawPath(path)
        gc.PopState()

    def highlightCorner(self, gc, corner=0):
        w, h = XYButtons.corner_size
        cx, cy = XYButtons.center
        ww, wh = self.GetSizeTuple()
        
        inset = 10
        if corner == 0:
            x, y = (cx - ww/2 + inset, cy - wh/2 + inset)
            self.drawCorner(gc, x+w/2, y+h/2, 0)
        elif corner == 1:
            x, y = (cx + ww/2 - inset, cy - wh/2 + inset)
            self.drawCorner(gc, x-w/2, y+h/2, math.pi/2)
        elif corner == 2:
            x, y = (cx + ww/2 - inset, cy + wh/2 - inset)
            self.drawCorner(gc, x-w/2, y-h/2, math.pi)
        elif corner == 3:
            x, y = (cx - ww/2 + inset, cy + wh/2 - inset)
            self.drawCorner(gc, x+w/2, y-h/2, math.pi*3/2)
        
207 208 209 210

    def draw(self, dc, w, h):
        dc.Clear()
        gc = wx.GraphicsContext.Create(dc)
211

212
        center = wx.Point(XYButtons.center[0], XYButtons.center[1])
213 214 215
        if self.bg_bmp:
            w, h = (self.bg_bmp.GetWidth(), self.bg_bmp.GetHeight())
            gc.DrawBitmap(self.bg_bmp, 0, 0, w, h)
216 217 218
        
        if self.enabled:
            # Brush and pen for grey overlay when mouse hovers over
219 220
            gc.SetPen(wx.Pen(wx.Colour(100,100,100,172), 4))
            gc.SetBrush(wx.Brush(wx.Colour(0,0,0,128)))
221 222 223 224 225 226 227 228 229

            if self.concentric != None:
                if self.concentric < len(XYButtons.concentric_circle_radii):
                    if self.quadrant != None:
                        self.highlightQuadrant(gc, self.quadrant, self.concentric)
                elif self.corner != None:
                    self.highlightCorner(gc, self.corner)
            
            if self.keypad_idx >= 0:
230
                padw, padh = (self.keypad_bmp.GetWidth(), self.keypad_bmp.GetHeight())
231
                pos = XYButtons.keypad_positions[self.keypad_idx]
232 233
                pos = (pos[0] - padw/2 - 3, pos[1] - padh/2 - 3)
                gc.DrawBitmap(self.keypad_bmp, pos[0], pos[1], padw, padh)
234 235 236 237 238 239 240 241
            
            # Draw label overlays
            gc.SetPen(wx.Pen(wx.Colour(255,255,255,128), 1))
            gc.SetBrush(wx.Brush(wx.Colour(255,255,255,128+64)))
            for idx, kpos in XYButtons.label_overlay_positions.items():
                if idx != self.concentric:
                    r = kpos[2]
                    gc.DrawEllipse(kpos[0]-r, kpos[1]-r, r*2, r*2)
242 243 244 245
        else:
            gc.SetPen(wx.Pen(wx.Colour(255,255,255,0), 4))
            gc.SetBrush(wx.Brush(wx.Colour(255,255,255,128)))
            gc.DrawRectangle(0, 0, w, h)
246
        
247 248

        # Used to check exact position of keypad dots, should we ever resize the bg image
249 250
        # for idx, kpos in XYButtons.label_overlay_positions.items():
        #    dc.DrawCircle(kpos[0], kpos[1], kpos[2])
251 252 253 254 255 256 257 258 259 260 261 262 263 264

    ## ------ ##
    ## Events ##
    ## ------ ##

    def OnTopLevelKey(self, evt):
        # Let user press escape on any control, and return focus here
        if evt.GetKeyCode() == wx.WXK_ESCAPE:
            self.SetFocus()
        evt.Skip()

    def OnKey(self, evt):
        if not self.enabled:
            return
265
        if self.keypad_idx >= 0:
266 267 268 269 270 271 272 273 274 275
            if evt.GetKeyCode() == wx.WXK_TAB:
                self.setKeypadIndex(self.cycleKeypadIndex())
            elif evt.GetKeyCode() == wx.WXK_UP:
                self.quadrant = 1
            elif evt.GetKeyCode() == wx.WXK_DOWN:
                self.quadrant = 3
            elif evt.GetKeyCode() == wx.WXK_LEFT:
                self.quadrant = 2
            elif evt.GetKeyCode() == wx.WXK_RIGHT:
                self.quadrant = 0
276 277
            elif evt.GetKeyCode() == wx.WXK_SPACE:
                pass
278 279 280 281 282 283 284 285 286 287 288 289 290
            else:
                evt.Skip()
                return
            
            if self.moveCallback:
                self.concentric = self.keypad_idx
                x, y = self.getMovement()
                self.moveCallback(x, y)

    def OnMotion(self, event):
        if not self.enabled:
            return
        
291
        oldcorner = self.corner
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        oldq, oldc = self.quadrant, self.concentric

        mpos = event.GetPosition()
        idx = self.mouseOverKeypad(mpos)
        self.quadrant = None
        self.concentric = None
        if idx == None:
            center = wx.Point(XYButtons.center[0], XYButtons.center[1])
            riseDist = self.distanceToLine(mpos, center.x-1, center.y-1, center.x+1, center.y+1)
            fallDist = self.distanceToLine(mpos, center.x-1, center.y+1, center.x+1, center.y-1)
            self.quadrant, self.concentric = self.getQuadrantConcentricFromPosition(mpos)

            # If mouse hovers in space between quadrants, don't commit to a quadrant
            if riseDist <= XYButtons.spacer or fallDist <= XYButtons.spacer:
                self.quadrant = None
        
        cx, cy = XYButtons.center
        if mpos.x < cx and mpos.y < cy:
            self.corner = 0
        if mpos.x >= cx and mpos.y < cy:
            self.corner = 1
        if mpos.x >= cx and mpos.y >= cy:
            self.corner = 2
        if mpos.x < cx and mpos.y >= cy:
            self.corner = 3

318
        if oldq != self.quadrant or oldc != self.concentric or oldcorner != self.corner:
319 320 321 322 323
            self.update()

    def OnLeftDown(self, event):
        if not self.enabled:
            return
324
        
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        # Take focus when clicked so that arrow keys can control movement
        self.SetFocus()

        mpos = event.GetPosition()

        idx = self.mouseOverKeypad(mpos)
        if idx == None:
            self.quadrant, self.concentric = self.getQuadrantConcentricFromPosition(mpos)
            if self.concentric != None:
                if self.concentric < len(XYButtons.concentric_circle_radii):
                    if self.quadrant != None:
                        x, y = self.getMovement()
                        if self.moveCallback:
                            self.moveCallback(x, y)
                elif self.corner != None:
                    if self.cornerCallback:
                        self.cornerCallback(self.corner)
        else:
            if self.keypad_idx == idx:
                self.setKeypadIndex(-1)
            else:
                self.setKeypadIndex(idx)
    
    def OnLeaveWindow(self, evt):
        self.quadrant = None
        self.concentric = None
351
        self.update()