def _Create_Manager_Frame( self ):
      """This method will create the frame to display the manager's info."""

      #create the containing frame which will be the top third of the 
      #current area
      man_frame = Frame( container = self,
                         top = 0,
                         height = (self.height / 4),
                         width = self.width )
      
      #create a label for the manager name
      self._manager_label = \
         Label( "Manager: " + \
                self._display_team.Get_Manager().Get_Manager_Name() )
         
      self._team_name_label = \
         Label( "Team Name: " + self._display_team.Get_Team_Name( ) )
         
      self._salary_label = \
         Label( "Current Salary: " + `self._display_team.Get_Team_Salary( )` )

      man_frame.place_column( [self._manager_label,
                               self._team_name_label,
                               self._salary_label],
                              left = 0,
                              top = 0 )

      return man_frame
 def __init__( self, items, row_spacing = 5, column_spacing = 10,
         align = 'l', equalize = '', expand_row = None, expand_column = None,
         padding = ( 0, 0 ), **kwds ):
    Frame.__init__( self )
    self._hpad, self._vpad = padding
    self._num_rows = len( items )
    
    self._num_cols = 0
    
    #make sure we have rows to show
    if self._num_rows > 0:
    
       self._num_cols = max( [len( row ) for row in items] )
       
    #end make sure there are rows to show
    self._col_widths = [0] * self._num_cols
    self._row_heights = [0] * self._num_rows
    
    self._items = items
    self._row_spacing = row_spacing
    self._column_spacing = column_spacing
    self._align = align
    self._equalize = equalize
    self._expand_row = expand_row
    self._expand_column = expand_column
    
    for i, row in enumerate( items ):
       for j, item in enumerate( row ):
          if item:
             self._row_heights[i] = max( self._row_heights[i], item.height )
             self._col_widths[j] = max( self._col_widths[j], item.width )
    self._reset_grid()
    self.set( **kwds )
   def __init__( self,
                 display_team,
                 player_keys,
                 **kwds ):
      """This is the constructor for the team frame."""
      ##
      # @param display_team: The object containing the team to be displayed's
      #                      information.
      #  
      # @param receiver: The object to receive the function calls.
      # 
      # @param function_to_call: The action function to invoke in the 
      #                          receiver when it's time to do something. Since
      #                          this is displaying the contents of a single
      #                          team, the action that needs to be invoked is
      #                          the same for each team.
      # 
      # @param kwds: List of common arguments to pass in to the parent class.
      # 
      
      
      #call the parent init
      Frame.__init__( self, **kwds )
      
      self._display_team = display_team
      
      #pull out the list of players
      self._player_list = display_team.Get_Player_List( )

      #create the frame to contain the manager information
      self._manager_frame = self._Create_Manager_Frame( )

      self._bottom_frame = Frame( container = self,
                                  top = self._manager_frame.height,
                                  anchor = "ltrb",
                                  height = self.height - self._manager_frame.height,
                                  width = self.width )

      self.place( self._manager_frame )
      self.place( self._bottom_frame )

      #the player frame will be the bottom two thirds of the team frame
      self._player_frame = \
         player_frame.Player_Frame( self._player_list,
                                    player_keys,
                                    #container = self._bottom_frame,
                                    container = self,
                                    top = self._manager_frame.height,
                                    #top = 0,
                                    anchor = "ltrb",
                                    #scrolling = "v",
                                    scrolling = "hv",
                                    height = (self.height * 2 / 3),
                                    #height = (50 * len(self._player_list)),
                                    #height = self._bottom_frame.height,
                                    #width = self.width )
                                    #extent = (0, (100 * len(self._player_list))) )
                                    width = self.width,
                                    extent = (750, 500) ) # TODO programatically determine what the scrolling extent needs to be. 
 def __init__( self, title, item, width=None ):
     Frame.__init__( self )
     self.title_label = Label(text=title)
     self.item = item
     self.place_row([self.title_label, self.item],left=0,top=0)
     self.shrink_wrap()
     if width is not None:
         self.width = width
Example #5
0
def test():
    win = Window(title = "Frame")
    frm = Frame()
    frm.place_column([
        Label("This is"),
        Label("A frame")],
        left = 0, top = 0)
    frm.shrink_wrap()
    win.place(frm, left = 30, top = 30)
    win.shrink_wrap(padding = (30, 30))
    win.show()
def frame_items( items, layout=DEFAULT_LAYOUT ):
    """Places a set of titled grids in a Frame according to the contents of LAYOUT."""
    result = Frame()
    top = 0
    for row_info in layout:
        grids = []
        for device,height in row_info:
            channel_items = [items[device][channel] for channel in device.iterchannels(clock=False)]
            grids.append( make_grid(device.display_name, channel_items, height) )
        row = Row( grids, spacing=3*PADDING )
        result.place( row, left=0, top=top )
        top = row.bottom + 3*PADDING
    result.shrink_wrap()
    return result
   def _Create_Overall_Player_Frame( self ):
      """This method is used to create the overall player frame used when 
      displaying the players."""

      #retrieve the main frame from the GUI
      main_frame = self._main_gui.Get_Main_Frame()

      #create the overall player frame
      self._overall_player_frame = \
         Frame( container = main_frame,
                anchor = "ltrb",
                size = ( main_frame.width,
                         main_frame.height ) )

      #create the search button
      self._player_search_button = Button( "Player Search", 
                                           action = "Player_Search", 
                                           style = "default" )
      
      #put the button in the frame
      self._overall_player_frame.place( self._player_search_button,
                                        left = 0,
                                        top = 0 )
      
      #create the text box
      self._player_search_field = \
         TextField( width = number_constants.text_box_width )
         
      #put the field on the frame
      self._overall_player_frame.place( \
              self._player_search_field,
              left = self._player_search_button.right )
    def __init__( self, directory, callback ):
        Frame.__init__( self )
        self.directory = directory
        self.callback = callback
        self.refs = []
        self.channels = []

        label = Label(text='-----', width=SelectionFrame.width)
        self.label_frame = LabeledItemFrame( "Files:", label )
        self.select_button = Button(title='Select', action=self.select,
                                        width=100)
        field = TextField(text='', width=SelectionFrame.width)
        self.channel_frame = LabeledItemFrame( "Channels:", field )

        self.place_column([self.label_frame, self.select_button,
                           self.channel_frame], left=0, top=0)
        self.shrink_wrap()
Example #9
0
 def __init__(self,
              items,
              spacing=10,
              align='l',
              equalize='',
              expand=None,
              padding=(0, 0),
              **kwds):
     Frame.__init__(self)
     hpad, vpad = padding
     if expand is not None and not isinstance(expand, int):
         expand = items.index(expand)
     equalize_components(items, equalize)
     width = 0
     for item in items:
         if item:
             width = max(width, item.width)
     y = vpad
     gap = 0
     vanchor = 't'
     hanchor = align
     for i, item in enumerate(items):
         if item:
             y += gap
             if 'l' in align:
                 x = 0
                 if 'r' in align:
                     item.width = width
             elif align == 'r':
                 x = width - item.width
             else:
                 x = (width - item.width) // 2
             item.position = (x + hpad, y)
             if i == expand:
                 item.anchor = 'tb' + hanchor
                 vanchor = 'b'
             else:
                 item.anchor = vanchor + hanchor
             y += item.height
         if i == expand:
             vanchor = 'b'
         gap = spacing
     self.size = (width + 2 * hpad, y + vpad)
     self.add(items)
     self.set(**kwds)
Example #10
0
 def __init__(self,
              items,
              spacing=10,
              align='c',
              equalize='',
              expand=None,
              padding=(0, 0),
              **kwds):
     Frame.__init__(self)
     hpad, vpad = padding
     if expand is not None and not isinstance(expand, int):
         expand = items.index(expand)
     equalize_components(items, equalize)
     height = 0
     for item in items:
         if item:
             height = max(height, item.height)
     x = hpad
     gap = 0
     hanchor = 'l'
     vanchor = align
     for i, item in enumerate(items):
         x += gap
         if item:
             if 't' in align:
                 y = 0
                 if 'b' in align:
                     item.height = height
             elif align == 'b':
                 y = height - item.height
             else:
                 y = (height - item.height) // 2
             item.position = (x, y + vpad)
             if i == expand:
                 item.anchor = 'lr' + vanchor
             else:
                 item.anchor = hanchor + vanchor
             x += item.width
         if i == expand:
             hanchor = 'r'
         gap = spacing
     self.size = (x + hpad, height + 2 * vpad)
     self.add(items)
     self.set(**kwds)
 def __init__(self, items, spacing = 10, align = 'l', equalize = '',
         expand = None, padding = (0, 0), **kwds):
     Frame.__init__(self)
     hpad, vpad = padding
     if expand is not None and not isinstance(expand, int):
         expand = items.index(expand)
     equalize_components(items, equalize)
     width = 0
     for item in items:
         if item:
             width = max(width, item.width)
     y = vpad
     gap = 0
     vanchor = 't'
     hanchor = align
     for i, item in enumerate(items):
         if item:
             y += gap
             if 'l' in align:
                 x = 0
                 if 'r' in align:
                     item.width = width
             elif align == 'r':
                 x = width - item.width
             else:
                 x = (width - item.width) // 2
             item.position = (x + hpad, y)
             if i == expand:
                 item.anchor = 'tb' + hanchor
                 vanchor = 'b'
             else:
                 item.anchor = vanchor + hanchor
             y += item.height
         if i == expand:
             vanchor = 'b'
         gap = spacing
     self.size = (width + 2 * hpad, y + vpad)
     self.add(items)
     self.set(**kwds)
Example #12
0
def test():
    win = Window(title="Frame")
    frm = Frame()
    frm.place_column([Label("This is"), Label("A frame")], left=0, top=0)
    frm.shrink_wrap()
    win.place(frm, left=30, top=30)
    win.shrink_wrap(padding=(30, 30))
    win.show()
   def __init__( self,
                 offering_team,
                 receiving_team,
                 initial_player = None,
                 **kwds ):
      """This is the constructor for the trade frame."""

      self._offering_team = offering_team
      self._receiving_team = receiving_team
      
      #create defaulted list of players being offered or received
      self._offering_players = {}
      self._receiving_players = {}
      
      #call the parent constructor
      Frame.__init__( self, **kwds )
      
      #if we were given an initial player to be involved in the trade
      if None <> initial_player:
      
         #add this player to the list of receiving players
         self._receiving_players[initial_player.Get_Name( )] = \
            initial_player
