Talk:Venn Interface

From RCC 2007

Jump to: navigation, search

Would anyone who knows MediaWiki formatting enjoy putting the graphic side-by-side with the "Displaying the data" section? --John Abbe 09:57, 7 February 2007 (UTC)

First Stab

There's still work to be done, but here's a very first stab.

You need to install wxPython to use this.

# Want:
#  * way to ADD & DELETE entries
#  * SAVE, LOAD
#  * circle w/o definition? 0-ring, 1-ring, 2-ring, or 3-ring
#  * some easy way to tell "am I in card boundaries or not?"
#  * smooth selection -- so that the Card remains stable when you
#    pick it up
#  * fix tabbing
#  * lost focus for A-B-C causes circle change
#  * diff color card when selected

import random
import math

import wx


ID_TIMER = 101
ID_VENNINTERFACE = 102
ID_VENNDISPLAY = 103

MILLISECONDS = 50

INITIAL_A = "friend"
INITIAL_B = "oldschool"
INITIAL_C = "seattle"


"""Point and Rectangle classes.

This code is in the public domain.

Point  -- point with (x,y) coordinates
Rect  -- two points, forming a rectangle
"""

import math


class Point:

    """A point identified by (x,y) coordinates.

    supports: +, -, *, /, str, repr

    as_tuple  -- construct tuple (x,y)
    clone  -- construct a duplicate
    integerize  -- convert x & y to integers
    floatize  -- convert x & y to floats
    distance_to  -- calculate distance between points
    move_to  -- reset x & y
    slide  -- move to +dx, +dy
    rotate  -- rotate around the origin
    rotate_about  -- rotate around another point
    """

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        """Point(x1+x2, y1+y2)"""
        return Point(self.x+other.x, self.y+other.y)

    def __sub__(self, other):
        """Point(x1-x2, y1-y2)"""
        return Point(self.x-other.x, self.y-other.y)

    def __mul__( self, scalar ):
        """Point(x1*x2, y1*y2)"""
        return Point(self.x*scalar, self.y*scalar)

    def __div__(self, scalar):
        """Point(x1/x2, y1/y2)"""
        return Point(self.x/scalar, self.y/scalar)

    def __str__(self):
        return "(%s, %s)" % (self.x, self.y)

    def __repr__(self):
        return "%s(%r, %r)" % (self.__class__.__name__, self.x, self.y)

    def as_tuple(self):
        """(x, y)"""
        return (self.x, self.y)

    def clone(self):
        """Return a full copy of this point."""
        return Point(self.x, self.y)

    def integerize(self):
        """Convert co-ordinate values to integers."""
        self.x = int(self.x)
        self.y = int(self.y)

    def floatize(self):
        """Convert co-ordinate values to floats."""
        self.x = float(self.x)
        self.y = float(self.y)

    def distance_to(self, pt):
        """Calculate the distance between two points."""
        dy = float(self.y - pt.y)
        dx = float(self.x - pt.x)
        return math.sqrt(dy*dy + dx*dx)
    
    def move_to(self, x, y):
        """Reset x & y coordinates."""
        self.x = x
        self.y = y

    def slide(self, dx, dy):
        Move to new (x+dx,y+dy).

        Can anyone think up a better name for this function?
        slide? shift? delta? move_by?
        
        self.x = self.x + dx
        self.y = self.y + dy

    def rotate(self, theta):
        """Rotate clockwise by theta degrees.

        Rotate the point clockwise, around the origin.
        The new position is returned as a new Point.

        WARNING: UNTESTED CODE.
        """
        r2 = math.sqrt(self.x)+math.sqrt(self.y)
        tmp = math.tan(theta*math.pi/90 + math.atan(self.x/self.y))
        return Point(math.sqrt(r2/(1+tmp*tmp)),
                     ret.x * tmp)

    def rotate_about(self, pt, theta):
        """Rotate clockwise around a point, by theta degrees.

        Rotate the point clockwise, around another point.
        The new position is returned as a new Point.

        WARNING: UNTESTED CODE.
        """
        result = self.clone()
        result.slide(-pt.x, -pt.y)
        result.rotate(theta)
        result.slide(pt.x, pt.y)
        return result


