Exemplo n.º 1
0
    def make_window(self, document):

        window_width = 800
        window_height = 600

        #create a Window object and associate it with our document
        #so when the window is closed the doc can ask the user if
        #he wants to save
        app_window = Window(size=(window_width, window_height),
                            document=document)

        #make a view for the window
        app_view = LineView(model=document,
                            extent=(window_width, window_height),
                            printable=False,
                            cursor=self.line_cursor)

        #place the view in the window, make it resizeable
        app_window.place(app_view,
                         left=0,
                         top=0,
                         right=0,
                         bottom=0,
                         sticky='nsew')

        #display the window when we are done initializing
        app_window.show()
Exemplo n.º 2
0
 def make_window(self, document):
     win = Window(size = (400, 400), document = document)
     view = AppView(model = document, extent = (1000, 1000), scrolling = 'hv', #menu_width = 50
         #cursor = self.app_cursor
         )
     win.place(view, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
     win.show()
Exemplo n.º 3
0
def test():
    view = GearsView(size=(300, 300))
    win = Window(title="Gears")
    win.place(view, sticky="nsew")
    view.become_target()
    win.shrink_wrap()
    win.show()
    application().run()
Exemplo n.º 4
0
 def make_window(self, document):
     win = Window(size=(400, 400), document=document)
     view = BlobView(model=document,
                     extent=(1000, 1000),
                     scrolling='hv',
                     cursor=self.blob_cursor)
     win.place(view, left=0, top=0, right=0, bottom=0, sticky='nsew')
     win.show()
def test():
    view = GearsView(size = (300, 300))
    win = Window(title = "Gears")
    win.place(view, sticky = "nsew")
    view.become_target()
    win.shrink_wrap()
    win.show()
    application().run()
Exemplo n.º 6
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()
Exemplo n.º 7
0
def main():
    global cb1, cb2, rg

    win = Window(title="Place Me By Your Side", width=720, height=500)

    view1 = TestDrawing(width=320, height=200)

    cb1 = CheckBox(title="Check Me!", action=checked_it)

    cb2 = CheckBox(title="Check Me Too!", action=checked_it)

    rbs = []
    for i in range(1, 4):
        rb = RadioButton(title="Hoopy Option %d" % i, value=i)
        rbs.append(rb)

    rg = RadioGroup(rbs, action=option_chosen)

    pb = Button(title="Push Me!", action=pushed_it)

    view2 = TestScrollableDrawing(width=300, height=300)

    label = Label(text="Flavour:")

    entry = TextField(width=200)

    win.place(view1, left=10, top=10, border=1)

    win.place_row([cb1, cb2], left=10, top=(view1, 20), spacing=20)

    win.place_column(rbs, left=view1 + 20, top=10)

    win.place(pb, right=-20, bottom=-10, anchor='rb')

    win.place(view2,
              left=rbs[0] + 20,
              top=10,
              right=-20,
              bottom=pb - 10,
              scrolling='hv',
              anchor='ltrb',
              border=1)

    win.place(label, left=10, top=(cb1, 20))

    win.place(
        entry,
        left=10,
        top=(label, 10),
        #border = 1
    )
    entry.become_target()

    win.show()

    import GUI
    GUI.run()
Exemplo n.º 8
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()
Exemplo n.º 9
0
def test():
    cursor = StdCursors.finger
    win = Window(title = "Cursor", width = 500, height = 400)
    view1 = TestDrawing(position = (20, 20), size = (100, 70), cursor = cursor)
    view2 = TestScrollableView(position = (140, 20), size = (200, 200),
        scrolling = 'hv')
    view2.cursor = cursor
    win.add(view1)
    win.place(view2, sticky = 'nsew')
    win.shrink_wrap((20, 20))
    win.show()
Exemplo n.º 10
0
def test():
    cursor = StdCursors.finger
    win = Window(title="Cursor", width=500, height=400)
    view1 = TestDrawing(position=(20, 20), size=(100, 70), cursor=cursor)
    view2 = TestScrollableView(position=(140, 20),
                               size=(200, 200),
                               scrolling='hv')
    view2.cursor = cursor
    win.add(view1)
    win.place(view2, sticky='nsew')
    win.shrink_wrap((20, 20))
    win.show()
Exemplo n.º 11
0
def make_view(db, options):
    pf = GLConfig(double_buffer=db)
    pf.alpha = "a" in options
    pf.depth_buffer = "d" in options
    pf.stencil_buffer = "s" in options
    pf.aux_buffers = "x" in options
    pf.accum_buffer = "A" in options
    view = TriangleView(pf, size=(200, 200))
    win = Window(title="%s Buffered GLView" % ["Single", "Double"][db],
                 size=(240, 240))
    win.place(view, left=20, top=20, sticky="nsew")
    view.become_target()
    win.show()
Exemplo n.º 12
0
def test():
    file = "grail_masked.tiff"
    # file = "spam_masked.tiff"
    image = Image(os.path.join(sys.path[0], file))
    cursor = Cursor(image)
    win = Window(title="Image Cursor", width=500, height=400)
    view1 = TestDrawing(position=(20, 20), size=(100, 70), cursor=cursor)
    view2 = TestScrollableView(position=(140, 20), size=(200, 200), scrolling="hv")
    view2.cursor = cursor
    win.add(view1)
    win.place(view2, sticky="nsew")
    win.shrink_wrap((20, 20))
    win.show()
Exemplo n.º 13
0
def test():
	def bing():
		say("Bing!")
		#fld._win_dump_flags()
	win = Window(title = "Shrink Wrap", resizable = 0)
	but = Button("Bing!", action = bing)
	cbx = CheckBox("Spam")
	fld = TextField(width = 100)
	win.place(but, left = 20, top = 20)
	win.place(cbx, left = but + 20, top = 20)
	win.place(fld, left = 20, top = but + 20)
	win.shrink_wrap()
	win.show()
	application().run()
Exemplo n.º 14
0
def make_view(db, options):
    pf = GLConfig(double_buffer = db)
    pf.alpha = "a" in options
    pf.depth_buffer = "d" in options
    pf.stencil_buffer = "s" in options
    pf.aux_buffers = "x" in options
    pf.accum_buffer = "A" in options
    view = TriangleView(pf, size = (200, 200))
    win = Window(
        title = "%s Buffered GLView" % ["Single", "Double"][db],
        size = (240, 240))
    win.place(view, left = 20, top = 20, sticky = "nsew")
    view.become_target()
    win.show()
Exemplo n.º 15
0
def test():
	file = "grail_masked.tiff"
	#file = "spam_masked.tiff"
	image = Image(os.path.join(sys.path[0], file))
	cursor = Cursor(image)
	win = Window(title = "Image Cursor", width = 500, height = 400)
	view1 = TestDrawing(position = (20, 20), size = (100, 70), cursor = cursor)
	view2 = TestScrollableView(position = (140, 20), size = (200, 200),
		scrolling = 'hv')
	view2.cursor = cursor
	win.add(view1)
	win.place(view2, sticky = 'nsew')
	win.shrink_wrap((20, 20))
	win.show()
Exemplo n.º 16
0
def test():
    def bing():
        say("Bing!")
        #fld._win_dump_flags()
    win = Window(title = "Shrink Wrap", resizable = 0)
    but = Button("Bing!", action = bing)
    cbx = CheckBox("Spam")
    fld = TextField(width = 100)
    win.place(but, left = 20, top = 20)
    win.place(cbx, left = but + 20, top = 20)
    win.place(fld, left = 20, top = but + 20)
    win.shrink_wrap()
    win.show()
    application().run()
Exemplo n.º 17
0
    def make_window(self, document):
        self.tabview = view = TabView()

        win = Window(size=(600, 400), document=document)

        self.view1 = Button(title='Item 1', action=self.item1Action)
        view.add_item(self.view1, title='asdfe')

        self.view2 = Button(title='Item 2', action=self.item2Action)
        view.add_item(self.view2, title="Two")

        win.place(view, left=0, top=0, right=0, bottom=0, sticky='nsew')

        win.show()
Exemplo n.º 18
0
def test():
    def select():
        i = group.value
        name = cursor_names[i]
        say("Selecting cursor no. %d (%s)" % (i, name))
        cursor = getattr(StdCursors, name)
        say("...", cursor)
        view.cursor = cursor
    win = Window(title = "Std Cursors")
    view = TestArea(size = (100, 100))
    win.place(view, left = 20, top = 20)
    group = RadioGroup(action = select)
    for i, name in enumerate(cursor_names):
        group.add_item(RadioButton(title = name, value = i))
    win.place_column(group, left = view + 20, top = 20, spacing = 0)
    win.shrink_wrap((20, 20))
    win.show()
    application().run()
Exemplo n.º 19
0
 def make_window(self, document):
     
     window_width = 800
     window_height = 600
     
     #create a Window object and associate it with our document 
     #so when the window is closed the doc can ask the user if
     #he wants to save
     app_window = Window(size = (window_width, window_height), document = document)
     
     #make a view for the window
     app_view = LineView(model = document, extent = (window_width, window_height), printable = False, cursor = self.line_cursor)
     
     #place the view in the window, make it resizeable
     app_window.place(app_view, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
     
     #display the window when we are done initializing
     app_window.show()
Exemplo n.º 20
0
    def open_soldier_chooser(self, blob, defender, x, y):
        win = Window(size=(220, 100), style='nonmodal_dialog')
        button = Button('Attack')
        text_field = TextField()
        button.style = 'normal'
        slider = Slider('h')

        def set_textfield():
            text_field.set_text(str(int(slider.get_value())))

        def start_conquering():
            winner = war(blob, defender, int(slider.get_value()))
            looser = blob if winner != blob else defender
            soldiers_left = int(slider.get_value() - (slider.max_value+1 - blob.get_soldiers()))
            conquer_territory(winner, looser, soldiers_left)
            self.model.set_blob_position(blob, x, y)
            print "Winner is: " + winner.territory.get_owner() + "!"
            win.destroy()

        if blob.get_soldiers() - 1 != 1:
            slider.max_value = blob.get_soldiers() - 1
            slider.min_value = 1
            slider.ticks = blob.get_soldiers() - 1
            slider.discrete = True
            slider.action = set_textfield
            button.action = start_conquering
            win.place(slider, left=0, top=10, right=220, bottom=50)
            win.place(button, left=15, top=50, right=55, bottom=90)
            win.place(text_field, left=170, top=50, right=210, bottom=70)
            win.show()
        else:
            winner = war(blob, defender, 1)
            looser = blob if winner != blob else defender
            soldiers_left = int(slider.get_value()) - (int(slider.max_value) - blob.get_soldiers())
            conquer_territory(winner, looser, soldiers_left)
            self.model.set_blob_position(blob, x, y)
            print "Winner is: " + winner.territory.get_owner() + "!"
Exemplo n.º 21
0
 def make_window(self, document):
     win = Window(size = (500, 500), document = document)
     view = BlobView(model = document, extent = (200, 200), scrolling = 'hv',cursor = self.blob_cursor)
     win.place(view, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
     win.show()
Exemplo n.º 22
0
                if button == Mouse.Right:
                    self.xxmin, self.xxmax = self.gwidget.zoomout(
                        self.xxmin, self.xxmax, self._xmin, self._xmax)
                    self.yymin, self.yymax = self.gwidget.zoomout(
                        self.yymin, self.yymax, self._ymin, self._ymax)
                else:
                    self.xxmin, self.xxmax, self.yymin, self.yymax = self._xmin, self._xmax, self._ymin, self._ymax
                self.gwidget.zoom(self.xxmin, self.xxmax, self.yymin,
                                  self.yymax)

                self.gwidget.make_data_list()
                self.gwidget.updateGL()
            self.px, self.py = None, None


##############################################################################
view = GLGraphWidget(size=(300, 300))
win = Window(title="Gears")
win.place(view, sticky="nsew")
view.become_target()
win.shrink_wrap()
win.show()

application().run()

#    app=QApplication(sys.argv)
#    g = glGraph()
#    app.setMainWidget(g.win)
#    g.win.show()
#    app.exec_loop()
Exemplo n.º 23
0
 def make_window(self):
     win = Window(size=(400, 400))
     tex = CodeEditor()
     win.place(tex, left=0, top=0, right=0, bottom=0, sticky="nesw")
     win.show()
Exemplo n.º 24
0
    dlog.place(Label(text = "Surprise!!!"), left = 20, top = 20)
    field = TextField()
    dlog.place(field, left = 20, top = 60, right = -20)
    field.become_target()
    dlog.default_button = DefaultButton()
    dlog.cancel_button = CancelButton()
    dlog.place(dlog.default_button, right = -20, bottom = -20)
    dlog.place(dlog.cancel_button, left = 20, bottom = -20)
    dlog.center()
    result = dlog.present()
    say("Result =", result)
    dlog.destroy()

win = Window(title = "Modal Dialogs", size = (200, 60))
dialog_button = Button(title = "Give Me A Dialog", action = modal_dialog)
win.place(dialog_button, left = 20, top = 20)
win.show()

instructions = """
Clicking the "Give Me A Dialog" button should pop up a modal
dialog centered on the screen, containing a label, a text
field, an OK button and a Cancel button.

While the dialog is up:
* Interaction with the main window should be prevented.
* Edit menu commands should be enabled as appropriate for the
  text field; other menu commands should be disabled.

Clicking the OK button or pressing Return or Enter should
dismiss the dialog and report "Result = True".
Exemplo n.º 25
0
    field = TextField()
    dlog.place(field, left=20, top=60, right=-20)
    field.become_target()
    dlog.default_button = DefaultButton()
    dlog.cancel_button = CancelButton()
    dlog.place(dlog.default_button, right=-20, bottom=-20)
    dlog.place(dlog.cancel_button, left=20, bottom=-20)
    dlog.center()
    result = dlog.present()
    say("Result =", result)
    dlog.destroy()


win = Window(title="Modal Dialogs", size=(200, 60))
dialog_button = Button(title="Give Me A Dialog", action=modal_dialog)
win.place(dialog_button, left=20, top=20)
win.show()

instructions = """
Clicking the "Give Me A Dialog" button should pop up a modal
dialog centered on the screen, containing a label, a text
field, an OK button and a Cancel button.

While the dialog is up:
* Interaction with the main window should be prevented.
* Edit menu commands should be enabled as appropriate for the
  text field; other menu commands should be disabled.

Clicking the OK button or pressing Return or Enter should
dismiss the dialog and report "Result = True".
Exemplo n.º 26
0
 def make_window(self, document):
     win = Window(size = (400, 400), document = document)
     view = BlobView(model = document, extent = (1000, 1000), scrolling = 'hv')
     win.place(view, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
     win.show()
Exemplo n.º 27
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()
Exemplo n.º 28
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
Exemplo n.º 29
0
 def make_window(self):
     win = Window(size=(400, 400))
     tex = CodeEditor()
     win.place(tex, left=0, top=0, right=0, bottom=0, sticky='nesw')
     win.show()