Example #14
0
 def __init__(self, items, spacing=10, align="c", equalize="", expand=None, padding=(0, 0), **kwds):
     Frame.__init__(self)
     hpad, vpad = padding
     if expand is not None and not isinstance(expand, int):
         expand = items.index(expand)
     equalize_components(items, equalize)
     height = 0
     for item in items:
         if item:
             height = max(height, item.height)
     x = hpad
     gap = 0
     hanchor = "l"
     vanchor = align
     for i, item in enumerate(items):
         x += gap
         if item:
             if "t" in align:
                 y = 0
                 if "b" in align:
                     item.height = height
             elif align == "b":
                 y = height - item.height
             else:
                 y = (height - item.height) // 2
             item.position = (x, y + vpad)
             if i == expand:
                 item.anchor = "lr" + vanchor
             else:
                 item.anchor = hanchor + vanchor
             x += item.width
         if i == expand:
             hanchor = "r"
         gap = spacing
     self.size = (x + hpad, height + 2 * vpad)
     self.add(items)
     self.set(**kwds)
   def _Create_Navigation_Frame( self ):
      """This method will create the navigation frame."""

      self._button_width = self._nav_width - number_constants.basic_pad

      #create the navigation frame
      self._nav_frame = Frame( width = self._nav_width,
                               height = self.height ) 

      #create the label to be at the top of the nav frame
      self._nav_label = Label( "Navigation",
                               just = "center",
                               font = self._bold_font,
                               width = self._button_width )

      self._my_team_button = Button( title = "My Team", 
                                     action = "Go_To_My_Team",
                                     width = self._button_width )

      self._league_button = Button( title = "League",
                                    action = "Go_To_League",
                                     width = self._button_width )

      self._players_button = Button( title = "Players",
                                     action = "Go_To_Players",
                                     width = self._button_width )

      self._transactions_button = Button( title = "My Transactions",
                                          action = "Go_To_Transactions",
                                          width = self._button_width )
      
      self._exit_button = Button( title = "Exit",
                                  action = "Exit_Commanded",
                                  width = self._button_width )

      #add the buttons to the frame
      self._nav_frame.place_column([self._nav_label,
                                    self._my_team_button,
                                    self._league_button,
                                    self._players_button,
                                    self._transactions_button,
                                    self._exit_button],
                                   left = 0, 
                                   top = 0)

      self.place( self._nav_frame, left = 20, top = 20 )
   def _Create_Overall_Team_Frame( self ):
      """This method will create the frame that contains the team frame."""
      
      #create the frame 
      self._overall_team_frame = \
         Frame( container = self._main_gui.Get_Main_Frame( ),
                anchor = "ltrb",
                size = ((self._main_gui.Get_Main_Frame_Width() - \
                         number_constants.basic_pad),
                        (self._main_gui.Get_Main_Frame_Height() - \
                         number_constants.basic_pad)))



      #create the drop-down
      self._team_dropdown = \
         team_dropdown.Team_Dropdown( manager_list = self._manager_list,
                                      receiver = self,
                                      receiver_function = "Show_Team",
                                      position = ( 0, 0 ),
                                      width = self._overall_team_frame.width )
      
      #add the drop down to the overall frame
      self._overall_team_frame.add( self._team_dropdown )
Example #17
0
 def __init__(self,
              items,
              row_spacing=5,
              column_spacing=10,
              align='l',
              equalize='',
              expand_row=None,
              expand_column=None,
              padding=(0, 0),
              **kwds):
     Frame.__init__(self)
     hpad, vpad = padding
     num_rows = len(items)
     num_cols = max([len(row) for row in items])
     col_widths = [0] * num_cols
     row_heights = [0] * num_rows
     for i, row in enumerate(items):
         for j, item in enumerate(row):
             if item:
                 row_heights[i] = max(row_heights[i], item.height)
                 col_widths[j] = max(col_widths[j], item.width)
     tot_width = 0
     row_top = 0
     row_gap = 0
     vanchor = 't'
     for i, row in enumerate(items):
         row_height = row_heights[i]
         row_top += row_gap
         col_left = 0
         col_gap = 0
         hanchor = 'l'
         if i == expand_row:
             vanchor = 'tb'
         for j, item in enumerate(row):
             col_width = col_widths[j]
             col_left += col_gap
             if item:
                 if 'l' in align:
                     x = 0
                 elif 'r' in align:
                     x = col_width - item.width
                 else:
                     x = (col_width - item.width) // 2
                 if 't' in align:
                     y = 0
                 elif 'b' in align:
                     y = row_height - item.height
                 else:
                     y = (row_height - item.height) // 2
                 item.position = (hpad + col_left + x, vpad + row_top + y)
                 if j == expand_column:
                     item.anchor = 'lr' + vanchor
                 else:
                     item.anchor = hanchor + vanchor
                 self.add(item)
             if j == expand_column:
                 hanchor = 'r'
             col_left += col_width
             col_gap = column_spacing
             tot_width = max(tot_width, col_left)
         if i == expand_row:
             vanchor = 'b'
         row_top += row_height
         row_gap = row_spacing
     tot_height = row_top
     self.size = (tot_width + 2 * hpad, tot_height + 2 * vpad)
     self.set(**kwds)
   def __init__( self,
                 controller,
                 logo_file,
                 **kwds ):
      """This method is the constructor for the class."""
      
      #self._win_has_menubar = False
      
      #call the parent constructor
      Window.__init__( self, size = ( 600, 400 ) )

      #set the title
      self.set_title( "Obscure Reference" )

      #center ourselves
      self.center( )

      #save the controller
      self._controller = controller

      #the navigation frame will take up the left quarter of the screen
      self._nav_width = self.width / 4
      
      #the main frame will take up the right remainder of the screen
      self._main_width = self.width - self._nav_width

      #create the bold font
      self._bold_font = Font( style = ["bold"] )

      self._Create_Navigation_Frame( )

      #create the main frame
      self._main_frame = \
         Frame( width = self._main_width,
                height = self.height )#- number_constants.menu_bar_height )
      
      
      #create the initial sub frame
      self._sub_frame = \
         Frame( width = (self._main_width - number_constants.basic_pad),
                height = self.height )

      self._logo_image = Image( logo_file )
      #self._intro_canvas = Canvas( None )
      #self._intro_canvas = View( )
      #self._intro_canvas = Frame( width = 500, height = 300 )

      #put the column on the GUI
      self._sub_frame.place_column( \
         [Label("Welcome to the Obscure Reference League",
                just = "center",
                width = (self._main_width - number_constants.basic_pad),
                font = self._bold_font ),
          #self._intro_canvas],          
          Label( "I would really like an image to be displayed here.")],
         left = 0,
         top = 0)
      self._main_frame.place( self._sub_frame )

      self.place( self._main_frame,
                  left = self._nav_frame.right,
                  top = 20,
                  sticky = "nsew" )
class Obscure_Main_Gui( Window ):

   def __init__( self,
                 controller,
                 logo_file,
                 **kwds ):
      """This method is the constructor for the class."""
      
      #self._win_has_menubar = False
      
      #call the parent constructor
      Window.__init__( self, size = ( 600, 400 ) )

      #set the title
      self.set_title( "Obscure Reference" )

      #center ourselves
      self.center( )

      #save the controller
      self._controller = controller

      #the navigation frame will take up the left quarter of the screen
      self._nav_width = self.width / 4
      
      #the main frame will take up the right remainder of the screen
      self._main_width = self.width - self._nav_width

      #create the bold font
      self._bold_font = Font( style = ["bold"] )

      self._Create_Navigation_Frame( )

      #create the main frame
      self._main_frame = \
         Frame( width = self._main_width,
                height = self.height )#- number_constants.menu_bar_height )
      
      
      #create the initial sub frame
      self._sub_frame = \
         Frame( width = (self._main_width - number_constants.basic_pad),
                height = self.height )

      self._logo_image = Image( logo_file )
      #self._intro_canvas = Canvas( None )
      #self._intro_canvas = View( )
      #self._intro_canvas = Frame( width = 500, height = 300 )

      #put the column on the GUI
      self._sub_frame.place_column( \
         [Label("Welcome to the Obscure Reference League",
                just = "center",
                width = (self._main_width - number_constants.basic_pad),
                font = self._bold_font ),
          #self._intro_canvas],          
          Label( "I would really like an image to be displayed here.")],
         left = 0,
         top = 0)
      self._main_frame.place( self._sub_frame )

      self.place( self._main_frame,
                  left = self._nav_frame.right,
                  top = 20,
                  sticky = "nsew" )

      #draw the image in to the view
      #self._logo_image.draw( \
      #   self._intro_canvas,
      #   self._logo_image.bounds,  
      #   self._logo_image.bounds )


   #end __init

   def _Create_Navigation_Frame( self ):
      """This method will create the navigation frame."""

      self._button_width = self._nav_width - number_constants.basic_pad

      #create the navigation frame
      self._nav_frame = Frame( width = self._nav_width,
                               height = self.height ) 

      #create the label to be at the top of the nav frame
      self._nav_label = Label( "Navigation",
                               just = "center",
                               font = self._bold_font,
                               width = self._button_width )

      self._my_team_button = Button( title = "My Team", 
                                     action = "Go_To_My_Team",
                                     width = self._button_width )

      self._league_button = Button( title = "League",
                                    action = "Go_To_League",
                                     width = self._button_width )

      self._players_button = Button( title = "Players",
                                     action = "Go_To_Players",
                                     width = self._button_width )

      self._transactions_button = Button( title = "My Transactions",
                                          action = "Go_To_Transactions",
                                          width = self._button_width )
      
      self._exit_button = Button( title = "Exit",
                                  action = "Exit_Commanded",
                                  width = self._button_width )

      #add the buttons to the frame
      self._nav_frame.place_column([self._nav_label,
                                    self._my_team_button,
                                    self._league_button,
                                    self._players_button,
                                    self._transactions_button,
                                    self._exit_button],
                                   left = 0, 
                                   top = 0)

      self.place( self._nav_frame, left = 20, top = 20 )

   #end _Create_Navigation_Frame

   def Receive_New_Frame( self,
                          new_frame ):
      """This method is used to receive a new frame to be displayed in the
      main frame area."""
      
      #remove the previous frame
      self._main_frame.remove( self._sub_frame )
            
      #put the new frame in the main frame area
      self._main_frame.place( new_frame,
                              sticky = "nsew", #Stick to all sides of the frame
                              left = 0,
                              top = 0 )
      
      #save the new frame as the current frame
      self._sub_frame = new_frame

      # cause the main frame area to be redrawn.
      self._main_frame.invalidate()

   #end Receive_New_Frame

   def draw( self, canvas, rect ):
      """Cause the frame to re-draw the important area."""
      canvas.erase_rect( rect )
   #end draw

   def Go_To_My_Team( self ):
      """This method will tell the parent that the user wants their team to
      be displayed."""
      
      manager_name = self._controller.Get_Current_Manager_Name( )
      
      #display the team
      self._controller.Show_Team( manager_name = manager_name,
                                  internal_switch = True ) 
      
   #end Go_To_My_Team

   def Go_To_League( self ):
      """This method will tell the controller that the user wants to display
      the league information."""
      
      None
   #end Go_To_League

   def Go_To_Players( self ):
      """This method will tell the controller that the user wants to display
      the list of players."""
      
      #inform the controller that it's supposed to show the players
      self._controller.Show_Players( )

   #end Go_To_Players

   def Go_To_Transactions( self ):
      """This method will tell the controller that the user wants to display
      the currently-pending transactions."""
      
      #inform the controller to show the user's transactions
      self._controller.Show_Transactions( )
      
   #end Go_To_Transactions

   def Exit_Commanded( self ):
      """This method will cause the application to exit."""
      
      #inform the controller that it's time to go away.
      self._controller.Exit( )

   #end Exit_Commanded

   def Get_Width( self ):
      """This method will retrieve the width of this window."""
      return self.width
   #end Get_Width
   
   def Get_Height( self ):
      """This method will retrieve the height of this window."""
      return self.height
   #end Get_Height
   
   def Get_Main_Frame_Width( self ):
      return self._main_frame.width
   #end Get_Main_Frame_Width

   def Get_Main_Frame_Height( self ):
      return self._main_frame.height
   #end Get_Main_Frame_Width
   
   def Get_Main_Frame( self ):
      return self._main_frame
   #end Get_Main_Frame