class Rect:
    
    """A rectangle identified by two points.
    
    The rectangle stores left, top, right, and bottom values.
    
    Coordinates are based on screen coordinates.
    
    origin                               top
       +-----> x increases                |
       |                           left  -+-  right
       v                                  |
    y increases                         bottom
    
    set_points  -- reset rectangle coordinates
    contains  -- is a point inside?
    overlaps  -- does a rectangle overlap?
    top_left  -- get top-left corner
    bottom_right  -- get bottom-right corner
    expanded_by  -- grow (or shrink)
    """
    
    def __init__(self, pt1, pt2):
        """Initialize a rectangle from two points."""
        self.set_points(pt1, pt2)
    
    def set_points(self, pt1, pt2):
        """Reset the rectangle coordinates."""
        (x1, y1) = pt1.as_tuple()
        (x2, y2) = pt2.as_tuple()
        self.left = min(x1, x2)
        self.top = min(y1, y2)
        self.right = max(x1, x2)
        self.bottom = max(y1, y2)
    
    def contains(self, pt):
        """Return true if a point is inside the rectangle."""
        x,y = pt.as_tuple()
        return (self.left <= x <= self.right and
                self.top <= y <= self.bottom)
    
    def overlaps(self, other):
        """Return true if a rectangle overlaps this rectangle."""
        return (self.right > other.left and self.left < other.right and
                self.top < other.bottom and self.bottom > other.top)
    
    def top_left(self):
        """Return the top-left corner as a Point."""
        return Point(self.left, self.top)
    
    def bottom_right(self):
        """Return the bottom-right corner as a Point."""
        return Point(self.right, self.bottom)
    
    def expanded_by(self, n):
        """Return a rectangle with extended borders.

        Create a new rectangle that is wider and taller than the
        immediate one. All sides are extended by "n" points.
        """
        p1 = Point(self.left-n, self.top-n)
        p2 = Point(self.right+n, self.bottom+n)
        return Rect(p1, p2)
    
    def width(self):
        """Return the width of the rectangle."""
        return self.right - self.left
    
    def height(self):
        """Return the height of the rectangle."""
        return self.bottom - self.top

    def center(self):
        """Return a point at the center of the rectangle."""
        return Point((self.right + self.left)/2,
                     (self.bottom + self.top)/2)
    
    def __str__( self ):
        return "<Rect (%s,%s)-(%s,%s)>" % (self.left,self.top,
                                           self.right,self.bottom)
    
    def __repr__(self):
        return "%s(%r, %r)" % (self.__class__.__name__,
                               Point(self.left, self.top),
                               Point(self.right, self.bottom))


class Card:
    
    def __init__(self, tags, title, text):
        self.title = title
        self.tags = tags
        self.text = text
        self.in_the_world = False  # In the world?
        self.x = None
        self.y = None
        self.loaded_w_h = False  # w, h loaded?
        self.w = None
        self.h = None
        self.color = wx.BLACK
    
    def Border(self):
        if not self.in_the_world:
            return None
        if not self.loaded_w_h:
            return None
        return Rect(Point(self.x - 3, self.y - 3),
                    Point(self.x + self.w + 6,
                          self.y + self.h + 2))
    
    def Draw(self, dc):
        if self.in_the_world:
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.SetPen(wx.LIGHT_GREY_PEN)
            dc.SetTextBackground(wx.WHITE)
            dc.SetTextForeground(wx.BLACK)
            if not self.loaded_w_h:
                (self.w, self.h) = dc.GetTextExtent(self.title)
                self.loaded_w_h = True
            border = self.Border()
            dc.DrawRectangle(border.left, border.top,
                             border.width(), border.height())
            dc.DrawText(self.title, self.x, self.y)
    
    def PointInside(self, x, y):
        border = self.Border()
        if border is None:
            return False
        return border.contains(Point(x,y))
    
    def Center(self):
        border = self.Border()
        if border is not None:
            return self.Border().center()
        return None
    
    def MoveTo(self, x, y):
        self.in_the_world = True
        self.x = x
        self.y = y
    
    def RemoveFromWorld(self):
        self.in_the_world = False
    
    def SetTitle(self, title):
        self.title = title
        self.loaded_w_h = False

    def SetTags(self, tags):
        self.tags = tags
        # Later, this will cause a relocation, somehow,
        # if it's in the world.
    
    def SetText(self, text):
        self.text = text
        # Later, this may cause effects, if it's presently displayed.

    def JumpAnywhere(self):
        self.MoveTo(random.randint(0, 400),
                    random.randint(0, 300))