#end class Obscure_Main_Gui
class Obscure_Reference_Main( main_application.Main_Application ):

   def __init__( self ):

      #call the parent constructor
      main_application.Main_Application.__init__( self )

      self._close = False

      #default our database parser
      self._parser = None

      #default the list of players
      self._player_list = {}

      #default the manager
      self._current_manager = None

      self._manager_list = {}

      self._overall_team_frame = None
      
      self._dropdown_string_table = []

   #end __init__

   def _Determine_Team_Information( self ):
      """This method will retrieve the information from the database that's
      pertinent to the individual team that's running."""
      
      #retrieve the manager table
      self._manager_table = \
         self._parser.Get_Table(string_definitions.managers_table_name)
         
      #retrieve the teams feed
      self._manager_feed = \
         self._parser.Get_Feed(self._manager_table)
         
      #because we could log in with any variation of periods in the 
      #username field, we need to strip them out to make sure we get a 
      #good comparison
      filtered_user_name = self._username.replace( ".", "" )

      #create manager objects based on the information in the table
      for raw_manager in self._manager_feed.entry:
      
         #create the object
         current_manager = manager.Manager( raw_manager )
      
         #save the manager in the manager list based on the username
         self._manager_list[current_manager.Get_Username( )] = current_manager

         current_manager_name = \
            current_manager.Get_Username( ).replace( ".", "" )
         

         #check for a match with the provided username
         if filtered_user_name == current_manager_name:
            self._current_manager = current_manager
         #end if we have a match with the login username
      
      #end loop through manager
      
   #end _Determine_Team_Information

   def _Determine_Session_Information( self ):
      """This method will retrieve the information from the database that's
      pertinent to the session that is currently running."""
      
      #Get the table the contains the information
      self._session_table = \
         self._parser.Get_Table( string_definitions.session_table_name )
      
      #pull out the year field
      self._current_year = \
         self._parser.Get_Current_Year( self._session_table )
      
   #end _Determine_Session_Information

   def Get_Current_Year( self ):
      """This method will return the current season year."""

      return self._current_year

   #end Get_Current_Year

   def Get_Current_Team( self ):
      """This method will retrieve the team associated with the currently-
      logged in manager."""
      
      return self._current_team

   #end Get_Current_Team

   def Get_Current_Manager( self ):
      """This method will retrieve the manager associated with the currently-
      logged-in user."""
      return self._current_manager
   #end Get_Current_Manager

   def _Perform_Login( self ):
      """This method will attempt to log in to Google database."""

      _credentials =  credentials_dialog.Credentials_Dialog( )

      #show the dialog
      _credentials.present( )

      #loop until we get a successful login or the user has canceled
      while self._parser is None and not _credentials.Get_User_Canceled():

         try:
            #try to log in to the parser using the received credentials
            self._parser = database_parser.Database_Parser( \
                              _credentials.Get_User( ),
                              _credentials.Get_Password( ),
                              string_definitions.default_database_name )
         #end try to log in
         except (gdata.service.BadAuthentication, 
                 gdata.service.CaptchaRequired):
            #let the user know that there was a problem
            _credentials.Set_Message( "Login failed. Try again" )
         #end BadAuthentication

      #end loop until successful login/user canceled

      if self._parser <> None:
         #save the username 
         self._username = _credentials.Get_User( )

         if self._username.count("@") > 0:
         
            char_index = self._username.index( "@" ) 
         
            #the user name needs to be everything before the at
            self._username = self._username[0:char_index]
         
         #end if we have the at symbol
      
      #end if valid login

   #end _Perform_Login

   def Load_Player_Data( self ):
      """This method will load the latest player data to be used."""

      #check to make sure that we have a valid parser
      if self._parser <> None:
         #call in to the database to reload the players
         self._parser.Reload_Players( )

         #retrieve the list of players
         raw_player_list = self._parser.Get_Player_List( )

         #if we had a previous list
         if 0 <> len( self._player_list ):

            #delete the previous list
            del( self._player_list )

         #end if we have a previous player list

         self._player_list = {}

         #get the list of keys available for the player table
         self._player_keys = raw_player_list[0].custom.keys()

         #the statically-defined
         self._player_header_keys = ["Action", 
                                     "Name", 
                                     "Manager", 
                                     "Cap Hit" ]

         year_list = []
         
         #loop through the keys looking for salary information
         for key in self._player_keys:
            
            #if we've found a salary
            if key.count( string_definitions.salary_field_prefix ):
   
               #add this year to the year list
               year_list.append( \
                  key.replace( string_definitions.salary_field_prefix, 
                               "" ) )
   
            #end if we've found a salary
   
         #end loop through keys
   
         #put the year list in inverse order
         year_list.sort( reverse=True )
   
         #add the year list to the header keys
         self._player_header_keys += year_list 


         #loop through the player list creating the objects
         for current_player in raw_player_list:
            
            #pull out the player name to make this code not quite as ugly
            player_name = \
               current_player.custom[string_definitions.player_name_field].text

            this_player = \
               player.Player( raw_data = current_player,
                              receiver = self,
                              add_player_function = "Add_Player",
                              drop_player_function = "Drop_Player",
                              trade_player_function = "Trade_Player" )

            #add the new player to our list
            self._player_list[player_name] = this_player

            #retrieve the manager name
            manager_name = this_player.Get_Manager_Name()

            #determine if this player is on a team
            if manager_name <> None and manager_name <> "":

               #get the manager
               current_manager = self._manager_list[manager_name]
   
               #add this player to the manager's team
               current_manager.Add_Player( this_player )
               
            #end if player is on a team
         
         #end loop through players
      #end if valid parser

   #end Load_Player_Data

   #this method doesn't conform to naming standard because it is 
   #automatically called by the GUI framework
   def open_app(self):
      
      #perform the login
      self._Perform_Login( )

      #if we have a successful login, create the main GUI
      if self._parser <> None:

         #determine the team information
         self._Determine_Team_Information( )

         #figure out the important bits about our current session
         self._Determine_Session_Information( )

      #end if valid parser
      else:
         
         #note to self: we're closing
         self._close = True
         
         #exit out of the application
         self.Exit( ) 
      #couldn't log in

      #make sure that we didn't cancel out
      if self._close <> True:

         #create the main GUI
         self._main_gui = \
            obscure_main_gui.Obscure_Main_Gui( controller = self,
                                               logo_file = _logo_file )
         
         #display the main GUI
         self._main_gui.show( )

         #while we're here, let's grab the player data
         self.Load_Player_Data( )

      #end if user didn't cancel out

   #end open_app

   def _Create_Overall_Player_Frame( self ):
      """This method is used to create the overall player frame used when 
      displaying the players."""

      #retrieve the main frame from the GUI
      main_frame = self._main_gui.Get_Main_Frame()

      #create the overall player frame
      self._overall_player_frame = \
         Frame( container = main_frame,
                anchor = "ltrb",
                size = ( main_frame.width,
                         main_frame.height ) )

      #create the search button
      self._player_search_button = Button( "Player Search", 
                                           action = "Player_Search", 
                                           style = "default" )
      
      #put the button in the frame
      self._overall_player_frame.place( self._player_search_button,
                                        left = 0,
                                        top = 0 )
      
      #create the text box
      self._player_search_field = \
         TextField( width = number_constants.text_box_width )
         
      #put the field on the frame
      self._overall_player_frame.place( \
              self._player_search_field,
              left = self._player_search_button.right )

   #end _Create_Overall_Player_Frame

   def Players_Matching_String( self,
                                search_string ):
      """This method will look through the player list for any matching the 
      provided search string."""
      
      #shift the search string to lower case
      search_string = search_string.lower()
      
      player_list = {}
      
      #loop through the player list
      for current_player in self._player_list:
         
         #shift the player name to lower case
         lower_current_player = current_player.lower( )
         
         #if we have a match with the player
         if 0 < lower_current_player.count( search_string ):
            #add this player to the list
            player_list[current_player] = self._player_list[current_player]
         #end if we have a match
      #end loop through player list
      
      return player_list
      
   #end Players_Matching_String

   def Player_Search( self ):
      """This method will be invoked when the user clicks the player search
      button."""

      #retrieve the search string
      search_string = self._player_search_field.get_text( )

      #get the players matching the search string
      player_list = self.Players_Matching_String( search_string )
      
      #clear the existing player frame
      self._overall_player_frame.remove( self._player_frame )

      main_frame = self._main_gui.Get_Main_Frame( )
      
      #create a new player frame with the new list
      self._player_frame = \
         player_frame.Player_Frame( player_list = player_list,
                                    player_keys = self._player_header_keys,
                                    container = self._overall_player_frame,
                                    anchor = "ltrb",
                                    scrolling = "",
                                    size = (main_frame.width - 40, #TODO: Magic numbers need tweaked and defined
                                            (self._overall_player_frame.height - 
                                             self._player_search_button.height -
                                             number_constants.basic_pad - 
                                             number_constants.half_pad)))

      #put the overall player frame on the GUI
      self._overall_player_frame.place( \
              self._player_frame,
              sticky = "nsew", 
              top = (self._player_search_button.bottom + \
                     number_constants.half_pad))

      self._main_gui.Receive_New_Frame(self._overall_player_frame)

   #end Player_Search

   def Show_Players( self ):
      """This method will cause the list of players to be displayed."""


      self._Create_Overall_Player_Frame( )

      #retrieve the main frame from the GUI
      main_frame = self._main_gui.Get_Main_Frame()

      #create the player frame
      self._player_frame = \
         player_frame.Player_Frame( player_list = self._player_list,
                                    player_keys = self._player_header_keys,
                                    container = self._overall_player_frame,
                                    anchor = "ltrb",
                                    scrolling = "",
                                    size = (main_frame.width - 40, #TODO: Magic numbers need tweaked and defined
                                            (self._overall_player_frame.height - 
                                             self._player_search_button.height -
                                             number_constants.basic_pad - 
                                             number_constants.half_pad)))

      #put the overall player frame on the GUI
      self._overall_player_frame.place( \
              self._player_frame,
              sticky = "nsew", 
              top = (self._player_search_button.bottom + \
                     number_constants.half_pad))

      #give the new frame to the main GUI
      self._main_gui.Receive_New_Frame( self._overall_player_frame )

   #end Show_Players

   def Show_Transactions( self ):
      """This method will cause the list of pending transactions to be
      displayed."""
      
      None
      
   #end Show_Transactions

   def _Ask_User( self,
                  question ):
      """This method will ask the user if they're sure that they
      want to do what they've said they do. Basically, we're protecting
      them from themselves."""

      
      #create the confirm dialog
      confirm_dialog = ModalDialog( title = "Please Confirm" )
      
      confirm_dialog.place( Label(text = question ), 
                            left = 20, 
                            top = 20 )

      #create the buttons for OK/Cancel
      confirm_dialog.default_button = DefaultButton()
      confirm_dialog.cancel_button = CancelButton()

      #put the buttons on the GUI
      confirm_dialog.place( confirm_dialog.default_button, 
                            right = -20, 
                            bottom = -20 )
      confirm_dialog.place( confirm_dialog.cancel_button, 
                            left = 20, 
                            bottom = -20 )

      #center the dialog
      confirm_dialog.center( )
      
      #ask for confirmation to make sure that the user really wants to do
      #this
      confirm = confirm_dialog.present( )      
      
      return confirm
      
   #end _Ask_User

   def Add_Player( self,
                   player_to_add ):
      """This function will add the player to the current team."""
      
      if self._current_manager <> None:
         
         if self._Ask_User( "Are you sure that you want to\n add " + \
                            player_to_add.Get_Name( ) + \
                            "?" ):
         
            # Change the local data
            self._current_manager.Add_Player( player_to_add )
         
            #tell the player their new manager
            player_to_add.Set_Manager_Name( \
               self._current_manager.Get_Email( ) )
            try:
               #update the database
               self._parser.Set_Player_Line(player_to_add.Get_Raw_Data())

               #change the player information with the username
               #string instead of the whole email address
               player_to_add.Set_Manager_Name( \
                  string_definitions.Extract_Username( \
                     self._current_manager.Get_Email( ) ) )
            
               #update the GUI
               self.Show_Team( self._current_manager.Get_Username( ) )
            #end try
            except gdata.service.RequestError:
               #create a modal dialog to show
               error_dialog = ModalDialog(title = "Couldn't Add Player", 
                                          size = (400, 70))
               
               #create an information label
               error_dialog.place(Label(text = "Player has already " + \
                                               "been added by someone else"), 
                                  left = 20, 
                                  top = 20)
                                  
               #create the button
               error_dialog.default_button = DefaultButton()
               
               error_dialog.place(error_dialog.default_button, 
                                  right = -20, 
                                  bottom = -20)
   
               #start the reload of the players
               self.Load_Player_Data( )
   
               #show the dialog
               error_dialog.present()
               
               #re-show the player data
               self.Show_Players()
   
            #end except

         #end if user confirmed
            
      #end if
   #end Add_Player

   def Drop_Player( self,
                    player ):
      """This function will add the player to the current team."""

      confirm = self._Ask_User( "Are you sure that you want to \ndrop " + \
                                player.Get_Name( ) + \
                                "?" )
      #if the user was sure
      if confirm:

            
            # Change the local data
            self._current_manager.Drop_Player( player )
         
            #tell the player they no longer have a mananger
            player.Set_Manager_Name( "" )
            try:
               #update the database
               self._parser.Set_Player_Line(player.Get_Raw_Data())

               #update the GUI
               self.Show_Team( self._current_manager.Get_Username( ) )
            #end try
            except gdata.service.RequestError:
               #create a modal dialog to show
               error_dialog = ModalDialog(title = "Couldn't Drop Player", 
                                          size = (400, 70))
               
               #create an information label
               error_dialog.place(Label(text = "Error when trying to drop " + \
                                        "player." ), 
                                  left = 20, 
                                  top = 20)
                                  
               #create the button
               error_dialog.default_button = DefaultButton()
               
               error_dialog.place(error_dialog.default_button, 
                                  right = -20, 
                                  bottom = -20)
   
               #start the reload of the players
               self.Load_Player_Data( )
   
               #show the dialog
               error_dialog.present()
               
               #re-show the player data
               self.Show_Players()
   
            #end except
      
      #end if user wants to continue
         
   #end Drop_Player

   def Trade_Player( self,
                     player ):
      """This function will add the player to the current team."""
      None
   #end Trade_Player

   def Get_Current_Manager_Name( self ):
      """This method will retrieve the name of this instance's manager."""
      
      return self._current_manager.Get_Username( )
   
   #end Get_Current_Manager_Name

   def _Create_Overall_Team_Frame( self ):
      """This method will create the frame that contains the team frame."""
      
      #create the frame 
      self._overall_team_frame = \
         Frame( container = self._main_gui.Get_Main_Frame( ),
                anchor = "ltrb",
                size = ((self._main_gui.Get_Main_Frame_Width() - \
                         number_constants.basic_pad),
                        (self._main_gui.Get_Main_Frame_Height() - \
                         number_constants.basic_pad)))



      #create the drop-down
      self._team_dropdown = \
         team_dropdown.Team_Dropdown( manager_list = self._manager_list,
                                      receiver = self,
                                      receiver_function = "Show_Team",
                                      position = ( 0, 0 ),
                                      width = self._overall_team_frame.width )
      
      #add the drop down to the overall frame
      self._overall_team_frame.add( self._team_dropdown )
      
   #end _Create_Overall_Team_Frame

   def Show_Team( self,
                  manager_name,
                  internal_switch = False ):
      """This method will show the team based on the name of the team's 
      manager."""

      if None == self._overall_team_frame:
         self._Create_Overall_Team_Frame( )
      #end if team frame didn't exist before
      else:
         #remove the existing team frame from the overall team frame
         self._overall_team_frame.remove( self._team_frame )
      #end if the team frame did exist before

      display_manager = self._manager_list[manager_name]

      #if this is a switch triggered by the program
      #if internal_switch:
      #   self._team_dropdown.Set_Value(  )
      #end if internal switch

      #create this team's frame      
      self._team_frame = \
         team_frame.Team_Frame( display_team = display_manager.Get_Team(),
                                player_keys = self._player_header_keys,
                                container = self._overall_team_frame,
                                anchor = "ltrb",
                                size = (self._overall_team_frame.width,
                                        (self._overall_team_frame.height - \
                                         self._team_dropdown.height - \
                                         number_constants.basic_pad) ) ) 

      #add the team frame to the overall team frame
      self._overall_team_frame.place( self._team_frame,
                                      sticky = "nsew", 
                                      left = 0,
                                      top = (self._team_dropdown.height + \
                                             number_constants.basic_pad) )

      #give the new frame to the main GUI
      self._main_gui.Receive_New_Frame(self._overall_team_frame)