cards = [Card(tags, title, text) for (tags, title, text) in
         [(["friend", "seattle", "oldschool"],
           "Vinnie Oliveri", "Vinnie, whom Lion met in 7th grade."),
          (["friend", "seattle", "oldschool"],
           "Shawn Kilburn", "Shawn, whom Lion met in 7th grade."),
          (["friend", "aptos", "oldschool"],
           "Joel Ford", "Joel, whom Lion met in 2nd grade."),
          (["friend"],
           "John Abbe", "John, whom Lion met during WikiVanning"),
          (["friend", "communitywiki"],
           "Mark Dilley", "Mark, whom Lion met during WikiVanning"),
          (["family", "seattle"],
           "Sakura Kimbro-Juliao", "Sakura, Lion's Daughter by Amber"),
          (["family", "seattle"],
           "Amber Straub", "Amber, Lion's Girlfriend"),]]

for card in cards:
    card.JumpAnywhere()


class Circle:
    def __init__(self, center_x, center_y, radius):
        self.center = Point(center_x, center_y)
        self.radius = radius
        self.tag = None
        self.loaded_w_h = False
        self.text_w = None
        self.text_h = None
        self.text_x = None
        self.text_y = None
    
    def SetTag(self, tag):
        self.tag = tag
        self.loaded_w_h = False
    
    def Draw(self, dc):
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen('CADET BLUE', 2))
        tl = self.center - Point(self.radius, self.radius)
        dc.DrawEllipse(tl.x, tl.y, self.radius*2, self.radius*2)
        if self.tag is not None:
            if not self.loaded_w_h:
                (self.text_w, self.text_h) = dc.GetTextExtent(self.tag)
                self.text_x = self.center.x - (self.text_w/2)
                self.text_y = self.center.y - (self.text_h/2)
                self.loaded_w_h = True
            dc.SetTextForeground(wx.GREEN)
            dc.DrawText(self.tag, self.text_x, self.text_y)
    
    def PointWithin(self, p):
        return self.center.distance_to(p) <= self.radius


def triangle(tl_x, tl_y, distance):
    tr_x = tl_x + distance
    bottom_x = tl_x + (distance / 2)
    bottom_y = tl_y + (distance * 1.414 * 0.5)
    return [(tl_x, tl_y), (tr_x, tl_y), (bottom_x, bottom_y)]


circles = [Circle(x, y, 120) for (x, y) in triangle(150, 150, 140)]
circles[0].SetTag(INITIAL_A)
circles[1].SetTag(INITIAL_B)
circles[2].SetTag(INITIAL_C)


class wxFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: wxFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        
        # Menu Bar
        self.MenuBar = wx.MenuBar()
        self.SetMenuBar(self.MenuBar)
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(wx.ID_ABOUT, "&About", "About", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(wx.ID_EXIT, "E&xit", "Exit Venn Interface", wx.ITEM_NORMAL)
        self.MenuBar.Append(wxglade_tmp_menu, "&File")
        # Menu Bar end
        self.StatusBar = self.CreateStatusBar(1, 0)
        self.Tags = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
        self.List = wx.ListBox(self, -1, choices=[], style=wx.LB_SINGLE)
        self.Text = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY)
        self.Display = VennDisplay(self, ID_VENNDISPLAY)
        self.LSD = wx.Button(self, -1, "LSD")
        self.TagA = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
        self.TagB = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
        self.TagC = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
        self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnTagsEntered, self.Tags)
        self.Bind(wx.EVT_LISTBOX, self.OnListSelection, self.List)
        self.Bind(wx.EVT_BUTTON, self.OnLSD, self.LSD)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnCircleTagChanged, self.TagA)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnCircleTagChanged, self.TagB)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnCircleTagChanged, self.TagC)
        # end wxGlade
        self.Display.Bind(wx.EVT_LEFT_DOWN, self.OnDown)
        self.Display.Bind(wx.EVT_LEFT_UP, self.OnUp)
        self.Display.Bind(wx.EVT_MOTION, self.OnMove)
        self.Timer = wx.Timer(self, ID_TIMER)
        self.Timer.Start(MILLISECONDS)
        self.Bind(wx.EVT_TIMER, self.OnTimer, id=ID_TIMER)
        self.SelectedCard = None
        self.TagA.SetValue(INITIAL_A)
        self.TagB.SetValue(INITIAL_B)
        self.TagC.SetValue(INITIAL_C)
    
    def __set_properties(self):
        # begin wxGlade: wxFrame.__set_properties
        self.SetTitle("Venn Interface")
        self.SetSize((700, 520))
        self.StatusBar.SetStatusWidths([-1])
        # statusbar fields
        StatusBar_fields = ["VennInterface_statusbar"]
        for i in range(len(StatusBar_fields)):
            self.StatusBar.SetStatusText(StatusBar_fields[i], i)
        # end wxGlade
    
    def __do_layout(self):
        # begin wxGlade: wxFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.BoxSizer(wx.VERTICAL)
        sizer_3.Add(self.Tags, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
        sizer_3.Add(self.List, 2, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
        sizer_3.Add(self.Text, 5, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
        sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
        sizer_2.Add(self.Display, 3, wx.EXPAND, 0)
        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
        sizer_4.Add(self.LSD, 0, wx.ADJUST_MINSIZE, 0)
        sizer_4.Add(self.TagA, 1, wx.ADJUST_MINSIZE, 0)
        sizer_4.Add(self.TagB, 1, wx.ADJUST_MINSIZE, 0)
        sizer_4.Add(self.TagC, 1, wx.ADJUST_MINSIZE, 0)
        sizer_1.Add(sizer_4, 0, wx.EXPAND, 0)
        self.SetAutoLayout(True)
        self.SetSizer(sizer_1)
        self.Layout()
        # end wxGlade
    
    def OnAbout(self, event): # wxGlade: wxFrame.<event_handler>
        d = wx.MessageDialog(self, "By Lion, for John", "About Venn Interface",
                             wx.OK)
        d.ShowModal()
        d.Destroy()
    
    def OnExit(self, event): # wxGlade: wxFrame.<event_handler>
        self.Close(1)
        event.Skip()
    
    def OnDown(self, event):
        global cards
        x = event.GetX()
        y = event.GetY()
        for card in cards:
            if card.PointInside(x, y):
                self.SelectedCard = card
                self.ShowInfo(card)
    
    def OnUp(self, event):
        global circles
        if self.SelectedCard is not None:
            x = event.GetX()
            y = event.GetY()
            p = Point(x, y)
            self.SelectedCard.MoveTo(x, y)
            tags = self.SelectedCard.tags
            for circle in circles:
                inside = circle.PointWithin(self.SelectedCard)
                if inside and (circle.tag not in tags):
                    tags.append(circle.tag)
                if not inside and (circle.tag in tags):
                    tags.remove(circle.tag)
            self.ShowInfo(self.SelectedCard)
            self.SelectedCard = None
            self.Display.UpdateDrawing()
    
    def OnMove(self, event):
        if self.SelectedCard is not None:
            x = event.GetX()
            y = event.GetY()
            self.SelectedCard.MoveTo(x, y)
            self.Display.UpdateDrawing()
    
    def OnCircleTagChanged(self, event): # wxGlade: wxFrame.<event_handler>
        global circles
        obj = event.GetEventObject()
        new_tag = obj.GetValue()
        if obj == self.TagA:
            circles[0].SetTag(new_tag)
        elif obj == self.TagB:
            circles[1].SetTag(new_tag)
        elif obj == self.TagC:
            circles[2].SetTag(new_tag)
    
    def OnTimer(self, event):
        global cards, circles
        for card in [card for card in cards if card.in_the_world]:
            for circle in circles:
                inside = circle.PointWithin(card.Center())
                tag_match = circle.tag in card.tags
                if inside != tag_match:
                    card.JumpAnywhere()
        self.Display.UpdateDrawing()


    def OnLSD(self, event): # wxGlade: wxFrame.<event_handler>
        global cards
        for card in cards:
            card.JumpAnywhere()
        self.Display.UpdateDrawing()

    def ShowInfo(self, card):
        """Show info about some card."""
        txt = "title: %s\ntags: %s\ntext:\n%s" % (card.title,
                                                  card.tags,
                                                  card.text)
        self.Text.SetValue(txt)

    def OnTagsEntered(self, event): # wxGlade: wxFrame.<event_handler>
        global cards
        self.List.Clear()
        tags = self.Tags.GetValue().split()
        for card in cards:
            ok = True
            for t in tags:
                if t not in card.tags:
                    ok = False
            if ok:
                i = self.List.Append(card.title)
                self.List.SetClientData(i, card)
    
    def OnListSelection(self, event): # wxGlade: wxFrame.<event_handler>
        if event.IsSelection():
            card = self.List.GetClientData(event.GetInt())
            self.ShowInfo(card)

# end of class wxFrame


class BufferedWindow(wx.Window):
    
    """A Buffered window class.
    
    To use it, subclass it and define a Draw(DC) method that takes a DC
    to draw to. In that method, put the code needed to draw the picture
    you want. The window will automatically be double buffered, and the
    screen will be automatically updated when a Paint event is received.
    
    When the drawing needs to change, you app needs to call the
    UpdateDrawing() method. Since the drawing is stored in a bitmap, you
    can also save the drawing to file by calling the
    SaveToFile(self,file_name,file_type) method.
    """
    
    def __init__(self, parent, id,
                 pos = wx.DefaultPosition,
                 size = wx.DefaultSize,
                 style = wx.NO_FULL_REPAINT_ON_RESIZE):
        wx.Window.__init__(self, parent, id, pos, size, style)
        
        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_SIZE(self, self.OnSize)
        
        # OnSize called to make sure the buffer is initialized.
        # This might result in OnSize getting called twice on some
        # platforms at initialization, but little harm done.
        self.OnSize(None)
    
    def Draw(self,dc):
        ## just here as a place holder.
        ## This method should be over-ridden when subclassed
        pass
    
    def OnPaint(self, event):
        # All that is needed here is to draw the buffer to screen
        dc = wx.BufferedPaintDC(self, self._Buffer)
    
    def OnSize(self,event):
        # The Buffer init is done here, to make sure the buffer is always
        # the same size as the Window
        Size  = self.GetClientSizeTuple()
        
        # Make new offscreen bitmap: this bitmap will always have the
        # current drawing in it, so it can be used to save the image to
        # a file, or whatever.
        self._Buffer = wx.EmptyBitmap(*Size)
        self.UpdateDrawing()
    
    def SaveToFile(self,FileName,FileType):
        ## This will save the contents of the buffer
        ## to the specified file. See the wxWindows docs for 
        ## wx.Bitmap::SaveFile for the details
        self._Buffer.SaveFile(FileName,FileType)
    
    def UpdateDrawing(self):
        """
        This would get called if the drawing needed to change, for whatever reason.
        
        The idea here is that the drawing is based on some data generated
        elsewhere in the system. If that data changes, the drawing needs to
        be updated.
        """
        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
        self.Draw(dc)


class VennDisplay(BufferedWindow):
    def __init__(self, parent, id = -1):
        ## Any data the Draw() function needs must be initialized before
        ## calling BufferedWindow.__init__, as it will call the Draw
        ## function.
        self.DrawData = {"Ellipses": triangle(50, 50, 95)}
        BufferedWindow.__init__(self, parent, id, style=wx.SUNKEN_BORDER | wx.TAB_TRAVERSAL | wx.NO_FULL_REPAINT_ON_RESIZE)
    
    def Draw(self, dc):
        global cards
        global circles
        dc.SetBackground( wx.Brush("White") )
        dc.Clear() # make sure you clear the bitmap!
        
        for circle in circles:
            circle.Draw(dc)
        for card in cards:
            card.Draw(dc)


app = wx.PySimpleApp()

frame = wxFrame(None, ID_VENNINTERFACE, "Venn Interface")
frame.Show(1)

app.MainLoop()
Personal tools