Example #21
0
 def __init__(
     self,
     items,
     row_spacing=5,
     column_spacing=10,
     align="l",
     equalize="",
     expand_row=None,
     expand_column=None,
     padding=(0, 0),
     **kwds
 ):
     Frame.__init__(self)
     hpad, vpad = padding
     num_rows = len(items)
     num_cols = max([len(row) for row in items])
     col_widths = [0] * num_cols
     row_heights = [0] * num_rows
     for i, row in enumerate(items):
         for j, item in enumerate(row):
             if item:
                 row_heights[i] = max(row_heights[i], item.height)
                 col_widths[j] = max(col_widths[j], item.width)
     tot_width = 0
     row_top = 0
     row_gap = 0
     vanchor = "t"
     for i, row in enumerate(items):
         row_height = row_heights[i]
         row_top += row_gap
         col_left = 0
         col_gap = 0
         hanchor = "l"
         if i == expand_row:
             vanchor = "tb"
         for j, item in enumerate(row):
             col_width = col_widths[j]
             col_left += col_gap
             if item:
                 if "l" in align:
                     x = 0
                 elif "r" in align:
                     x = col_width - item.width
                 else:
                     x = (col_width - item.width) // 2
                 if "t" in align:
                     y = 0
                 elif "b" in align:
                     y = row_height - item.height
                 else:
                     y = (row_height - item.height) // 2
                 item.position = (hpad + col_left + x, vpad + row_top + y)
                 if j == expand_column:
                     item.anchor = "lr" + vanchor
                 else:
                     item.anchor = hanchor + vanchor
                 self.add(item)
             if j == expand_column:
                 hanchor = "r"
             col_left += col_width
             col_gap = column_spacing
             tot_width = max(tot_width, col_left)
         if i == expand_row:
             vanchor = "b"
         row_top += row_height
         row_gap = row_spacing
     tot_height = row_top
     self.size = (tot_width + 2 * hpad, tot_height + 2 * vpad)
     self.set(**kwds)
Example #22
0
            self.general.window.on_quit(wx.EVT_CLOSE)

        sys.exit()

    def create_thread_communicator(self, ip, port):
        """
            The function receives a port and ip and creates the thread communicator.
        """

        self.general.thread_com = ThreadCommunication(self.general, ip, port)

        self.general.thread_com.start()


#-----Main Code-----#

general = GeneralVariables()

main = Main(general)

# Start the GUI of the client.
general.app = wx.App()

# Create the main frame of the GUI.
general.window = Frame(None, -1, "CodeDup", general)

# Start the main code of the client.
main.start()

# Start the GUI main loop.
general.app.MainLoop()
Example #23
0
    def make_window(self, document):
        win = Window(size=(700, 500), document=document)

        panel = Frame(width=170)

        def crop_action():
            if view.selection is None:
                view.setselection(shrink_rect(view.viewrect, 0.8))
                return

            croprect = view.pdfcoord(view.selection)
            #print 'view: %s, crop: %s' % (view.selection, croprect)
            view.model.crop(view.pagenum, croprect)
            view.selection = None
            view.set_status(selection=None)
            hide(view.crop_button)

        crop_button = Button(title='Crop', visible=True, action=crop_action)
        status = Label(text='\n\n\n\n')

        view = PDFView(pagenum=0, model=document, scrolling='hv',
                       status=status, cursor=crosshair, crop_button=crop_button)
        #view = PDFView(... extent=(1000, 1000), cursor = self.blob_cursor)

        def page_changer(delta):

            def change():
                np = win.document.numpages
                view.pagenum += delta

                if view.pagenum <= 0:
                    view.pagenum = 0
                    prevpage.enabled = False
                else:
                    prevpage.enabled = True

                if view.pagenum >= np - 1:
                    view.pagenum = np - 1
                    nextpage.enabled = False
                else:
                    nextpage.enabled = True

                page.text = '%s / %s' % (view.pagenum+1, np)
                view.invalidate()

            return change

        prevpage = Button(title='<', action=page_changer(-1))
        nextpage = Button(title='>', action=page_changer(+1))
        page = Label(just='center', anchor='b')
        page_changer(0)()

        panel.place(prevpage, top=5, left=5, sticky='w')
        panel.place(nextpage, top=5, right=-5, sticky='e')
        panel.place(page, bottom=prevpage.bottom, 
                    left=prevpage, right=nextpage, sticky='ew')

        panel.place(status, left=5, top=prevpage+5, right=0, sticky='ew')
        panel.place(crop_button, left=5, top=status, right=-5, sticky='ew')

        win.place(panel, left=0, top=0, bottom=0, sticky='nsw')
        win.place(view, left=panel, top=0, right=0, bottom=0, sticky='nsew')
        win.shrink_wrap()
        win.show()
Example #24
0
            if self.general.window.quit:

                sys.exit()

    def create_thread_communicator(self, ip, port):
        """
            The function receives a port and ip and creates the thread communicator.
        """

        self.general.thread_com = ThreadCommunication(self.general, ip, port)

        self.general.thread_com.start()


#-----Main Code-----#

general = GeneralVariables()

main = Main(general)

# Start the GUI of the client.
general.app = wx.App()

# Create the main frame of the GUI.
general.window = Frame(None, -1, "Project", general)

# Start the main code of the client.
main.start()

# Start the GUI main loop.
general.app.MainLoop()
Example #25
0
class Tool(Application):
    def __init__(self):
        Application.__init__(self, title = "Log Analysis Tool")
        print >>sys.stderr, "app init'd"

        self.window = Window(size = (1200, 750), title = "Log Analysis Tool")
        print >>sys.stderr, "made window"

        # Create db cursor
        db = get_conn(dbname = 'reduced_log')
        self.cur = db.cursor()
        print >>sys.stderr, "made db cursor"

        self.current_table_suffix = None
        
        # Load the dummy image for now
        self.image = GraphView(size = (640, 460), position = (10, 10))
        self.graph_panel = Frame()
        self.graph_panel.add(self.image)
        print >>sys.stderr, "loaded dummy image"

        # Declare other image lists
        self.full_ = None
        self.peruser_alltime_ = None
        self.peruser_divided_total_ = None
        self.peruser_divided_ = None

        # Create the display selection radio
        self.display_select_radiogroup = RadioGroup(action = 
                                                    self.change_images)
        height, startx = 495, 20
        sp = 10
        r1 = RadioButton("All users",
                         group = self.display_select_radiogroup,
                         value = 'all_users')
        r2 = RadioButton("Per user, query type",
                         group = self.display_select_radiogroup,
                         value = 'peruser_querytype')
        r3 = RadioButton("Per user, time",
                         group = self.display_select_radiogroup,
                         value = 'peruser_time')
        r4 = RadioButton("Per user, query type and time",
                         group = self.display_select_radiogroup,
                         value = 'peruser_querytype_time')
        
        self.graph_panel.place(r1, top = self.image + 10, left = sp)
        self.graph_panel.place(r2, top = self.image + 10, left = r1 + sp)
        self.graph_panel.place(r3, top = self.image + 10, left = r2 + sp)
        self.graph_panel.place(r4, top = self.image + 10, left = r3 + sp)
        self.window.place(self.graph_panel, top=0, left=0)
        self.display_select_radiogroup.value = 'all_users'
        
        # Create the top queries textbox
        self.topqueries = TopqueryPanel(size = (500, 460),
                                        extent = (500, 1000))
        self.topqueries.panels = [[TopqueryLabel("This is a placeholder until you select a filter",
                                                ["This is where", "the values", "will go"])]]
        self.window.place(self.topqueries, top=10, left=680)

        topqueries_next_button = Button("Next", action = self.topqueries.next)
        topqueries_prev_button = Button("Prev", action = self.topqueries.prev)
        self.window.place(topqueries_next_button, left = 930, top = top - 50)
        self.window.place(topqueries_prev_button, left = 830, top = top - 50)
        print >>sys.stderr, "made top queries text box"

        # Declare the filter and last updated filter pointers
        self.fil = None
        self.last_used_fil = None
        
        #
        # *************************
        # FILTER PANEL
        # *************************
        #

        # **CREATE DATE PANEL**
        field_width = 140
        self.date_panel = Frame()
        self.begin_date_field = TextField(size = (field_width, 30),
                                          position = (0, 5),
                                          text = DEFAULT_BEGIN_DATE_TEXT)
        self.end_date_field = TextField(size = (field_width, 30),
                                        position = (0, 35),
                                        text = DEFAULT_END_DATE_TEXT)
        self.date_panel.size = (field_width, 0)

        # Time division radios
        self.time_division_radiogroup = RadioGroup()
        left, right = 5, 70
        row1, rowspace = 95, 25

        group_by_label = Label("Group by:",
                               position = (5, 70))
        hour = RadioButton("Hour",
                           position = (left, row1),
                           group = self.time_division_radiogroup,
                           value = 'hour')
        day = RadioButton("Day",
                          position = (right, row1),
                          group = self.time_division_radiogroup,
                          value = 'day')
        week = RadioButton('Week',
                           position = (left, row1 + rowspace),
                           group = self.time_division_radiogroup,
                           value = 'week',
                           enabled = False) #TODO: implement 'week' in the gnuplot function
        month = RadioButton("Month",
                            position = (right, row1 + rowspace),
                            group = self.time_division_radiogroup,
                            value = 'month')
        year = RadioButton("Year", 
                           position = (left, row1 + 2*rowspace),
                           group = self.time_division_radiogroup,
                           value = 'year')
        self.time_division_radiogroup.value = 'day'
        self.last_grouped_by = None

        # Add all to date panel
        self.date_panel.add([self.begin_date_field, self.end_date_field])
        self.date_panel.add([group_by_label, hour, day, week, month, year])
        self.window.place(self.date_panel, top=top, left=10)
        print >>sys.stderr, "made date panel"

        # **CREATE QUERY TYPE FILTER CHECKBOXES**
        x_pos = 0
        y_pos = 0
        y_spacing = 20
        self.query_type_checkboxes = {}
        for qtype in querytypes:
            # underscores don't display properly, need an extra space after
            self.query_type_checkboxes[qtype] = CheckBox(qtype.replace('_', '_ '),
                                                         position = (x_pos,
                                                                     y_pos),
                                                         value = True)
            y_pos += y_spacing


        # Add the query type checkboxes and buttons to a Frame
        self.query_type_panel = Frame()
        maxw = 0
        for cbox in self.query_type_checkboxes.values():
            self.query_type_panel.add(cbox)
            maxw = max(cbox.size[0], maxw)
        self.query_type_panel.size = (maxw, 0)

        # Create all/none/invert buttons for query types
        buttonsize = (55, 25)
        self.query_type_panel.add(Button("All",
                                         action = (self.select_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))
        y_pos += 25
        self.query_type_panel.add(Button("None",
                                         action = (self.deselect_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))
        y_pos += 25
        self.query_type_panel.add(Button("Invert",
                                         action = (self.invert_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))

        # Add query_type_panel to the window
        self.window.place(self.query_type_panel, top = top,
                          left=self.date_panel + horiz_sp)
        print >>sys.stderr, "made query type cboxes"


        # **CREATE USER AND SERVER CHECKBOX LISTS**
        self.user_panel = None
        self.server_panel = None
        self.create_checkbox_lists(initial=True)

        self.cur.execute("SELECT user, userid FROM users")
        self.userids = dict(self.cur.fetchall())
        self.cur.execute("SELECT server, serverid FROM servers")
        self.serverids = dict(self.cur.fetchall())

        print >>sys.stderr, "made user, server cboxes"


        # **CREATE QUERY SEARCH STRING PANEL**
        num_search_strings = 5
        spacing = 30
        field_width = 250
        self.search_string_panel = Frame()
        self.search_string_panel.size = (field_width, 0)
        self.search_string_fields = [TextField(size = (field_width, 30),
                                               position = (0, spacing * i),
                                               text = "Query Search String {0}".format(i + 1))
                                     for i in range(num_search_strings)]
        self.search_string_panel.add(self.search_string_fields)

        self.any_all_radiogroup = RadioGroup()
        any_string_radio = RadioButton("Any",
                                       position = (40, 10 + spacing * \
                                                   num_search_strings),
                                       group = self.any_all_radiogroup,
                                       value = 'any')
        all_strings_radio = RadioButton("All",
                                        position = (130, 10 + spacing * \
                                                    num_search_strings),
                                        group = self.any_all_radiogroup,
                                        value = 'all')
        no_string_radio = RadioButton("None",
                                      position = (40, 30 + spacing * \
                                                  num_search_strings),
                                      group = self.any_all_radiogroup,
                                      value = 'none')
        not_all_string_radio = RadioButton("Not All",
                                           position = (130, 30 + spacing * \
                                                       num_search_strings),
                                           group = self.any_all_radiogroup,
                                           value = 'not all')
        self.any_all_radiogroup.value = 'any'
        self.search_string_panel.add(any_string_radio)
        self.search_string_panel.add(all_strings_radio)
        self.search_string_panel.add(no_string_radio)
        self.search_string_panel.add(not_all_string_radio)
        self.window.place(self.search_string_panel, top = top,
                          left = self.server_panel + 10)
        print >>sys.stderr, "made search string panel"


        # SELECT ALL/NONE, INVERT USERS
        # TODO: create user, server panels? atm only the cboxes are in
        # a ScrollableView
        buttonsize = (55, 25)
        invertbuttonsize = (60, 25)
        userstart = 295
        serverstart = 565
        self.window.place(Button("All",
                                 action = (self.select_all,
                                           'user'),
                                 size = buttonsize),
                          top = top + 155, left = userstart)
        self.window.place(Button("None",
                                 action = (self.deselect_all,
                                           'user'),
                                 size = buttonsize),
                          top = top + 155, left = userstart + 55 + 5)
        self.window.place(Button("Invert",
                                 action = (self.invert_all,
                                           'user'),
                                 size = invertbuttonsize),
                          top = top + 155, left = userstart + 55 + 5 + 55 + 5)
    
        # user search string textbox
        # TODO: the action is always one keystroke behind the text field.
        # This is a PyGUI 'bug',but it may only happen on windows (not sure
        # how the X server works).
        # See http://mail.python.org/pipermail/pygui/2010-November/000102.html
        self.user_search_string = ResponsiveTextField(emptyaction = None,
                                                      action = (self.select_all_matching,
                                                                'user'),
                                                      size = (180, 30),
                                                      text = DEFAULT_USER_SEARCH_STRING)
        self.window.place(self.user_search_string,
                          top = top + 155 + 25 + 5,
                          left = userstart)

        # SELECT ALL/NONE, INVERT SERVERS
        self.window.place(Button("All",
                                 action = (self.select_all,
                                           'server'),
                                 size = buttonsize),
                          top = top + 155, left = serverstart)
        self.window.place(Button("None",
                                 action = (self.deselect_all,
                                           'server'),
                                 size = buttonsize),
                          top = top + 155, left = serverstart + 55 + 5)
        self.window.place(Button("Invert",
                                 action = (self.invert_all,
                                           'server'),
                                 size = invertbuttonsize),
                          top = top + 155,
                          left = serverstart + 55 + 5 + 55 + 5)

        # server search string textbox
        self.server_search_string = ResponsiveTextField(emptyaction = None,
                                                        action = (self.select_all_matching,
                                                                  'server'),
                                                        size = (180, 30),
                                                        text = DEFAULT_SERVER_SEARCH_STRING)
        self.window.place(self.server_search_string,
                          top = top + 155 + 25 + 5, left=serverstart)

        self.window.show()


        # **CREATE BUTTONS**
        self.negate = CheckBox("Negate Filter", position=(0, 0), value=False)
        self.refresh_button = Button("Refresh",
                                     position = (0, 25),
                                     action=self.refresh)
        self.update_button = Button("Update",
                                    position = (0, 60),
                                    action = self.update)
    
        # Add buttons to a panel
        self.button_panel = Frame()
        self.button_panel.add([self.negate,
                               self.refresh_button,
                               self.update_button])
        self.window.place(self.button_panel, top = top,
                          left=self.search_string_panel + horiz_sp)
        print >>sys.stderr, "made button panel"


    def create_checkbox_lists(self, initial=False):
        """
        Removes the current user and server checkbox panels from the window,
        if they exist (if they don't, they will be None, from __init__())
        creates new ones with data from the current table, then adds them
        to the window again. If @initial is True, only the last partition
        (month) of the 'unified' table will be used for counts, but all
        users and servers will still be shown

        @initial - if this is the first time the checkbox lists are being
                   generated, it works a bit differently: the counts are
                   taken from just the last partition of the unified table
                   so that startup doesn't take forever. We then also need
                   to grab the names of other users who didn't appear in
                   this first partition
        """

        # Remove current user and server checkbox panels from the window
        if self.user_panel:
            self.window.remove(self.user_panel)
        if self.server_panel:
            self.window.remove(self.server_panel)

        # Create user filter checkboxes
        if initial:
            print_and_execute("""SELECT PARTITION_NAME
                                 FROM INFORMATION_SCHEMA.PARTITIONS
                                 WHERE TABLE_SCHEMA = 'reduced_log'
                                       AND TABLE_NAME = 'unified'""", self.cur)
            # there will be each month, then the 'other' partition, so we want to
            # select from the 2nd to last partition
            last_partition = [x for x, in self.cur.fetchall()][-2]
            table_to_use = "unified PARTITION({0})".format(last_partition)
        else:
            table_to_use = self.current_table_name()

        print_and_execute("""SELECT userid, user, count
                             FROM (SELECT userid, COUNT(*) AS count
                                   FROM {0} GROUP BY userid
                                  ) AS sth
                               NATURAL JOIN users
                             ORDER BY count DESC
                          """.format(table_to_use), self.cur)
        userlist = [x for x in self.cur.fetchall()]

        x_pos = 0
        y_pos = 0
        y_spacing = 20
        self.user_checkboxes = {}
        size_width = 220
        extent_width = size_width
        for userid, user, count in userlist:
            self.user_checkboxes[user] = CheckBox("{0} ({1})".format(user.replace('_', '_ '),
                                                                     count),
                                                  position = (x_pos, y_pos),
                                                  value = True)
            extent_width = max(self.user_checkboxes[user].size[0], extent_width)
            y_pos += y_spacing

        # Get users that didn't appear in the last partition, if @initial
        if initial:
            self.cur.execute("SELECT user, userid FROM users")
            for user, userid in self.cur.fetchall():
                if user in self.user_checkboxes:
                    continue
                self.user_checkboxes[user] = CheckBox(user.replace('_', '_ ') + " (0)",
                                                      position = (x_pos, y_pos),
                                                      value = True)
                extent_width = max(self.user_checkboxes[user].size[0], extent_width)
                y_pos += y_spacing

        # Add the user checkboxes to a ScrollableView:
        self.user_panel = ScrollableView(size = (size_width, 150),
                                         extent = (extent_width,
                                                   max(150, y_pos)),
                                         scrolling = 'v' if extent_width <= size_width else 'hv')
        for cbox in self.user_checkboxes.values():
            self.user_panel.add(cbox)
        # Add the panel to the window
        self.window.place(self.user_panel, top = top,
                          left = self.query_type_panel + horiz_sp)

        # Create server filter checkboxes
        print_and_execute("""SELECT serverid, server, count
                             FROM (SELECT serverid, COUNT(*) AS count
                                   FROM {0} GROUP BY serverid
                                  ) as sth
                               NATURAL JOIN servers
                             ORDER BY count DESC
                         """.format(table_to_use), self.cur)
        serverlist = [x for x in self.cur.fetchall()]

        x_pos = 0
        y_pos = 0
        y_spacing = 20
        self.server_checkboxes = {}
        size_width = 300
        extent_width = size_width
        for serverid, server, count in serverlist:
            self.server_checkboxes[server] = CheckBox("{0} ({1})".format(server,
                                                                         count),
                                                      position = (x_pos, y_pos),
                                                      value = True)
            extent_width = max(self.server_checkboxes[server].size[0], extent_width)
            y_pos += y_spacing

        if initial:
            self.cur.execute("SELECT server FROM servers")
            for server, in self.cur.fetchall():
                if server in self.server_checkboxes:
                    continue
                self.server_checkboxes[server] = CheckBox(server.replace('_', '_ ') + " (0)",
                                                          position = (x_pos, y_pos),
                                                          value = True)
                extent_width = max(self.server_checkboxes[server].size[0], extent_width)
                y_pos += y_spacing

        # Add the server checkboxes to a ScrollableView
        self.server_panel = ScrollableView(size = (size_width, 150),
                                           extent = (extent_width,
                                                     max(150, y_pos)),
                                           scrolling = 'v' if extent_width <= size_width else 'hv')
        for cbox in self.server_checkboxes.values():
            self.server_panel.add(cbox)
        # Add the server panel to the window
        self.window.place(self.server_panel, top = top,
                          left=self.user_panel + 10)


    def get_new_filter(self):
        """
        Set self.fil to a new Filter reflecting the current status of the
        GUI elements
        """

        # Get the status of GUI elements
        # TODO: support for one date field but not the other
        # (should be done mostly in Filter class)
        if self.begin_date_field.text \
           and self.begin_date_field.text != DEFAULT_BEGIN_DATE_TEXT \
           and self.end_date_field.text \
           and self.end_date_field.text != DEFAULT_END_DATE_TEXT:
            daterange = (datetime.strptime(self.begin_date_field.text,
                                           DATEFORMAT),
                         datetime.strptime(self.end_date_field.text,
                                           DATEFORMAT))
        else:
            daterange = None

        # User
        user = [self.userids[u] for u, cb in self.user_checkboxes.iteritems() \
                if cb.value]
        if len(user) == len(self.user_checkboxes): #all users selected
            user = None

        # Server
        server = [self.serverids[s] for s, cb in self.server_checkboxes.iteritems() \
                  if cb.value]
        if len(server) == len(self.server_checkboxes):
            server = None

        # Search String List
        search_string = SearchStringList(self.any_all_radiogroup.value)
        search_string.extend([fld.text for fld in self.search_string_fields \
                              if fld.text and not fld.text.startswith('Query Search String ')])

        # Query types
        query_type = [qtype for qtype, cb in self.query_type_checkboxes.iteritems() if cb.value]
        query_type = clean_list(query_type)
        if not query_type or len(query_type) == len(querytypes):
            #all types selected
            query_type = None

        # Create the filter object
        self.fil = Filter(daterange = daterange,
                          user = user,
                          server = server,
                          search_string = search_string,
                          query_type = query_type,
                          negate = self.negate.value)


    def refresh(self):
        """
        Regenerate the graphs/top query lists without changing the table that
        the tool pulls from
        """
        # Get the status of GUI elements
        self.get_new_filter()

        # Don't repeat the query if self.filter hasn't changed since the last
        # update
        if self.fil != self.last_used_fil:
            self.create_new_temp_table()
            self.create_new_graphs_and_topqueries()
        elif self.last_grouped_by != self.time_division_radiogroup.value:
            self.create_new_graphs_and_topqueries()
            

    def create_new_temp_table(self):
        # Create a temp table
        lasttable = self.current_table_name()
        nexttable = self.next_table_name()

        # Create main table
        self.cur.execute("DROP TABLE IF EXISTS {0}".format(nexttable))
        print_and_execute("CREATE TEMPORARY TABLE {0} AS {1}".format(nexttable,
                                                                     self.fil.sql(lasttable)),
                          self.cur)
        print_and_execute("ALTER TABLE {0} ADD INDEX (userid)".format(nexttable), self.cur)
        print_and_execute("ALTER TABLE {0} ADD INDEX (serverid)".format(nexttable), self.cur)

        self.last_used_fil = self.fil

    def create_new_graphs_and_topqueries(self):
        prefix = config.get('plot_dir') or 'plots'
        current_dir = os.getcwd()

        # Get profiles of the created table
        nexttable = self.next_table_name()
        
        profiles = query_profile(nexttable,
                                 config.get("numtop") or 200,
                                 self.time_division_radiogroup.value,
                                 self.cur)
        peruser_divided, peruser_alltime, full_divided, full_alltime, full_topqueries, peruser_topqueries = profiles

        # Remove previous plotted data
        if os.path.exists(prefix):
            os.system("rm -r {0}".format(prefix))
        os.mkdir(prefix)
        os.chdir(prefix)
        gnuplot(profiles, time_axis_label=self.time_division_radiogroup.value)
        # use a for loop so that gnuplot settings don't stick around between scripts
        os.system("for x in *.gnu; do gnuplot $x; done")

        # Load the new image lists
        self.full_ = [Image(file=x) for x in glob('full_*.png')]
        self.peruser_alltime_ = [Image(file=x) for x in \
                                 glob('peruser_alltime_*.png')]
        self.peruser_divided_ = [Image(file=x) for x in \
                                 glob('peruser_divided_*.png') if '_total_' not in x]
        self.peruser_divided_total_ = [Image(file=x) for x in \
                                       glob('peruser_divided_total_*.png')]
        
        os.chdir(current_dir)

        # Set self.image.images = whatever's selected in the radio
        # (we got new lists)
        self.change_images()

        # Generate the new topquery panel text
        self.topqueries.new_profiles(full_topqueries, peruser_topqueries)

        self.last_grouped_by = self.time_division_radiogroup.value


    def update(self):
        """
        Regenerate the graphs/top query lists, then change the table that the
        tool pulls from to the newly generated table. Update the lists of
        checkboxes.
        """

        self.refresh()

        if self.current_table_suffix:
            self.current_table_suffix += 1
        else:
            self.current_table_suffix = 1
        
        # update lists of checkboxes
        self.create_checkbox_lists()
        
        # reset status of GUI elements that weren't just recreated
        # self.begin_date_field.text = DEFAULT_BEGIN_DATE_TEXT
        # self.end_date_field.text = DEFAULT_END_DATE_TEXT
        # for cbox in self.query_type_checkboxes.values():
        #     cbox.value = True
        # for i, fld in enumerate(self.search_string_fields):
        #     fld.text = "Query Search String {0}".format(i + 1)


    def change_images(self):
        string = self.display_select_radiogroup.value
        if string == 'all_users':
            self.image.images = self.full_
        elif string == 'peruser_querytype':
            self.image.images = self.peruser_alltime_
        elif string == 'peruser_time':
            self.image.images = self.peruser_divided_total_
        elif string == 'peruser_querytype_time':
            self.image.images = self.peruser_divided_
        else:
            print >>sys.stderr, "Unrecognized display_select_radiogroup value %s" % string
        
        if not self.image.images:
            print >>sys.stderr, "image list assigned to self.image.images is None, using dummy"
            self.image.images = GraphView.DUMMY_IMLIST
        self.image.im_num = 0
        self.image.invalidate()

    def current_table_name(self):
        """
        Return the name of the table we are currently pulling from
        """
        if self.current_table_suffix:
            return "analysis_tool_temp" + str(self.current_table_suffix)
        return 'unified'


    def next_table_name(self):
        """
        Return the name of the table we should insert into
        """
        if self.current_table_suffix:
            return "analysis_tool_temp" + str(self.current_table_suffix + 1)
        else:
            return "analysis_tool_temp1"
        

    def select_all(self, what):
        """
        Set the value property of all checkboxes in the list to True

        @what must be one of 'user' or 'server'
        """
        if what == 'user':
            cboxes = self.user_checkboxes.values()
        elif what == 'server':
            cboxes = self.server_checkboxes.values()
        elif what == 'query_type':
            cboxes = self.query_type_checkboxes.values()
        else:
            print >>sys.stderr, "unrecognized thing to select all: %s" % what
            return

        for cbox in cboxes:
            cbox.value = True

    def deselect_all(self, what):
        """
        Set the value property of all checkboxes in the list to False

        @what must be one of 'user' or 'server'
        """
        if what == 'user':
            cboxes = self.user_checkboxes.values()
        elif what == 'server':
            cboxes = self.server_checkboxes.values()
        elif what == 'query_type':
            cboxes = self.query_type_checkboxes.values()
        else:
            print >>sys.stderr, "unrecognized thing to deselect all: %s" % what
            return

        for cbox in cboxes:
            cbox.value = False

    def invert_all(self, what):
        """
        Set the value property of all checkboxes in the list to its inverse

        @what must be one of 'user' or 'server'
        """
        if what == 'user':
            cboxes = self.user_checkboxes.values()
        elif what == 'server':
            cboxes = self.server_checkboxes.values()
        elif what == 'query_type':
            cboxes = self.query_type_checkboxes.values()
        else:
            print >>sys.stderr, "unrecognized thing to select all: %s" % what
            return

        for cbox in cboxes:
            cbox.value = not cbox.value


    def enable_all(self, what):
        """
        Enable all elements in the list
        
        @what must be one of 'user' or 'server' and the relevant
        checkboxes will be enabled
        """
        if what == 'user':
            elements = self.user_checkboxes.values()
        elif what == 'server':
            elements = self.server_checkboxes.values()
        elif what == 'query_type':
            elements = self.query_type_checkboxes.values()
        else:
            print >>sys.stderr, "unrecognized thing to enable all: %s" % what
            return

        for elem in elements:
            elem.enabled = True


    def disable_all(self, what):
        """
        Disable all elements inthe list

        @what must be one of 'user' or 'server' and the relevant
        checkboxes will be disabled
        """
        if what == 'user':
            elements = self.user_checkboxes.values()
        elif what == 'server':
            elements = self.server_checkboxes.values()
        elif what == 'query_type':
            elements = self.query_type_checkboxes.values()
        else:
            print >>sys.stderr, "unrecognized thing to disable all: %s" % what
            return

        for elem in elements:
            elem.enabled = False

    def select_all_matching(self, where):
        if where == 'user':
            elements = self.user_checkboxes
            search_string = self.user_search_string.text
        elif where == 'server':
            elements = self.server_checkboxes
            search_string = self.server_search_string.text
        else:
            print >>sys.stderr, "unrecognized thing select all matching: %s" % where
            return

        for text, cbox in elements.iteritems():
            if search_string in text:
                cbox.value = True
            else:
                cbox.value = False
            

    def change_topquery_ptr(self, how_much):
        """
        Changes the variable indicating which topquery view is to be selected
        And then updates self.topqueries.text
        """
        self.topquery_ptr += how_much
        self.topqueries.text = self.topquery_texts[self.topquery_ptr % len(self.topquery_texts)]


    def open_app(self):
        # Everything done in __init__()
        pass
Example #26
0
    def __init__(self):
        Application.__init__(self, title = "Log Analysis Tool")
        print >>sys.stderr, "app init'd"

        self.window = Window(size = (1200, 750), title = "Log Analysis Tool")
        print >>sys.stderr, "made window"

        # Create db cursor
        db = get_conn(dbname = 'reduced_log')
        self.cur = db.cursor()
        print >>sys.stderr, "made db cursor"

        self.current_table_suffix = None
        
        # Load the dummy image for now
        self.image = GraphView(size = (640, 460), position = (10, 10))
        self.graph_panel = Frame()
        self.graph_panel.add(self.image)
        print >>sys.stderr, "loaded dummy image"

        # Declare other image lists
        self.full_ = None
        self.peruser_alltime_ = None
        self.peruser_divided_total_ = None
        self.peruser_divided_ = None

        # Create the display selection radio
        self.display_select_radiogroup = RadioGroup(action = 
                                                    self.change_images)
        height, startx = 495, 20
        sp = 10
        r1 = RadioButton("All users",
                         group = self.display_select_radiogroup,
                         value = 'all_users')
        r2 = RadioButton("Per user, query type",
                         group = self.display_select_radiogroup,
                         value = 'peruser_querytype')
        r3 = RadioButton("Per user, time",
                         group = self.display_select_radiogroup,
                         value = 'peruser_time')
        r4 = RadioButton("Per user, query type and time",
                         group = self.display_select_radiogroup,
                         value = 'peruser_querytype_time')
        
        self.graph_panel.place(r1, top = self.image + 10, left = sp)
        self.graph_panel.place(r2, top = self.image + 10, left = r1 + sp)
        self.graph_panel.place(r3, top = self.image + 10, left = r2 + sp)
        self.graph_panel.place(r4, top = self.image + 10, left = r3 + sp)
        self.window.place(self.graph_panel, top=0, left=0)
        self.display_select_radiogroup.value = 'all_users'
        
        # Create the top queries textbox
        self.topqueries = TopqueryPanel(size = (500, 460),
                                        extent = (500, 1000))
        self.topqueries.panels = [[TopqueryLabel("This is a placeholder until you select a filter",
                                                ["This is where", "the values", "will go"])]]
        self.window.place(self.topqueries, top=10, left=680)

        topqueries_next_button = Button("Next", action = self.topqueries.next)
        topqueries_prev_button = Button("Prev", action = self.topqueries.prev)
        self.window.place(topqueries_next_button, left = 930, top = top - 50)
        self.window.place(topqueries_prev_button, left = 830, top = top - 50)
        print >>sys.stderr, "made top queries text box"

        # Declare the filter and last updated filter pointers
        self.fil = None
        self.last_used_fil = None
        
        #
        # *************************
        # FILTER PANEL
        # *************************
        #

        # **CREATE DATE PANEL**
        field_width = 140
        self.date_panel = Frame()
        self.begin_date_field = TextField(size = (field_width, 30),
                                          position = (0, 5),
                                          text = DEFAULT_BEGIN_DATE_TEXT)
        self.end_date_field = TextField(size = (field_width, 30),
                                        position = (0, 35),
                                        text = DEFAULT_END_DATE_TEXT)
        self.date_panel.size = (field_width, 0)

        # Time division radios
        self.time_division_radiogroup = RadioGroup()
        left, right = 5, 70
        row1, rowspace = 95, 25

        group_by_label = Label("Group by:",
                               position = (5, 70))
        hour = RadioButton("Hour",
                           position = (left, row1),
                           group = self.time_division_radiogroup,
                           value = 'hour')
        day = RadioButton("Day",
                          position = (right, row1),
                          group = self.time_division_radiogroup,
                          value = 'day')
        week = RadioButton('Week',
                           position = (left, row1 + rowspace),
                           group = self.time_division_radiogroup,
                           value = 'week',
                           enabled = False) #TODO: implement 'week' in the gnuplot function
        month = RadioButton("Month",
                            position = (right, row1 + rowspace),
                            group = self.time_division_radiogroup,
                            value = 'month')
        year = RadioButton("Year", 
                           position = (left, row1 + 2*rowspace),
                           group = self.time_division_radiogroup,
                           value = 'year')
        self.time_division_radiogroup.value = 'day'
        self.last_grouped_by = None

        # Add all to date panel
        self.date_panel.add([self.begin_date_field, self.end_date_field])
        self.date_panel.add([group_by_label, hour, day, week, month, year])
        self.window.place(self.date_panel, top=top, left=10)
        print >>sys.stderr, "made date panel"

        # **CREATE QUERY TYPE FILTER CHECKBOXES**
        x_pos = 0
        y_pos = 0
        y_spacing = 20
        self.query_type_checkboxes = {}
        for qtype in querytypes:
            # underscores don't display properly, need an extra space after
            self.query_type_checkboxes[qtype] = CheckBox(qtype.replace('_', '_ '),
                                                         position = (x_pos,
                                                                     y_pos),
                                                         value = True)
            y_pos += y_spacing


        # Add the query type checkboxes and buttons to a Frame
        self.query_type_panel = Frame()
        maxw = 0
        for cbox in self.query_type_checkboxes.values():
            self.query_type_panel.add(cbox)
            maxw = max(cbox.size[0], maxw)
        self.query_type_panel.size = (maxw, 0)

        # Create all/none/invert buttons for query types
        buttonsize = (55, 25)
        self.query_type_panel.add(Button("All",
                                         action = (self.select_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))
        y_pos += 25
        self.query_type_panel.add(Button("None",
                                         action = (self.deselect_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))
        y_pos += 25
        self.query_type_panel.add(Button("Invert",
                                         action = (self.invert_all,
                                                   'query_type'),
                                         size = buttonsize,
                                         position = (20, y_pos)))

        # Add query_type_panel to the window
        self.window.place(self.query_type_panel, top = top,
                          left=self.date_panel + horiz_sp)
        print >>sys.stderr, "made query type cboxes"


        # **CREATE USER AND SERVER CHECKBOX LISTS**
        self.user_panel = None
        self.server_panel = None
        self.create_checkbox_lists(initial=True)

        self.cur.execute("SELECT user, userid FROM users")
        self.userids = dict(self.cur.fetchall())
        self.cur.execute("SELECT server, serverid FROM servers")
        self.serverids = dict(self.cur.fetchall())

        print >>sys.stderr, "made user, server cboxes"


        # **CREATE QUERY SEARCH STRING PANEL**
        num_search_strings = 5
        spacing = 30
        field_width = 250
        self.search_string_panel = Frame()
        self.search_string_panel.size = (field_width, 0)
        self.search_string_fields = [TextField(size = (field_width, 30),
                                               position = (0, spacing * i),
                                               text = "Query Search String {0}".format(i + 1))
                                     for i in range(num_search_strings)]
        self.search_string_panel.add(self.search_string_fields)

        self.any_all_radiogroup = RadioGroup()
        any_string_radio = RadioButton("Any",
                                       position = (40, 10 + spacing * \
                                                   num_search_strings),
                                       group = self.any_all_radiogroup,
                                       value = 'any')
        all_strings_radio = RadioButton("All",
                                        position = (130, 10 + spacing * \
                                                    num_search_strings),
                                        group = self.any_all_radiogroup,
                                        value = 'all')
        no_string_radio = RadioButton("None",
                                      position = (40, 30 + spacing * \
                                                  num_search_strings),
                                      group = self.any_all_radiogroup,
                                      value = 'none')
        not_all_string_radio = RadioButton("Not All",
                                           position = (130, 30 + spacing * \
                                                       num_search_strings),
                                           group = self.any_all_radiogroup,
                                           value = 'not all')
        self.any_all_radiogroup.value = 'any'
        self.search_string_panel.add(any_string_radio)
        self.search_string_panel.add(all_strings_radio)
        self.search_string_panel.add(no_string_radio)
        self.search_string_panel.add(not_all_string_radio)
        self.window.place(self.search_string_panel, top = top,
                          left = self.server_panel + 10)
        print >>sys.stderr, "made search string panel"


        # SELECT ALL/NONE, INVERT USERS
        # TODO: create user, server panels? atm only the cboxes are in
        # a ScrollableView
        buttonsize = (55, 25)
        invertbuttonsize = (60, 25)
        userstart = 295
        serverstart = 565
        self.window.place(Button("All",
                                 action = (self.select_all,
                                           'user'),
                                 size = buttonsize),
                          top = top + 155, left = userstart)
        self.window.place(Button("None",
                                 action = (self.deselect_all,
                                           'user'),
                                 size = buttonsize),
                          top = top + 155, left = userstart + 55 + 5)
        self.window.place(Button("Invert",
                                 action = (self.invert_all,
                                           'user'),
                                 size = invertbuttonsize),
                          top = top + 155, left = userstart + 55 + 5 + 55 + 5)
    
        # user search string textbox
        # TODO: the action is always one keystroke behind the text field.
        # This is a PyGUI 'bug',but it may only happen on windows (not sure
        # how the X server works).
        # See http://mail.python.org/pipermail/pygui/2010-November/000102.html
        self.user_search_string = ResponsiveTextField(emptyaction = None,
                                                      action = (self.select_all_matching,
                                                                'user'),
                                                      size = (180, 30),
                                                      text = DEFAULT_USER_SEARCH_STRING)
        self.window.place(self.user_search_string,
                          top = top + 155 + 25 + 5,
                          left = userstart)

        # SELECT ALL/NONE, INVERT SERVERS
        self.window.place(Button("All",
                                 action = (self.select_all,
                                           'server'),
                                 size = buttonsize),
                          top = top + 155, left = serverstart)
        self.window.place(Button("None",
                                 action = (self.deselect_all,
                                           'server'),
                                 size = buttonsize),
                          top = top + 155, left = serverstart + 55 + 5)
        self.window.place(Button("Invert",
                                 action = (self.invert_all,
                                           'server'),
                                 size = invertbuttonsize),
                          top = top + 155,
                          left = serverstart + 55 + 5 + 55 + 5)

        # server search string textbox
        self.server_search_string = ResponsiveTextField(emptyaction = None,
                                                        action = (self.select_all_matching,
                                                                  'server'),
                                                        size = (180, 30),
                                                        text = DEFAULT_SERVER_SEARCH_STRING)
        self.window.place(self.server_search_string,
                          top = top + 155 + 25 + 5, left=serverstart)

        self.window.show()


        # **CREATE BUTTONS**
        self.negate = CheckBox("Negate Filter", position=(0, 0), value=False)
        self.refresh_button = Button("Refresh",
                                     position = (0, 25),
                                     action=self.refresh)
        self.update_button = Button("Update",
                                    position = (0, 60),
                                    action = self.update)
    
        # Add buttons to a panel
        self.button_panel = Frame()
        self.button_panel.add([self.negate,
                               self.refresh_button,
                               self.update_button])
        self.window.place(self.button_panel, top = top,
                          left=self.search_string_panel + horiz_sp)
        print >>sys.stderr, "made button panel"