class App:
	def __init__(self,parent):
		# Create frame, buttons, etc
		self.f = Frame(parent)
		self.f.pack(padx=15,pady=15)
    
   		self.entry = Entry(self.f,text="Enter the search term")
		self.entry.pack(side= TOP,padx=10,pady=12)
		self.entry.bind("<Key>", self.key)
		self.entry.focus_set()
		
		self.exit = Button(self.f, text="Exit", command=self.f.quit)
		self.exit.pack(side=BOTTOM,padx=10,pady=10)

		self.button = Button(self.f, text="Search",command=self.search)
		self.button.pack(side=BOTTOM,padx=10,pady=10)

	def key(self, event):
		# If ENTER was pressed, search
		if event.char == '\r':
			self.search()

	def search(self):
		# If there's something to search, search!
		if self.entry.get() != '':
			self.button.config(text='Searching...', state=DISABLED)

			th = SearchThread(self, self.entry.get())
			th.start()
		else:
			tkMessageBox.showinfo('Hey', 'You should type something in the search. That\'s the point, really...')
示例#2
0
    def createToolbar( self ):
        "Create and return our toolbar frame."

        toolbar = Frame( self )

        # Tools
        for tool in self.tools:
            cmd = ( lambda t=tool: self.activate( t ) )
            b = Button( toolbar, text=tool, font=self.smallFont, command=cmd)
            if tool in self.images:
                b.config( height=35, image=self.images[ tool ] )
                # b.config( compound='top' )
            b.pack( fill='x' )
            self.buttons[ tool ] = b
        self.activate( self.tools[ 0 ] )

        # Spacer
        Label( toolbar, text='' ).pack()

        # Commands
        for cmd, color in [ ( 'Stop', 'darkRed' ), ( 'Run', 'darkGreen' ) ]:
            doCmd = getattr( self, 'do' + cmd )
            b = Button( toolbar, text=cmd, font=self.smallFont,
                        fg=color, command=doCmd )
            b.pack( fill='x', side='bottom' )

        return toolbar
示例#3
0
 def test_dimensions(self):
     button = Tkbutton(self.frame,text="dsds")
     button.config(height=5,width=5)
     button.pack(side=LEFT)   
     button = Tkbutton(self.frame,height = 1,width=4)
     button.pack(side=LEFT)    
     button = Tkbutton(self.frame,height = 3,width=10)
     button.pack(side=LEFT)    
class UsernameOverlay(Overlay):
    def __init__(self, *args, **kwargs):
        Overlay.__init__(self, *args, **kwargs)
        self.label = ""
        self.field = ""
        self.button = ""
        self.user = ""
        self.logger = JPYLogger(self)
        self.config(
            background="gold",
            cursor="arrow"
        )

        self.renderLabel()
        self.renderField()
        self.renderButton()

    def renderLabel(self):
        self.label = Label(self)
        self.label.config(
            text="CHANGE PLAYERNAME",
            font=Fonts.MONEY_BIG,
            background="gold"
        )
        self.label.pack()

    def renderField(self):
        self.field = Entry(self)
        self.field.config(
            relief="solid",
            bd=2,
            highlightcolor="black",
            font=Fonts.USER_LABEL_NAME_BIG
        )
        self.field.pack()

    def renderButton(self):
        Label(self, text='\n', background="gold").pack()
        self.button = Button(self)
        self.button.config(
            text="OK",
            relief="solid",
            background="black",
            foreground="gold",
            font=Fonts.MONEY_MEDIUM,
            command=self.save
        )
        self.button.pack()

    def save(self):
        self.logger.prompt("User " + str(self.user.id) + " changed name from '" + self.user.name.get() + "' to '" + self.field.get() + "'")
        self.user.name.set(self.field.get())
        self.hide(self)
        self.root.root.inputController.blockBuzzer = False

    def insert(self, user):
        self.field.delete(0, END)
        self.field.insert(0, user.name.get())
示例#5
0
class SendGCode(LabelFrame):
	def __init__(self, root, prtr, settings, log, *arg):
		LabelFrame.__init__(self, root, *arg, text="Send gcode")
		self.app = root
		self.printer = prtr
		self.settings = settings
		self.log = log

		self.entry = Entry(self, width=50)
		self.entry.grid(row=1, column=1, columnspan=3, sticky=N+E+W)
		
		self.bSend = Button(self, text="Send", width=4, command=self.doSend, state=DISABLED)
		self.bSend.grid(row=1, column=4, padx=2)
		
		self.entry.delete(0, END)
		
		self.entry.bind('<Return>', self.hitEnter)
		self.gcv = StringVar(self)
		
		gclist = gcoderef.gcKeys()
		self.gcv.set(gclist[0])

		l = Label(self, text="G Code Reference:", justify=LEFT)
		l.grid(row=2, column=1, columnspan=2, sticky=W)

		self.gcm = Combobox(self, textvariable=self.gcv)
		self.gcm['values'] = gclist
		self.gcm.grid(row=2, column=3, padx=2)
		
		self.gcm.bind('<<ComboboxSelected>>', self.gcodeSel)
		
		#self.bInfo = Button(self, text="Info", width=9, command=self.doInfo)
		#self.bInfo.grid(row=2, column=4, padx=2)
		
	#def doInfo(self):
	def gcodeSel(self, *arg):
		verb = self.gcv.get()
		self.log.logMsg("%s: %s" % (verb, gcoderef.gcText(verb)))
		
	def activate(self, flag):
		if flag:
			self.bSend.config(state=NORMAL)
		else:
			self.bSend.config(state=DISABLED)
			
	def hitEnter(self, e):
		self.doSend()
		
	def doSend(self): 
		cmd = self.entry.get()
		verb = cmd.split()[0]
		
		if self.app.printerAvailable(cmd=verb):
			self.log.logMsg("Sending: %s" % cmd)
			self.printer.send_now(cmd)
class SamplerFrame(InstrumentFrame):
    def __init__(self, master, instrument):
        InstrumentFrame.__init__(self, master, instrument, text_label="")

        file_name = os.path.basename(self.instrument.filename)
        self.load_file_button = Button(self, text=file_name, command=self.load_file, width=_FILE_BUTTON_WIDTH)
        self.load_file_button.grid(row=0, column=1)

    def load_file(self):
        file_path = tkFileDialog.askopenfile(filetypes=[("audio files", ".wav")])
        if file_path:
            file_name = os.path.basename(file_path.name)
            self.instrument.load_file(file_path.name)
            self.load_file_button.config(text=file_name)
示例#7
0
文件: Chess.py 项目: LilCheabs/Chess
 def new_piece_gui(self, row, col, color):
     if color == "DimGray":
         queen = self.white_pieces[3]
         rook = self.white_pieces[0]
         bishop = self.white_pieces[2]
         knight = self.white_pieces[1]
     else:
         queen = self.black_pieces[3]
         rook = self.black_pieces[0]
         bishop = self.black_pieces[2]
         knight = self.black_pieces[1]
         
     self.piece_window = Toplevel()
     self.piece_window.title("Pick Your Piece")
     queen_label = Label(self.piece_window, text="Queen")
     rook_label = Label(self.piece_window, text="Rook")
     bishop_label = Label(self.piece_window, text="Bishop")
     knight_label = Label(self.piece_window, text="Knight")
     queen_label.grid(row=0, column=0, pady=10, padx=20)
     rook_label.grid(row=1, column=0, pady=10, padx=20)
     bishop_label.grid(row=2, column=0, pady=10, padx=20)
     knight_label.grid(row=3, column=0, pady=10, padx=20)
     queen_button = Button(self.piece_window, image=queen, width=144, height=90, bg="white")
     rook_button = Button(self.piece_window, image=rook, width=144, height=90, bg="black")
     bishop_button = Button(self.piece_window, image=bishop, width=144, height=90, bg="white")
     knight_button = Button(self.piece_window, image=knight, width=144, height=90, bg="black")
     queen_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_queen(i, j, k))
     rook_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_rook(i, j, k))
     bishop_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_bishop(i, j, k))
     knight_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_knight(i, j, k))
     queen_button.grid(row=0, column=1)
     rook_button.grid(row=1, column=1)
     bishop_button.grid(row=2, column=1)
     knight_button.grid(row=3, column=1)
示例#8
0
    def test_image(self):
        
        photo = PhotoImage(file="../scripts/buildgifs/8:30-9:10-270-68-68-rgb(97,91,92).gif")
        font = tkFont.Font(family="Monospace", size=20)   
        # slant=tkFont.ITALIC
        # weight=tkFont.BOLD

        mycolor = '#%02x%02x%02x' % (97, 91, 92) # #615b5c

        
        print mycolor
        self.master.grid()
        button = Tkbutton(self.master)
        button = Tklabel(self.master)
        button.config(image=photo,width="100",height="100",bg=mycolor)
        button.grid()
        #button.pack(side=LEFT, fill=BOTH,expand=1)
        self.master.mainloop()
示例#9
0
class SaveClassifiedImage(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        
        self.parent = parent
        self.classified_img = None
        
        self.save_button = Button(self, text = 'Save classified image', 
                                  relief = 'raised', width = 23,
                                  command=self._save_classified_image,
                                  state = 'disabled')
        self.save_button.pack()
        
    def set_classified_image(self, classified_img):
        self.classified_img = classified_img
        self.save_button.config(state = 'normal')
        
    def _save_classified_image(self):
        save_image_file(self, self.classified_img)
示例#10
0
    def __init__(self, notification_manager, builder, index, x, y, h, v, padx, pady, background=None, on_hide=None):
        Toplevel.__init__(self)
        
        self._notification_manager = notification_manager

        self.index = index
        self.on_hide = on_hide

        # Removes the native window boarder.
        self.overrideredirect(True)

        # Disables resizing of the widget.
        self.resizable(False, False)

        # Places window above all other windows in the window stack.
        self.wm_attributes("-topmost", True)

        notification_frame = Frame(self)
        notification_frame.pack(expand=True, fill=BOTH, padx=padx, pady=pady)

        top_row = Frame(notification_frame)
        top_row.pack(fill=X)
        
        if not hasattr(notification_manager, "_close_icon"):
            notification_manager._close_icon = PhotoImage(data="R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw==")

        close_button = Button(top_row, image=notification_manager._close_icon, highlightthickness=0, borderwidth=0, command=self.close)
        close_button.pack(side=RIGHT, anchor=E)

        self.interior = Frame(notification_frame)
        self.interior.pack(expand=True, fill=BOTH)

        if builder:
            builder(self.interior)
        
        if background is not None:
            top_row.config(background=background)
            notification_frame.config(background=background)
            self.config(background=background)
            self.interior.config(background=background)
            close_button.config(background=background)
            
        self.place(x,y, h, v)
示例#11
0
 def __init__(self,parent,labels,disablesorting=0,**kw):
     Frame.__init__(self,parent)
     self.labels=labels
     self.lists=[]
     self.disablesorting=disablesorting
     kw["exportselection"]=0
     for i in range(len(labels)):
         b=Button(self,text=labels[i],anchor=W,height=1,pady=0)
         b.config(command=lambda s=self,i=i:s.setSort(i))
         b.grid(column=i,row=0,sticky=N+E+W)
         box=apply(Listbox,(self,),kw)
         box.grid(column=i,row=1,sticky=N+E+S+W)
         self.lists.append(box)
     grid_setexpand(self)
     self.rowconfigure(0,weight=0)
     self._callall("bind",'<Button-1>',self.Button1)
     self._callall("bind",'<B1-Motion>',self.Button1)
     self.bind('<Up>',self.UpKey)
     self.bind('<Down>',self.DownKey)
     self.sort=None
示例#12
0
    def display(self, frame_obj):

        canvas_popup = Canvas(frame_obj, background=conf.left_nav_background)
        # canvas_popup.config(x=0, y=0)
        canvas_popup.place(x=(frame_obj.sw/2), y=(frame_obj.sh/2)-100)

        if self.title != "":
            title_label = Label(canvas_popup, text=self.title, fg=conf.main_text_color)
            title_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            title_label.grid(row=0, sticky='e,w', padx=10, pady=10)

        if self.content != "":
            content_label = Label(canvas_popup, text=self.content, fg=conf.main_text_color)
            content_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            content_label.grid(row=1, sticky='e,w', padx=10, pady=10)

        if self.content != "":
            action_button = Button(canvas_popup, text="Ok", fg=conf.main_text_color)
            action_button.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            action_button.bind("<Button-1>", self.dismiss)
            action_button.grid(row=2, sticky='e,w', padx=10, pady=10)
示例#13
0
class haltface(Frame):

    def __init__(self, x):
        Frame.__init__(self, x)
        self.config(relief=GROOVE)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10) 
        
        self.config(borderwidth=2)

        self.HALTbutton = Button(self)
        self.HALTbutton.config(text = "HALT")
        self.HALTbutton.config(fg = "red")
        self.HALTbutton.config(command =  self.quit)
        self.HALTbutton.grid(row=0, column=0, sticky="wens")

        self.pack()
示例#14
0
class RealtimeVisualiser(Visualiser):
    """A VTK-powered realtime visualiser which runs in its own thread.
    In addition to the functions provided by the standard visualiser,
    the following additional functions are provided:

    update() - Sync the visualiser to the current state of the model.
    Should be called inside the evolve loop.

    evolveFinished() - Clean up synchronisation constructs that tie the
    visualiser to the evolve loop. Call this after the evolve loop finishes
    to ensure a clean shutdown.
    """
    def __init__(self, source):
        """The source parameter is assumed to be a Domain.
        """
        Visualiser.__init__(self, source)

        self.running = True

        self.xmin = None
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.zmin = None
        self.zmax = None

        # Synchronisation Constructs
        self.sync_idle = Event()
        self.sync_idle.clear()
        self.sync_unpaused = Event()
        self.sync_unpaused.set()
        self.sync_redrawReady = Event()
        self.sync_redrawReady.clear()
        
    def setup_grid(self):
        self.vtk_cells = vtkCellArray()
        triangles = self.source.get_triangles()
        N_tri = len(self.source)
        verticies = self.source.get_vertex_coordinates()
        N_vert = len(verticies)

        # Also build vert_index - a list of the x & y values of each vertex
        self.vert_index = num.zeros((N_vert,2), num.float)
        for n in range(N_tri):
            self.vtk_cells.InsertNextCell(3)
            for v in range(3):
                self.vert_index[n * 3 + v] = verticies[n * 3 + v]
                self.vtk_cells.InsertCellPoint(n * 3 + v)

    def update_height_quantity(self, quantityName, dynamic=True):
        N_vert = len(self.source.get_vertex_coordinates())
        qty_index = num.zeros(N_vert, num.float)
        triangles = self.source.get_triangles()
        vertex_values, _ = self.source.get_quantity(quantityName).get_vertex_values(xy=False, smooth=False)

        
        for n in range(N_vert):
            qty_index[n] = vertex_values[n]

        points = vtkPoints()
        for v in range(N_vert):
            points.InsertNextPoint(self.vert_index[v][0],
                                   self.vert_index[v][1],
                                   qty_index[v] * self.height_zScales[quantityName]
                                   + self.height_offset[quantityName])
            if self.xmin == None or self.xmin > self.vert_index[v][0]:
                self.xmin = self.vert_index[v][0]
            if self.xmax == None or self.xmax < self.vert_index[v][0]:
                self.xmax = self.vert_index[v][0]
            if self.ymin == None or self.ymin > self.vert_index[v][1]:
                self.ymin = self.vert_index[v][1]
            if self.ymax == None or self.ymax < self.vert_index[v][1]:
                self.ymax = self.vert_index[v][1]
            if self.zmin == None or self.zmin > qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]:
                self.zmin = qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]
            if self.zmax == None or self.zmax < qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]:
                self.zmax = qty_index[v] * self.height_zScales[quantityName] + self.height_offset[quantityName]

        polydata = self.vtk_polyData[quantityName] = vtkPolyData()
        polydata.SetPoints(points)
        polydata.SetPolys(self.vtk_cells)

    def get_3d_bounds(self):
        return [self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax]
        
    def build_quantity_dict(self):
        triangles = self.source.get_triangles()
        quantities = {}
        for q in self.source.get_quantity_names():
            #quantities[q], _ = self.source.get_quantity(q).get_vertex_values(xy=False)
            quantities[q]  = self.source.get_quantity(q).vertex_values.flatten()
        return quantities

    def setup_gui(self):
        Visualiser.setup_gui(self)
        self.tk_pauseResume = Button(self.tk_controlFrame, text="Pause", command=self.pauseResume)
        self.tk_pauseResume.grid(row=1, column=0, sticky=E+W)

    def pauseResume(self):
        if self.sync_unpaused.isSet():
            self.sync_unpaused.clear()
            self.tk_pauseResume.config(text="Resume")
        else:
            self.sync_unpaused.set()
            self.tk_pauseResume.config(text="Pause")

    def shutdown(self):
        Visualiser.shutdown(self)
        self.running = False
        self.sync_idle.set()
        self.sync_unpaused.set()

    def redraw(self):
        if self.running and self.sync_unpaused.isSet():
            self.sync_redrawReady.wait()
            self.sync_redrawReady.clear()
            self.redraw_quantities()
            self.sync_idle.set()
        Visualiser.redraw(self)

    def update(self,pause=False):
        """Sync the visualiser to the domain. Call this in the evolve loop."""
            
        if self.running:
            self.sync_redrawReady.set()
            self.sync_idle.wait()
            self.sync_idle.clear()
            self.sync_unpaused.wait()

        if pause and self.running:
            if self.sync_unpaused.isSet():
                self.sync_unpaused.clear()
                self.tk_pauseResume.config(text="Resume")
                
                self.sync_redrawReady.set()
                self.sync_idle.wait()
                self.sync_idle.clear()
                self.sync_unpaused.wait()
            
        return self.running

    def evolveFinished(self):
        """Stop the visualiser from waiting on signals from the evolve loop.
        Call this just after the evolve loop to ensure a clean shutdown."""
        self.running = False
        self.sync_redrawReady.set()
示例#15
0
class ChargenColor:
    def __init__(self, parent):
        self.colorNegative = []
        self.colorNeutral = []
        self.colorPositive = []

        self.scaleNegative = 0.0
        self.scalePositive = 0.0

        self.cNegative = '#ff0000'
        self.cNeutral = '#000000'
        self.cPositive = '#0000ff'

        self.minNegativeLbl = Label(rootC, text='Min Found: -')
        self.maxPositiveLbl = Label(rootC, text='Max Found: -')

        self.scaleLbl = Label(rootC, text='Scale: - to -')

        self.sclSelectPositive = Spinbox(rootC)
        self.sclSelectPositive.insert(0, 0.0)
        self.sclSelectNegative = Spinbox(rootC)
        self.sclSelectNegative.insert(0, 0.0)

        self.buttonNegativeCharge = Button(
            rootC, text='Negative Charge Color', command=self.chooseNegativeCharge)
        self.buttonNeutralCharge = Button(
            rootC, text='Neutral Charge Color', command=self.chooseNeutralCharge)
        self.buttonPositiveCharge = Button(
            rootC, text='Positive Charge Color', command=self.choosePositiveCharge)
        self.buttonBG = Button(
            rootC, text='Background Color', command=self.chooseBackground)

        self.buttonUpdateColor = Button(
            rootC, text='Update', command=self.updateColor)

        self.title = Label(rootC, text="Select your colors")
        self.buttonClose = Button(rootC, text="Close", command=rootC.destroy)

        self.buttonBG.pack()
        self.title.pack()
        self.buttonNegativeCharge.pack()
        self.buttonNeutralCharge.pack()
        self.buttonPositiveCharge.pack()
        self.minNegativeLbl.pack()
        self.maxPositiveLbl.pack()
        self.scaleLbl.pack()
        self.sclSelectNegative.pack()
        self.sclSelectPositive.pack()
        self.buttonUpdateColor.pack()
        self.buttonClose.pack()

    def chooseNegativeCharge(self):
        self.colorNegative = askcolor(
            color=self.cNegative, title="Negative Charge Color")
        self.buttonNegativeCharge.config(fg=self.colorNegative[1])
        self.cNegative = self.colorNegative[1]

    def chooseNeutralCharge(self):
        self.colorNeutral = askcolor(
            color=self.cNeutral, title="Neutral Charge Color")
        self.buttonNeutralCharge.config(fg=self.colorNeutral[1])
        self.cNeutral = self.colorNeutral[1]

    def choosePositiveCharge(self):
        self.colorPositive = askcolor(
            color=self.cPositive, title="Positive Charge Color")
        self.buttonPositiveCharge.config(fg=self.colorPositive[1])
        self.cPositive = self.colorPositive[1]

    def chooseBackground(self):
        bgcolor = askcolor(
            color=self.cPositive, title="Positive Charge Color")
        cmd.set_color("bg_chargy_color", bgcolor[0])
        cmd.bg_color("bg_chargy_color")

    def updateColor(self):
        selection = 'all'
        stored.atoms_charge = []
        stored.atoms_colors = []
        cmd.map_new('chargyc_map', selection="(all)")

        if not self.colorNeutral:
            tkMessageBox.showerror("Error", "Set Neutral Color, Please")
            return
        if not self.colorNegative:
            tkMessageBox.showerror("Error", "Set Negative Color, Please")
            return
        if not self.colorPositive:
            tkMessageBox.showerror("Error", "Set Positive Color, Please")
            return

        cmd.iterate_state(1, '(' + selection + ')',
                          'stored.atoms_charge.append(partial_charge)')

        _i = 0
        minValue = None
        maxValue = None
        while _i < len(stored.atoms_charge):
            color = []
            if _i == 0:
                maxValue = stored.atoms_charge[_i]
                minValue = stored.atoms_charge[_i]

            if(stored.atoms_charge[_i] > maxValue):
                maxValue = stored.atoms_charge[_i]
            if stored.atoms_charge[_i] < minValue:
                minValue = stored.atoms_charge[_i]
            _i += 1

        self.minNegativeLbl["text"] = 'Min Found: ' + str(round(minValue, 3))
        self.maxPositiveLbl["text"] = 'Max Found: ' + str(round(maxValue, 3))

        if(self.scaleNegative == 0.0 and self.scalePositive == 0.0):
            self.scaleNegative = round(minValue, 3)
            self.scalePositive = round(maxValue, 3)
            self.sclSelectNegative.delete(0, "end")
            self.sclSelectPositive.delete(0, "end")
            self.sclSelectNegative.insert(0, round(minValue, 3))
            self.sclSelectPositive.insert(0, round(maxValue, 3))
        else:
            self.scaleNegative = float(self.sclSelectNegative.get())
            self.scalePositive = float(self.sclSelectPositive.get())
            minValue = float(self.sclSelectNegative.get())
            maxValue = float(self.sclSelectPositive.get())

        self.scaleLbl["text"] = 'Scale: ' + str(
            self.scaleNegative) + ' to ' + str(self.scalePositive)

        middleValue = 0
        if(maxValue < 0):
            maxValue = 0
        if(minValue > 0):
            minValue = 0

        _i = 0
        while _i < len(stored.atoms_charge):
            color = []
            cmd.set_color("neutral_color", self.colorNeutral[0])
            cmd.set_color("positive_color", self.colorPositive[0])
            cmd.set_color("negative_color", self.colorNegative[0])
            if(stored.atoms_charge[_i] >= middleValue):
                if(stored.atoms_charge[_i] == middleValue):
                    cmd.set_color(str(_i) + "_color", self.colorNeutral[0])
                else:
                    cmd.set_color(str(_i) + "_color", self.getColor(
                        self.colorNeutral[0], self.colorPositive[0], maxValue, stored.atoms_charge[_i] if stored.atoms_charge[_i] < maxValue else maxValue))
            else:
                cmd.set_color(str(_i) + "_color", self.getColor(
                    self.colorNeutral[0], self.colorNegative[0], abs(minValue), abs(stored.atoms_charge[_i]) if abs(stored.atoms_charge[_i]) < abs(minValue) else abs(minValue)))

            index = cmd.get_color_index(str(_i) + "_color")
            stored.atoms_colors.append(index)
            _i += 1

        cmd.alter_state(1, '(' + selection + ')',
                        "color=stored.atoms_colors.pop(0)")
        cmd.ramp_new('chargy_ramp', 'chargyc_map', range=[self.scaleNegative, ((self.scaleNegative+self.scalePositive)/2.0), self.scalePositive],
                     color=['negative_color', 'neutral_color', 'positive_color'])

    def getColor(self, color, colorMax, step, index):
        colorStep = [0, 0, 0]

        colorStep[0] = ((colorMax[0]-color[0])/step)
        colorStep[1] = ((colorMax[1]-color[1])/step)
        colorStep[2] = ((colorMax[2]-color[2])/step)

        return [
            1.0 if (color[0] + (colorStep[0]*index)) /
            255.0 >= 1 else (color[0] + (colorStep[0]*index))/255.0,
            1.0 if (color[1] + (colorStep[1]*index)) /
            255.0 >= 1 else (color[1] + (colorStep[1]*index))/255.0,
            1.0 if (color[2] + (colorStep[2]*index)) /
            255.0 >= 1 else (color[2] + (colorStep[2]*index))/255.0
        ]
示例#16
0
class IntroView(Frame):
    def __init__(self, controller, parent):     # formerly init_intro_nav():

        '''     using class objects for all these vars now
        global intro_nav, background_frame, can, button_load_game\
            , button_new_game, button_quit, intro_fill_bottom\
            , label_version, title_image_res\
            , intro_top_padding, intro_btm_padding
        '''

        self.controller = controller
        self.parent = parent
        self.app = self.controller.app

        # declare vars

        self.background_frame = 0
        self.intro_nav = 0
        self.intro_top_padding = 0

    def build(self):        # prev: build_intro_nav

        # frame setup
        conf = self.app.conf

        self.background_frame = Frame(self.parent, height=self.parent.sh, width=self.parent.sw
                                      , background=conf.window_background)
        self.intro_nav = Frame(self.background_frame, height=500, width=500
                               , background=conf.intro_background)

        # elements

        self.intro_top_padding = Canvas(self.intro_nav)
        self.intro_top_padding.configure(height=conf.intro_padding_height
                                         , background=conf.intro_background
                                         , highlightbackground=conf.intro_background)

        self.title_image_resource = Image.open(conf.title_image_path)
        self.title_image_res = ImageTk.PhotoImage(self.title_image_resource)
        self.can = Canvas(self.intro_nav, background=conf.intro_background
                          , highlightbackground=conf.intro_background)
        self.can.title_image_res = self.title_image_res
        self.can.config(width=self.title_image_res.width(), height=self.title_image_res.height())

        self.button_new_game = Button(self.intro_nav, text="New Game"
                                      , command=self.controller.event_button_new_game
                                      , bg=conf.intro_background)
        self.button_new_game.config(highlightbackground=conf.intro_background)

        self.button_load_game = Button(self.intro_nav, text="Load Game"
                                       , command=self.controller.event_button_load_game
                                       , bg=conf.intro_background)
        self.button_load_game.config(highlightbackground=conf.intro_background)
        self.button_load_game.config(state='disabled')

        self.button_quit = Button(self.intro_nav, text="Quit"
                                  , command=self.controller.event_button_quit
                                  , bg=conf.intro_background)
        self.button_quit.config(highlightbackground=conf.intro_background)

        self.label_version = Label(self.intro_nav, bg=conf.intro_background, text=conf.version)

        self.intro_btm_padding = Canvas(self.intro_nav)
        self.intro_btm_padding.configure(height=conf.intro_padding_height
                                         , background=conf.intro_background
                                         , highlightbackground=conf.intro_background)

    def hide(self):     # formerly hide_intro_nav
        self.intro_nav.destroy()
        self.background_frame.destroy()
        self.can.destroy()
        self.button_load_game.destroy()
        self.button_new_game.destroy()
        self.button_quit.destroy()
        self.label_version.destroy()
        self.title_image_res.__del__()
        self.intro_top_padding.destroy()
        self.intro_btm_padding.destroy()


    def draw(self):       # formerly draw_intro_nav()

        # frame setup

        self.intro_top_padding.pack()

        self.background_frame.pack(fill='both')
        self.intro_nav.pack(fill='both', padx=(self.parent.sw/2)-250, pady=(self.parent.sh/2)-250)

        self.app.debug(("Drew Intro, padding: (", (self.parent.sw/2)-250, ",", (self.parent.sh/2)-250, ")"))

        # elements

        self.can.pack(fill='both', side='top', padx=50, pady=50)
        self.can.create_image(2, 2, image=self.title_image_res, anchor='nw')

        self.button_new_game.pack(fill="x", padx=50)
        self.button_load_game.pack(fill="x", padx=50)
        self.button_quit.pack(fill="x", padx=50)
        self.label_version.pack(fill='y', padx=10, pady=10)

        self.intro_btm_padding.pack()

        '''
示例#17
0
    def __init__(self,
                 notification_manager,
                 builder,
                 index,
                 x,
                 y,
                 h,
                 v,
                 padx,
                 pady,
                 background=None,
                 on_hide=None):
        Toplevel.__init__(self)

        self._notification_manager = notification_manager
        #self.geometry("1x1")
        self.index = index
        self.on_hide = on_hide

        # Removes the native window boarder.
        self.overrideredirect(True)

        # Disables resizing of the widget.
        self.resizable(False, False)

        # Places window above all other windows in the window stack.
        self.wm_attributes("-topmost", True)

        notification_frame = Frame(self)
        notification_frame.pack(expand=True, fill=BOTH, padx=padx, pady=pady)

        top_row = Frame(notification_frame)
        top_row.pack(fill=X)

        if not hasattr(notification_manager, "_close_icon"):
            notification_manager._close_icon = PhotoImage(
                data=
                "R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw=="
            )

        close_button = Button(top_row,
                              image=notification_manager._close_icon,
                              highlightthickness=0,
                              borderwidth=0,
                              command=self.close)
        close_button.pack(side=RIGHT, anchor=E)

        self.interior = Frame(notification_frame)
        self.interior.pack(expand=True, fill=BOTH)

        if builder:
            builder(self.interior)

        if background is not None:
            top_row.config(background=background)
            notification_frame.config(background=background)
            self.config(background=background)
            self.interior.config(background=background)
            close_button.config(background=background)

        self.place(x, y, h, v)
class ExpSonar:

    def __init__(self, fileloc, rng=5, sleeptime=2):
        # experiment with range rng
        self.rng = rng
        self.sleeptime = sleeptime
        self.fileloc = fileloc
        # list of points and coords of experiments
        self.pt_dict = {'1': '68,68', '2': '67,136','3': '138,68','4': '138,136','5': '197,68','6': '197,136','7': '259,68','8': '259,136','9': '327,68','10': '327,136','11': '366,25','12': '366,136','13': '353,204','14': '353,272','15': '295,204','16': '295,272','17': '353,348','18': '353,408','19': '353,476','20': '295,348','21': '295,408','22': '295,476'}

        self.make_pub()

        self.r = Tk()
        self.c = Canvas(self.r, width=400, height=600)
        self.c.pack()
        self.mv = []
        self.smath = s_math.SonarMath()
        self.pts = []
        self.ovals = []
        self.run = Button(self.r, text='run', command=self.run)
        self.run.pack()
        self.reset = Button(self.r, text='reset', command=self.reset)
        self.reset.pack()
        for key in self.pt_dict:
            a = map(int, self.pt_dict[key].split(','))
            self.pts.append(a)
            self.c.create_oval(a[0] -1, a[1] -1, a[0] + 1, a[1] + 1)
    
        self.c.bind("<Button-1>", self.path)
        self.r.mainloop()

    def path(self, event):
        x = event.x
        y = event.y
        pe = [x,y]
        
        for pt in self.pts:
            if self.smath.pt_dist(pt, pe) <= 10:
                self.mv.append(pt)

        if len(self.mv) > 1:
            self.c.create_line(self.mv[-2][0], self.mv[-2][1], self.mv[-1][0], self.mv[-1][1], tags='mvline')

    def reset(self):
        self.mv = []
        self.c.delete('mvline')
        
    def run(self):
        for i, p in enumerate(self.mv):
            fname = '%s/prc_%d_%d_%d.txt'%(self.fileloc, p[0],p[1], self.rng)
            data = proc_sonar()
            try:
                f = open(fname, 'r')
                # print '%s/prc_%d_%d_%d.txt'%(self.fileloc, p[0],p[1], self.rng)
                data.prev = point(self.mv[i - 1][0],self.mv[i - 1][1]) if i != 0 else point(self.mv[i][0], self.mv[i][1])
                data.next = point(self.mv[i][0], self.mv[i][1])
                data.angle = 0
                data.ranges = map(float, f.read().split(' '))
                data.actual = point(p[0], p[1])
                self.pub.publish(data)
            except IOError:
                print 'file %s does not exist'%(fname)

            rospy.sleep(self.sleeptime) # artificial time an action takes
        self.run.config(state='disabled')
        
    def make_pub(self):
        self.pub = rospy.Publisher('sonar_sim_readable', proc_sonar)
        rospy.init_node('experiment_gui')
示例#19
0
class ToolBar(Frame):
	def __init__(self, root, printer, settings, logger, *arg):
		self.app = root
		self.printer = printer
		self.settings = settings
		self.logger = logger
		
		self.app.printing = False
		self.app.connected = False
		self.app.paused = False
		
		Frame.__init__(self, root, *arg)
		topBar = Frame(self)
		topBar.grid(row=1, column=1, columnspan=3, sticky=W)
		speedBar = Frame(self)
		speedBar.grid(row=1, column=5, sticky=E)
		bottomBar = Frame(self)
		bottomBar.grid(row=2, column=1, columnspan=6, sticky=W+E)
		
		self.bPort = Button(topBar, text="Port", width=BWIDTH, command=self.doPort)
		self.bPort.pack(side=LEFT, padx=2, pady=2)
		ports = self.scanSerial()
		self.spPort = Spinbox(topBar, values=ports, state="readonly")
		self.spPort.pack(side=LEFT, padx=2, pady=2)
		l = Label(topBar, text=" @ ")
		l.pack(side=LEFT, padx=2, pady=2)
		self.spBaud = Spinbox(topBar, values=baudChoices)
		self.spBaud.pack(side=LEFT, padx=2, pady=2)
		self.spBaud.delete(0, END)
		self.spBaud.insert(0, 115200)
		self.spBaud.config(state="readonly")

		self.bConnectMode = CM_CONNECT
		self.bConnect = Button(topBar, text=connectText[CM_CONNECT], width=BWIDTH, command=self.doConnect)
		self.bConnect.pack(side=LEFT, padx=2, pady=2)
		if len(ports) == 0:
			self.bConnect.config(state=DISABLED)
		else:
			self.bConnect.config(state=NORMAL)


		self.bReset = Button(topBar, text="Reset", width=BWIDTH, command=self.doReset, state=DISABLED)
		self.bReset.pack(side=LEFT, padx=2, pady=2)
		
		l = Label(speedBar, text="Speed:", justify=RIGHT)
		l.grid(row=1, column=1, sticky=E)

		self._speedJob = None		
		self.currentSpeed = self.app.FeedMultiply
		self.scSpeed = Scale(speedBar, from_=MINSPEED, to=MAXSPEED, orient=HORIZONTAL, command=self.updateSpeedCommand)
		self.scSpeed.grid(row=1, column=2)
		self.scSpeed.set(self.currentSpeed);

		l = Label(speedBar, text="Fan:", width=10, anchor=E, justify=RIGHT)
		l.grid(row=1, column=3, sticky=E)
		
		self._fanJob = None		
		self.currentFanSpeed = self.app.FanSpeed
		self.scFan = Scale(speedBar, from_=0, to=255, orient=HORIZONTAL, command=self.updateFanSpeedCommand)
		self.scFan.grid(row=1, column=4)
		self.scFan.set(self.currentFanSpeed);

		if self.settings.speedcommand is not None:
			self.cbvAssertFan = IntVar()
			if self.settings.forcefanspeed:
				self.cbvAssertFan.set(1)
			else:
				self.cbvAssertFan.set(0)
			self.cbAssertFan = Checkbutton(speedBar, text="Force", variable=self.cbvAssertFan,
				command=self.clickAssertFan)
			self.cbAssertFan.grid(row=1, column=5)

		self.bSliceMode = SM_SLICE
		self.bSlice = Button(bottomBar, text=sliceText[SM_SLICE], width=BWIDTH*2, command=self.doSlice)
		self.bSlice.pack(side=LEFT, padx=2, pady=2)
		
		self.bLoad = Button(bottomBar, text="Load GCode", width=BWIDTH, command=self.doLoad)
		self.bLoad.pack(side=LEFT, padx=2, pady=2)
		self.setSliceText()
		
		self.bSD = Button(bottomBar, text="SD", width=BWIDTH, command=self.doSD, state=DISABLED)
		self.bSD.pack(side=LEFT, padx=2, pady=2)
		
		self.bPrintMode = PR_PRINT		
		self.bPrint = Button(bottomBar, text=printText[PR_PRINT], width=BWIDTH, command=self.doPrint, state=DISABLED)
		self.bPrint.pack(side=LEFT, padx=2, pady=2)
		
		self.bPauseMode = PM_PAUSE
		self.bPause = Button(bottomBar, text=pauseText[PM_PAUSE], width=BWIDTH, command=self.doPause, state=DISABLED)
		self.bPause.pack(side=LEFT, padx=2, pady=2)

		self.bAbandon = Button(bottomBar, text="Abandon SD Print", width=BWIDTH+8, command=self.doAbandon, state=DISABLED)
		self.bAbandon.pack(side=LEFT, padx=2, pady=2)
		
		self.cbvLiftOnPause = IntVar()
		if self.settings.liftonpause:
			self.cbvLiftOnPause.set(1)
		else:
			self.cbvLiftOnPause.set(0)
		self.cbLiftOnPause = Checkbutton(bottomBar, text="Lift Head/Retract on Pause", variable=self.cbvLiftOnPause,
			command=self.clickLiftOnPause)
		self.cbLiftOnPause.pack(side=LEFT, padx=2)

		self.cbvResumeAtPause = IntVar()
		if self.settings.resumeatpausepoint:
			self.cbvResumeAtPause.set(1)
		else:
			self.cbvResumeAtPause.set(0)
		self.cbResumeAtPause = Checkbutton(bottomBar, text="Resume print at pause point", variable=self.cbvResumeAtPause,
			command=self.clickResumeAtPause)
		self.cbResumeAtPause.pack(side=LEFT, padx=2)
		
	def clickAssertFan(self):
		if self.cbvAssertFan.get() == 1:
			self.settings.forcefanspeed = True
			self.settings.setModified()
		else:
			self.settings.forcefanspeed = False
			self.settings.setModified()
		
	def clickLiftOnPause(self):
		if self.cbvLiftOnPause.get() == 1:
			self.settings.liftonpause = True
			self.settings.setModified()
		else:
			self.settings.liftonpause = False
			self.settings.setModified()
		
	def clickResumeAtPause(self):
		if self.cbvResumeAtPause.get() == 1:
			self.settings.resumeatpausepoint = True
			self.settings.setModified()
		else:
			self.settings.resumeatpausepoint = False
			self.settings.setModified()
	
	def setSliceText(self):
		if self.settings.slicer == SLIC3R:
			sl = "slic3r:%s" % self.app.slic3r.getProfile()
		else:
			sl = "skeinforge:%s" % self.app.skeinforge.getProfile()
		sliceText[SM_SLICE] = "Slice (%s)" % sl
		if self.bSliceMode == SM_SLICE:
			self.bLoad.config(state=NORMAL)
			self.app.allowLoadGCodeMenu(True)
			lt = len(sliceText[SM_SLICE])+2
			if lt < BWIDTH:
				lt = BWIDTH
			self.bSlice.config(text=sliceText[SM_SLICE], width=lt)
		
	def updateSpeedCommand(self, *arg):
		if self._speedJob:
			self.app.master.after_cancel(self._speedJob)
			
		self._speedJob = self.app.master.after(500, self.updateSpeed)

	def updateSpeed(self, *arg):
		v = self.scSpeed.get()
		self.setSpeed(v)
		
	def setSpeed(self, v):
		if v < MINSPEED or v > MAXSPEED:
			self.logger.logMsg("Attempt to change speed outside of allowable range (%d-%d)" % (MINSPEED, MAXSPEED))
		elif int(v) != self.currentSpeed:
			if self.app.connected:
				self.currentSpeed = int(v)
				self.logger.logMsg("changing speed percentage to %d%%" % self.currentSpeed)
				cmd = "M220 S%d" % self.currentSpeed
				self.printer.send_now(cmd)
			else:
				self.logger.logMsg("Printer is off-line")

		self.scSpeed.set(self.currentSpeed)
		
	def updateFanSpeedCommand(self, *arg):
		if self._fanJob:
			self.app.master.after_cancel(self._fanJob)
			
		self._fanJob = self.app.master.after(500, self.updateFanSpeed)
		
	def updateFanSpeed(self, *arg):
		v = self.scFan.get()
		self.setFanSpeed(v)
		self.app.FanSpeed = v

	def forceFanSpeed(self, v):
		self.currentFanSpeed = -1
		self.setFanSpeed(v)

	def setFanSpeed(self, v):
		if int(v) != self.currentFanSpeed:
			if self.app.connected:
				self.currentFanSpeed = int(v)
				cmd = "M106 S%d" % self.currentFanSpeed
				self.printer.send_now(cmd)
			else:
				self.logger.logMsg("Printer is off-line")
		self.scFan.set(self.currentFanSpeed)
		
	def syncSpeeds(self):
		self.currentSpeed = self.app.FeedMultiply
		self.scSpeed.set(self.currentSpeed)
		self.currentFanSpeed = self.app.FanSpeed
		self.scFan.set(self.currentFanSpeed)
		
	def initializeToolbar(self):
		self.bReset.config(state=DISABLED)
		self.bSliceMode = SM_SLICE
		self.bSlice.config(text=sliceText[SM_SLICE])
		self.bLoad.config(state=NORMAL)
		self.app.allowLoadGCodeMenu(True)
		if not self.app.sdprinting and not self.app.sdpaused:
			self.bPrintMode = PR_PRINT
			self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
			self.bPauseMode = PM_PAUSE
			self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED)
		
	def setSDPrint(self):
		self.bPause.config(text=pauseText[PM_PAUSE], state=NORMAL)
		self.bPauseMode = PM_PAUSE
		self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
		self.bPrintMode = PR_PRINT
		self.bAbandon.config(state=NORMAL)
		
	def clearSDPrint(self):
		self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED)
		self.bPauseMode = PM_PAUSE
		self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
		self.bPrintMode = PR_PRINT
		self.bAbandon.config(state=DISABLED)
		self.checkAllowPrint()
		
	def setCancelMode(self):
		self.bSliceMode = SM_CANCEL
		self.bSlice.config(text=sliceText[SM_CANCEL], width=BWIDTH)
		self.bLoad.config(state=DISABLED)
		self.app.allowLoadGCodeMenu(False)
		self.app.allowSliceMenu(False)

	def setLoading(self, flag):
		if flag:
			self.bLoad.config(state=DISABLED)
			self.bSlice.config(state=DISABLED)
			self.app.allowLoadGCodeMenu(False)
			self.app.allowSliceMenu(False)
		else:
			self.bLoad.config(state=NORMAL)
			self.bSlice.config(state=NORMAL)
			self.app.allowLoadGCodeMenu(True)
			self.app.allowSliceMenu(True)
		
	def clearCancelMode(self):
		self.bSliceMode = SM_SLICE
		lt = len(sliceText[SM_SLICE])+2
		if lt < BWIDTH:
			lt = BWIDTH
		self.bSlice.config(text=sliceText[SM_SLICE], width=lt)
		self.bLoad.config(state=NORMAL)
		self.app.allowLoadGCodeMenu(True)
		self.app.allowSliceMenu(True)
		
	def doConnect(self):
		if self.bConnectMode == CM_CONNECT:
			port = self.spPort.get()
			baud = int(self.spBaud.get())
			self.printer.onlinecb = self.onlinecb
			try:
				self.printer.connect(port, baud)
			except SerialException:
				self.logger.logMsg("Unable to open printer port %s" % port)
		else:
			if self.app.printing:
				self.logger.logMsg("Please wait until printing has finished or is paused")
			else:
				self.printer.disconnect()
				self.printer.onlinecb = None
				self.app.printerConnected(False)
#				self.app.connected = False
				self.bConnectMode = CM_CONNECT
				self.bConnect.config(text=connectText[CM_CONNECT])
				self.bReset.config(state=DISABLED)
				self.bSD.config(state=DISABLED)
				if self.app.paused:
					self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
					self.bPrintMode = PR_PRINT
					self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED)
					self.bPauseMode = PM_PAUSE
					self.app.printing = False
					self.app.paused = False
					
	def doReset(self):
		if tkMessageBox.askyesno("Reset?", "Are you sure you want to reset the printer?", parent=self.app):
			self.printer.reset()
			self.printer.printing = 0
			self.app.printing = False
			self.bSlice.config(state=NORMAL)
			self.bLoad.config(state=NORMAL)
			self.app.allowLoadGCodeMenu(True)
			self.app.allowSliceMenu(True)

			self.bPrintMode = PR_PRINT
			self.bPrint.config(text=printText[PR_PRINT], state=NORMAL)
			if self.app.paused:
				self.printer.paused = 0
				self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED)
				self.bPauseMode = PM_PAUSE
				self.app.paused = False

	def onlinecb(self):
		self.logger.logMsg("Printer is on-line")
		self.app.printerConnected(True)
#		self.app.connected = True
		self.bConnectMode = CM_DISCONNECT
		self.bConnect.config(text=connectText[CM_DISCONNECT])
		self.bReset.config(state=NORMAL)
		self.bSD.config(state=NORMAL)
		self.checkAllowPrint()
	
	def checkAllowPrint(self):
		if self.app.connected and len(self.app.gcode) != 0 and not self.app.printing and not self.app.sdprinting:
			self.bPrint.config(text=printText[PR_PRINT], state=NORMAL)
			self.bPrintMode = PR_PRINT
			
	def printComplete(self):
		self.app.endTime = time.time()
		self.app.elapsedTime = self.app.endTime - self.app.startTime
		self.logger.logMsg("Printing completed at %s" % time.strftime('%H:%M:%S', time.localtime()))
		self.logger.logMsg("Total elapsed time: %s" % formatElapsed(self.app.elapsedTime))
		self.bPrintMode = PR_PRINT
		self.bPrint.config(text=printText[PR_PRINT], state=NORMAL)
		
		self.bPauseMode = PM_PAUSE
		self.bPause.config(text=pauseText[PM_PAUSE], state=DISABLED)
		
		self.app.printing = False
		self.bSlice.config(state=NORMAL)
		self.bLoad.config(state=NORMAL)
		self.app.allowLoadGCodeMenu(True)
		self.app.allowSliceMenu(True)
		self.app.paused = False
		self.app.gc.updatePrintProgress(0)
		self.app.closeAllReports()
		if self.settings.endprintmacro is not None:
			self.app.doMacro(name=self.settings.endprintmacro, silent=True)

		
	def doPause(self):
		if self.bPauseMode == PM_PAUSE:
			if self.app.printing:
				self.app.paused = True
				self.printer.pause()
			elif self.app.sdprinting:
				self.app.sdpaused = True
				self.printer.send_now("M25")
				self.app.sdprinting = False
				self.bPause.config(text=pauseText[PM_RESUME])
				self.bPauseMode = PM_RESUME
				self.bPrint.config(text=printText[PR_RESTART], state=NORMAL)
				self.bPrintMode = PR_RESTART
		else:
			if self.app.sdpaused:
				self.printer.send_now("M24")
				self.app.sdpaused = False
				self.app.sdprinting = True
				self.bPause.config(text=pauseText[PM_PAUSE])
				self.bPauseMode = PM_PAUSE
				self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
				self.bPrintMode = PR_PRINT
			else:
				self.hitPrint = False
				if self.settings.resumeatpausepoint:
					self.printer.send_now("G1 X%s Y%s F%s" % (self.app.pausePoint[XAxis], self.app.pausePoint[YAxis], self.settings.xyfeed))
					self.printer.send_now("G1 Z%s F%s" % (self.app.pausePoint[ZAxis], self.settings.zfeed))
					self.printer.send_now("G92 E%s" % self.app.pausePoint[EAxis])
					self.printer.send_now("G1 F%s" % self.settings.xyfeed)
				self.printer.startcb = self.startcb
				self.printer.resume()
				
	def doAbandon(self):
		self.printer.send_now("M25")
		self.app.sdpaused = False
		self.app.sdprinting = False
		self.clearSDPrint()

	def doSlice(self):
		if self.bSliceMode == SM_SLICE:
			self.bLoad.config(state=DISABLED)
			self.app.allowLoadGCodeMenu(False)
			self.app.openSTLFile()
		else:
			self.app.slicerCancel = True
			self.bLoad.config(state=NORMAL)
			self.app.allowLoadGCodeMenu(True)
			
	def doLoad(self):
		self.app.openGCodeFile()
	
	def doPrint(self):
		if self.app.sdpaused:
			self.printer.send_now("M26 S0")
			self.printer.send_now("M24")
			self.app.sdpaused = False
			self.app.sdprinting = True
			self.bPause.config(text=pauseText[PM_PAUSE])
			self.bPauseMode = PM_PAUSE
			self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
			self.bPrintMode = PR_PRINT
		else:
			if len(self.app.gcode) == 0:
				self.logger.logMsg("Nothing to print")
			else:
				#if not self.app.paused:
				self.app.gc.updatePrintProgress(0, restart=True)
	
				self.bPauseMode = PM_PAUSE
				self.bPause.config(text=pauseText[PM_PAUSE], state=NORMAL)
				self.hitPrint = True
				self.printer.startcb = self.startcb
				self.printer.startprint(self.app.gcode)
			
	def startcb(self):
		self.printer.startcb = None
		if not self.app.paused:
			self.app.startTime = time.time()
			self.logger.logMsg("Printing Started at %s" % time.strftime('%H:%M:%S', time.localtime(self.app.startTime)))
			self.app.printing = True
			
			self.bSlice.config(state=DISABLED)
			self.bLoad.config(state=DISABLED)
			self.app.allowLoadGCodeMenu(False)
			self.app.allowSliceMenu(False)

			self.bPrint.config(text=printText[PR_RESTART], state=DISABLED)
			self.bPrintMode = PR_RESTART
			self.printer.endcb = self.endcb
		else:
			if self.hitPrint:
				self.app.startTime = time.time()
				self.logger.logMsg("Printing restarted at %s" % time.strftime('%H:%M:%S', time.localtime()))
			else:
				self.logger.logMsg("Printing resumed at %s" % time.strftime('%H:%M:%S', time.localtime()))
			self.bPause.config(text=pauseText[PM_PAUSE])
			self.bPauseMode = PM_PAUSE
			self.app.printing = True
			
			self.bSlice.config(state=DISABLED)
			self.bLoad.config(state=DISABLED)
			self.app.allowLoadGCodeMenu(False)
			self.app.allowSliceMenu(False)


			self.app.paused = False
			self.bPrint.config(state=DISABLED)
			self.printer.endcb = self.endcb
		
	def endcb(self):
		self.printer.endcb = None
		if not self.app.paused:
			self.printComplete()
			if self.app.sduploading:
				self.app.sduploading = False
				self.printer.send_now("M29")
		else:
			self.app.event_generate(MWM_REQUESTPOSITIONREPORT)
			# record the current printer position and how many intervals were willing to wait fo the response
			self.maxWait114 = MAXWAIT114;
			self.waitPos = self.printer.queueindex
			self.check114Response()
		
	def check114Response(self) :
		# tick off 1 interval, and make sure we haven't either received the report or we've waited max intervals
		self.maxWait114 -= 1
		if self.app.m114count == 0 or self.maxWait114 <= 0:
			# one way or the other we're done waiting here
			if self.maxWait114 <= 0:
				self.app.m114count = 0
				self.logger.logMsg("Location report not received - proceeding")
				
			self.app.pausePoint[XAxis] = self.app.location[XAxis]
			self.app.pausePoint[YAxis] = self.app.location[YAxis]
			self.app.pausePoint[ZAxis] = self.app.location[ZAxis]
			self.app.pausePoint[EAxis] = self.app.location[EAxis]

			self.logger.logMsg("Pause location: X:%f Y:%f Z:%f E:%f" %
				(self.app.pausePoint[XAxis], self.app.pausePoint[YAxis], self.app.pausePoint[ZAxis], self.app.pausePoint[EAxis]))
			
			if self.settings.liftonpause:
				self.printer.send_now("G1 E%s F%s" % (self.app.pausePoint[EAxis]-2, self.settings.efeed))
				self.printer.send_now("G1 Z%s F%s" % (self.app.pausePoint[ZAxis]+10, self.settings.zfeed))

			self.bPause.config(text=pauseText[PM_RESUME])
			self.bPauseMode = PM_RESUME
			self.app.printing = False
			
			self.bSlice.config(state=NORMAL)
			self.bLoad.config(state=NORMAL)
			self.app.allowLoadGCodeMenu(True)
			self.app.allowSliceMenu(True)


			if self.app.sduploading:
				self.bPrint.config(text=printText[PR_PRINT], state=DISABLED)
				self.bPrintMode = PR_PRINT
			else:
				self.bPrint.config(text=printText[PR_RESTART], state=NORMAL)
				self.bPrintMode = PR_RESTART
		else:
			# we still are waiting for the report, but reset everything if the printer is still moving
			if self.waitPos != self.printer.queueindex:
				self.waitPos = self.printer.queueindex
				self.maxWait114 = MAXWAIT114
				
			self.app.master.after(500, self.check114Response)
	
	def doPort(self):
		l = self.scanSerial()
		self.spPort.config(values=l)
		if len(l) == 0:
			self.bConnect.config(state=DISABLED)
		else:
			self.bConnect.config(state=NORMAL)
	
	def scanSerial(self):
		"""scan for available ports. return a list of device names."""
		baselist=[]
		if os.name=="nt":
			try:
				key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
				i=0
				while(1):
					baselist+=[_winreg.EnumValue(key,i)[1]]
					i+=1
			except:
				pass
		return baselist+glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') +glob.glob("/dev/tty.*")+glob.glob("/dev/cu.*")+glob.glob("/dev/rfcomm*")
	
	def doSD(self):
		self.app.doSD()
示例#20
0
class TopoConsole(tk.AppWindow,tk.TkParameterized):
    """
    Main window for the Tk-based GUI.
    """

    def _getmenubar(self):
        return self.master.menubar

    menubar = property(_getmenubar)

    def __getitem__(self,menu_name):
        """Allow dictionary-style access to the menu bar."""
        return self.menubar[menu_name]

    def __init__(self,root,**params):
        tk.AppWindow.__init__(self,root,status=True)
        tk.TkParameterized.__init__(self,root,**params)

        # Instead of displaying tracebacks on the commandline, try to display
        # them on the originating window.
        # CEBALERT: on destroy(), ought to revert this
        Tkinter.Misc._report_exception=_tkinter_report_exception

        self.auto_refresh_panels = []
        self._init_widgets()
        self.title(topo.sim.name) # If -g passed *before* scripts on commandline, this is useless.
                                  # So topo.misc.commandline sets the title as its last action (if -g)



        # catch click on the 'x': offers choice to quit or not
        self.protocol("WM_DELETE_WINDOW",self.quit_topographica)


        ##########
        ### Make cascade menus open automatically on linux when the mouse
        ### is over the menu title.
        ### [Tkinter-discuss] Cascade menu issue
        ### http://mail.python.org/pipermail/tkinter-discuss/2006-August/000864.html
        if topo.tkgui.system_platform is 'linux':
            activate_cascade = """\
            if {[%W cget -type] != {menubar} && [%W type active] == {cascade}} {
                %W postcascade active
               }
            """
            self.bind_class("Menu", "<<MenuSelect>>", activate_cascade)
        ##########

        # Install warning and message handling
        from param.parameterized import Parameterized
        self.__orig_P_warning = Parameterized.warning
        #self.__orig_P_message = Parameterized.message
        type.__setattr__(Parameterized,'warning',self.gui_warning)
        #type.__setattr__(Parameterized,'message',self.gui_message)

    def gui_warning(self,*args):
        stat = self.__get_status_bar()
        s = string.join(args,' ')
        stat.warn(s)
        self.__orig_P_warning(self,*args)

    def gui_message(self,*args):
        stat = self.__get_status_bar()
        s = string.join(args,' ')
        stat.message(s)
        self.__orig_P_message(self,*args)


    def title(self,t=None):
        newtitle = "Topographica"
        if t: newtitle+=": %s" % t
        tk.AppWindow.title(self,newtitle)


    def _init_widgets(self):

        ## CEBALERT: now we can have multiple operations at the same time,
        ## status bar could be improved to show all tasks?

        # CEBALERT
        self.messageBar = self.status

        self.some_area = DockManager(self)
        self.some_area.pack(fill="both", expand=1)

        ### Balloon, for pop-up help
        self.balloon = tk.Balloon(self.content)

        ### Top-level (native) menu bar
        #self.menubar = tk.ControllableMenu(self.content)
        self.configure(menu=self.menubar)

        #self.menu_balloon = Balloon(topo.tkgui.root)

        # no menubar in tile yet
        # http://news.hping.org/comp.lang.tcl.archive/4679.html

        self.__simulation_menu()
        self.__create_plots_menu()
        self.refresh_plots_menu()
        self.__help_menu()


        ### Running the simulation
        run_frame = Frame(self.content)
        run_frame.pack(side='top',fill='x',padx=4,pady=8)

        self.run_frame = run_frame

        Label(run_frame,text='Run for: ').pack(side=LEFT)

        self.run_for_var=DoubleVar()
        self.run_for_var.set(1.0)

        run_for = tk.TaggedSlider(run_frame,
                               variable=self.run_for_var,
                               tag_width=11,
                               slider_length=150,
                               bounds=(0,20000))
        self.balloon.bind(run_for,"Duration to run the simulation, e.g. 0.0500, 1.0, or 20000.")
        run_for.pack(side=LEFT,fill='x',expand=YES)
        run_for.tag.bind("<Return>",self.run_simulation)

        # When return is pressed, the TaggedSlider updates itself...but we also want to run
        # the simulation in this case.
        run_frame.optional_action=self.run_simulation

        go_button = Button(run_frame,text="Go",
                           command=self.run_simulation)
        go_button.pack(side=LEFT)

        self.balloon.bind(go_button,"Run the simulation for the specified duration.")

        self.step_button = Button(run_frame,text="Step",command=self.run_step)
        self.balloon.bind(self.step_button,"Run the simulation through the time at which the next events are processed.")
        self.step_button.pack(side=LEFT)

        self.sizeright()


    def __simulation_menu(self):
        """Add the simulation menu options to the menubar."""
        simulation_menu = ControllableMenu(self.menubar,tearoff=0)

        self.menubar.add_cascade(label='Simulation',menu=simulation_menu)

        simulation_menu.add_command(label='Run script',command=self.run_script)
        simulation_menu.add_command(label='Save script',command=self.save_script_repr)
        simulation_menu.add_command(label='Load snapshot',command=self.load_snapshot)
        simulation_menu.add_command(label='Save snapshot',command=self.save_snapshot)
        #simulation_menu.add_command(label='Reset',command=self.reset_network)
        simulation_menu.add_command(label='Test Pattern',command=self.open_test_pattern)

        simulation_menu.add_command(label='Model Editor',command=self.open_model_editor)
        simulation_menu.add_command(label='Quit',command=self.quit_topographica)



    def open_test_pattern(self):
        return open_plotgroup_panel(TestPattern)






    def __create_plots_menu(self):
        """
        Add the plot menu to the menubar, with Basic plots on the menu itself and
        others in cascades by category (the plots come from plotgroup_templates).
        """
        plots_menu = ControllableMenu(self.menubar,tearoff=0)
        self.menubar.add_cascade(label='Plots',menu=plots_menu)


    # CEBALERT: should split other menus in same way as plots (create/refresh)
    def refresh_plots_menu(self):
        plots_menu = self['Plots']
        plots_menu.delete(0,'end')

        # create menu entries, and get list of categories
        entries=KeyedList() # keep the order of plotgroup_templates (which is also KL)
        categories = []
        for label,plotgroup in plotgroups.items():
            entries[label] = PlotsMenuEntry(plotgroup)
            categories.append(plotgroup.category)
        categories = sorted(set(categories))


        # The Basic category items appear on the menu itself.
        assert 'Basic' in categories, "'Basic' is the category for the standard Plots menu entries."
        for label,entry in entries:
            if entry.plotgroup.category=='Basic':
                    plots_menu.add_command(label=label,command=entry.__call__)

        categories.remove('Basic')

        plots_menu.add_separator()

        # Add the other categories to the menu as cascades, and the plots of each category to
        # their cascades.
        for category in categories:
            category_menu = ControllableMenu(plots_menu,tearoff=0)
            plots_menu.add_cascade(label=category,menu=category_menu)

            # could probably search more efficiently than this
            for label,entry in sorted(entries):
                if entry.plotgroup.category==category:
                    category_menu.add_command(label=label,command=entry.__call__)


        plots_menu.add_separator()

        plots_menu.add_command(label="Help",command=(lambda x=plotting_help_locations: self.open_location(x)))


    def __help_menu(self):
        """Add the help menu options."""

        help_menu = ControllableMenu(self.menubar,tearoff=0,name='help')
        self.menubar.add_cascade(label='Help',menu=help_menu)

        help_menu.add_command(label='About',command=self.new_about_window)
        help_menu.add_command(label="User Manual",
                              command=(lambda x=user_manual_locations: self.open_location(x)))

        help_menu.add_command(label="Tutorials",
                              command=(lambda x=tutorials_locations: self.open_location(x)))

        help_menu.add_command(label="Examples",
                              command=self.run_example_script)

        help_menu.add_command(label="Reference Manual",
                              command=(lambda x=reference_manual_locations: self.open_location(x)))

        help_menu.add_command(label="Topographica.org",
                              command=(lambda x=topo_www_locations: self.open_location(x)))

        help_menu.add_command(label="Python documentation",
                              command=(lambda x=python_doc_locations: self.open_location(x)))




    def quit_topographica(self,check=True,exit_status=0):
        """Quit topographica."""
        if not check or (check and tk.askyesno("Quit Topographica","Really quit?")):
            self.destroy()

            # matplotlib's tk backend starts its own Tk instances; we
            # need to close these ourselves (at least to avoid error
            # message about 'unusual termination' in Windows).
            try: # not that there should be an error, but just in case...
                import matplotlib._pylab_helpers
                for figman in matplotlib._pylab_helpers.Gcf.get_all_fig_managers():
                    figman.destroy()
            except:
                pass

            print "Quit selected; exiting"

            # Workaround for obscure problem on some UNIX systems
            # as of 4/2007, probably including Fedora Core 5.
            # On these systems, if Topographica is started from a
            # bash prompt and then quit from the Tkinter GUI (as
            # opposed to using Ctrl-D in the terminal), the
            # terminal would suppress echoing of all future user
            # input.  stty sane restores the terminal to sanity,
            # but it is not clear why this is necessary.
            # For more info:
            # http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d0f33c8eb2e02d
            if topo.tkgui.system_platform=="linux" and os.getenv('EMACS')!='t':
                try: os.system("stty sane")
                except: pass
            # CEBALERT: re. above. Shouldn't we be able to store the
            # output of "stty --save" before starting the gui, then
            # ensure that when the gui exits (however badly it
            # happens) run "stty saved_settings"?

            # CEBALERT: there was no call to self.master.destroy()
            sys.exit(exit_status)


    def run_script(self):
        """
        Dialog to run a user-selected script

        The script is exec'd in __main__.__dict__ (i.e. as if it were specified on the commandline.)
        """
        script = askopenfilename(initialdir=normalize_path(),filetypes=SCRIPT_FILETYPES)
        if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('Run canceled')
        else:
            execfile(script,__main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)

    # CEBALERT: duplicates most of run_script()
    def run_example_script(self):


        script = askopenfilename(initialdir=topo.misc.genexamples.find_examples(),
                                 filetypes=SCRIPT_FILETYPES)

        if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('No example opened')
        else:
            execfile(script,__main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)



    def save_script_repr(self):
        script_name = asksaveasfilename(filetypes=SCRIPT_FILETYPES,
                                        initialdir=normalize_path(),
                                        initialfile=topo.sim.basename()+"_script_repr.ty")

        if script_name:
            topo.command.save_script_repr(script_name)
            self.messageBar.response('Script saved to ' + script_name)


    def load_snapshot(self):
        """
        Dialog to load a user-selected snapshot (see topo.command.load_snapshot() ).
        """
        snapshot_name = askopenfilename(initialdir=normalize_path(),filetypes=SAVED_FILETYPES)

        if snapshot_name in ('',(),None):
            self.messageBar.response('No snapshot loaded.')
        else:
            self.messageBar.dynamicinfo('Loading snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.load_snapshot(snapshot_name)
            self.messageBar.response('Loaded snapshot ' + snapshot_name)
            self.title(topo.sim.name)

        self.auto_refresh()


    def save_snapshot(self):
        """
        Dialog to save a snapshot (see topo.command.save_snapshot() ).

        Adds the file extension .typ if not already present.
        """
        snapshot_name = asksaveasfilename(filetypes=SAVED_FILETYPES,
                                          initialdir=normalize_path(),
                                          initialfile=topo.sim.basename()+".typ")

        if snapshot_name in ('',(),None):
            self.messageBar.response('No snapshot saved.')
        else:
            if not snapshot_name.endswith('.typ'):
                snapshot_name = snapshot_name + SAVED_FILE_EXTENSION

            self.messageBar.dynamicinfo('Saving snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.save_snapshot(snapshot_name)
            self.messageBar.response('Snapshot saved to ' + snapshot_name)


    def auto_refresh(self, update=True):
        """
        Refresh all windows in auto_refresh_panels.

        Panels can add and remove themselves to the list; those in the list
        will have their refresh() method called whenever this console's
        autorefresh() is called.
        """
        for win in self.auto_refresh_panels:
            win.refresh(update)

        self.set_step_button_state()
        self.update_idletasks()


    ### CEBERRORALERT: why doesn't updatecommand("display=True") for an
    ### orientation preference map measurement work with the
    ### hierarchical example? I guess this is the reason I thought the
    ### updating never worked properly (or I really did break it
    ### recently - or I'm confused)...
    def refresh_activity_windows(self):
        """
        Update any windows with a plotgroup_key ending in 'Activity'.

        Used primarily for debugging long scripts that present a lot of activity patterns.
        """
        for win in self.auto_refresh_panels:
            if re.match('.*Activity$',win.plotgroup.name):
                win.refresh()
                self.update_idletasks()


    def open_model_editor(self):
        """Start the Model editor."""
        return ModelEditor(self)


    def new_about_window(self):
        win = tk.AppWindow(self)
        win.withdraw()
        win.title("About Topographica")
        text = Label(win,text=topo.about(display=False),justify=LEFT)
        text.pack(side=LEFT)
        win.deiconify()
        #self.messageBar.message('state', 'OK')

    def open_location(self, locations):
        """
        Try to open one of the specified locations in a new window of the default
        browser. See webbrowser module for more information.

        locations should be a tuple.
        """
        # CB: could have been a list. This is only here because if locations is set
        # to a string, it will loop over the characters of the string.
        assert isinstance(locations,tuple),"locations must be a tuple."

        for location in locations:
            try:
                existing_location = resolve_path(location)
                webbrowser.open(existing_location,new=2,autoraise=True)
                self.messageBar.response('Opened local file '+existing_location+' in browser.')
                return ###
            except:
                pass

        for location in locations:
            if location.startswith('http'):
                try:
                    webbrowser.open(location,new=2,autoraise=True)
                    self.messageBar.response('Opened remote location '+location+' in browser.')
                    return ###
                except:
                    pass

        self.messageBar.response("Could not open any of %s in a browser."%locations)


    # CEBALERT: need to take care of removing old messages automatically?
    # (Otherwise callers might always have to pass 'ok'.)
    def status_message(self,m):
        self.messageBar.response(m)


    def run_simulation(self,event=None): # event=None allows use as callback
        """
        Run the simulation for the duration specified in the
        'run for' taggedslider.
        """
        fduration = self.run_for_var.get()
        self.open_progress_window(timer=topo.sim.timer)
        topo.sim.run_and_time(fduration)
        self.auto_refresh()


    # CEBERRORALERT: Step button does strange things at time==0.
    # E.g. for lissom_oo_or, nothing appears to happen. For
    # hierarchical, runs to time==10.
    def run_step(self):

        if not topo.sim.events:
            # JP: step button should be disabled if there are no events,
            # but just in case...
            return

        # JPALERT: This should really use .run_and_time() but it doesn't support
        # run(until=...)
        topo.sim.run(until=topo.sim.events[0].time)
        self.auto_refresh()

    def set_step_button_state(self):
        if topo.sim.events:
            self.step_button.config(state=NORMAL)
        else:
            self.step_button.config(state=DISABLED)


    def __get_status_bar(self,i=2):
        # Hack to find appropriate status bar: Go back through frames
        # until a widget with a status bar is found, and return it.
        try:
            while True:
                f = sys._getframe(i)
                if hasattr(f,'f_locals'):
                    if 'self' in f.f_locals:
                        o = f.f_locals['self']
                        # (temporary hack til ScrolledFrame cleaned up)
                        if o.__class__.__name__!='ScrolledFrame':
                            if hasattr(o,'messageBar'):
                                return o.messageBar
                            elif hasattr(o,'status'):
                                return o.status
                    i+=1
        except:
            pass

        #print "GUI INTERNAL WARNING: failed to determine window on which to display message."
        return self.messageBar


    def open_progress_window(self,timer,title=None):
        """
        Provide a convenient link to progress bars.
        """
        stat = self.__get_status_bar()
        return stat.open_progress_window(timer=timer,sim=topo.sim)
示例#21
0
class Automation(Frame):
    """The Automation class is a GUI that provides radio automation."""
    _state = None
    _button_text = None
    _button = None

    _meter = None
    _cart_queue = None

    _list_time = None
    _list_track = None
    _list_artist = None

    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master,
                              textvariable=self._button_text,
                              command=self._update_state,
                              width=16,
                              height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=16,
              text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist,
                           orient=Tkinter.VERTICAL,
                           command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist,
                                  selectmode=Tkinter.SINGLE,
                                  yscrollcommand=scroll.set,
                                  exportselection=0,
                                  width=16,
                                  height=20)
        self._list_track = Listbox(inner_playlist,
                                   selectmode=Tkinter.SINGLE,
                                   yscrollcommand=scroll.set,
                                   exportselection=0,
                                   width=32,
                                   height=20)
        self._list_artist = Listbox(inner_playlist,
                                    selectmode=Tkinter.SINGLE,
                                    yscrollcommand=scroll.set,
                                    exportselection=0,
                                    width=32,
                                    height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT,
                             fill=Tkinter.X,
                             expand=True,
                             padx=2,
                             pady=2)
        self._list_track.pack(side=Tkinter.LEFT,
                              fill=Tkinter.X,
                              expand=True,
                              padx=2,
                              pady=2)
        self._list_artist.pack(side=Tkinter.LEFT,
                               fill=Tkinter.X,
                               expand=True,
                               padx=2,
                               pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _scroll_playlist(self, *args):
        """Scroll the playlist view.

        :param args
        """
        self._list_time.yview(*args)
        self._list_track.yview(*args)
        self._list_artist.yview(*args)

    def _update_state(self):
        """Move Automation to the next state.

        The state machine is as follows:
        STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED
        """
        if self._state is STATE_STOPPED:
            print "Starting Automation..."
            self._cart_queue.start()
            self._state = STATE_PLAYING
        elif self._state is STATE_PLAYING:
            print "Stopping Automation after this track..."
            self._cart_queue.stop_soft()
            self._state = STATE_STOPPING
        elif self._state is STATE_STOPPING:
            print "Stopping Automation immediately."
            self._cart_queue.transition()
            self._state = STATE_STOPPED
        self._update_ui()

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()
        self._update_ui()

    def _cart_stop(self):
        """Reset the meter when a cart stops.

        Also, if a soft stop occured, update the button state.
        """
        self._meter.reset()

        if self._state is STATE_STOPPING:
            self._state = STATE_STOPPED
            self._update_ui()

    def _update_ui(self):
        """Update the button and playlist."""
        self._button_text.set(TEXT_BUTTON[self._state])
        self._button.config(bg=COLOR_BUTTON[self._state],
                            highlightbackground=COLOR_BUTTON[self._state])

        self._list_time.delete(0, Tkinter.END)
        self._list_track.delete(0, Tkinter.END)
        self._list_artist.delete(0, Tkinter.END)

        for cart in self._cart_queue.get_queue():
            self._list_time.insert(Tkinter.END,
                                   cart.start_time.strftime("%I:%M:%S %p"))
            self._list_track.insert(Tkinter.END, cart.title)
            self._list_artist.insert(Tkinter.END, cart.issuer)

    def _get_meter_data(self):
        """Get meter data for the first track in the queue."""
        queue = self._cart_queue.get_queue()

        if len(queue) > 0:
            return queue[0].get_meter_data()
        else:
            return None
示例#22
0
class LintGui(object):
    """Build and control a window to interact with pylint"""
    def __init__(self, root=None):
        """init"""
        self.root = root or Tk()
        self.root.title('Pylint')
        #reporter
        self.reporter = None
        #message queue for output from reporter
        self.msg_queue = Queue.Queue()
        self.msgs = []
        self.visible_msgs = []
        self.filenames = []
        self.rating = StringVar()
        self.tabs = {}
        self.report_stream = BasicStream(self)
        #gui objects
        self.lb_messages = None
        self.showhistory = None
        self.results = None
        self.btnRun = None
        self.information_box = None
        self.convention_box = None
        self.refactor_box = None
        self.warning_box = None
        self.error_box = None
        self.fatal_box = None
        self.txtModule = None
        self.status = None
        self.msg_type_dict = None
        self.init_gui()

    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Binding F5 application-wide to run lint
        self.root.bind('<F5>', self.run_lint)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lb_messages = Listbox(msg_frame,
                                   yscrollcommand=rightscrollbar.set,
                                   xscrollcommand=bottomscrollbar.set,
                                   bg="white")
        self.lb_messages.bind("<Double-Button-1>", self.show_sourcefile)
        self.lb_messages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lb_messages.yview)
        bottomscrollbar.config(command=self.lb_messages.xview)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                                   yscrollcommand=rightscrollbar2.set,
                                   xscrollcommand=bottomscrollbar2.set,
                                   bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labelbl_ratingls
        lbl_rating_label = Label(rating_frame, text='Rating:')
        lbl_rating_label.pack(side=LEFT)
        lbl_rating = Label(rating_frame, textvariable=self.rating)
        lbl_rating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txt_module = Entry(top_frame, background='white')
        self.txt_module.bind('<Return>', self.run_lint)
        self.txt_module.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                               yscrollcommand=rightscrollbar.set,
                               xscrollcommand=bottomscrollbar.set,
                               bg="white",
                               font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame,
               text='Open Package',
               command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame,
                        text="Information",
                        fg=COLORS['(I)'],
                        variable=self.information_box,
                        command=self.refresh_msg_window)
        c = Checkbutton(check_frame,
                        text="Convention",
                        fg=COLORS['(C)'],
                        variable=self.convention_box,
                        command=self.refresh_msg_window)
        r = Checkbutton(check_frame,
                        text="Refactor",
                        fg=COLORS['(R)'],
                        variable=self.refactor_box,
                        command=self.refresh_msg_window)
        w = Checkbutton(check_frame,
                        text="Warning",
                        fg=COLORS['(W)'],
                        variable=self.warning_box,
                        command=self.refresh_msg_window)
        e = Checkbutton(check_frame,
                        text="Error",
                        fg=COLORS['(E)'],
                        variable=self.error_box,
                        command=self.refresh_msg_window)
        f = Checkbutton(check_frame,
                        text="Fatal",
                        fg=COLORS['(F)'],
                        variable=self.fatal_box,
                        command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame,
                             text="Report",
                             variable=self.box,
                             value="Report",
                             command=self.refresh_results_window)
        raw_met = Radiobutton(radio_frame,
                              text="Raw metrics",
                              variable=self.box,
                              value="Raw metrics",
                              command=self.refresh_results_window)
        dup = Radiobutton(radio_frame,
                          text="Duplication",
                          variable=self.box,
                          value="Duplication",
                          command=self.refresh_results_window)
        ext = Radiobutton(radio_frame,
                          text="External dependencies",
                          variable=self.box,
                          value="External dependencies",
                          command=self.refresh_results_window)
        stat = Radiobutton(radio_frame,
                           text="Statistics by type",
                           variable=self.box,
                           value="Statistics by type",
                           command=self.refresh_results_window)
        msg_cat = Radiobutton(radio_frame,
                              text="Messages by category",
                              variable=self.box,
                              value="Messages by category",
                              command=self.refresh_results_window)
        msg = Radiobutton(radio_frame,
                          text="Messages",
                          variable=self.box,
                          value="Messages",
                          command=self.refresh_results_window)
        source_file = Radiobutton(radio_frame,
                                  text="Source File",
                                  variable=self.box,
                                  value="Source File",
                                  command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        raw_met.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=W)
        stat.grid(column=0, row=1, sticky=W)
        msg_cat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, sticky=W)
        source_file.grid(column=3, row=1, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I': lambda: self.information_box.get() == 1,
            'C': lambda: self.convention_box.get() == 1,
            'R': lambda: self.refactor_box.get() == 1,
            'E': lambda: self.error_box.get() == 1,
            'W': lambda: self.warning_box.get() == 1,
            'F': lambda: self.fatal_box.get() == 1
        }
        self.txt_module.focus_set()

    def select_recent_file(self, event):
        """adds the selected file in the history listbox to the Module box"""
        if not self.showhistory.size():
            return

        selected = self.showhistory.curselection()
        item = self.showhistory.get(selected)
        #update module
        self.txt_module.delete(0, END)
        self.txt_module.insert(0, item)

    def refresh_msg_window(self):
        """refresh the message window with current output"""
        #clear the window
        self.lb_messages.delete(0, END)
        self.visible_msgs = []
        for msg in self.msgs:
            if self.msg_type_dict.get(msg.C)():
                self.visible_msgs.append(msg)
                msg_str = convert_to_string(msg)
                self.lb_messages.insert(END, msg_str)
                fg_color = COLORS.get(msg_str[:3], 'black')
                self.lb_messages.itemconfigure(END, fg=fg_color)

    def refresh_results_window(self):
        """refresh the results window with current output"""
        #clear the window
        self.results.delete(0, END)
        try:
            for res in self.tabs[self.box.get()]:
                self.results.insert(END, res)
        except:
            pass

    def process_incoming(self):
        """process the incoming messages from running pylint"""
        while self.msg_queue.qsize():
            try:
                msg = self.msg_queue.get(0)
                if msg == "DONE":
                    self.report_stream.output_contents()
                    return False

                #adding message to list of msgs
                self.msgs.append(msg)

                #displaying msg if message type is selected in check box
                if self.msg_type_dict.get(msg.C)():
                    self.visible_msgs.append(msg)
                    msg_str = convert_to_string(msg)
                    self.lb_messages.insert(END, msg_str)
                    fg_color = COLORS.get(msg_str[:3], 'black')
                    self.lb_messages.itemconfigure(END, fg=fg_color)

            except Queue.Empty:
                pass
        return True

    def periodic_call(self):
        """determine when to unlock the run button"""
        if self.process_incoming():
            self.root.after(100, self.periodic_call)
        else:
            #enabling button so it can be run again
            self.btnRun.config(state=NORMAL)

    def mainloop(self):
        """launch the mainloop of the application"""
        self.root.mainloop()

    def quit(self, _=None):
        """quit the application"""
        self.root.quit()

    def halt(self):
        """program halt placeholder"""
        return

    def file_open(self, package=False, _=None):
        """launch a file browser"""
        if not package:
            filename = askopenfilename(parent=self.root,
                                       filetypes=[('pythonfiles', '*.py'),
                                                  ('allfiles', '*')],
                                       title='Select Module')
        else:
            filename = askdirectory(title="Select A Folder", mustexist=1)

        if filename == ():
            return

        self.txt_module.delete(0, END)
        self.txt_module.insert(0, filename)

    def update_filenames(self):
        """update the list of recent filenames"""
        filename = self.txt_module.get()
        if not filename:
            filename = os.getcwd()
        if filename + '\n' in self.filenames:
            index = self.filenames.index(filename + '\n')
            self.filenames.pop(index)

        #ensure only 10 most recent are stored
        if len(self.filenames) == 10:
            self.filenames.pop()
        self.filenames.insert(0, filename + '\n')

    def set_history_window(self):
        """update the history window with info from the history file"""
        #clear the window
        self.showhistory.delete(0, END)
        # keep the last 10 most recent files
        try:
            view_history = open(HOME + HISTORY, 'r')
            for hist in view_history.readlines():
                if not hist in self.filenames:
                    self.filenames.append(hist)
                self.showhistory.insert(END, hist.split('\n')[0])
            view_history.close()
        except IOError:
            # do nothing since history file will be created later
            return

    def run_lint(self, _=None):
        """launches pylint"""
        self.update_filenames()
        self.root.configure(cursor='watch')
        self.reporter = GUIReporter(self, output=self.report_stream)
        module = self.txt_module.get()
        if not module:
            module = os.getcwd()

        #cleaning up msgs and windows
        self.msgs = []
        self.visible_msgs = []
        self.lb_messages.delete(0, END)
        self.tabs = {}
        self.results.delete(0, END)
        self.btnRun.config(state=DISABLED)

        #setting up a worker thread to run pylint
        worker = Thread(target=lint_thread,
                        args=(
                            module,
                            self.reporter,
                            self,
                        ))
        self.periodic_call()
        worker.start()

        # Overwrite the .pylint-gui-history file with all the new recently added files
        # in order from filenames but only save last 10 files
        write_history = open(HOME + HISTORY, 'w')
        write_history.writelines(self.filenames)
        write_history.close()
        self.set_history_window()

        self.root.configure(cursor='')

    def show_sourcefile(self, event=None):
        selected = self.lb_messages.curselection()
        if not selected:
            return

        msg = self.visible_msgs[int(selected[0])]
        scroll = msg.line - 3
        if scroll < 0:
            scroll = 0

        self.tabs["Source File"] = open(msg.path, "r").readlines()
        self.box.set("Source File")
        self.refresh_results_window()
        self.results.yview(scroll)
        self.results.select_set(msg.line - 1)
示例#23
0
class OfflineVisualiser(Visualiser):
    """A VTK-powered offline visualiser which runs in its own thread.
    In addition to the functions provided by the standard visualiser,
    the following additional functions are provided:

    precache_height_quantities() - Precache all the vtkpoints
    structures for any dynamic height based quantities to render.
    """
    def __init__(self, source, frameDelay=100, frameStep=1):
        """The source parameter is assumed to be a NetCDF sww file.
        The frameDelay parameter is the number of milliseconds waited between frames.
        """
        Visualiser.__init__(self, source)

        self.frameNumber = 0
        fin = NetCDFFile(self.source, 'r')
        self.maxFrameNumber = fin.variables['time'].shape[0] - 1
        fin.close()

        #self.frameNumberTkVariable = StringVar()
        #self.frameNumberTkVariable.set('Frame - %05g'%self.framNumber)

        self.frameDelay = frameDelay

        self.xmin = None
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.zmin = None
        self.zmax = None

        self.frameStep = frameStep

        self.vtk_heightQuantityCache = []
        for i in range(self.maxFrameNumber +
                       1):  # maxFrameNumber is zero indexed.
            self.vtk_heightQuantityCache.append({})

        self.paused = False
        self.movie = False

    def setup_grid(self):
        fin = NetCDFFile(self.source, 'r')
        self.vtk_cells = vtkCellArray()
        N_tri = fin.variables['volumes'].shape[0]
        for v in range(N_tri):
            self.vtk_cells.InsertNextCell(3)
            for i in range(3):
                self.vtk_cells.InsertCellPoint(fin.variables['volumes'][v][i])
        fin.close()

    def update_height_quantity(self, quantityName, dynamic=True):
        polydata = self.vtk_polyData[quantityName] = vtkPolyData()
        if dynamic is True:
            #print ' - Frame',self.frameNumber,'of',self.maxFrameNumber
            if not self.vtk_heightQuantityCache[self.frameNumber].has_key(
                    quantityName):
                self.vtk_heightQuantityCache[self.frameNumber][quantityName]\
                    = self.read_height_quantity(quantityName, True, self.frameNumber)
            polydata.SetPoints(
                self.vtk_heightQuantityCache[self.frameNumber][quantityName])
        else:
            polydata.SetPoints(self.read_height_quantity(quantityName, False))
        polydata.SetPolys(self.vtk_cells)

    def get_3d_bounds(self):
        return [
            self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax
        ]

    def read_height_quantity(self, quantityName, dynamic=True, frameNumber=0):
        """Read in a height based quantity from the NetCDF source file
        and return a vtkPoints object. frameNumber is ignored if
        dynamic is false."""
        fin = NetCDFFile(self.source, 'r')
        points = vtkPoints()
        if dynamic is True:
            N_vert = fin.variables[quantityName].shape[1]
        else:
            N_vert = len(fin.variables[quantityName])
        x = num.ravel(num.array(fin.variables['x'], num.float))
        y = num.ravel(num.array(fin.variables['y'], num.float))
        if dynamic is True:
            q = num.array(fin.variables[quantityName][frameNumber], num.float)
        else:
            q = num.ravel(num.array(fin.variables[quantityName], num.float))

        q *= self.height_zScales[quantityName]
        q += self.height_offset[quantityName]

        for v in range(N_vert):
            points.InsertNextPoint(x[v], y[v], q[v])
            if self.xmin is None or self.xmin > x[v]:
                self.xmin = x[v]
            if self.xmax is None or self.xmax < x[v]:
                self.xmax = x[v]
            if self.ymin is None or self.ymin > y[v]:
                self.ymin = y[v]
            if self.ymax is None or self.ymax < y[v]:
                self.ymax = y[v]
            if self.zmin is None or self.zmin > q[v]:
                self.zmin = q[v]
            if self.zmax is None or self.zmax < q[v]:
                self.zmax = q[v]
        fin.close()
        return points

    def precache_height_quantities(self):
        """Precache any height-based quantities. Call before rendering
        beigns."""
        for q in self.height_quantities:
            if self.height_dynamic[q] is True:
                print 'Precaching %s' % q
                for i in range(self.maxFrameNumber +
                               1):  # maxFrameNumber is zero-indexed
                    print ' - Frame %d of %d' % (i, self.maxFrameNumber)
                    self.vtk_heightQuantityCache[i][q]\
                        = self.read_height_quantity(q, True, i)

    def build_quantity_dict(self):
        quantities = {}
        fin = NetCDFFile(self.source, 'r')
        for q in filter(
                lambda n: n != 'x' and n != 'y' and n != 'z' and n != 'time'
                and n != 'volumes', fin.variables.keys()):
            if len(fin.variables[q].shape) == 1:  # Not a time-varying quantity
                quantities[q] = num.ravel(
                    num.array(fin.variables[q], num.float))
            else:  # Time-varying, get the current timestep data
                quantities[q] = num.array(fin.variables[q][self.frameNumber],
                                          num.float)
        fin.close()
        return quantities

    def setup_gui(self):
        Visualiser.setup_gui(self)
        self.tk_quit.grid(row=0, column=0, sticky=W + E)
        self.tk_movie_toggle = Button(self.tk_controlFrame,
                                      text="Movie off",
                                      command=self.movie_toggle)
        self.tk_movie_toggle.grid(row=0, column=6, sticky=W + E)

        self.tk_restart = Button(self.tk_controlFrame,
                                 text="<<<",
                                 command=self.restart,
                                 width=5)
        self.tk_restart.grid(row=1, column=0, sticky=W + E)
        self.tk_back10 = Button(self.tk_controlFrame,
                                text="<<",
                                command=self.back10,
                                width=5)
        self.tk_back10.grid(row=1, column=1, sticky=W + E)
        self.tk_back = Button(self.tk_controlFrame,
                              text="<",
                              command=self.back,
                              width=5)
        self.tk_back.grid(row=1, column=2, sticky=W + E)
        self.tk_pauseResume = Button(self.tk_controlFrame,
                                     text="Pause",
                                     command=self.pauseResume,
                                     width=15)
        self.tk_pauseResume.grid(row=1, column=3, sticky=W + E)
        self.tk_forward = Button(self.tk_controlFrame,
                                 text=">",
                                 command=self.forward,
                                 width=5)
        self.tk_forward.grid(row=1, column=4, sticky=W + E)
        self.tk_forward10 = Button(self.tk_controlFrame,
                                   text=">>",
                                   command=self.forward10,
                                   width=5)
        self.tk_forward10.grid(row=1, column=5, sticky=W + E)
        self.tk_forwardEnd = Button(self.tk_controlFrame,
                                    text=">>>",
                                    command=self.forwardEnd,
                                    width=5)
        self.tk_forwardEnd.grid(row=1, column=6, sticky=W + E)

        self.tk_frameNumber = Label(self.tk_controlFrame, text='Frame')
        self.tk_frameNumber.grid(row=2, column=0, sticky=W + E)
        self.tk_gotoFrame = Scale(self.tk_controlFrame,
                                  from_=0,
                                  to=self.maxFrameNumber,
                                  orient=HORIZONTAL)
        self.tk_gotoFrame.grid(row=2, column=1, columnspan=2, sticky=W + E)
        self.tk_stepLabel = Label(self.tk_controlFrame, text='Step')
        self.tk_stepLabel.grid(row=2, column=4, sticky=W + E)
        self.tk_frameStep = Scale(self.tk_controlFrame,
                                  from_=0,
                                  to=self.maxFrameNumber,
                                  orient=HORIZONTAL)
        self.tk_frameStep.grid(row=2, column=5, columnspan=2, sticky=W + E)

        # Make the buttons stretch to fill all available space
        for i in range(7):
            self.tk_controlFrame.grid_columnconfigure(i, weight=1)

    def run(self):
        self.alter_tkroot(Tk.after, (self.frameDelay, self.animateForward))
        Visualiser.run(self)

    def restart(self):
        self.frameNumber = 0
        self.redraw_quantities()
        self.update_labels()
        self.pause()

        if self.movie:
            self.save_image()

    def forwardEnd(self):
        self.frameNumber = self.maxFrameNumber
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def movie_toggle(self):
        if self.movie == True:
            self.movie = False
            self.tk_movie_toggle.config(text='Movie off')
        else:
            self.movie = True
            self.tk_movie_toggle.config(text='Movie on ')

    def save_image(self):

        from vtk import vtkJPEGWriter, vtkJPEGWriter, vtkPNGWriter
        from vtk import vtkPNMWriter, vtkWindowToImageFilter
        from os import path

        sourcebase, _ = path.splitext(self.source)
        fname = sourcebase + '%05g.png' % self.frameNumber
        #print fname

        extmap = {
            '.jpg': vtkJPEGWriter,
            '.jpeg': vtkJPEGWriter,
            '.png': vtkPNGWriter,
            '.pnm': vtkPNMWriter,
        }
        basename, ext = path.splitext(fname)
        try:
            Writer = extmap[ext.lower()]
        except KeyError:
            error_msg("Don't know how to handle %s files" % ext, parent=self)
            return

        renWin = self.vtk_renderer.GetRenderWindow()
        w2i = vtkWindowToImageFilter()
        writer = Writer()
        w2i.SetInput(renWin)
        w2i.Update()
        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(fname)
        renWin.Render()
        writer.Write()

    def back10(self):
        if self.frameNumber - 10 >= 0:
            self.frameNumber -= 10
        else:
            self.frameNumber = 0
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def back(self):
        if self.frameNumber > 0:
            self.frameNumber -= 1
            self.redraw_quantities()
            self.update_labels()
            self.pause()

    def pauseResume(self):
        if self.paused is True:
            self.resume()
        else:
            self.pause()

    def pause(self):
        self.paused = True
        self.tk_pauseResume.config(text="Resume")

    def resume(self):
        self.paused = False
        self.tk_pauseResume.config(text="Pause")
        self.frameNumber = self.tk_gotoFrame.get()
        self.frameStep = self.tk_frameStep.get()
        self.tk_root.after(self.frameDelay, self.animateForward)

    def forward(self):
        if self.frameNumber < self.maxFrameNumber:
            self.frameNumber += 1
            self.redraw_quantities()
            self.update_labels()
            self.pause()

    def forward_step(self):
        if self.frameNumber + self.frameStep <= self.maxFrameNumber:
            self.frameNumber += self.frameStep
            self.redraw_quantities()
            self.update_labels()
        else:
            self.frameNumber = self.maxFrameNumber
            self.redraw_quantities()
            self.update_labels()
            self.pause()

        if self.movie:
            self.save_image()

    def forward10(self):
        if self.frameNumber + 10 <= self.maxFrameNumber:
            self.frameNumber += 10
        else:
            self.frameNumber = self.maxFrameNumber
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def animateForward(self):
        if self.paused is not True:
            self.forward_step()
            self.tk_root.after(self.frameDelay, self.animateForward)

    def update_labels(self):
        #self.tk_frameNumber.config(text='%05g of %05g'%(self.frameNumber,self.maxFrameNumber))
        self.tk_gotoFrame.set(self.frameNumber)
        self.tk_frameStep.set(self.frameStep)

    def shutdown(self):
        #self.pause()
        self.tk_root.withdraw()
        self.tk_root.destroy()
示例#24
0
class App(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack(fill=BOTH, expand=True)

        url_lab = Label(frame,
                        text='URL:',
                        fg='green',
                        font=('Courier New', 16))
        url_lab.grid(row=0, column=0, sticky=N + E)

        self.url_text = Text(frame,
                             width=60,
                             height=3,
                             font=('Courier New', 12))
        self.url_text.grid(row=0, column=1)

        f5_lab = Label(frame,
                       text='F5 Big-Ip:',
                       fg='blue',
                       font=('Courier New', 14))
        f5_lab.grid(row=1, column=0, sticky=N)

        self.f5bigip = StringVar()
        self.f5bigipEntry = Entry(frame, textvariable=self.f5bigip)
        self.f5bigipEntry.config(font=('Courier New', 12))
        self.f5bigipEntry.config(width=60)
        self.f5bigipEntry.grid(row=1, column=1)

        self.testbtn = Button(frame, text='检测', font=('Courier New', 12))
        self.testbtn.config(width=25)
        self.testbtn.config(bg='LightSkyBlue')
        self.testbtn.grid(row=2, column=1, sticky=W)

        self.decodebtn = Button(frame,
                                text='解码F5 Big-Ip 值',
                                font=('Courier New', 12))
        self.decodebtn.config(width=25)
        self.decodebtn.config(bg='LightSkyBlue')
        self.decodebtn.grid(row=2, column=1, sticky=E)

        self.result_lab = Label(frame,
                                text='执行结果:',
                                fg='blue',
                                font=('Courier New', 14))
        self.result_lab.grid(row=3, column=0, sticky=N + E)

        scroll = Scrollbar(frame)
        scroll.grid(row=3, column=1, sticky=E + N + S)
        self.response = Text(frame,
                             width=58,
                             height=18,
                             font=('Courier New', 12))
        self.response.grid(row=3, column=1, sticky=W + S)
        self.response.config(yscrollcommand=scroll.set)
        scroll.config(command=self.response.yview)

        self.msg = StringVar()
        self.msg_lab = Label(frame,
                             textvariable=self.msg,
                             fg='blue',
                             font=('Courier New', 12))
        self.msg_lab.grid(row=4, column=0, columnspan=2, sticky=N + S + W + E)

        self.testbtn.bind('<Button-1>', self.check)
        self.decodebtn.bind('<Button-1>', self.decode_bigip2)

        self.url = ''
        self.pattern = re.compile('^(?:http|https)://(?:\w+\.)+.+')

        self.headers = {
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
        }

    def check(self, event):
        self.msg.set('')
        self.url = self.url_text.get(1.0, END).strip()
        chek_url = self.pattern.match(self.url)
        # print chek_url.group()
        if not chek_url:
            # print ('123')
            self.msg.set('请输入正确的(GET)URL!')
        else:
            try:
                self.msg.set('')
                self.f5bigip.set('')
                self.response.delete(1.0, END)
                response = get(self.url, headers=self.headers)
                headers = response.headers
                set_cookie = headers.get('Set-cookie', None)
                headers = '\n'.join(
                    [':'.join(item) for item in response.headers.iteritems()])
                # print headers

                if set_cookie:
                    bigip_value = self.getBigIPvalue(set_cookie)
                    if bigip_value:
                        self.f5bigip.set(bigip_value)
                        self.msg_lab.config(fg='red')
                        host = self.decode_bigip(bigip_value)
                        self.msg.set(
                            'F5 BIG-IP Cookie Remote Information Disclosure\n'
                            '存在信息泄露漏洞!\n'
                            '内网地址:' + host)

                    else:
                        self.msg_lab.config(fg='blue')
                        self.msg.set('不存在信息泄露漏洞!')
                else:
                    self.msg_lab.config(fg='blue')
                    self.msg.set('不存在信息泄露漏洞!')

                self.response.delete(1.0, END)
                self.response.insert(END, headers + '\n\n' + response.text)

            except:
                self.msg_lab.config(fg='red')
                self.msg.set('网络资源请求失败,请确保已经接入互联网和网址的有效性!')

    def getBigIPvalue(self, set_cookie):
        if set_cookie:
            lst = set_cookie.split(';')
            lst = [item.split('=') for item in lst]
            # print lst
            for key, value in lst:
                if re.search('BIGipServer.*?', key):
                    return value

        return ''

    def decode_bigip(self, bigip_value):
        if bigip_value:
            if re.match('\d+\.\d+\.\d+', bigip_value):
                host, port, end = bigip_value.split('.')
                host = [ord(i) for i in struct.pack("<I", int(host))]
                port = [ord(e) for e in struct.pack("<H", int(port))]
                host = '.'.join([str(i) for i in host])
                port = '0x%02X%02X' % (port[0], port[1])
                # print port
                port = str(int(port, 16))

                return ':'.join([host, port])
            else:
                showerror(
                    'Decode F5 Bigip Error',
                    'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) '
                )
                return ''

        return ''

    def decode_bigip2(self, event):
        bigip_value = self.f5bigip.get().strip()
        result = self.decode_bigip(bigip_value)
        if result:
            showinfo("Decode F5 Bigip ", "%s : %s" % (bigip_value, result))
        else:
            showerror(
                'Decode F5 Bigip Error',
                'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) ')
示例#25
0
文件: gui.py 项目: cyphyhouse/UI-
class MapUI:
    def __init__(self, master):
        def center(win):
            win.update_idletasks()
            width = win.winfo_width()
            height = win.winfo_height()
            x = (win.winfo_screenwidth() // 4) - (width // 2) + 40
            y = (win.winfo_screenheight() // 4) - (height // 2) + 40
            win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

        def callback(event):
            event.widget.focus_set()
            print "clicked at", event.x, event.y

            if self.add_tasks_flg.get() == 1:
                # Select number of robots
                # Define elements of pop up window
                self.top = Toplevel()

                self.num_robots = StringVar(self.top)
                self.num_robots.set("1")  # default value
                w = OptionMenu(self.top, self.num_robots, '1', '2', '3',
                               '4').grid(row=0, column=1)
                text1 = Message(self.top, text="Number of robots:",
                                width=150).grid(row=0, column=0)

                self.e = Entry(self.top, width=10)
                self.e.grid(row=1, column=1)
                text2 = Message(self.top, text="Task duration:",
                                width=150).grid(row=1, column=0)
                text3 = Message(self.top, text="(s)", width=60).grid(row=1,
                                                                     column=2)

                newline = Message(self.top, text=" ").grid(row=2)

                button = Button(self.top,
                                text='Enter',
                                command=lambda: self.enter_task(event)).grid(
                                    row=3, column=1)
                button_cancel = Button(self.top,
                                       text='Cancel',
                                       command=self.cancel_task).grid(row=3,
                                                                      column=2)

                center(self.top)

        master.title("Map Interface")
        master.minsize(width=1000, height=750)
        master.maxsize(width=1000, height=750)
        master.config(bg=BKG_COLOUR)
        self.master = master

        # Canvas for overlaying map
        self.map_canvas = Canvas(master,
                                 width=CANVAS_W,
                                 height=CANVAS_H,
                                 bg='gray85',
                                 highlightthickness=0)
        self.map_canvas.pack(side='right', padx=50)
        self.map_canvas.bind("<Button-1>", callback)
        global CANVAS_PTR
        CANVAS_PTR = self.map_canvas
        self.master.update()
        w = self.map_canvas.winfo_width()
        h = self.map_canvas.winfo_height()
        # Overlay a grid
        for i in range(0, w, SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(i, 0, i, h, dash=1)
        for i in range(0, h, SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(0, i, w, i, dash=1)

        # Load in flame icon from flame.gif
        self.flame_icon = PhotoImage(file="flame.gif")
        # Load in the drone icon from drone.gif
        global DRONE_ICON
        DRONE_ICON = PhotoImage(file="drone.gif")

        buttons_frame = Canvas(master,
                               width=163,
                               height=230,
                               bg=BUTTONS_BKG_COLOUR,
                               highlightthickness=1,
                               highlightbackground='dim grey')
        buttons_frame.place(x=40, y=200)

        # Define UI buttons
        self.add_tasks_flg = IntVar()
        self.add_tasks_b = Checkbutton(master,
                                       text="Add Tasks",
                                       variable=self.add_tasks_flg,
                                       highlightbackground=BUTTONS_BKG_COLOUR,
                                       background=BUTTONS_BKG_COLOUR)
        self.add_tasks_b.place(x=77, y=240)

        self.clear_wp_b = Button(master,
                                 text='Clear Tasks',
                                 command=self.clear_wp,
                                 highlightbackground=BUTTONS_BKG_COLOUR)
        self.clear_wp_b.config(width=10)
        self.clear_wp_b.place(x=65, y=270)
        '''
        self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR)
        self.gen_wp_file_b.config(width=20)
        self.gen_wp_file_b.place(x=20, y=250)
        '''

        self.land_b = Button(master,
                             text='Land',
                             command=self.land,
                             highlightbackground=BUTTONS_BKG_COLOUR)
        self.land_b.config(width=10)
        self.land_b.place(x=65, y=350)

        # Set up coordinate system conversion and display corners of room:
        file_obj = open('antenna_locations.txt', 'r')
        anchors = []
        for line in file_obj:
            cur_anchors = map(float, line.split())
            anchors.append(cur_anchors)
        file_obj.close()
        anchors = (np.array(anchors)).T

        # Find largest (abs) x and y values to use a reference for conversion ratio
        x_vals = anchors[0]
        largest_x_val = x_vals[np.argmax(abs(x_vals))]
        y_vals = anchors[1]
        largest_y_val = y_vals[np.argmax(abs(y_vals))]

        if largest_x_val > largest_y_val:
            largest_y_val = largest_x_val
        else:
            largest_x_val = largest_y_val

        global m_per_pixel_x
        m_per_pixel_x = float(largest_x_val / (CANVAS_W / 2))
        global m_per_pixel_y
        m_per_pixel_y = float(largest_y_val / (CANVAS_H / 2))

        # Place antenna (anchors) on UI
        anchors = anchors.T
        for cur_anchor in anchors:
            x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W / 2
            y_pixel_loc = -1 * (cur_anchor[1] / m_per_pixel_y) + CANVAS_H / 2

            # Draw antenna @ location
            global ANTENNA_LIST
            antenna_id = self.map_canvas.create_oval(x_pixel_loc - 15,
                                                     y_pixel_loc - 15,
                                                     x_pixel_loc + 15,
                                                     y_pixel_loc + 15,
                                                     fill='red')

        self.master.update()

    global SQ_SIZE
    SQ_SIZE = 20
    global BKG_COLOUR
    BKG_COLOUR = 'gray95'
    global BUTTONS_BKG_COLOUR
    BUTTONS_BKG_COLOUR = 'grey66'
    global CANVAS_W
    CANVAS_W = 700
    global CANVAS_H
    CANVAS_H = 700
    global TASK_LIST
    TASK_LIST = None
    global m_per_pixel_x
    m_per_pixel_x = None
    global m_per_pixel_y
    m_per_pixel_y = None
    global NEW_TASK_FLAG
    NEW_TASK_FLAG = False
    global ANTENNA_LIST
    ANTENNA_LIST = None
    global DRONE_ICON
    DRONE_ICON = None

    flame_icon = None
    ui_wp_list = None
    #task_list = None
    add_wp_flag = False
    task_id = 0
    add_tasks_flg = None

    def add_tasks(self):
        print "adding tasks"
        # function imp here
        self.add_wp_flag = True
        self.map_canvas.config(cursor='pencil')

    def clear_wp(self):
        print "clear tasks"
        global TASK_LIST
        TASK_LIST = None
        for element_id in self.ui_wp_list:
            self.map_canvas.delete(element_id[0])
        self.ui_wp_list = None

    '''
    def gen_wp_file(self):
        print "generate wp file"
        # function imp here
    '''

    def land(self):
        # Send a new task with position (0,0,0) z=0 tells drone to land
        print("land")

    def enter_task(self, event):
        # Determine square (top left corner coords):
        w_start = event.x - event.x % SQ_SIZE
        h_start = event.y - event.y % SQ_SIZE

        #Translate pixel location to physical location
        x_pixel = event.x
        y_pixel = event.y
        # Find out how many pixels from center:
        x_pixel = x_pixel - CANVAS_W / 2
        x_physical = x_pixel * m_per_pixel_x

        #vertical case, note this is flipped
        y_pixel = y_pixel - CANVAS_W / 2
        y_pixel = -1 * y_pixel
        y_physical = y_pixel * m_per_pixel_y

        try:
            # Add to task list
            global TASK_LIST
            if TASK_LIST == None:
                TASK_LIST = [[
                    self.task_id,
                    int(self.num_robots.get()),
                    float(self.e.get()), x_physical, y_physical
                ]]
                global NEW_TASK_FLAG
                NEW_TASK_FLAG = True
            else:
                TASK_LIST.append([
                    self.task_id,
                    int(self.num_robots.get()),
                    float(self.e.get()), x_physical, y_physical
                ])
                global NEW_TASK_FLAG
                NEW_TASK_FLAG = True

            # Indicate task in UI
            element_id = self.map_canvas.create_image(event.x,
                                                      event.y,
                                                      image=self.flame_icon)
            if self.ui_wp_list == None:
                self.ui_wp_list = [[element_id]]
            else:
                self.ui_wp_list.append([element_id])
        except:
            print("Invalid Task Entry")

        self.map_canvas.config(cursor='arrow')
        self.add_wp_flag = False

        print(TASK_LIST)

        self.task_id = self.task_id + 1
        self.top.destroy()

    def cancel_task(self):
        self.top.destroy()
示例#26
0
class You2XBMC():
	""" XBMC Object"""
	def __init__(self):
		#Initialize GUI
		self.address=None
		self.video = None
		self.ipAddress = None
		self.home = expanduser("~")
	
		self.config_widgets() #Configure Window and Widgets

		# Test if file exists, and if it does read the ip address
		if not isfile(self.home+"/"+"xbmcIP.txt"): 
			print "No File :("
			self.ipAddress = False 
		elif isfile(self.home+"/"+"xbmcIP.txt"): 
			print "File Exists :)"
			self.ipAddress = open(self.home+"/"+"xbmcIP.txt", "r").read().splitlines()[0] 
			print self.ipAddress
			
		if self.ipAddress != False: 
			self.ipEntry.insert(0, self.ipAddress)
			
		#Pack and Mainloop
		self.grid_everything()
		self.mainloop()
		
	def set_video(self):
		# Create a thread that sets the video
		x = Thread(target=self.set_video_callback)
		x.start()
		
	def set_video_callback(self):
		# This function creates a new file if a file doesn't exist with the ip address of the xbmc
		# it also sends the video to the JSON server
		if self.ipAddress == False:
			self.ipAddress = self.ipEntry.get() 
			xbmcIP = open(self.home+"/"+"xbmcIP.txt", "w")
			xbmcIP.write(str(self.ipAddress))
			xbmcIP.close()
		
		# Send video to XBMC	
		self.ipAddress = ("http://"+self.ipEntry.get()+"/jsonrpc")
		xbmc = XBMC(self.ipAddress)
		address = self.addressEntry.get()
		video = pafy.new(address)
		video = video.getbest()
		print xbmc.Player.Open(item={"file": video.url})

	def get_clipboard(self):
		# Get a video address fom clipboard
		string = self.window.clipboard_get()
		self.addressEntry.delete(0,END)
		self.addressEntry.insert(0, string)
		self.set_video()
		
	def config_widgets(self):
		# Create window and widgets
		self.window = Tk()
		self.window.title("Send youtube video to XBMC")
		self.window.resizable(0,0)
		self.addressEntry = Entry()
		self.addressEntry.config(width=50)
		self.addressEntry.config(justify=CENTER)
		self.addressLabel = Label(text="Insert youtube video address: ")
		self.ipEntry = Entry()
		self.ipEntry.config(justify=CENTER)
		self.ipLabel = Label(text="Ip address of XBMC machine: ")
		self.sendButton = Button(self.window, text="Play on XBMC", command=self.set_video)
		self.sendButton.config(width=30)
		self.clipboardButton = Button(text="Click to get from clipboard", command=self.get_clipboard)
		
	def grid_everything(self):
		# Grid everything up
		self.addressLabel.grid(row=0, column=0,pady=5, padx=20)
		self.addressEntry.grid(row=0, column=1, pady=10)
		self.sendButton.grid(row=3, column=1, pady=5)
		self.clipboardButton.grid(row=0, column=2, padx=3)
		self.ipEntry.grid(row=2, column=1, pady=10)
		self.ipLabel.grid(row=2, column=0,pady=5, padx=20)

	def mainloop(self):
		mainloop()
示例#27
0
文件: window.py 项目: timpauls/raypy
class Window(Frame):
    RENDER_PROCESSES = 2

    def __init__(self, width, height, scene, tracer, calculate=None):
        Frame.__init__(self, master=None)

        if calculate is None:
            calculate = [0, 0]

        self.d = calculate
        self.scene = scene
        self.after_id = 0
        self.tracer = tracer
        self.width = width
        self.height = height

        self.__init_window(height, width)

        self.master.mainloop()

    def __init_window(self, height, width):
        self.master.title = "Ray Py"
        canvas = Canvas(self.master, width=width, height=height)
        canvas.pack(side=TOP)
        self.img = PhotoImage(width=width, height=height)
        canvas.create_image((width / 2, height / 2),
                            image=self.img,
                            state="normal")
        self.startButton = Button(self.master,
                                  text="Render",
                                  command=lambda: self.__onStartPressed())
        self.startButton.pack(side=RIGHT)
        self.resetButton = Button(self.master,
                                  text="Reset",
                                  command=lambda: self.__onResetPressed())
        self.resetButton.config(state="disabled")
        self.resetButton.pack(side=RIGHT)

        self.listbox = Listbox(self.master, height=5)
        self.listbox.bind('<<ListboxSelect>>', self.__selectTracer)
        self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow",
                            "Recursive", "PathTracer")
        self.listbox.pack(side=LEFT)

        self.listbox.selection_set(0)
        self.listbox.activate(0)
        self.listbox.focus_set()

    def __selectTracer(self, evt):
        value = self.listbox.get(self.listbox.curselection())
        if value == "Simple":
            self.tracer = SimpleRayTracer()
        elif value == "Shadow":
            self.tracer = SimpleShadowRayTracer()
        elif value == "ShadingShadow":
            self.tracer = ShadingShadowRayTracer(self.scene.eye)
        elif value == "Recursive":
            self.tracer = RecursiveRayTracer(self.scene.eye)
        elif value == "PathTracer":
            self.tracer = PathTracer(self.scene.eye)

    def __onStartPressed(self):
        self.startButton.config(state="disabled")
        self.listbox.config(state="disabled")
        self.__draw()

    def __update(self):
        if self.finishedQueue.qsize() >= self.RENDER_PROCESSES:
            self.finishedThreads = self.RENDER_PROCESSES
            while not self.finishedQueue.empty():
                self.finishedQueue.get()

        if not self.dataQueue.empty():
            item = self.dataQueue.get()
            self.img.put(item[1], item[0])
            self.master.update()
        elif self.finishedThreads == self.RENDER_PROCESSES:
            for t in self.threads:
                t.join()

            self.master.after_cancel(self.after_id)
            self.resetButton.config(state="active")
            return

        self.after_id = self.master.after(0, self.__update)

    def __draw(self):
        from processes import BlockProcess
        from multiprocessing import Queue
        self.finishedQueue = Queue()
        self.dataQueue = Queue()
        self.finishedThreads = 0

        self.threads = BlockProcess.forCount(self.RENDER_PROCESSES, self.width,
                                             self.height, self.tracer,
                                             self.scene, self.dataQueue,
                                             self.finishedQueue)

        for t in self.threads:
            t.start()

        self.__update()

        self.after_id = self.master.after(0, self.__update)

    def __onResetPressed(self):
        self.img.blank()
        self.d = [0, 0]
        self.resetButton.config(state="disabled")
        self.startButton.config(state="active")
        self.listbox.config(state="normal")
示例#28
0
class GetKeysDialog(Toplevel):
    def __init__(self,parent,title,action,currentKeySequences,_htest=False):
        """
        action - string, the name of the virtual event these keys will be
                 mapped to
        currentKeys - list, a list of all key sequence lists currently mapped
                 to virtual events, for overlap checking
        _htest - bool, change box location when running htest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE,width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.action=action
        self.currentKeySequences=currentKeySequences
        self.result=''
        self.keyString=StringVar(self)
        self.keyString.set('')
        self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label
        self.modifier_vars = []
        for modifier in self.modifiers:
            variable = StringVar(self)
            variable.set('')
            self.modifier_vars.append(variable)
        self.advanced = False
        self.CreateWidgets()
        self.LoadFinalKeyList()
        self.withdraw() #hide while setting geometry
        self.update_idletasks()
        self.geometry(
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )  #centre dialog over parent (or below htest box)
        self.deiconify() #geometry set, unhide
        self.wait_window()

    def CreateWidgets(self):
        frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
        frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
        frameButtons=Frame(self)
        frameButtons.pack(side=BOTTOM,fill=X)
        self.buttonOK = Button(frameButtons,text='OK',
                width=8,command=self.OK)
        self.buttonOK.grid(row=0,column=0,padx=5,pady=5)
        self.buttonCancel = Button(frameButtons,text='Cancel',
                width=8,command=self.Cancel)
        self.buttonCancel.grid(row=0,column=1,padx=5,pady=5)
        self.frameKeySeqBasic = Frame(frameMain)
        self.frameKeySeqAdvanced = Frame(frameMain)
        self.frameControlsBasic = Frame(frameMain)
        self.frameHelpAdvanced = Frame(frameMain)
        self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.lift()
        self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.lift()
        self.buttonLevel = Button(frameMain,command=self.ToggleLevel,
                text='Advanced Key Binding Entry >>')
        self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5)
        labelTitleBasic = Label(self.frameKeySeqBasic,
                text="New keys for  '"+self.action+"' :")
        labelTitleBasic.pack(anchor=W)
        labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT,
                textvariable=self.keyString,relief=GROOVE,borderwidth=2)
        labelKeysBasic.pack(ipadx=5,ipady=5,fill=X)
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check=Checkbutton(self.frameControlsBasic,
                command=self.BuildKeyString,
                text=label,variable=variable,onvalue=modifier,offvalue='')
            check.grid(row=0,column=column,padx=2,sticky=W)
            self.modifier_checkbuttons[modifier] = check
            column += 1
        labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
                            text=\
                            "Select the desired modifier keys\n"+
                            "above, and the final key from the\n"+
                            "list on the right.\n\n" +
                            "Use upper case Symbols when using\n" +
                            "the Shift modifier.  (Letters will be\n" +
                            "converted automatically.)")
        labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
        self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
                selectmode=SINGLE)
        self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
        self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
        scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
                command=self.listKeysFinal.yview)
        self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
        scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
        self.buttonClear=Button(self.frameControlsBasic,
                text='Clear Keys',command=self.ClearKeySeq)
        self.buttonClear.grid(row=2,column=0,columnspan=4)
        labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
                text="Enter new binding(s) for  '"+self.action+"' :\n"+
                "(These bindings will not be checked for validity!)")
        labelTitleAdvanced.pack(anchor=W)
        self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
                textvariable=self.keyString)
        self.entryKeysAdvanced.pack(fill=X)
        labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
            text="Key bindings are specified using Tkinter keysyms as\n"+
                 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
                 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
                 "Upper case is used when the Shift modifier is present!\n\n" +
                 "'Emacs style' multi-keystroke bindings are specified as\n" +
                 "follows: <Control-x><Control-y>, where the first key\n" +
                 "is the 'do-nothing' keybinding.\n\n" +
                 "Multiple separate bindings for one action should be\n"+
                 "separated by a space, eg., <Alt-v> <Meta-v>." )
        labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)

    def SetModifiersForPlatform(self):
        """Determine list of names of key modifiers for this platform.

        The names are used to build Tk bindings -- it doesn't matter if the
        keyboard has these keys, it matters if Tk understands them. The
        order is also important: key binding equality depends on it, so
        config-keys.def must use the same ordering.
        """
        if sys.platform == "darwin":
            self.modifiers = ['Shift', 'Control', 'Option', 'Command']
        else:
            self.modifiers = ['Control', 'Alt', 'Shift']
        self.modifier_label = {'Control': 'Ctrl'} # short name

    def ToggleLevel(self):
        if  self.buttonLevel.cget('text')[:8]=='Advanced':
            self.ClearKeySeq()
            self.buttonLevel.config(text='<< Basic Key Binding Entry')
            self.frameKeySeqAdvanced.lift()
            self.frameHelpAdvanced.lift()
            self.entryKeysAdvanced.focus_set()
            self.advanced = True
        else:
            self.ClearKeySeq()
            self.buttonLevel.config(text='Advanced Key Binding Entry >>')
            self.frameKeySeqBasic.lift()
            self.frameControlsBasic.lift()
            self.advanced = False

    def FinalKeySelected(self,event):
        self.BuildKeyString()

    def BuildKeyString(self):
        keyList = modifiers = self.GetModifiers()
        finalKey = self.listKeysFinal.get(ANCHOR)
        if finalKey:
            finalKey = self.TranslateKey(finalKey, modifiers)
            keyList.append(finalKey)
        self.keyString.set('<' + string.join(keyList,'-') + '>')

    def GetModifiers(self):
        modList = [variable.get() for variable in self.modifier_vars]
        return [mod for mod in modList if mod]

    def ClearKeySeq(self):
        self.listKeysFinal.select_clear(0,END)
        self.listKeysFinal.yview(MOVETO, '0.0')
        for variable in self.modifier_vars:
            variable.set('')
        self.keyString.set('')

    def LoadFinalKeyList(self):
        #these tuples are also available for use in validity checks
        self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9',
                'F10','F11','F12')
        self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
        self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
        self.whitespaceKeys=('Tab','Space','Return')
        self.editKeys=('BackSpace','Delete','Insert')
        self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
                'Right Arrow','Up Arrow','Down Arrow')
        #make a tuple of most of the useful common 'final' keys
        keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
                self.whitespaceKeys+self.editKeys+self.moveKeys)
        self.listKeysFinal.insert(END, *keys)

    def TranslateKey(self, key, modifiers):
        "Translate from keycap symbol to the Tkinter keysym"
        translateDict = {'Space':'space',
                '~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
                '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
                '(':'parenleft',')':'parenright','_':'underscore','-':'minus',
                '+':'plus','=':'equal','{':'braceleft','}':'braceright',
                '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
                ':':'colon',',':'comma','.':'period','<':'less','>':'greater',
                '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
                'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
                'Down Arrow': 'Down', 'Tab':'Tab'}
        if key in translateDict.keys():
            key = translateDict[key]
        if 'Shift' in modifiers and key in string.ascii_lowercase:
            key = key.upper()
        key = 'Key-' + key
        return key

    def OK(self, event=None):
        if self.advanced or self.KeysOK():  # doesn't check advanced string yet
            self.result=self.keyString.get()
            self.destroy()

    def Cancel(self, event=None):
        self.result=''
        self.destroy()

    def KeysOK(self):
        '''Validity check on user's 'basic' keybinding selection.

        Doesn't check the string produced by the advanced dialog because
        'modifiers' isn't set.

        '''
        keys = self.keyString.get()
        keys.strip()
        finalKey = self.listKeysFinal.get(ANCHOR)
        modifiers = self.GetModifiers()
        # create a key sequence list for overlap check:
        keySequence = keys.split()
        keysOK = False
        title = 'Key Sequence Error'
        if not keys:
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No keys specified.')
        elif not keys.endswith('>'):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='Missing the final Key')
        elif (not modifiers
              and finalKey not in self.functionKeys + self.moveKeys):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No modifier key(s) specified.')
        elif (modifiers == ['Shift']) \
                 and (finalKey not in
                      self.functionKeys + self.moveKeys + ('Tab', 'Space')):
            msg = 'The shift modifier by itself may not be used with'\
                  ' this key symbol.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        elif keySequence in self.currentKeySequences:
            msg = 'This key combination is already in use.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        else:
            keysOK = True
        return keysOK
示例#29
0
class Interface():
    def __init__(self, init, speed):
        self.init_compt = init
        self.speed = speed

        self.window = Tk()
        self.title = self.window.title('IA Minoïde')
        self.window.geometry('500x200')

        self.lbl = Label(self.window)
        self.btn = Button(self.window)

        self.reinit()

        self.window.mainloop()

    def start(self):
        net = self.NETWORK.get()
        chk1 = self.chk_state1.get()
        try:
            value0 = int(self.txt1.get())
            value1 = int(self.txt2.get())
            value2 = int(self.txt3.get())
            self.terget = [value0, value1, value2]
        except:
            #Messagebox.showinfo('Attention/',
            #'Les valeurs entrées ne sont pas correctes !')
            return
        self.txt1.destroy()
        self.txt2.destroy()
        self.txt3.destroy()
        self.chk0.destroy()
        self.chk1.destroy()
        self.res = 'Coordonnées cible: ('\
            + str(value0) + ', ' + str(value1)\
            +", "+ str(value2) + ')'

        #robot = VrepPioneerSimulation()
        robot = Pioneer(rospy)
        HL_size = 10  # nbre neurons of Hiden layer
        network = NN(3, HL_size, 2)
        self.trainer = OnlineTrainer(robot, network)

        if net:
            with open('last_w.json') as fp:
                json_obj = json.load(fp)
            for i in range(3):
                for j in range(HL_size):
                    network.wi[i][j] = json_obj["input_weights"][i][j]
            for i in range(HL_size):
                for j in range(2):
                    network.wo[i][j] = json_obj["output_weights"][i][j]
            print('Check 0 True')
        else:
            print('Check 0 False')

        if chk1:
            print('Check 1 True')
            thread = threading.Thread(target=self.trainer.train,
                                      args=(self.terget, ))
            thread.start()
        else:
            print('Check 1 False')

        if net:
            self.window.after(1, self.loop)
        else:
            self.window.after(1, self.save_file)

    def save_file(self):
        self.txt = Entry(self.window, width=30)
        self.lbl.config(text='Give a name to the log file (default to last):')
        self.btn.config(text='Valider', command=self.loop)

        self.txt.grid(column=0, row=1)
        self.lbl.grid(column=0, row=0)
        self.btn.grid(column=0, row=2)

        try:
            self.file_name = self.txt.get()
        except:
            """Messagebox.showinfo('Attention/',
                                "Le nom de fichier n'est pas correct")"""
        if self.file_name == '':
            self.file_name = 'last'
        with open("logs/" + self.file_name + ".json", 'w') as f:
            print(self.trainer.log_file)
            json.dump(self.trainer.log_file, f)
        f.close()
        print('Graph values have been saved in ' + self.file_name +
              '.json file')

    def loop(self):

        self.lbl.config(text=self.res)
        self.btn.config(text='Stop', command=self.stop)
        try:
            self.txt.destroy()
        except:
            pass

        if self.arret == 1:
            self.arret = 0
            self.lbl.config(text='Arrêt')
            self.btn.config(text='Réinitialiser', command=self.reinit)
            return

        if self.compt <= 0:
            self.lbl.config(text='Time is over !')
            self.btn.config(text='Réinitialiser', command=self.reinit)
            return

        self.compt -= self.speed / 100

        self.window.after(1, self.loop)

    def stop(self):
        self.arret = 1

    def reinit(self):
        self.arret = 0
        self.compt = self.init_compt

        self.lbl.config(text='Saisissez les coordonnées:',
                        bg="blue",
                        fg="white",
                        width=20)
        self.lbl.grid(column=0, row=0)
        self.txt1Lbl = Label(self.window)
        self.txt1 = Entry(self.window, width=3)
        self.txt2 = Entry(self.window, width=3)
        self.txt3 = Entry(self.window, width=3)

        self.txt1Lbl.config(text='X', bg="red", fg="white", width=3)
        self.txt1Lbl.grid(column=0, row=1)
        #self.lbl.pack()
        #self.txt1Lbl.pack()
        self.txt1.grid(column=1, row=1)
        self.txt2.grid(column=1, row=2)
        self.txt3.grid(column=1, row=3)

        self.NETWORK = BooleanVar()
        self.chk_state1 = BooleanVar()
        self.NETWORK.set(False)
        self.chk_state1.set(False)  #set check state
        self.chk0 = Checkbutton(self.window,
                                text='Load previous network',
                                var=self.NETWORK)
        self.chk1 = Checkbutton(self.window, text='Learn', var=self.chk_state1)

        self.chk0.grid(column=2, row=1)
        self.chk1.grid(column=2, row=2)

        self.btn.config(text='Lancer', command=self.start)
        self.btn.grid(column=0, row=4)
示例#30
0
class ImagePicker(Frame):
    """
    A custom widget that allows for the selection and preview of a picture
    Note that in the current format, the image picker is specific to the
    maze builder project
    """
    def __init__(self, parent, label, default="No File Selected", auto_move=False, move_fold=None):
        """
        Construct the image picker instance

        :param default:     Use to set the image path and inital data loaded
        :param auto_move:   If this is set to true, the image picker will automatically
                            move the image into a defined relative folder in the same
                            relative location
        """
        Frame.__init__(self, parent)
        self._image_ref = None
        self._file_name = default if not default == "No File Selected" else None
        self._file_path = self._file_name
        self._parent = parent

        self._auto_move = auto_move
        if auto_move is True:
            self._folder = "/" + move_fold + "/"

        # Text label
        self._label = Label(self, text=label, anchor=W)
        self._label.grid(row=0, column=0, sticky=W, padx=2)
        self._label.config(width=10)

        # The label that displays the name of the selected file
        self._img_label = Label(self, text=default)
        self._img_label.config(width=15)
        self._img_label.grid(row=0, column=1, sticky=W)

        # Button that enables the previewing of the loaded picture
        self._pButton = Button(self, text="Preview", command=self._display_img, padx=5)
        self._pButton.config(width=8)
        self._pButton.grid(row=0, column=3, sticky=W)

        # Button that enables the loading of files
        self._fButton = Button(self, text="|...|", command=self._load_img_label, padx=5)
        self._fButton.config(width=4)
        self._fButton.grid(row=0, column=2)

    def _display_img(self):
        """
        Display a loaded image in a dialog
        """
        if self._file_path is None:
            Debug.printi("No picture has been loaded to preview", Debug.Level.ERROR)
            return
        photo = self._open_img(self._file_path)
        ImageViewDialog(self._parent, self._file_name, photo)


    def _open_img(self, img_name):
        """
        Open an image from its location on disk

        Retrieves an image in ImageTk form from a given file path
        and loads it for application use

        :img_name: The path/name (?) of the image to open
        """
        try:
            img = Image.open(img_name)
            photo = ImageTk.PhotoImage(img)
            return photo
        except IOError:
            Debug.printi("Unable to find image " + img_name, Debug.Level.ERROR)

    def _launch_file_b(self):
        """
        Launch a file selector dialog
        """
        types = [
            ("JPG", "*.jpg"),
            ("Bitmap", "*.bmp"),
            ("PNG", "*.png"),
            ("GIF", "*.gif"),
            ("All files", "*")]
        dialog = tkFileDialog.Open(self, filetypes = types)
        self._file_path = dialog.show()

        self._file_name = self._scrub_name(self._file_path)
        self._move_img()
        return self._file_name

    def _move_img(self):
        if self._auto_move is False:
            return
        # Else, move the image to the given folder that is in the same dir as this module
        try:
            src = self._file_path
            dest = os.path.dirname(os.path.realpath(__file__)) +"/" + self._file_name
            shutil.copy(src, dest)
            Debug.printi("Moving file " + self._file_path + " to location "
                         + os.path.dirname(os.path.realpath(__file__))
                         + self._file_name, Debug.Level.INFO)
        # eg. src and dest are the same file
        except shutil.Error as e:
            print('Error: %s' % e + " " +dest)
        # eg. source or destination doesn't exist
        except IOError as e:
            print('Error: %s' % e.strerror +" "+ dest)

    def _scrub_name(self, file_path):
        """
        Override: Parse and clean the filename
        """
        split = self._file_path.split("/")
        if self._auto_move is True:
            f_name = self._folder[1:] + split[-1]
        else:
            f_name = split[-1]
        return f_name

    def _load_img_label(self):
        """
        Changes the text in the widget label to the (adjusted) filepath of the image
        """
        name = self._launch_file_b()
        self._img_label.configure(text=name)

    def get(self):
        return self._file_name

    def set(self, val):
        self._file_name = val
        self._img_label.config(text=val)
示例#31
0
class Window(Frame):
    def __init__(self, master=None):
        if not headless:
            Frame.__init__(self, master)
            self.master = master
            self.init_window()

    def settrainer(self, n):
        global power_curve, user_defaults
        user_defaults["power_curve"] = n
        power_curve = n
        if n == "power_calc_factors_imagic.txt":
            self.PowerCurveVariable.set("I-Magic")
        elif n == "power_calc_factors_fortius.txt":
            self.PowerCurveVariable.set("Fortius")
        elif n == "power_calc_factors_custom.txt":
            self.PowerCurveVariable.set("Custom")

    def init_window(self):
        global user_defaults
        self.grid()

        # Setup menu content###

        self.master.title("Antifier v0.9")
        self.master.option_add("*tearOff", False)

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a menu instance
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # create the Setup object)
        Setup = Menu(menu)

        # add commands to the Setup option
        Setup.add_command(label="Head Unit", command=self.HeadUnit_window)

        subSetup = Menu(Setup)
        subSetup.add_command(
            label="iMagic",
            command=lambda p="power_calc_factors_imagic.txt": self.settrainer(
                p),
        )
        subSetup.add_command(
            label="Fortius",
            command=lambda p="power_calc_factors_fortius.txt": self.settrainer(
                p),
        )
        subSetup.add_command(
            label="Custom Curve",
            command=lambda p="power_calc_factors_custom.txt": self.settrainer(
                p),
        )

        Setup.add_cascade(label="Power Curve", menu=subSetup)

        Setup.add_separator()
        Setup.add_command(label="Exit", command=self.EXITbutton)

        # added "Setup" to our menu
        menu.add_cascade(label="Setup", menu=Setup)

        # create the Options object)
        Options = Menu(menu)

        # add commands to the Options option
        Options.add_command(label="Debug", command=self.DebugButton)
        Options.add_command(label="Simulate Trainer",
                            command=self.Simulatebutton)
        Options.add_command(label="Power Factor",
                            command=self.PowerFactor_Window)

        # added "Options" to our menu
        menu.add_cascade(label="Options", menu=Options)

        # create the Help object
        Help = Menu(menu)

        # adds a command to the Help option.
        Help.add_command(label="Readme", command=self.Readme)
        Help.add_command(label="Zwift shortcuts", command=self.Zwift_shortcuts)

        # added "Help" to our menu
        menu.add_cascade(label="Help", menu=Help)

        # Setup GUI buttons and labels###

        self.FindHWbutton = Button(self,
                                   height=1,
                                   width=15,
                                   text=u"1. Locate HW",
                                   command=self.ScanForHW)
        self.FindHWbutton.grid(column=0, row=0)

        label = Label(self, height=1, width=10, text="Head Unit")
        label.grid(column=0, row=1, sticky="EW")
        self.trainerVariable = StringVar()
        label = Label(self,
                      textvariable=self.trainerVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=1, columnspan=2, sticky="EW")

        label = Label(self, height=1, width=10, text="Power curve")
        label.grid(column=0, row=2, sticky="EW")
        self.PowerCurveVariable = StringVar()
        label = Label(
            self,
            textvariable=self.PowerCurveVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=2, columnspan=2, sticky="EW")
        if "power_curve" in user_defaults:
            self.settrainer(user_defaults["power_curve"])

        label = Label(self, height=1, width=10, text="ANT+")
        label.grid(column=0, row=3, sticky="EW")
        self.ANTVariable = StringVar()
        label = Label(self,
                      textvariable=self.ANTVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=3, columnspan=2, sticky="EW")

        label = Label(self, text="Power factor")
        label.grid(column=0, row=4, sticky="EW")
        self.PowerFactorVariable = StringVar()
        label = Label(
            self,
            textvariable=self.PowerFactorVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=4, columnspan=2, sticky="EW")

        self.RunoffButton = Button(self,
                                   height=1,
                                   width=15,
                                   text=u"2. Perform Runoff",
                                   command=self.Runoff)
        self.RunoffButton.grid(column=0, row=5)
        self.RunoffButton.config(state="disabled")
        self.runoffVariable = StringVar()
        label = Label(
            self,
            textvariable=self.runoffVariable,
            anchor="w",
            fg="black",
            bg="grey",
            width=40,
        )
        label.grid(column=1, row=5, columnspan=2, sticky="EW")

        self.StartAPPbutton = Button(self,
                                     height=1,
                                     width=15,
                                     text=u"3. Start script",
                                     command=self.Start)
        self.StartAPPbutton.grid(column=0, row=6)
        self.StartAPPbutton.config(state="disabled")

        self.StopAPPbutton = Button(
            self,
            height=1,
            width=15,
            text=u"Stop script",
            command=self.Stop,
            state="disabled",
        )
        self.StopAPPbutton.grid(column=1, row=6)

        label = Label(self, text="Speed")
        label.grid(column=0, row=7, sticky="EW")

        self.SpeedVariable = StringVar()
        label = Label(self,
                      textvariable=self.SpeedVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=7, columnspan=2, sticky="EW")
        self.SpeedVariable.set(u"0")

        label = Label(self, text="Heartrate")
        label.grid(column=0, row=8, sticky="EW")
        self.HeartrateVariable = StringVar()
        label = Label(self,
                      textvariable=self.HeartrateVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=8, columnspan=2, sticky="EW")
        self.HeartrateVariable.set(u"0")

        label = Label(self, text="Cadence")
        label.grid(column=0, row=9, sticky="EW")

        self.CadenceVariable = StringVar()
        label = Label(self,
                      textvariable=self.CadenceVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=9, columnspan=2, sticky="EW")
        self.CadenceVariable.set(u"0")

        label = Label(self, text="Power")
        label.grid(column=0, row=10, sticky="EW")
        self.PowerVariable = StringVar()
        label = Label(self,
                      textvariable=self.PowerVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=10, columnspan=2, sticky="EW")
        self.PowerVariable.set(u"0")

        label = Label(self, text="Slope")
        label.grid(column=0, row=11, sticky="EW")
        self.SlopeVariable = StringVar()
        label = Label(self,
                      textvariable=self.SlopeVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=11, columnspan=2, sticky="EW")

        label = Label(self, text="Target Power")
        label.grid(column=0, row=12, sticky="EW")
        self.TargetPowerVariable = StringVar()
        label = Label(
            self,
            textvariable=self.TargetPowerVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=12, columnspan=2, sticky="EW")

        label = Label(self, text="Resistance Level")
        label.grid(column=0, row=13, sticky="EW")
        self.ResistanceLevelVariable = StringVar()
        label = Label(
            self,
            textvariable=self.ResistanceLevelVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=13, columnspan=2, sticky="EW")
        self.ResistanceLevelVariable.set(u"0")

    def PowerFactor_Window(self):
        self.PowerFactor_Window = Toplevel(self.master)
        self.app = PowerFactor_Window(self.PowerFactor_Window)

    def HeadUnit_window(self):
        self.HeadUnitWindow = Toplevel(self.master)
        self.app = HeadUnit_Window(self.HeadUnitWindow)

    def Runoff(self):
        global runoff_loop_running

        def run():
            global dev_trainer, runoff_loop_running
            rolldown = False
            rolldown_time = 0
            speed = 0
            # self.InstructionsVariable.set('''
            # CALIBRATION TIPS:
            # 1. Tyre pressure 100psi (unloaded and cold) aim for 7.2s rolloff
            # 2. Warm up for 2 mins, then cycle 30kph-40kph for 30s
            # 3. Speed up to above 40kph then stop pedalling and freewheel
            # 4. Rolldown timer will start automatically when you hit 40kph, so stop pedalling quickly!
            # ''')

            while runoff_loop_running:  # loop every 100ms
                last_measured_time = time.time() * 1000
                # receive data from trainer
                speed, pedecho, heart_rate, force_index, cadence = trainer.receive(
                    dev_trainer)  # get data from device
                self.SpeedVariable.set(speed)
                if speed == "Not found":
                    self.TrainerStatusVariable.set(
                        "Check trainer is powered on")

                # send data to trainer
                resistance_level = 6
                trainer.send(dev_trainer, resistance_level, pedecho)

                if speed > 40:  # speed above 40, start rolldown
                    self.runoffVariable.set(
                        "Rolldown timer started - STOP PEDALLING!")
                    rolldown = True

                if speed <= 40 and rolldown:  # rolldown timer starts when dips below 40
                    if rolldown_time == 0:
                        rolldown_time = time.time(
                        )  # set initial rolldown time
                    self.runoffVariable.set(
                        "Rolldown timer started - STOP PEDALLING! %s " %
                        (round((time.time() - rolldown_time), 1)))

                if speed < 0.1 and rolldown:  # wheel stopped
                    runoff_loop_running = False  # break loop
                    self.runoffVariable.set(
                        "Rolldown time = %s seconds (aim 7s)" % round(
                            (time.time() - rolldown_time), 1))

                time_to_process_loop = time.time() * 1000 - last_measured_time
                sleep_time = 0.1 - (time_to_process_loop) / 1000
                if sleep_time < 0:
                    sleep_time = 0
                time.sleep(sleep_time)

            self.RunoffButton.config(
                text="2. Perform Runoff")  # reset runoff button
            self.StartAPPbutton.config(state="normal")

        if self.RunoffButton.cget(
                "text") == "2. Perform Runoff":  # start runoff
            self.runoffVariable.set("Cycle to above 40kph then stop")
            self.RunoffButton.config(text="2. Stop Runoff")
            self.StartAPPbutton.config(state="disabled")
            runoff_loop_running = True  # loop switch
            t1 = threading.Thread(target=run)
            t1.start()
        else:  # stop loop
            runoff_loop_running = False
            self.runoffVariable.set("Stopped")
            self.RunoffButton.config(text="2. Perform Runoff")
            self.StartAPPbutton.config(state="normal")

    def Readme(self):
        os.startfile("README.txt")

    def Zwift_shortcuts(self):
        os.startfile("Zwift_shortcuts.txt")

    def EXITbutton(self):
        self.destroy()
        exit()

    def DebugButton(self):
        global debug
        if debug:
            debug = True
        else:
            debug = False

    def Simulatebutton(self):
        global simulatetrainer
        simulatetrainer = True

    def Stop(self):
        global switch
        switch = False
        self.StartAPPbutton.config(state="normal")
        self.StopAPPbutton.config(state="disabled")

    def ScanForHW(self):
        global dev_trainer, dev_ant, simulatetrainer
        # get ant stick
        if debug:
            print("get ant stick")
        if not dev_ant:
            dev_ant, msg = ant.get_ant(debug)
            if not dev_ant:
                if not headless:
                    self.ANTVariable.set(msg)
                return False
        if not headless:
            self.ANTVariable.set(msg)

        if not headless:
            self.PowerFactorVariable.set(powerfactor)
        if debug:
            print("get trainer")
        # find trainer model for Windows and Linux
        if not dev_trainer:
            # find trainer
            if simulatetrainer:
                if not headless:
                    self.trainerVariable.set(u"Simulated Trainer")
                else:
                    print("Simulated Trainer")
            else:
                dev_trainer = trainer.get_trainer()
                if not dev_trainer:
                    if not headless:
                        self.trainerVariable.set("Trainer not detected")
                    else:
                        print("Trainer not detected")
                    return False
                else:
                    if not headless:
                        self.trainerVariable.set("Trainer detected")
                    else:
                        print("Trainer detected")
                    trainer.initialise_trainer(
                        dev_trainer)  # initialise trainer

        if not headless:
            self.StartAPPbutton.config(state="normal")
            if not simulatetrainer:
                self.RunoffButton.config(state="normal")
            self.FindHWbutton.config(state="disabled")

        return True

    def Start(self):
        def run():
            global dev_ant, dev_trainer, simulatetrainer, switch, power_curve
            if power_curve == "":
                if not headless:
                    self.PowerCurveVariable.set(
                        "Choose a power curve under setup menu")
                    self.StartAPPbutton.config(state="normal")
                    self.StopAPPbutton.config(state="disabled")
                return
            pc_dict = trainer.parse_factors(
                power_curve)  # get power curve dictionary
            if len(pc_dict) != 14:
                if not headless:
                    self.PowerCurveVariable.set(
                        "Need 14 levels for power curve")
                    self.StartAPPbutton.config(state="normal")
                    self.StopAPPbutton.config(state="disabled")
                    return
            pc_sorted_keys = sorted(pc_dict.iterkeys())  # -1,-0,2,3 etc.
            if debug:
                print("reset ant stick")
            ant.antreset(dev_ant, debug)  # reset dongle
            if debug:
                print("calibrate ant stick")
            ant.calibrate(dev_ant, debug)  # calibrate ANT+ dongle
            if debug:
                print("calibrate ant stick FE-C")
            ant.master_channel_config(dev_ant,
                                      debug)  # calibrate ANT+ channel FE-C
            if debug:
                print("calibrate ant stick HR")
            ant.second_channel_config(dev_ant,
                                      debug)  # calibrate ANT+ channel HR

            if not headless:
                self.RunoffButton.config(state="disabled")
            else:
                print("Ctrl-C to exit")
            speed, cadence, power, heart_rate = (0, ) * 4  # initialise values
            grade = False
            target_power = False
            accumulated_power = 0
            heart_beat_event_time = time.time() * 1000
            heart_beat_event_time_start_cycle = time.time() * 1000
            heart_toggle = 0
            heart_beat_count = 0
            switch = True
            cot_start = time.time()
            eventcounter = 0
            # p.44 [10] general fe data, [19] eqpt type trainer, [89] acc value time since start in 0.25s r/over 64s, [8c] acc value time dist travelled in m r/over 256m,
            # [8d] [20] speed lsb msb 0.001m/s, [00] hr, [30] capabilities bit field
            accumulated_time = time.time() * 1000
            distance_travelled = 0
            last_dist_time = time.time() * 1000

            # p.60 [19] specific trainer data, [10] counter rollover 256, [5a] inst cadence, [b0] acc power lsb, [47] acc power msb (r/over 65536W), [1b] inst power lsb,
            # [01] bits 0-3 inst power MSB bits 4-7 trainer status bit, [30] flags bit field
            last_measured_time = time.time() * 1000
            try:
                while switch:
                    if debug:
                        print("Running",
                              round(time.time() * 1000 - last_measured_time))
                    last_measured_time = time.time() * 1000
                    if eventcounter >= 256:
                        eventcounter = 0
                    # TRAINER- SHOULD WRITE THEN READ 70MS LATER REALLY
                    # ##################GET DATA FROM TRAINER##################
                    if simulatetrainer:
                        speed, pedecho, heart_rate, force_index, cadence = (
                            20,
                            0,
                            70,
                            5,
                            90,
                        )
                    else:
                        speed, pedecho, heart_rate, force_index, cadence = trainer.receive(
                            dev_trainer)  # get data from device
                    if speed == "Not Found":
                        speed, pedecho, heart_rate, force_index, cadence = 0, 0, 0, 0, 0
                        if not headless:
                            self.trainerVariable.set(
                                "Cannot read from trainer")
                        else:
                            print("Cannot read from trainer")
                    else:
                        if not headless:
                            self.trainerVariable.set("Trainer detected")
                    # print force_index
                    factors = pc_dict[pc_sorted_keys[force_index]]
                    calc_power = int(speed * factors[0] + factors[1])
                    if calc_power < 0:
                        calc_power = 0
                    if debug:
                        print(speed, pedecho, heart_rate, force_index, cadence,
                              calc_power)
                    # ##################SEND DATA TO TRAINER##################
                    # send resistance data to trainer
                    if debug:
                        print(
                            datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")
                            [:-3], "GRADE", grade, "%")
                    # set resistance level
                    if not grade and not target_power:  # if trainer not been been set a grade or target power
                        grade = 0
                    resistance_level = len(
                        pc_dict) - 1  # set to highest by default
                    if grade is not False:  # find resistance for grade
                        for idx, g in enumerate(sorted(pc_dict)):
                            if g >= grade:  # find resistance value immediately above grade set by zwift
                                resistance_level = idx
                                break
                    elif target_power:  # get resistance closest for power target
                        if speed < 10:
                            speed = 10  # default to at least 10 kph
                        closest = 1000
                        for idx, g in enumerate(sorted(pc_dict)):  # iterate up
                            power_at_level = int(speed * pc_dict[g][0] +
                                                 pc_dict[g][1])
                            # print idx,g,power_at_level
                            if (target_power - power_at_level)**2 < closest**2:
                                resistance_level = idx
                                closest = ((target_power -
                                            power_at_level)**2)**0.5
                    # print resistance_level
                    if not simulatetrainer:
                        trainer.send(dev_trainer, resistance_level, pedecho)

                        # time.sleep(0.2)#simulated trainer timeout
                    # ############BROADCAST AND RECEIVE ANT+ data##############
                    if speed == "Not Found":
                        speed, pedecho, calc_power, cadence = 0, 0, 0, 0
                    if calc_power >= 4094:
                        calc_power = 4093
                    accumulated_power += calc_power
                    if accumulated_power >= 65536:
                        accumulated_power = 0

                    if (
                            eventcounter + 1
                    ) % 66 == 0 or eventcounter % 66 == 0:  # send first and second manufacturer's info packet
                        newdata = "a4 09 4e 00 50 ff ff 01 0f 00 85 83 bb 00 00"

                    elif (eventcounter + 32) % 66 == 0 or (
                            eventcounter + 33
                    ) % 66 == 0:  # send first and second product info packet
                        newdata = "a4 09 4e 00 51 ff ff 01 01 00 00 00 b2 00 00"

                    elif eventcounter % 3 == 0:  # send general fe data every 3 packets
                        accumulated_time_counter = int(
                            (time.time() * 1000 - accumulated_time) / 1000 /
                            0.25)  # time since start in 0.25 seconds
                        if (accumulated_time_counter >= 256
                            ):  # rollover at 64 seconds (256 quarter secs)
                            accumulated_time_counter = 0
                            accumulated_time = time.time() * 1000
                        newdata = "{0}{1}{2}".format(
                            "a4 09 4e 00 10 19 ",
                            hex(accumulated_time_counter)[2:].zfill(2),
                            " 8c 8d 20 00 30 72 00 00",
                        )  # set time
                        distance_travelled_since_last_loop = (
                            (time.time() * 1000 - last_dist_time) / 1000 *
                            speed * 1000 / 3600
                        )  # speed reported in kph- convert to m/s
                        last_dist_time = time.time(
                        ) * 1000  # reset last loop time
                        distance_travelled += distance_travelled_since_last_loop
                        if distance_travelled >= 256:  # reset at 256m
                            distance_travelled = 0
                        newdata = "{0}{1}{2}".format(
                            newdata[:21],
                            hex(int(distance_travelled))[2:].zfill(2),
                            newdata[23:],
                        )  # set distance travelled
                        hexspeed = hex(int(speed * 1000 * 1000 /
                                           3600))[2:].zfill(4)
                        newdata = "{0}{1}{2}{3}{4}".format(
                            newdata[:24], hexspeed[2:], " ", hexspeed[:2],
                            newdata[29:])  # set speed
                        newdata = "{0}{1}{2}".format(
                            newdata[:36], ant.calc_checksum(newdata),
                            newdata[38:])  # recalculate checksum

                    else:  # send specific trainer data
                        newdata = "{0}{1}{2}".format(
                            "a4 09 4e 00 19 ",
                            hex(eventcounter)[2:].zfill(2),
                            " 5a b0 47 1b 01 30 6d 00 00",
                        )  # increment event count
                        if cadence >= 254:
                            cadence = 253
                        newdata = "{0}{1}{2}".format(
                            newdata[:18],
                            hex(cadence)[2:].zfill(2),
                            newdata[20:])  # instant cadence
                        hexaccumulated_power = hex(
                            int(accumulated_power))[2:].zfill(4)
                        newdata = "{0}{1}{2}{3}{4}".format(
                            newdata[:21],
                            hexaccumulated_power[2:],
                            " ",
                            hexaccumulated_power[:2],
                            newdata[26:],
                        )  # set accumulated power
                        hexinstant_power = hex(int(calc_power))[2:].zfill(4)
                        hexinstant_power_lsb = hexinstant_power[2:]
                        newdata = "{0}{1}{2}".format(
                            newdata[:27], hexinstant_power_lsb,
                            newdata[29:])  # set power lsb byte
                        hexinstant_power_msb = hexinstant_power[:2]
                        bits_0_to_3 = bin(int(hexinstant_power_msb,
                                              16))[2:].zfill(4)
                        power_msb_trainer_status_byte = "0000" + bits_0_to_3
                        newdata = "{0}{1}{2}".format(
                            newdata[:30],
                            hex(int(power_msb_trainer_status_byte))[2:].zfill(
                                2),
                            newdata[32:],
                        )  # set mixed trainer data power msb byte
                        newdata = "{0}{1}{2}".format(
                            newdata[:36], ant.calc_checksum(newdata),
                            newdata[38:])  # recalculate checksum

                    if debug:
                        print(
                            datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")
                            [:-3], "TRAINER DATA", newdata)
                    reply = ant.send_ant([newdata], dev_ant, debug)
                    # reply = []
                    # if rv[6:8]=="33":
                    # rtn = {'grade' : int(rv[18:20]+rv[16:18],16) * 0.01 - 200} #7% in zwift = 3.5% grade in ANT+
                    matching = [s for s in reply
                                if "a4094f0033" in s]  # target resistance
                    # 0x33 a4094f00 33 ffffffff964fff f7 is gradient message
                    if matching:
                        grade = (
                            int(matching[0][20:22] + matching[0][18:20], 16) *
                            0.01 - 200)
                        target_power = False
                        if not headless:
                            self.SlopeVariable.set(round(grade, 1))
                        if not headless:
                            self.TargetPowerVariable.set("")
                        if debug:
                            print(grade, matching[0])
                    else:
                        matching = [s for s in reply
                                    if "a4094f0031" in s]  # target watts
                        # 0x31 a4094f00 31 ffffffffff5c02 72 is target power message in 0.25w 0x025c = 604 = 151W
                        if matching:
                            target_power = (int(
                                matching[0][22:24] + matching[0][20:22], 16) /
                                            4)
                            grade = False
                            if not headless:
                                self.TargetPowerVariable.set(target_power)
                            if not headless:
                                self.SlopeVariable.set("")
                    # ##################HR#######################
                    # HR format
                    # D00000693_-_ANT+_Device_Profile_-_Heart_Rate_Rev_2.1.pdf
                    # [00][FF][FF][FF][55][03][01][48]p. 18 [00] bits 0:6 data page no, bit 7 toggle every 4th message, [ff][ff][ff] (reserved for page 0), [55][03] heart beat event time [lsb][ msb] rollover 64s, [01] heart beat count rollover 256, [instant heart rate]max 256
                    # [00][FF][FF][FF][55][03][01][48]
                    # [00][FF][FF][FF][AA][06][02][48]
                    # [00][FF][FF][FF][AA][06][02][48]
                    # [80][FF][FF][FF][AA][06][02][48]
                    # [80][FF][FF][FF][AA][06][02][48]
                    # [80][FF][FF][FF][FF][09][03][48]
                    # [80][FF][FF][FF][FF][09][03][48]
                    # [00][FF][FF][FF][FF][09][03][48]
                    # [00][FF][FF][FF][54][0D][04][48]
                    # [00][FF][FF][FF][54][0D][04][48]
                    # [00][FF][FF][FF][54][0D][04][48]

                    # every 65th message send manufacturer and product info -apge 2 and page 3
                    # [82][0F][01][00][00][3A][12][48] - [82] page 2 with toggle on (repeat 4 times)
                    # [83][01][01][33][4F][3F][13][48] - [83] page 3 with toggle on
                    # if eventcounter > 40: heart_rate = 100 #comment out in production
                    if heart_rate > 0:  # i.e. heart rate belt attached
                        if eventcounter % 4 == 0:  # toggle bit every 4 counts
                            if heart_toggle == 0:
                                heart_toggle = 128
                            else:
                                heart_toggle = 0

                        # check if heart beat has occurred as tacx only reports instanatenous heart rate data
                        # last heart beat is at heart_beat_event_time
                        # if now - heart_beat_event_time > time taken for hr to occur, trigger beat. 70 bpm = beat every 60/70 seconds
                        if (time.time() * 1000 - heart_beat_event_time
                            ) >= (60 / float(heart_rate)) * 1000:
                            heart_beat_count += 1  # increment heart beat count
                            heart_beat_event_time += (
                                60 / float(heart_rate)
                            ) * 1000  # reset last time of heart beat

                        if (heart_beat_event_time -
                                heart_beat_event_time_start_cycle >=
                                64000):  # rollover every 64s
                            heart_beat_event_time = (
                                time.time() * 1000
                            )  # reset last heart beat event
                            heart_beat_event_time_start_cycle = (
                                time.time() * 1000)  # reset start of cycle

                        if heart_beat_count >= 256:
                            heart_beat_count = 0

                        if heart_rate >= 256:
                            heart_rate = 255

                        hex_heart_beat_time = int(
                            (heart_beat_event_time -
                             heart_beat_event_time_start_cycle) *
                            1.024)  # convert ms to 1/1024 of a second
                        hex_heart_beat_time = hex(
                            hex_heart_beat_time)[2:].zfill(4)

                        hr_byte_4 = hex_heart_beat_time[2:]
                        hr_byte_5 = hex_heart_beat_time[:2]
                        hr_byte_6 = hex(heart_beat_count)[2:].zfill(2)
                        hr_byte_7 = hex(heart_rate)[2:].zfill(2)

                        # data page 1,6,7 every 80s
                        if (
                                eventcounter % 65 == 0
                                or (eventcounter + 1) % 65 == 0
                                or (eventcounter + 2) % 65 == 0
                                or (eventcounter + 3) % 65 == 0
                        ):  # send first and second manufacturer's info packet
                            hr_byte_0 = hex(2 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = "0f"
                            hr_byte_2 = "01"
                            hr_byte_3 = "00"
                            # [82][0F][01][00][00][3A][12][48]
                        elif ((eventcounter + 31) % 65 == 0
                              or (eventcounter + 32) % 65 == 0
                              or (eventcounter + 33) % 65 == 0
                              or (eventcounter + 34) % 65 == 0
                              ):  # send first and second product info packet
                            hr_byte_0 = hex(3 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = "01"
                            hr_byte_2 = "01"
                            hr_byte_3 = "33"
                            # [83][01][01][33][4F][3F][13][48]
                        elif ((eventcounter + 11) % 65 == 0
                              or (eventcounter + 12) % 65 == 0
                              or (eventcounter + 13) % 65 == 0
                              or (eventcounter + 44) % 65 == 0
                              ):  # send page 0x01 cumulative operating time
                            cot = int((time.time() - cot_start) / 2)
                            cot_hex = hex(cot)[2:].zfill(6)
                            hr_byte_0 = hex(1 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = cot_hex[4:6]
                            hr_byte_2 = cot_hex[2:4]
                            hr_byte_3 = cot_hex[0:2]
                        elif ((eventcounter + 21) % 65 == 0
                              or (eventcounter + 22) % 65 == 0
                              or (eventcounter + 23) % 65 == 0
                              or (eventcounter + 24) % 65
                              == 0):  # send page 0x06 capabilities
                            hr_byte_0 = hex(6 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = "ff"
                            hr_byte_2 = "00"
                            hr_byte_3 = "00"
                        elif ((eventcounter + 41) % 65 == 0
                              or (eventcounter + 42) % 65 == 0
                              or (eventcounter + 43) % 65 == 0
                              or (eventcounter + 44) % 65
                              == 0):  # send page 0x07 battery
                            hr_byte_0 = hex(7 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = "64"
                            hr_byte_2 = "55"
                            hr_byte_3 = "13"
                        else:  # send page 0
                            hr_byte_0 = hex(0 + heart_toggle)[2:].zfill(2)
                            hr_byte_1 = "ff"
                            hr_byte_2 = "ff"
                            hr_byte_3 = "ff"

                        hrdata = ("a4 09 4e 01 " + hr_byte_0 + " " +
                                  hr_byte_1 + " " + hr_byte_2 + " " +
                                  hr_byte_3 + " " + hr_byte_4 + " " +
                                  hr_byte_5 + " " + hr_byte_6 + " " +
                                  hr_byte_7 + " 02 00 00")
                        hrdata = ("a4 09 4e 01 " + hr_byte_0 + " " +
                                  hr_byte_1 + " " + hr_byte_2 + " " +
                                  hr_byte_3 + " " + hr_byte_4 + " " +
                                  hr_byte_5 + " " + hr_byte_6 + " " +
                                  hr_byte_7 + " " + ant.calc_checksum(hrdata) +
                                  " 00 00")
                        time.sleep(0.125)  # sleep for 125ms
                        if debug:
                            print(
                                datetime.utcnow().strftime(
                                    "%Y-%m-%d %H:%M:%S.%f")[:-3], "HEART RATE",
                                hrdata)
                        ant.send_ant([hrdata], dev_ant, debug)
                    # ###################wait ####################

                    # add wait so we only send every 250ms
                    time_to_process_loop = time.time(
                    ) * 1000 - last_measured_time
                    sleep_time = 0.25 - (time_to_process_loop) / 1000
                    if sleep_time < 0:
                        sleep_time = 0
                    time.sleep(sleep_time)
                    eventcounter += 1

                    if not headless:
                        self.SpeedVariable.set(speed)
                        self.HeartrateVariable.set(heart_rate)
                        self.CadenceVariable.set(cadence)
                        self.PowerVariable.set(calc_power)
                        self.ResistanceLevelVariable.set(resistance_level)
                    elif eventcounter % 4 == 0:
                        print("Power %sW, HR %s, Cadence %s, Resistance %s" % (
                            calc_power,
                            heart_rate,
                            cadence,
                            resistance_level,
                        ))

            except KeyboardInterrupt:
                print("Stopped")

            ant.antreset(dev_ant, debug)  # reset dongle
            if os.name == "posix":  # close serial port to ANT stick on Linux
                dev_ant.close()
            if debug:
                print("stopped")
            if not headless:
                self.RunoffButton.config(state="normal")

            with open("user_defaults", "wb") as handle:  # save defaults
                pickle.dump(user_defaults,
                            handle,
                            protocol=pickle.HIGHEST_PROTOCOL)

        if not headless:
            self.FindHWbutton.config(state="disabled")
            self.StartAPPbutton.config(state="disabled")
            self.StopAPPbutton.config(state="normal")
            thread = threading.Thread(target=run)
            thread.start()
        else:
            run()
示例#32
0
class ConditionalsEditor:
    def __init__(self, my_window, conditionals, close_callback):
        #Tk.__init__(self)
        self.my_window = my_window
        self.my_window.title("Condition Editor")
        self.close_callback = close_callback
        self.conditionals = conditionals

        shared_pad_x = 3
        shared_pad_y = 3

        main_frame = Frame(self.my_window)
        main_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        image_path = "images"
        image_files = [
            f for f in os.listdir(image_path) if
            os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png")
        ]
        self.icons = {}
        for image_file in image_files:
            self.icons[os.path.splitext(
                os.path.basename(image_file))[0]] = PhotoImage(
                    file=os.path.join(image_path, image_file))

        up_down_button_frame = Frame(main_frame)

        self.up_button = Button(up_down_button_frame,
                                state="disabled",
                                text="Move up",
                                image=self.icons["gtk-go-up"],
                                command=self.up_pressed)
        self.up_button.grid(column=0, row=0, sticky=(E))

        self.down_button = Button(up_down_button_frame,
                                  state="disabled",
                                  text="Move down",
                                  image=self.icons["gtk-go-down"],
                                  command=self.down_pressed)
        self.down_button.grid(column=0, row=1, sticky=(E))

        up_down_button_frame.grid(column=0, row=0, sticky=(E))

        condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1)
        condition_list.grid(column=1,
                            row=0,
                            sticky=(N, S, E, W),
                            padx=shared_pad_x,
                            pady=shared_pad_y,
                            columnspan=1)
        self.condition_list_scrollbar = Scrollbar(condition_list)

        self.state_listbox = Listbox(condition_list,
                                     relief=FLAT,
                                     exportselection=False,
                                     borderwidth=0,
                                     highlightthickness=0,
                                     yscrollcommand=self.state_listbox_scroll,
                                     activestyle="none")
        self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S))
        self.state_listbox.bind("<<ListboxSelect>>",
                                self.state_listbox_selected)

        self.condition_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.condition_listbox_scroll,
            activestyle="none")
        self.condition_listbox.grid(column=1,
                                    row=0,
                                    sticky=(N, S, E, W),
                                    padx=0)
        self.condition_listbox.bind("<<ListboxSelect>>",
                                    self.condition_listbox_selected)

        self.execution_target_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.execution_target_listbox_scroll,
            activestyle="none")
        self.execution_target_listbox.grid(column=2,
                                           row=0,
                                           padx=0,
                                           sticky=(N, S))
        self.execution_target_listbox.bind(
            "<<ListboxSelect>>", self.execution_target_listbox_selected)

        self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S))
        self.condition_list_scrollbar.config(
            command=self.condition_list_scrollbar_callback)
        condition_list.grid_rowconfigure(0, weight=1)

        for conditional in self.conditionals:
            self.state_listbox.insert(END, conditional[0])
            self.condition_listbox.insert(END, conditional[1])
            self.execution_target_listbox.insert(END, conditional[2])
        #for i in range(5):
        #    self.state_listbox.insert(END, "Foo %d"%i)
        #    self.condition_listbox.insert(END, "Bar %d"%i)
        #    self.execution_target_listbox.insert(END, "Baz %d"%i)

        if_label = Label(main_frame, text="If:", padx=10)
        if_label.grid(column=0, row=1, sticky=(N, E))
        self.if_text_variable = StringVar()
        if_entry = Entry(main_frame, textvariable=self.if_text_variable)
        if_entry.grid(
            column=1,
            row=1,
            sticky=(E, W),
            padx=shared_pad_x,
            pady=shared_pad_y,
        )

        then_label = Label(main_frame, text="Then:", padx=10)
        then_label.grid(column=0, row=2, sticky=(N, E))
        self.then_entry = Text(main_frame)
        self.then_entry.grid(
            column=1,
            row=2,
            sticky=(N, S, E, W),
            padx=shared_pad_x,
            rowspan=2,
        )

        option_frame = Frame(main_frame)
        execution_target_label = Label(option_frame, text="Execution target:")
        execution_target_label.grid(column=0,
                                    row=0,
                                    sticky=(N, W),
                                    pady=(10, shared_pad_y))
        self.execution_target = StringVar()
        self.execution_target.set("Debugger")
        debugger_radiobutton = Radiobutton(option_frame,
                                           text="Debugger",
                                           variable=self.execution_target,
                                           value="Debugger")
        debugger_radiobutton.grid(column=0, row=1, sticky=(N, W))
        python_radiobutton = Radiobutton(option_frame,
                                         text="Python",
                                         variable=self.execution_target,
                                         value="Python")
        python_radiobutton.grid(column=0, row=2, sticky=(N, W))
        state_label = Label(option_frame, text="State")
        state_label.grid(column=0,
                         row=3,
                         sticky=(N, W),
                         pady=(10, shared_pad_y))

        self.active_checkbutton = StringVar()
        self.active_checkbutton.set("Enabled")
        active_checkbutton = Checkbutton(option_frame,
                                         text="Enabled",
                                         variable=self.active_checkbutton,
                                         onvalue="Enabled",
                                         offvalue="Disabled")
        active_checkbutton.grid(column=0, row=4, sticky=(N, W))
        option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5)

        button_frame = Frame(main_frame)
        self.add_button = Button(button_frame,
                                 state="disabled",
                                 text="Add",
                                 image=self.icons["gtk-add"],
                                 compound=LEFT)
        self.add_button.grid(column=0, row=0, sticky=(E))
        self.update_button = Button(button_frame,
                                    state="disabled",
                                    text="Update",
                                    image=self.icons["gtk-edit"],
                                    compound=LEFT)
        self.update_button.grid(column=1, row=0, sticky=(E))
        self.delete_button = Button(button_frame,
                                    state="disabled",
                                    text="Delete",
                                    image=self.icons["gtk-remove"],
                                    compound=LEFT)
        self.delete_button.grid(column=2, row=0, sticky=(E))
        button_frame.grid(column=0,
                          row=4,
                          columnspan=2,
                          sticky=(E),
                          padx=shared_pad_x,
                          pady=shared_pad_y)

        close_frame = Frame(main_frame)
        close_button = Button(close_frame,
                              text="Close",
                              image=self.icons["gtk-close"],
                              compound=LEFT,
                              command=self.on_closing)
        close_button.grid(column=0, row=0, sticky=(S, E))
        close_frame.grid(column=0,
                         row=5,
                         columnspan=2,
                         sticky=(S, E),
                         padx=shared_pad_x,
                         pady=(15, shared_pad_y))

        self.my_window.grid_columnconfigure(0, weight=1)
        self.my_window.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_rowconfigure(2, weight=0)
        main_frame.grid_rowconfigure(3, weight=1)
        main_frame.grid_rowconfigure(4, weight=1)
        main_frame.grid_rowconfigure(5, weight=1)
        condition_list.grid_columnconfigure(1, weight=1)
        button_frame.grid_rowconfigure(0, weight=1)

        self.my_window.protocol("WM_DELETE_WINDOW", self.on_closing)

    def on_closing(self):
        if self.close_callback is not None:
            self.close_callback()
        self.my_window.destroy()

    def up_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index - 1, state_current)
        self.condition_listbox.insert(index - 1, condition_current)
        self.execution_target_listbox.insert(index - 1,
                                             execution_target_current)

        self.conditionals.insert(index - 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index - 1)
        self.condition_listbox.selection_set(index - 1)
        self.execution_target_listbox.selection_set(index - 1)
        self.state_listbox.see(index - 1)

        if index - 1 == 0:
            self.up_button.config(state="disabled")
        self.down_button.config(state="normal")

    def down_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index + 1, state_current)
        self.condition_listbox.insert(index + 1, condition_current)
        self.execution_target_listbox.insert(index + 1,
                                             execution_target_current)

        self.conditionals.insert(index + 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index + 1)
        self.condition_listbox.selection_set(index + 1)
        self.execution_target_listbox.selection_set(index + 1)
        self.state_listbox.see(index + 1)

        if index + 1 == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        self.up_button.config(state="normal")

    def condition_list_scrollbar_callback(self, *args):
        self.state_listbox.yview(*args)
        self.condition_listbox.yview(*args)
        self.execution_target_listbox.yview(*args)

    def state_listbox_scroll(self, *args):
        self.condition_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])
        self.condition_list_scrollbar.set(*args)

    def condition_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])

    def execution_target_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.condition_listbox.yview_moveto(args[0])

    def any_listbox_selected(self):
        self.up_button.config(state="normal")
        self.down_button.config(state="normal")
        if self.state_listbox.curselection(
        )[0] == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        if self.state_listbox.curselection()[0] == 0:
            self.up_button.config(state="disabled")
        self.delete_button.config(state="normal")
        self.then_entry.delete("1.0", END)
        self.then_entry.insert(
            END, self.conditionals[self.state_listbox.curselection()[0]][3])
        self.if_text_variable.set(
            self.conditionals[self.state_listbox.curselection()[0]][1])

        self.execution_target.set(
            self.conditionals[self.state_listbox.curselection()[0]][2])

        self.active_checkbutton.set(
            self.conditionals[self.state_listbox.curselection()[0]][0])

    def state_listbox_selected(self, event):
        index = self.state_listbox.curselection()[0]
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def condition_listbox_selected(self, event):
        index = self.condition_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def execution_target_listbox_selected(self, event):
        index = self.execution_target_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        self.any_listbox_selected()
示例#33
0
class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.grid()
        self.grid_columnconfigure(1, minsize=200)
        self.grid_columnconfigure(2, minsize=200)
        self.StartText = StringVar()
        self.StartText.set(u"Start")
        Label(self, text="Step 1: Rundown test").grid(row=1, column=1, sticky="E")
        Label(self, text="Step 2: Calibrate power meter").grid(
            row=2, column=1, sticky="E"
        )
        Label(self, text="Step 3: Run power curve").grid(row=3, column=1, sticky="E")
        Label(self, text="Trainer Status: ").grid(row=4, column=1, sticky="E")
        Label(self, text="ANT+ Status: ").grid(row=5, column=1, sticky="E")
        Label(self, text="Calibrated: ").grid(row=6, column=1, sticky="E")
        Label(self, text="Resistance Level: ").grid(row=7, column=1, sticky="E")
        Label(self, text="Speed: ").grid(row=8, column=1, sticky="E")
        Label(self, text="Power: ").grid(row=9, column=1, sticky="E")
        Label(self, text="Instructions: ").grid(row=10, column=1, sticky="E")

        self.InstructionsVariable = StringVar()
        label = Label(
            self,
            textvariable=self.InstructionsVariable,
            anchor=W,
            justify=LEFT,
            wraplength=400,
        )
        label.grid(row=11, column=1, sticky=W, columnspan=2)

        self.RunoffButton = Button(
            self, height=1, width=15, text="Start Runoff", command=self.StartRunoff
        )
        self.RunoffButton.grid(column=2, row=1)

        self.CalibrateButton = Button(
            self, height=1, width=15, text="Calibrate", command=self.Calibrate
        )
        self.CalibrateButton.grid(column=2, row=2)
        # self.CalibrateButton.config(state="disabled")

        self.FindHWbutton = Button(
            self,
            height=1,
            width=15,
            textvariable=self.StartText,
            command=self.ScanForHW,
        )
        self.FindHWbutton.grid(column=2, row=3)
        # self.FindHWbutton.config(state="disabled")

        self.TrainerStatusVariable = StringVar()
        label = Label(self, textvariable=self.TrainerStatusVariable, anchor="w")
        label.grid(row=4, column=2, sticky="EW")

        self.ANTStatusVariable = StringVar()
        label = Label(self, textvariable=self.ANTStatusVariable, anchor="w")
        label.grid(row=5, column=2, sticky="EW")

        self.CalibratedVariable = StringVar()
        label = Label(self, textvariable=self.CalibratedVariable, anchor="w")
        label.grid(row=6, column=2, sticky="EW")
        self.CalibratedVariable.set("False")

        self.ResistanceVariable = StringVar()
        label = Label(self, textvariable=self.ResistanceVariable, anchor="w")
        label.grid(row=7, column=2, sticky="EW")

        self.SpeedVariable = StringVar()
        label = Label(self, textvariable=self.SpeedVariable, anchor="w")
        label.grid(row=8, column=2, sticky="EW")

        self.PowerVariable = StringVar()
        label = Label(self, textvariable=self.PowerVariable, anchor="w")
        label.grid(row=9, column=2, sticky="EW")

    def StartRunoff(self):
        def run():
            global dev_trainer
            self.RunoffButton.config(state="disabled")
            runoff_loop_running = True
            rolldown = False
            rolldown_time = 0
            speed = 0
            self.InstructionsVariable.set(
                """
  CALIBRATION TIPS:
  1. Tyre pressure 100psi (unloaded and cold) aim for 7.2s rolloff
  2. Warm up for 2 mins, then cycle 30kph-40kph for 30s
  3. Speed up to above 40kph then stop pedalling and freewheel
  4. Rolldown timer will start automatically when you hit 40kph, so stop pedalling quickly!
  """
            )

            if not dev_trainer:  # if trainer not already captured
                dev_trainer = trainer.get_trainer()
                if not dev_trainer:
                    self.TrainerStatusVariable.set("Trainer not detected")
                    self.RunoffButton.config(state="normal")
                    return
                else:
                    self.TrainerStatusVariable.set("Trainer detected")
                    trainer.initialise_trainer(dev_trainer)  # initialise trainer

            while runoff_loop_running:  # loop every 100ms
                last_measured_time = time.time() * 1000

                # receive data from trainer
                speed, pedecho, heart_rate, force_index, cadence = trainer.receive(
                    dev_trainer
                )  # get data from device
                self.SpeedVariable.set(speed)
                if speed == "Not found":
                    self.TrainerStatusVariable.set("Check trainer is powered on")

                # send data to trainer
                resistance_level = 6
                trainer.send(dev_trainer, resistance_level, pedecho)

                if speed > 40:  # speed above 40, start rolldown
                    self.InstructionsVariable.set(
                        "Rolldown timer started - STOP PEDALLING!"
                    )
                    rolldown = True

                if speed <= 40 and rolldown:  # rolldown timer starts when dips below 40
                    if rolldown_time == 0:
                        rolldown_time = time.time()  # set initial rolldown time
                    self.InstructionsVariable.set(
                        "Rolldown timer started - STOP PEDALLING! %s "
                        % (round((time.time() - rolldown_time), 1))
                    )

                if speed < 0.1 and rolldown:  # wheel stopped
                    runoff_loop_running = False  # break loop
                    self.InstructionsVariable.set(
                        "Rolldown time = %s seconds (aim 7s)"
                        % round((time.time() - rolldown_time), 1)
                    )

                time_to_process_loop = time.time() * 1000 - last_measured_time
                sleep_time = 0.1 - (time_to_process_loop) / 1000
                if sleep_time < 0:
                    sleep_time = 0
                time.sleep(sleep_time)

            self.CalibrateButton.config(state="normal")
            # if speed > 40 or rolldown == True:
            # if rolldown_time == 0:
            # rolldown_time = time.time()#set initial rolldown time
            # self.InstructionsVariable.set("Rolldown timer started - STOP PEDALLING! %s " % ( round((time.time() - rolldown_time),1) ) )
            # rolldown = True
            # if speed < 0.1:#wheel stopped
            # running = False#break loop
            # if time.time() - rolldown_time > 7.5 :
            # msg = "More pressure from trainer on tyre required"
            # elif time.time() - rolldown_time < 6.5 :
            # msg = "Less pressure from trainer on tyre required"
            # else:
            # self.CalibrateButton.config(state="normal")
            # msg = "Pressure on tyre from trainer correct"
            # self.InstructionsVariable.set("Rolldown time = %s seconds\n%s" % (round((time.time() - rolldown_time),1), msg))

            # time_to_process_loop = time.time() * 1000 - last_measured_time
            # sleep_time = 0.1 - (time_to_process_loop)/1000
            # if sleep_time < 0: sleep_time = 0
            # time.sleep(sleep_time)
            self.RunoffButton.config(state="normal")

        t1 = threading.Thread(target=run)
        t1.start()

    def Calibrate(self):
        def run():
            # self.CalibrateButton.config(state="disabled")
            global dev_ant
            # find ANT stick
            self.ANTStatusVariable.set("Looking for ANT dongle")
            dev_ant, msg = ant.get_ant(False)
            if not dev_ant:
                self.ANTStatusVariable.set("ANT dongle not found")
                return

            self.ANTStatusVariable.set("Initialising ANT dongle")
            ant.antreset(dev_ant, False)
            ant.calibrate(dev_ant, False)  # calibrate ANT+ dongle
            ant.powerdisplay(dev_ant, False)  # calibrate as power display
            self.ANTStatusVariable.set("ANT dongle initialised")
            self.InstructionsVariable.set(
                "Place pedals in positions instructed by power meter manufacturer. Calibration will start in 5 seconds"
            )
            time.sleep(5)
            self.ANTStatusVariable.set("Sending calibration request")
            ant.send_ant(
                ["a4 09 4f 00 01 aa ff ff ff ff ff ff 49 00 00"], dev_ant, False
            )
            i = 0
            while i < 40:  # wait 10 seconds
                if i % 4 == 0:
                    self.ANTStatusVariable.set(
                        "Sending calibration request %s" % (10 - (i / 4))
                    )
                read_val = ant.read_ant(dev_ant, False)
                matching = [
                    s for s in read_val if "a4094f0001" in s
                ]  # calibration response
                if matching:
                    if matching[0][10:12] == "ac":
                        self.ANTStatusVariable.set("Calibration successful")
                        self.CalibratedVariable.set("True")
                        self.FindHWbutton.config(state="normal")
                    elif matching[0][10:12] == "af":
                        self.ANTStatusVariable.set("Calibration failed")
                        self.CalibratedVariable.set("False")
                    else:
                        self.ANTStatusVariable.set("Unknown calibration response")
                        self.CalibratedVariable.set("False")
                    i = 999
                i += 1
                time.sleep(0.25)
            if i == 40:  # timeout
                self.ANTStatusVariable.set("No calibration data received- try again")
                self.CalibratedVariable.set("False")
            self.CalibrateButton.config(state="normal")
            self.InstructionsVariable.set("")

        t1 = threading.Thread(target=run)
        t1.start()

    def ScanForHW(self):  # calibration loop
        def run():
            global dev_trainer, dev_ant
            power = 0
            resistance_level = 0
            save_data = []

            if not dev_trainer:  # if trainer not already captured
                dev_trainer = trainer.get_trainer()
                if not dev_trainer:
                    self.TrainerStatusVariable.set("Trainer not detected")
                    return
                else:
                    self.TrainerStatusVariable.set("Trainer detected")
                    trainer.initialise_trainer(dev_trainer)  # initialise trainer

            # find ANT stick
            if not dev_ant:
                dev_ant, msg = ant.get_ant(False)
                if not dev_ant:
                    self.ANTStatusVariable.set(u"no ANT dongle found")
                    return False
            self.ANTStatusVariable.set(u"ANT dongle found")

            ant.antreset(dev_ant, False)  # reset dongle
            ant.calibrate(dev_ant, False)  # calibrate ANT+ dongle
            ant.powerdisplay(dev_ant, False)  # calibrate as power display

            iterations = 0
            rest = 1
            stop_loop = False

            # ##################DATA LOOP FROM ANT STICK###################
            while self.StartText.get() == "Stop":
                # print iterations
                last_measured_time = time.time() * 1000
                if iterations == 240:  # inc resistance level every 60s (240 iterations)
                    iterations = 0
                    rest = 1  # go into rest mode
                    resistance_level += 1
                    if resistance_level == 14:
                        stop_loop = True
                if stop_loop:
                    self.StartText.set(u"Start")
                    self.InstructionsVariable.set("Test finished. Please exit")
                    break
                if rest > 0:
                    rest += 1
                    self.InstructionsVariable.set(
                        "Rest for %s seconds at a slow spin in an easy gear"
                        % int(round((40 - rest) / 4))
                    )
                    if rest == 40:
                        rest = 0
                else:
                    iterations += 1
                    self.InstructionsVariable.set(
                        "Over next %s seconds gradually increase your power from easy to near maximum"
                        % int(round((240 - iterations) / 4))
                    )

                try:
                    read_val = ant.read_ant(dev_ant, False)
                    matching = [
                        s for s in read_val if "a4094e0010" in s
                    ]  # a4094e0010ecff00be4e000010 #10 power page be 4e accumulated power 00 00 iunstant power
                    if matching:
                        power = int(matching[0][22:24], 16) * 256 + int(
                            matching[0][20:22], 16
                        )
                    # receive data from trainer
                    speed, pedecho, heart_rate, calc_power, cadence = trainer.receive(
                        dev_trainer
                    )  # get data from device
                    if speed == "Not found":
                        self.TrainerStatusVariable.set("Check trainer is powered on")
                        speed = 0
                    # send data to trainer
                    trainer.send(dev_trainer, resistance_level, pedecho)

                    self.PowerVariable.set(power)
                    self.SpeedVariable.set(speed)
                    self.ResistanceVariable.set(resistance_level)

                    if rest == 0 and speed > 0:  # in calibration mode and moving
                        save_data.append([resistance_level, speed, power])

                except usb.core.USBError:  # nothing from stick
                    pass

                time_to_process_loop = time.time() * 1000 - last_measured_time
                sleep_time = 0.25 - (time_to_process_loop) / 1000
                if sleep_time < 0:
                    sleep_time = 0
                time.sleep(sleep_time)
            # ##################END DATA LOOP FROM ANT STICK###############
            # ant.send(["a4 01 4a 00 ef 00 00"],dev_ant, False)#reset ANT+ dongle
            with open("calibration.pickle", "wb") as handle:
                pickle.dump(save_data, handle, protocol=pickle.HIGHEST_PROTOCOL)

            msg = produce_power_curve_file(save_data)
            self.InstructionsVariable.set(msg)

        if self.StartText.get() == "Start":
            self.StartText.set(u"Stop")
            t1 = threading.Thread(target=run)
            t1.start()

        else:
            self.StartText.set(u"Start")
示例#34
0
class App(Frame):

    def __init__(self, master=None):
        self.computing = False
        self.S = None

        self.progress_queue = Queue.Queue()
        self.cancel_event = threading.Event()

        Frame.__init__(self, master)
        self.grid()
        self.master.protocol("WM_DELETE_WINDOW", self.close_handler)

        w = Label(self,text=" ",fg="red")
        w.grid(row=0,column=0,pady=10,sticky=W)

        ## Object parameters
        w = Label(self,text="Tower parameters:",fg="red")
        w.grid(row=0,column=1,pady=10,sticky=W)

        w = Label(self,text="Latitude (deg):")
        w.grid(row=1,column=1,sticky=W)
        self.lat_ent = Entry(self,width=36)
        self.lat_ent.grid(row=1,column=2,sticky=W)
        self.lat_ent.insert(0, "60")

        w = Label(self,text="Tower height (m):")
        w.grid(row=2,column=1,sticky=W)
        self.height_ent = Entry(self,width=36)
        self.height_ent.grid(row=2,column=2,sticky=W)
        self.height_ent.insert(0, "50")

        w = Label(self,text="Tower diameter (m):")
        w.grid(row=3,column=1,sticky=W)
        self.diam_ent = Entry(self,width=36)
        self.diam_ent.grid(row=3,column=2,sticky=W)
        self.diam_ent.insert(0, "30")

        ## Simulation parameters
        w = Label(self,text="Simulation parameters",fg="red")
        w.grid(row=4,column=1,pady=10,sticky=SW)

        w = Label(self,text="Time vector (s):")
        w.grid(row=5,column=1,sticky=W)
        self.time_ent = Entry(self,width=36)
        self.time_ent.grid(row=5,column=2)
        self.time_ent.insert(0, "arange(0,365*24*3600,10*60)")


        ## Output parameters
        w = Label(self,text="Output parameters",fg="red")
        w.grid(row=6,column=1,pady=10,sticky=SW)

        w = Label(self,text="East-west grid (m):")
        w.grid(row=7,column=1,sticky=W)
        self.gridx_ent = Entry(self,width=36)
        self.gridx_ent.grid(row=7,column=2)
        self.gridx_ent.insert(0, "linspace(-4*tower_height,4*tower_height,10)")

        w = Label(self,text="South-north grid (m):")
        w.grid(row=8,column=1,sticky=W)
        self.gridy_ent = Entry(self,width=36)
        self.gridy_ent.grid(row=8,column=2)
        self.gridy_ent.insert(0, "linspace(-4*tower_height,4*tower_height,10)")

        self.compute_btn = Button(self, text="Start computation", width=15, command=self.compute_btn_handler)
        self.compute_btn.grid(row=9,column=1,pady=10,sticky=E)

        w = Label(self,text=" ",fg="red")
        w.grid(row=0,column=3,pady=10,sticky=W)

        self.periodicCall()

    def close_handler(self):
        self.cancel_event.set()
        self.master.quit()

    def parse_entries(self):
        self.phi = 0
        self.latitude = float(eval(self.lat_ent.get()))
        tower_height = float(eval(self.height_ent.get()))
        self.tower_height = tower_height
        self.tower_diameter = float(eval(self.diam_ent.get()))
        self.time_vector = eval(self.time_ent.get())
        x = eval(self.gridx_ent.get())
        y = eval(self.gridy_ent.get())
        X,Y = meshgrid(x,y)
        self.X = X
        self.Y = Y

    def compute_btn_handler(self):
        if self.computing:
            self.cancel_event.set()
            self.thread1.join()
            self.compute_btn.config(text="Start computation")
        else:
            self.cancel_event = threading.Event()
            self.meter = Meter(self, relief='ridge', bd=3, width=250)
            self.meter.grid(row=9,column=2)
            self.parse_entries()
            self.compute_btn.config(text="Stop computation")
            self.thread1 = threading.Thread(target=self.worker_thread)
            self.thread1.start()


    def periodicCall(self):
        """
        Check every 100 ms if there is something new in the queue.
        """
        while self.progress_queue.qsize():
            try:
                msg = self.progress_queue.get(0)
                if msg == 1.0:
                    self.meter.set(msg,"Completed successfully")
                else:
                    self.meter.set(msg)
            except Queue.Empty:
                pass
        if self.computing:
            self.compute_btn.config(text="Stop computation")
        else:
            self.compute_btn.config(text="Start computation")

        if self.S != None:
            self.plot_shadow_map()
            self.S = None

        self.master.after(100, self.periodicCall)
    
    def plot_shadow_map(self):
        ion()
        contourf(self.X, self.Y, self.S/3600.,levels=[0.1,5,10,15,30,40,50,100,1e6],cmap=cm.get_cmap(name="gist_heat_r"))
        clim(0,100)
        colorbar()
        CS = contour(self.X, self.Y, self.S/3600.,levels=[0.0001,5,10,15,30,40,50,100],antialiased=True,colors='k')
        clabel(CS, inline=1, fontsize=8)
        xlabel('Location west-east (m)')
        ylabel('Location south-north (m)')
	show()

    def worker_thread(self):
        self.S = None
        self.computing = True
        S = shadow.tower_shadow_map(self.phi, \
                                    self.latitude*pi/180., \
                                    self.tower_height, \
                                    self.tower_diameter, \
                                    self.time_vector, \
                                    self.X, \
                                    self.Y, \
                                    self.progress_queue, \
                                    self.cancel_event)
        self.S = S

        self.computing = False
示例#35
0
class TopLevel(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="gray")
        self.parent = parent
        self.init_global_vars()
        self.init_UI()
        self.detect_debug_mode()
        self.set_state_stopped()

    def init_global_vars(self):
        self.switch_status = 'none'
        self.home_result = IntVar()
        self.move_result = IntVar()
        self.timer_active = IntVar()
        self.test_active = False
        self.test_paused = False

        self.timer = [0, 0]
        self.timer_reset_val = [0, 0]

        #self.active_cycle = 0
        #self.active_temp = 'foo'
        #self.up_motor_res = 2
        #self.right_motor_res = 2

        self.move_motor_resolution = 2

        self.up_full_steps = 3200
        self.right_full_steps = 7200

        self.debug_mode = False

        self.event_schedule = []

        self.move_total_duration = 0
        self.move_direction = ''
        self.move_started_time = datetime.now()
        self.pause_time = datetime.now()
        self.resume_time = datetime.now()
        self.planned_steps = 0

    def init_UI(self):

        self.parent.title('Liquid Thermal Shock Tester v0.2')
        self.pack(fill=BOTH, expand=True)
        options_frame = Frame(self, background='gray', pady=5, padx=5)
        options_frame.pack(side=LEFT, fill=BOTH, expand=True)

        options_label = Label(options_frame,
                              text='Test Setup',
                              background='gray',
                              font=('Courier', 22, 'bold'),
                              justify=LEFT)
        ul_bold_font = Font(options_label, options_label.cget('font'))
        ul_bold_font.configure(underline=True)
        options_label.configure(font=ul_bold_font)
        options_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        cycles_frame = Frame(options_frame, background='gray', pady=5)
        cycles_frame.pack(side=TOP, fill=BOTH, expand=True)

        cycles_label = Label(cycles_frame,
                             text='# of cycles',
                             background='gray',
                             font=('Courier', 12),
                             justify=CENTER)
        cycles_label.grid(row=0,
                          column=0,
                          rowspan=1,
                          columnspan=2,
                          sticky='news')
        ul_plain_font = Font(cycles_label, cycles_label.cget('font'))
        ul_plain_font.configure(underline=True)
        cycles_label.configure(font=ul_plain_font)

        self.cycles_select_disp = Label(cycles_frame,
                                        text='5',
                                        background='white',
                                        font=('Courier', 32))
        self.cycles_select_disp.grid(row=1,
                                     column=0,
                                     rowspan=2,
                                     columnspan=1,
                                     sticky='wens',
                                     padx=5,
                                     pady=5)

        self.cycles_increase_button = Button(cycles_frame,
                                             text=u'\u25b2',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_increment)
        self.cycles_increase_button.grid(row=1,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.cycles_decrease_button = Button(cycles_frame,
                                             text=u'\u25BC',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_decrement)
        self.cycles_decrease_button.grid(row=2,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.fix_grid(cycles_frame)

        soak_time_frame = Frame(options_frame, background='gray', pady=5)
        soak_time_frame.pack(side=TOP, fill=BOTH, expand=True)

        soak_time_label = Label(soak_time_frame,
                                text='Minutes per Soak',
                                background='gray',
                                font=('Courier', 12),
                                justify=CENTER)
        soak_time_label.grid(row=0,
                             column=0,
                             rowspan=1,
                             columnspan=2,
                             sticky='news')
        soak_time_label.configure(font=ul_plain_font)

        self.soak_time_disp = Label(soak_time_frame,
                                    text='5',
                                    background='white',
                                    font=('Courier', 32))
        self.soak_time_disp.grid(row=1,
                                 column=0,
                                 rowspan=2,
                                 columnspan=1,
                                 sticky='wens',
                                 padx=5,
                                 pady=5)

        self.soak_time_increment_button = Button(
            soak_time_frame,
            text=u'\u25b2',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_increment)
        self.soak_time_increment_button.grid(row=1,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.soak_time_decrement_button = Button(
            soak_time_frame,
            text=u'\u25BC',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_decrement)
        self.soak_time_decrement_button.grid(row=2,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.fix_grid(soak_time_frame)

        controls_frame = Frame(self, background='gray')
        controls_frame.pack(side=LEFT, fill=BOTH, expand=True)

        run_pause_frame = Frame(controls_frame, background='gray')
        run_pause_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        self.run_button = Button(run_pause_frame,
                                 text='RUN',
                                 background='green',
                                 activebackground='green',
                                 font=('Courier', 30, 'bold'),
                                 width=5,
                                 command=self.run_init)
        self.run_button.grid(row=0, column=0, sticky='wens', padx=5, pady=5)

        self.pause_button = Button(run_pause_frame,
                                   text='PAUSE',
                                   background='orange',
                                   activebackground='orange',
                                   font=('Courier', 30, 'bold'),
                                   width=5,
                                   command=self.pause_button_pressed)
        self.pause_button.grid(row=0, column=1, sticky='wens', padx=5, pady=5)

        self.fix_grid(run_pause_frame)

        stop_button = Button(controls_frame,
                             text='STOP',
                             background='red',
                             activebackground='red',
                             font=('Courier', 36, 'bold'),
                             command=self.stop_test)
        stop_button.pack(side=TOP, fill=BOTH, expand=True, padx=5)

        jog_frame = Frame(controls_frame, background='gray')
        jog_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        jog_label = Label(jog_frame,
                          text='Motor\rjog',
                          font=('Courier', 12, 'bold'),
                          background='gray')
        jog_label.grid(row=1, column=1)

        self.jog_up_button = Button(jog_frame,
                                    text=u'\u25b2',
                                    font=('Courier', 18, 'bold'))
        self.jog_up_button.grid(row=0,
                                column=1,
                                rowspan=1,
                                columnspan=1,
                                sticky='wens',
                                padx=5,
                                pady=5)
        self.jog_up_button.bind("<Button-1>", self.jog_up_on)
        self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_left_button = Button(jog_frame,
                                      text=u'\u25C4',
                                      font=('Courier', 18, 'bold'))
        self.jog_left_button.grid(row=1,
                                  column=0,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_left_button.bind("<Button-1>", self.jog_left_on)
        self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_right_button = Button(jog_frame,
                                       text=u'\u25BA',
                                       font=('Courier', 18, 'bold'))
        self.jog_right_button.grid(row=1,
                                   column=2,
                                   rowspan=1,
                                   columnspan=1,
                                   sticky='wens',
                                   padx=5,
                                   pady=5)
        self.jog_right_button.bind("<Button-1>", self.jog_right_on)
        self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_down_button = Button(jog_frame,
                                      text=u'\u25BC',
                                      font=('Courier', 18, 'bold'))
        self.jog_down_button.grid(row=2,
                                  column=1,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_down_button.bind("<Button-1>", self.jog_down_on)
        self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off)

        self.fix_grid(jog_frame)

        status_frame = Frame(self, background='gray')
        status_frame.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)

        status_label = Label(status_frame,
                             text='Tester Status',
                             background='gray',
                             font=('Courier', 22, 'bold'),
                             justify=LEFT)
        status_label.configure(font=ul_bold_font)
        status_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        self.status_disp = Text(status_frame)
        self.status_disp.pack(side=TOP, fill=BOTH, padx=5, pady=5)
        self.status_disp.configure(state='disabled')

        self.power_button = Button(status_frame,
                                   text='POWER OFF',
                                   font=('Courier', 24, 'bold'),
                                   background="red",
                                   activebackground="red",
                                   command=self.shutdown,
                                   height=2)
        self.power_button.pack(side=TOP, fill=BOTH, padx=5, pady=5)

    def fix_grid(self, target_frame):
        [columns, rows] = target_frame.grid_size()
        for i in range(rows):
            target_frame.rowconfigure(i, weight=1)
        for j in range(columns):
            target_frame.columnconfigure(j, weight=1)

    def detect_debug_mode(self):
        if str(sys.argv[0]) == 'debug':
            self.update_status('Tester is in debug mode.', 'newline')
            self.update_status('', 'newline')
            self.update_status('The tester will run with a 6 second',
                               'newline')
            self.update_status('  soak time regardless of the soak', 'newline')
            self.update_status('  time selected in the GUI.', 'newline')
            self.debug_mode = True
        else:
            self.update_status('Welcome to the Liquid Thermal Shock',
                               'newline')
            self.update_status('  Tester. Select the number of', 'newline')
            self.update_status('  cycles and the soak time per cycle',
                               'newline')
            self.update_status('  to begin testing. Please ensure', 'newline')
            self.update_status('  that the limit switches are free', 'newline')
            self.update_status('  from obstructions prior to running',
                               'newline')
            self.update_status('  a test.', 'newline')
            self.debug_mode = False

    def cycles_increment(self):
        """ Increments the number of cycles per test. """

        str_num_cycles = self.cycles_select_disp.cget('text')
        num_cycles = int(str_num_cycles)
        num_cycles += 1
        self.cycles_select_disp.configure(text=str(num_cycles))

    def cycles_decrement(self):
        """ Decrements the number of cycles per test. """

        str_num_cycles = self.cycles_select_disp.cget('text')
        num_cycles = int(str_num_cycles)

        # Check for attempts to set num_cycles < 1.
        if num_cycles <= 1:
            self.cycles_select_disp.configure(text=str(num_cycles))
        else:
            num_cycles -= 1
            self.cycles_select_disp.configure(text=str(num_cycles))

    def soak_time_increment(self):
        """ Increments the soak time. """

        str_soak_time = self.soak_time_disp.cget('text')
        soak_time = int(str_soak_time)
        soak_time += 1
        self.soak_time_disp.configure(text=str(soak_time))
        self.reset_timer()

    def soak_time_decrement(self):
        """ Decrements the soak time. """

        str_soak_time = self.soak_time_disp.cget('text')
        soak_time = int(str_soak_time)

        # Check for attempts to set soak time < 1.
        if soak_time <= 1:
            self.soak_time_disp.configure(text=str(soak_time))
        else:
            soak_time -= 1
            self.soak_time_disp.configure(text=str(soak_time))
        self.reset_timer()

    def reset_timer(self):
        """ Resets the timer to whatever is displayed in the
            soak time window."""

        str_soak_time = self.soak_time_disp.cget('text')

        if self.debug_mode:
            self.timer = [0, 6]
        else:
            self.timer = [int(str_soak_time), 0]

        # Use line below for tester debugging -- forces a 5 second soak time.
        # Comment out for normal operations.
        # self.timer = [0, 5]

    # Callback functions for manual motor jog
    def jog_off(self, event):
        motors_off()

    def jog_up_on(self, event):
        jog_motor('up')

    def jog_down_on(self, event):
        jog_motor('down')

    def jog_left_on(self, event):
        jog_motor('left')

    def jog_right_on(self, event):
        jog_motor('right')

    def shutdown(self):
        """ Shuts down the tester. """

        motors_off()
        confirm_string = "Do you really want to power down the tester?"
        confirm = tkMessageBox.askokcancel("Shutdown", confirm_string)
        if confirm:
            subprocess.call("sudo poweroff", shell=True)
        else:
            pass

    def update_status(self, new_text, writemode):
        """ Prints text to the tester status window. """

        self.status_disp.configure(state='normal')
        if writemode == 'overwrite':
            self.status_disp.delete('end-1c linestart', 'end')
        self.status_disp.insert('end', '\n' + new_text)
        self.status_disp.see(END)
        self.status_disp.configure(state='disabled')

    def append_event(self, cycle, type, destination, direction, steps,
                     duration):
        """ Add new event (motor move or temperature soak) to event schedule. """

        self.event_schedule.append({
            'Cycle': cycle,
            'Event type': type,
            'Destination': destination,
            'Direction': direction,
            'Steps': steps,
            'Duration': duration
        })

    def start_homing_move(self, direction):
        """ Starts the homing procedure in the given direction. """

        self.update_status('Finding ' + direction + ' home position...',
                           'newline')
        self.status_disp.update()
        self.home_result.set(0)
        self.queue = Queue.Queue()
        Find_Home_Nonblocking(self.queue, direction).start()
        self.master.after(100, self.process_homing_queue)
        self.wait_variable(self.home_result)

        if self.home_result.get() == 0:
            self.update_status('Homing error. Test aborted.', 'newline')
            return
        else:
            self.update_status(
                direction.capitalize() + ' home position found.', 'newline')

    def run_init(self):
        """ Run button callback.  
        
            Collects run parameters, creates event schedule, then runs the 
            series of scheduled events.
        """

        self.set_state_running()

        # Set number of steps for each motor move. Depends on motor resolution
        # set in static variables section.
        up_steps = self.up_full_steps * (2**self.move_motor_resolution)
        right_steps = self.right_full_steps * (2**self.move_motor_resolution)

        # Get the total number of cycles
        total_cycles_str = self.cycles_select_disp.cget('text')
        total_cycles_int = int(total_cycles_str)

        # Get the soak time in minutes. This is forced to 0.1 minutes when
        # the GUI is launched in debug mode
        if self.debug_mode:
            soak_time_str = '0.1'
            soak_time_float = 0.1
        else:
            soak_time_str = self.soak_time_disp.cget('text')
            soak_time_float = float(soak_time_str)

        # Build event schedule
        self.event_schedule = []
        for i in range(1, total_cycles_int + 1):
            self.append_event(i, 'move', 'hot', 'down', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'soak', 'hot', '', '', soak_time_float)
            self.append_event(i, 'move', 'cold', 'up', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'move', 'cold', 'left', right_steps,
                              right_steps / 2000.0)
            self.append_event(i, 'move', 'cold', 'down', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'soak', 'cold', '', '', soak_time_float)
            self.append_event(i, 'move', 'hot', 'up', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'move', 'hot', 'right', right_steps,
                              right_steps / 2000.0)

        # Set the destination to 'complete' for the final 'up' and 'right' moves.
        # Edit the 'Steps' parameter of the final move to end the test in the
        # center of the rail.
        self.event_schedule[-2]['Destination'] = 'complete'
        self.event_schedule[-1]['Destination'] = 'complete'
        self.event_schedule[-1]['Steps'] = right_steps / 2
        self.event_schedule[-1][
            'Duration'] = self.event_schedule[-1]['Steps'] / 2000.0

        self.test_active = True

        # Print initial runtime message to status window
        if soak_time_float == 1.0:
            soak_time_out = '1 minute'
        else:
            soak_time_out = soak_time_str + ' minutes'

        self.update_status('', 'newline')
        self.update_status('Test started.', 'newline')
        out_string = 'The tester will run for ' + total_cycles_str + ' cycles, '
        self.update_status(out_string, 'newline')
        out_string = soak_time_out + ' per cycle.'
        self.update_status(out_string, 'newline')

        if self.test_active == True:
            self.start_homing_move('up')
        if self.test_active == True and self.home_result.get() == 1:
            self.start_homing_move('right')

        if self.test_active == True and self.home_result.get() == 1:
            self.update_status('Moving to hot position...', 'newline')
            self.run_scheduled_events()

    def run_scheduled_events(self):
        """ Runs the series of events listed in self.event_schedule. """

        if self.test_active == True:

            current_event = self.event_schedule.pop(0)

            if current_event['Event type'] == 'soak':
                self.set_state_running()
                self.reset_timer()
                cycle = str(current_event['Cycle'])
                temperature = current_event['Destination']
                self.timer_active.set(1)
                self.countdown_timer(cycle, temperature)
                self.wait_variable(self.timer_active)

            elif current_event['Event type'] == 'move':

                if current_event['Direction'] == 'up':
                    self.set_state_running()
                    if current_event['Destination'] == 'complete':
                        out_string = 'Test complete, moving to neutral '
                        out_string += '      position...'
                        self.update_status(out_string, 'newline')
                    else:
                        out_string = 'Moving to ' + current_event['Destination']
                        out_string += ' position...'
                        self.update_status(out_string, 'newline')

                elif current_event['Direction'] == 'down':
                    self.set_state_running()

                else:
                    self.pause_button.config(state='normal')
                    self.move_direction = current_event['Direction']
                    self.move_total_duration = current_event['Duration']
                    self.planned_steps = current_event['Steps']

                #self.move_result.set(0)
                self.queue = Queue.Queue()
                self.move_started_time = datetime.now()
                Move_Motor_Nonblocking(self.queue, current_event['Direction'],
                                       self.move_motor_resolution,
                                       current_event['Steps']).start()
                self.master.after(100, self.process_move_queue)
                self.wait_variable(self.move_result)
                motors_off()

        # If there are any events left in the schedule, run the next scheduled
        # event.  If there are no events left in the schedule and the last event
        # was a completed move, then the test is complete and this function should
        # output the 'test complete' message.  If there are no events in the schedule
        # and the last event was not a completed move, then the test is paused and
        # this function should do nothing else.
        if self.event_schedule:
            self.after(1000, self.run_scheduled_events)
        elif self.move_result.get() == 1:
            self.update_status('Test complete.', 'overwrite')
            self.set_state_stopped()
        else:
            pass

    def set_state_running(self):
        """ Deactivates cycle time select, soak time select, motor jog
            and power off buttons.

            This is to stop users from changing test parameters during a
            running test, which could result in some difficult to handle
            undefined states.
        """

        self.cycles_increase_button.config(state='disabled')
        self.cycles_decrease_button.config(state='disabled')
        self.soak_time_increment_button.config(state='disabled')
        self.soak_time_decrement_button.config(state='disabled')
        self.run_button.config(state='disabled')
        self.jog_up_button.config(state='disabled')
        self.jog_down_button.config(state='disabled')
        self.jog_left_button.config(state='disabled')
        self.jog_right_button.config(state='disabled')
        self.power_button.config(state='disabled')
        self.pause_button.config(state='disabled')

        # This is absurd, but apparently setting a button to 'disabled' does
        # not actually disable the button event bindings, so binding the buttons
        # to a 'do_nothing()' function is required.
        self.jog_up_button.bind("<Button-1>", self.do_nothing)
        self.jog_up_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_down_button.bind("<Button-1>", self.do_nothing)
        self.jog_down_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_left_button.bind("<Button-1>", self.do_nothing)
        self.jog_left_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_right_button.bind("<Button-1>", self.do_nothing)
        self.jog_right_button.bind("<ButtonRelease-1>", self.do_nothing)

    def set_state_stopped(self):
        """ Reactivates all of the buttons deactivated in the
            set_state_running function.
        """

        self.test_active = False
        self.test_paused = False

        self.cycles_increase_button.config(state='normal')
        self.cycles_decrease_button.config(state='normal')
        self.soak_time_increment_button.config(state='normal')
        self.soak_time_decrement_button.config(state='normal')
        self.run_button.config(state='normal')
        self.jog_up_button.config(state='normal')
        self.jog_down_button.config(state='normal')
        self.jog_left_button.config(state='normal')
        self.jog_right_button.config(state='normal')
        self.power_button.config(state='normal')
        self.pause_button.config(state='disabled')
        self.pause_button.config(text='PAUSE',
                                 background='orange',
                                 activebackground='orange')

        self.jog_up_button.bind("<Button-1>", self.jog_up_on)
        self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_down_button.bind("<Button-1>", self.jog_down_on)
        self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_left_button.bind("<Button-1>", self.jog_left_on)
        self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_right_button.bind("<Button-1>", self.jog_right_on)
        self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off)

    def do_nothing(self, event):
        """ Does absolutely nothing. This is a workaround for the fact that
            button event bindings are not disabled when a button's state is
            set to 'disabled'.
        """

        pass

    def pause_timer(self):
        """ Displays the running duration of a test pause. """

        if self.test_paused:
            timer_string = '{0:1d}:{1:02d}'.format(self.timer[0],
                                                   self.timer[1])

            out_string = 'Test paused for ' + timer_string
            self.update_status(out_string, 'overwrite')

            self.timer[1] += 1
            if self.timer[1] >= 60:
                self.timer[0] += 1
                self.timer[1] -= 60

            self.after(1000, self.pause_timer)

    def countdown_timer(self, cycle, temperature):
        """ Displays countdown timer and current cycle number/temperature
            information in status window.

            This function will only process if the timer_active flag is set to
            1. The function will then recursively call itself after a 1 second
            wait until the timer_active flag is set to zero.

            The timing is not precise because it will wait 1 full second between
            function calls, and therefore does not take into account the time
            necessary to process the function itself. However, over a typical
            soak time this will only amount to milliseconds, so it's certainly
            close enough for this application.
        """

        if self.timer_active.get() == 1:
            timer_string = '{0:1d}:{1:02d}'.format(self.timer[0],
                                                   self.timer[1])
            out_string = 'Cycle ' + cycle + ' of '
            out_string += self.cycles_select_disp.cget('text') + ', '
            out_string += temperature + '. ' + timer_string + ' remaining.'

            self.update_status(out_string, 'overwrite')

            # Decrement 1 second from timer. If this flips the seconds to a
            # negative value, decrement 1 minute and add 60 seconds
            self.timer[1] -= 1
            if self.timer[1] < 0:
                # If timer is run down to zero, display soak complete message
                # and set timer_active flag to zero.
                if self.timer[0] <= 0:
                    out_string = 'Cycle ' + cycle + ' of '
                    out_string += self.cycles_select_disp.cget('text') + ', '
                    out_string += temperature + ' complete.'
                    self.update_status(out_string, 'overwrite')
                    self.timer_active.set(0)
                else:
                    self.timer[0] -= 1
                    self.timer[1] += 60

            # Have the countdown_timer function recursively call itself
            # after 1000ms.
            self.after(1000, self.countdown_timer, cycle, temperature)

    def stop_test(self):
        """ Stop button callback.  Allows user to abort test sequence. """

        # Clear event schedule and toggle home and move result monitoring
        # variables. This helps prevent errors on restart
        motors_off()

        self.event_schedule = []
        self.home_result.set(0)
        self.move_result.set(0)

        if self.test_active:
            self.update_status('Test stopped by user.', 'newline')

        self.test_active = False

        # Stop and reset timer, reactivate buttons (in case the test
        # needs to be restarted).
        self.timer_active.set(0)
        self.reset_timer()
        self.set_state_stopped()

    def pause_button_pressed(self):
        """ Pause button callback. """

        if self.test_paused:
            self.test_paused = False
            self.resume_test()
        else:
            self.test_paused = True
            self.timer = [0, 0]
            self.pause_test()

    def pause_test(self):
        """ Pauses a running test """

        motors_off()
        self.pause_time = datetime.now()

        self.pause_button.config(text='RESUME',
                                 background='green',
                                 activebackground='green')

        self.resume_schedule = self.event_schedule

        self.event_schedule = []
        self.move_result.set(0)
        pause_delta = self.pause_time - self.move_started_time
        pause_delta_seconds = float(pause_delta.seconds)
        pause_delta_seconds += pause_delta.microseconds / 1000000.0

        steps_prepause = int(pause_delta_seconds * 2000)

        steps_remaining = self.planned_steps - steps_prepause

        move_time_remaining = self.move_total_duration - pause_delta_seconds

        resume_event = {
            'Cycle': '',
            'Event type': 'move',
            'Destination': '',
            'Direction': self.move_direction,
            'Steps': steps_remaining,
            'Duration': move_time_remaining
        }

        self.resume_schedule.insert(0, resume_event)

        self.update_status('', 'newline')
        self.pause_timer()

    def resume_test(self):
        """ Resumes a paused test """

        self.pause_button.config(text='PAUSE',
                                 background='orange',
                                 activebackground='orange')
        self.resume_time = datetime.now()

        self.event_schedule = self.resume_schedule

        pause_duration = self.resume_time - self.pause_time

        pause_duration_seconds = float(pause_duration.seconds)
        pause_duration_seconds += pause_duration.microseconds / 1000000.0

        self.test_active = True
        self.update_status('Test resumed.', 'newline')
        self.run_scheduled_events()

    def process_homing_queue(self):
        """ Checks if homing function has returned a value. """

        # Try to read the first value in the queue. If nothing is there, then
        # the homing function has not yet returned a value and must still be
        # active. In this case, the function recursively calls itself after
        # 100ms. If there is something in the queue, the value is read into
        # the self.home_result variable and the function is not called again.
        try:
            self.home_result.set(self.queue.get(0))
        except Queue.Empty:
            self.master.after(10, self.process_homing_queue)

    def process_move_queue(self):
        """ Checks if motor move queue as returned value. """

        # Try to read the first value in the queue. If nothing is there, then
        # the motor move function has not yet returned a value and must still be
        # active. In this case, the function recursively calls itself after
        # 100ms. If there is something in the queue, the value is read into
        # the self.move_result variable and the function is not called again.

        try:
            self.move_result.set(self.queue.get(0))
        except Queue.Empty:
            self.master.after(100, self.process_move_queue)
示例#36
0
class GEditor: 
	def __init__(self, parent, gcode, fname): 
		self.textChanged = False
		self.app = parent
		self.fname = fname
		top = self.top = Toplevel(parent)
		if fname != None:
			self.top.title(fname) 
		else:
			self.top.title("Live GCode")
			
		self.editBox = Text(top) 
		self.editBox.grid(row=1, column=1, sticky=N+E+W+S)
		self.sb = Scrollbar(top)
		self.sb.config(command=self.editBox.yview)
		self.sb.grid(column=2, row=1, sticky=N+S+E)
		self.editBox.tag_configure("mymatch",foreground="#ff0000") 
		self.matchStart = None
		self.matchEnd = None

		self.editBox.config(yscrollcommand=self.sb.set)	
		
		self.editBox.delete("1.0", END)
		for l in gcode:
			self.editBox.insert(END, l + '\n')
		self.editBox.mark_set("insert", "1.0")
		
		self.editBox.edit_modified(False)
		self.editBox.bind('<<Modified>>', self.changed)

		bf = Frame(top)
		bf.grid(row=2, column=1, columnspan=2)
		self.bCancel = Button(bf, text='Exit', command=self.doCancel, width=6) 
		self.bCancel.pack(side=LEFT, padx=2, pady=2)

		self.bSave = Button(bf, text='Save', command=self.doSave, width = 6, state=DISABLED) 
		self.bSave.pack(side=LEFT, padx=2, pady=2)
		
		self.bSearch = Button(bf, text="Search", command=self.doSearch, width=6)
		self.bSearch.pack(side=LEFT, padx=2, pady=2)
		
		self.eSearch = Entry(bf, width=30)
		self.eSearch.pack(side=LEFT, padx=2)
		
		self.bReplace = Button(bf, text="Replace", command=self.doReplace, width=6)
		self.bReplace.pack(side=LEFT, padx=2, pady=2)

		self.eReplace = Entry(bf, width=30)
		self.eReplace.pack(side=LEFT, padx=2)
		
		self.top.grab_set()
		self.app.wait_window(self.top)


	def doCancel(self): 
		if not self.textChanged:
			self.top.destroy()
			
		elif tkMessageBox.askyesno("Cancel?", "Are you sure you want to lose your changes?", parent=self.top):
			self.top.destroy()

	def doSave(self): 
		rc = self.app.gEditSave(self.editBox.get("1.0", END).rstrip().split("\n"), self.fname, self.top)
		if self.fname == None:
			self.top.destroy() 
		else:
			if rc:
				self.editBox.edit_modified(False)
				self.textChanged = False
				self.bCancel.config(text="Exit")
				self.bSave.config(state=DISABLED)
		
	def changed(self, evt):
		if not self.textChanged:
			self.bSave.config(state=NORMAL)
			self.bCancel.config(text="Cancel")
			self.textChanged = True
			
	def doSearch(self):
		sval = self.eSearch.get()
		if len(sval) == 0:
			return

		try:
			start = self.editBox.index(INSERT + "+1c")
		except:
			start = "1.0"	

		pos = self.editBox.search(sval, start, stopindex=END)
		if not pos:
			pos = self.editBox.search(sval, "1.0", stopindex=start)
				
		if not pos:
			return
		
		e = self.editBox.index(pos + "+%dc" % len(sval))
		self.editBox.see(pos)
		self.editBox.mark_set("insert", pos)
		if self.matchStart != None:
			self.editBox.tag_remove("mymatch", self.matchStart, self.matchEnd)
		self.editBox.tag_add("mymatch", pos, e) 
		self.matchStart = pos
		self.matchEnd = e
		
		self.editBox.focus_force()
	
	def doReplace(self):
		rval = self.eReplace.get()
		
		if self.matchStart == None:
			return
		
		self.editBox.delete(self.matchStart, self.matchEnd)
		self.editBox.insert(self.matchStart, rval)
		
		self.editBox.focus_force()
示例#37
0
class DirectorySelectButton(object):
    # %%
    """
    Initializes the DirectorySelectButton.
    
    @param   fileType    string
    @param   openTypes   string[]
    """
    def __init__(self, master, frame, directType, width, height, callback=None):
        self.master = master
        self.directType = directType
        self.width = width
        self.height = height
        self.button = Button(
            frame,
            text="Choose {} Directory".format(self.directType),
            command=self.callback,
            width=width,
            height=self.height)
        self.directoryName = ""
        self.extraCallback = callback
    
    """
    Wrapper function for self.button.grid.
    """
    def grid(self, **args):
        self.button.grid(**args)
    
    """
    Sets the state of the button.
    """
    def setState(self, state):
        self.button.config(state = state)
    
    # %%
    """
    Callback for the button.
    
    Gets the directoryName from user with tkFileDialog.
    Updates the display to reflect directory choice.
    """
    def callback(self):
        directoryName = tkFileDialog.askdirectory(initialdir=self.master.lastFileLoc, \
                    title = "Select {} File".format(self.directType))
        if directoryName == "":
            return
        self.directoryName = directoryName
        self.master.lastFileLoc = self.directoryName
        
        #update the Gui
        directoryRoots = self.directoryName.split("/")
        displayDirectory = str()
        while(len(directoryRoots) != 0):
            currentLine = directoryRoots.pop(0)
            if len(directoryRoots) != 0:
                while(len(currentLine) + len(directoryRoots[0]) < self.width):
                    currentLine = "{}\\{}".format(currentLine, directoryRoots.pop(0))
                    if len(directoryRoots) == 0:
                        break
            
            displayDirectory = "{}{}".format(displayDirectory, currentLine)
        
        self.button.config(
            text="{}: {}".format(self.directType, displayDirectory),
            anchor='w')
        
        if self.extraCallback != None:
            self.extraCallback()
示例#38
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.padx = 3
        self.pady = 3
        self.grid()
        self.results = []
        self.playlists = []
        self.vids = []
        self.__createWidgets()

    def __createWidgets(self):
        self.__searchFields()
        self.__resultArea()
        self.__buttons()
        self.__markdownArea()
        self.bind('<Return>', self.search_button)

    def __buttons(self):
        self.resultSelect = Button(text='OK', state=DISABLED)
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)
        self.status = Label(text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.grid(row=9, column=0, columnspan=10, sticky=N + E + S + W)
        self.__vidButtons()
        self.__rmVidButtons()
        self.resultSelect.grid_forget()

    def __searchFields(self):
        Label(text="User", anchor=E).grid(row=0, column=0,
                                          padx=self.padx, pady=self.pady,
                                          sticky=W)
        self.user_entry = Entry()
        self.user_entry.grid(row=0, column=1, padx=self.padx, pady=self.pady,
                             sticky=W)
        Label(text="Search terms").grid(row=0, column=3,
                                        padx=self.padx, pady=self.pady,
                                        sticky=W)
        self.search_terms = Entry()
        self.search_terms.grid(row=0, column=4,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        Label(text="playlist id").grid(row=1, column=3,
                                       padx=self.padx, pady=self.pady,
                                       sticky=W)
        self.playlist_id = Entry()
        self.playlist_id.grid(row=1, column=4, padx=self.padx, pady=self.pady,
                              sticky=W)
        self.search_button = Button(text="Search", command=self.__search)
        self.search_button.grid(row=2, column=4,
                                padx=self.padx, pady=self.pady, sticky=E)

    def __resultArea(self):
        self.result_label = Label(text="Results")
        self.result_label.grid(row=2, column=0,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        self.resultshowbut = Button(text="View", command=self.__showResults)
        self.resultshowbut.grid(row=2, column=1, sticky=W)
        self.yScroll = Scrollbar(orient=VERTICAL)
        self.xScroll = Scrollbar(orient=HORIZONTAL)
        self.listbox = Listbox(xscrollcommand=self.xScroll.set,
                                yscrollcommand=self.yScroll.set,
                                selectmode=SINGLE)
        self.xScroll.config(command=self.listbox.xview)
        self.yScroll.config(command=self.listbox.yview)

    def __showResults(self):
        self.resultshowbut.config(text="Hide", command=self.__hideResults)
        self.yScroll.grid(row=3, column=5, sticky=N + S)
        self.xScroll.grid(row=4, column=0, sticky=E + W, columnspan=5)
        self.listbox.grid(row=3, column=0, sticky=N + S + E + W, columnspan=5)
        self.markdownarea.config(height=10)

    def __hideResults(self):
        self.resultshowbut.config(text="View", command=self.__showResults)
        self.yScroll.grid_forget()
        self.xScroll.grid_forget()
        self.listbox.grid_forget()
        self.markdownarea.config(height=30)

    def __markdownArea(self):
        self.markdownlabel = Label(text="Markdown")
        self.mdyScroll = Scrollbar(orient=VERTICAL)
        self.mdxScroll = Scrollbar(orient=HORIZONTAL)
        self.markdownarea = Text(wrap=WORD, height=10,
                                 yscrollcommand=self.mdyScroll.set,
                                 xscrollcommand=self.mdxScroll.set)
        self.copymarkdown = Button(text="Copy To Clipboard",
                                  command=self.__copyMarkdown)
        self.mdxScroll.config(command=self.markdownarea.xview)
        self.mdyScroll.config(command=self.markdownarea.yview)

    def __vidButtons(self):
        self.modtitle = Button(text='Modify titles', command=self.__modTitles)
        #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2,
        #                   padx=self.padx, pady=self.pady)
        self.getcaps = Button(text="Get captions", command=self.__getCaptions)
        self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmVidButtons(self):
        self.modtitle.grid_remove()
        self.getcaps.grid_remove()
        self.bind('<Return>', self.search_button)

    def __search(self):
        user = self.user_entry.get()
        playlist = self.playlist_id.get()
        searchterms = self.search_terms.get()
        self.__showResults()
        self.resultSelect.config(state=DISABLED)
        self.__rmVidButtons()
        self.__rmMarkdown()
        if not self.__validparams(user, searchterms, playlist):
            return False

        if len(playlist) > 0:
            self.__searchPlaylist(playlist)
            return

        self.__searchUser(user, searchterms)

    def __showMarkdown(self):
        self.markdownlabel.grid(row=5, column=0,
                                    padx=self.padx, pady=self.pady,
                                    sticky=W)
        self.markdownarea.grid(row=6, column=0, columnspan=5,
                               padx=self.padx, pady=self.pady,
                               sticky=N + S + E + W)
        self.mdyScroll.grid(row=6, column=5, sticky=N + S)
        self.mdxScroll.grid(row=7, column=0, sticky=E + W, columnspan=5)
        self.copymarkdown.grid(row=8, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmMarkdown(self):
        self.markdownarea.grid_forget()
        self.markdownlabel.grid_forget()
        self.copymarkdown.grid_forget()
        self.mdyScroll.grid_forget()
        self.mdxScroll.grid_forget()

    def __searchPlaylist(self, playlistid):
        self.__getvids(playlistid)

    def __searchUser(self, user, searchterms):
        self.listbox.delete(0, END)
        self.__status("Searching for%splaylists by user \"%s\"" % (
                      " \"%s\" " % searchterms if len(searchterms) else " ",
                      user))
        self.playlists = []
        try:
            self.playlists = lib.yt.search.PlaylistSearch(user=user,
                                                 search=searchterms).query()
        except HTTPError:
            self.__status("User %s does not exist at youtube" % user)
            return
        if self.playlists is None or len(self.playlists) == 0:
            self.__status("Search returned no results")
            return
        self.__populateResults([v['title'] for v in self.playlists])
        self.resultSelect.config(command=self.__getVidsFromSelected,
                                 state=NORMAL)
        self.__status("")
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)

    def __populateResults(self, values):
        self.listbox.delete(0, END)
        for i, val in enumerate(values):
            self.listbox.insert(i, val)
        self.listbox.activate(0)
        self.listbox.selection_set(0)

    def __getVidsFromSelected(self):
        selected = int(self.listbox.curselection()[0])
        self.__getvids(self.playlists[selected]['id'])

    def __getvids(self, playlistid):
        self.playlist_id.delete(0, END)
        self.playlist_id.insert(0, playlistid)
        self.resultSelect.grid_forget()
        title = playlistid
        if len(self.playlists) > 0:
            for playlist in self.playlists:
                if playlist['id'] == playlistid:
                    title = playlist['title']
                    break

        self.__status("Getting videos for %s" % title)
        self.listbox.delete(0, END)
        try:
            self.vids = lib.yt.search.PlaylistVideoSearch(
                                                    id=playlistid).query()
            self.__populateResults([v['title'] for v in self.vids])
            self.__status("%d Videos found" % len(self.vids))
            self.__vidButtons()
            self.bind('<Return>', self.getcaps)
        except HTTPError:
            self.__status("No videos found! is %s a valid playlist?" %
                          playlistid)

    def __status(self, msg):
        if len(msg) > 75:
            msg = msg[:70] + '...'
        self.status.config(text=msg)
        self.status.update_idletasks()

    def __trackSelect(self, vid, tracks, preftrack=None):
        pref = self.__prefAvailable(preftrack, tracks)
        if pref is None:
            sel = lib.trackSelect.TrackSelect(self, vid=vid,
                                              tracks=tracks)
            if sel.result is None:
                self.__status("skipped")
                tracks = None
            else:
                tracks = [sel.result[0]]
                if sel.preflang is not None:
                    preftrack['lang'] = sel.preflang
                if sel.prefname is not None:
                    preftrack['name'] = sel.prefname
        else:
            tracks = pref
        return tracks, preftrack

    def __getCaptions(self):
        preftrack = {'name': None, 'lang': None}
        self.listbox.delete(0, END)
        self.markdownarea.delete(1.0, END)
        self.__showMarkdown()
        for i, vid in enumerate(self.vids):
            nocapmsg = '[%02d] --NO CAPTIONS-- %s' % (i + 1, vid['title'])
            tracks = lib.yt.search.CaptionSearch(id=vid['id']).query()
            self.vids[i]['text'] = ''
            if len(tracks) == 0:
                self.__status('No captions available for %s' %
                              self.vids[i]['title'])
                self.listbox.insert(END, nocapmsg)

            elif len(tracks) > 1:
                sel = self.__trackSelect(vid, tracks, preftrack)
                if sel[0] is None:
                    msg = '[%02d] --SKIPPED-- %s' % (i + 1, vid['title'])
                    self.listbox.insert(END, msg)
                    self.listbox.see(END)
                    continue
                tracks = sel[0]

            if len(tracks) == 1:
                self.__trackCaps(i, tracks, nocapmsg)
        self.__status('')
        self.__hideResults()

    def __trackCaps(self, vidIndex, tracks, nocapmsg):
        i = vidIndex
        vid = self.vids[i]
        msg = '%02d of %02d Getting captions for %s' % (
                        i + 1, len(self.vids), self.vids[i]['title'])
        self.__status(msg)
        self.listbox.insert(END, msg)
        self.vids[i]['text'] = lib.markdown.heading(vid['title'])
        captions = lib.yt.search.GetCaptions(id=vid['id'],
                                lang=tracks[0]['lang'],
                                name=tracks[0]['name'])
        captions.query()
        captiontext = captions.textOnly()
        sleep(0.2)
        msg = nocapmsg
        if captiontext is not None and len(captiontext) > 0:
            self.vids[i]['text'] += (lib.markdown.to_utf8(captiontext)
                                     + '\n\n')
            msg = '[%02d] --DONE-- %s' % (i + 1, vid['title'])
        self.listbox.delete(END, END)
        self.listbox.insert(END, msg)
        self.listbox.see(END)
        self.markdownarea.insert(END, self.vids[i]['text'])
        self.markdownarea.see(END)

    def __prefAvailable(self, preftrack, tracks):
        if preftrack['lang'] is None:
            return None

        pref = None
        for track in tracks:
            if (track['lang'] == preftrack['lang'] and
                track['name'] == preftrack['name']):
                return [track]
            if track['lang'] == preftrack['lang'] and pref is None:
                pref = [track]

        return pref

    def __modTitles(self):
        pass

    def __validparams(self, user, searchterms, playlist):
        if len(user) == 0 and len(playlist) == 0:
            msg = "Either a valid youtube user or playlist id must be given."
            tkMessageBox.showwarning("missing information", msg)
            return False

        if len(user) > 0 and not self.__validstring(user):
            msg = "The user given contains invalid characters"
            tkMessageBox.showwarning('Bad user', msg)
            return False

        if len(playlist) > 0 and not self.__validstring(playlist):
            msg = "The playlist given contains invalid characters"
            tkMessageBox.showwarning('Bad playlist', msg)
            return False

        if len(searchterms) > 0 and not self.__validstring(searchterms, True):
            msg = "The search terms given contain invalid characters"
            tkMessageBox.showwarning('Bad search', msg)
            return False

        return True

    def __validstring(self, s, spacechar=False):
        validchars = string.letters + string.digits + string.punctuation
        if spacechar:
            validchars += ' '
        for c in s:
            if c not in validchars:
                return False
        return True

    def __copyMarkdown(self):
        self.markdownarea.clipboard_clear()
        self.markdownarea.clipboard_append(self.markdownarea.get(1.0, END))
示例#39
0
class QRReturnMainWindow(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.serial_num_internal = StringVar()
        self.master = master
        self.results = StringVar()
        self.__initUi()

    #===========================================================================
    # Initialize and reset GUI
    #===========================================================================
    def __initUi(self):
        self.master.title('Shine Production')
        self.pack(fill=BOTH, expand=1)

        Style().configure("TFrame", background="#333")

        #Status of Test frame
        self.status_frame = LabelFrame(self, text='Status', relief=RIDGE, width=800, height=500)
        self.status_frame.place(x=20, y=20)
        
        #QR SERIAL # Frame
        self.path_frame = LabelFrame(self, text='QR Serial Code', relief=RIDGE, height=60, width=235)
        self.path_frame.place(x=400, y=550)
        entry = Entry(self.path_frame, bd=5, textvariable=self.serial_num_internal)
        entry.place(x=50, y=5)

        #TEST RESULTS LABEL
        w = Label(self.status_frame, textvariable=self.results)
        w.place(x=50, y=50)

        #START Button
        self.start_button = Button(self, text="Start", command=self.start, height=4, width=20)
        self.start_button.place(x=100, y=550)

        # Initialize the DUT
        initDUT()

    def start(self):
        self.start_button.config(state=DISABLED)
        self.start_button.update()
        self.results.set("")
        self.__setStatusLabel(2)
        uiText = ""
        self.results.set(uiText)

        self.serial_num_internal.set("S123Z12345")
        serial_num_internal = "S123Z12345"
        # self.serial_num.set("FL11111111")
        # serial_num = "FL11111111"  
        print "Serial number (internal): %s" % serial_num_internal

        # Initialize the Agilent 34461
        instr = A34461(AGILENT_BASE_ADDRESS, AGILENT_SUB_ADDRESS)
        instr.setModeToCurrent()

        results = executeReturnTestSequence(self.serial_num_internal.get(), instr)

        # self.parseResults(results)
        self.__setStatusLabel(results)
        
        self.serial_num_internal.set("")
        self.start_button.config(state=ACTIVE)
        self.start_button.update()

    def parseResults(self, results):
        uiText = ''
        success = 1
        print results
        if results == -1:
            success = 3
            uiText += "Something wrong with connection to source meter."
        else:
            if results[SCAN_FAIL] == 1:
                success = 0
                uiText += "Couldn't find Shine \n"

            if results[CHECK_FW_FAIL] == 1:
                success = 0
                uiText += "Invalid firmware version. \n"
                
            if results[ACCEL_STREAM_FAIL] == 1:
                success = 0
                uiText += "Acceleromete data not correct. \n"

            if results[SN_DEFAULT_FAIL] == 1:
                success = 0
                uiText += "This serial # is 9876543210.\n"

            if results[SN_MISMATCH_FAIL] == 1:
                success = 0
                uiText += "Serial # scanned does not match internal (bt) serial #. \n"

            if results[TIMEOUT_FAIL] == 1:
                success = 0
                uiText += "Bluetooth connection timeout. \n"

            if results[AVG_CURRENT_FAIL] == 1:
                success = 0
                uiText += "Average operating current falls outside accepted range for this firmware. \n"

            if results[SN_DUPLICATE_FAIL] == 1:
                success = 0
                uiText += "This Shine is a duplicate serial number. \n"

            if results[RECENTLY_SYNCED_FAIL] == 1:
                success = 0
                uiText += "A Shine with this SN was synced in the past month. \n"

            if results[BATTERY_PLOT_FAIL] == 1:
                success = 0
                uiText += "Human determined battery plots failed."

            if success:
                uiText = "This Shine is in good condition!\n"

        self.results.set(uiText)
        self.__setStatusLabel(success)

    def __setStatusLabel(self, success):
        if success == 1:
            self.status_frame.config(text='SUCCESS', bg=STATUS_OK_COLOR)
        elif success == 2:
            self.status_frame.config(text='Status', bg='yellow')
        elif success == 3:
            self.status_frame.config(text='Something Wrong', bg='blue')
        else:
            self.status_frame.config(text='FAIL', bg=STATUS_ERROR_COLOR)
        self.update()
示例#40
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)
        self.mutex = Lock()

    def prepare(self):
        self.deviceList.config(state='normal')
        self.versionList.config(state='disabled')
        self.engList.config(state='disabled')
        self.packageList.config(state='disabled')
        self.ok.config(state='disabled')
        self.setData(self.controller.data)
        self.setDeviceList(self.data.keys())
        self.controller.setDefault(self, self.controller.loadOptions())
        self.deviceList.focus_force()

    def printErr(self, message):
        self.errLog.config(text=message)

    def setData(self, data):
        self.data = data

    def setupView(self, title="Select your flash", data=None):
        if(data):
            self.setData(data)
        self.errLog = Label(self, text="")
        self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE")
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self,
                         text='Next',
                         command=lambda: self.
                         confirm())
        self.ok.grid(row=4, column=3, sticky="E")
        self.ok.config(state="disabled")
        self.deviceLabel = Label(self, text="Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        self.deviceList.grid(row=2, column=0)
        self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect)
        self.deviceList.config(state="disabled")
        self.versionLabel = Label(self, text="Branch", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        self.versionList.grid(row=2, column=1)
        self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect)
        self.versionList.config(state="disabled")
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=2)
        self.engList = Listbox(self, exportselection=0)
        self.engList.grid(row=2, column=2)
        self.engList.bind('<<ListboxSelect>>', self.engOnSelect)
        self.engList.config(state="disabled")
        self.packageLabel = Label(
            self,
            text="Gecko/Gaia/Full",
            font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=3)
        self.packageList = Listbox(self, exportselection=0)
        self.packageList.grid(row=2, column=3)
        self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect)
        self.packageList.config(state="disabled")
        self.bidVar = StringVar()
        Label(self, text="Build ID").grid(row=3, column=0, sticky='E')
        self.bidInput = Entry(
            self,
            textvariable=self.bidVar,
            width="30")
        self.bidInput.grid(
            row=3,
            column=1,
            columnspan=2,
            sticky="W")
        self.bidVar.set('latest')
        # binding unfocus for build id field
        self.bidInput.bind('<FocusOut>', self.updateBuildId)
        # binding the Return Key to each componments
        self.deviceList.bind('<Return>', self.pressReturnKey)
        self.versionList.bind('<Return>', self.pressReturnKey)
        self.engList.bind('<Return>', self.pressReturnKey)
        self.packageList.bind('<Return>', self.pressReturnKey)
        self.bidInput.bind('<Return>', self.pressReturnKey)
        self.ok.bind('<Return>', self.pressReturnKey)

    def selection_all_checked(self):
        result = False
        if len(self.deviceList.curselection()) == 0:
            self.logger.log('Please select device.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.deviceList.focus_set()
        elif len(self.versionList.curselection()) == 0:
            self.logger.log('Please select branch.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.versionList.focus_set()
        elif len(self.engList.curselection()) == 0:
            self.logger.log('Please select user or engineer build.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.engList.focus_set()
        elif len(self.packageList.curselection()) == 0:
            self.logger.log('Please select package to flash.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.packageList.focus_set()
        elif len(self.bidVar.get()) == 0:
            self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr)
            self.bidVar.set('latest')
        else:
            result = True
        return result

    def updateBuildId(self, event=None):
        if len(self.engList.curselection()) != 0:
            self.refreshPackageList()

    def pressReturnKey(self, event=None):
        if self.selection_all_checked():
            self.ok.config(state="disabled")
            self.confirm()

    def deviceOnSelect(self, evt):
        self.setVersionList()

    def versionOnSelect(self, evt):
        self.setEngList()

    def engOnSelect(self, evt):
        self.refreshPackageList()  # hard coded right now

    def packageOnSelect(self, evt):
        self.ok.config(state="normal")

    def confirm(self):
        self.mutex.acquire()
        try:
            if self.selection_all_checked():
                self.ok.config(state="disabled")
                params = []
                package = self.packageList.get(self.packageList.curselection()[0])
                self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr)
                if(PathParser._IMAGES in package):
                    params.append(PathParser._IMAGES)
                else:
                    if(PathParser._GAIA in package):
                        params.append(PathParser._GAIA)
                    if(PathParser._GECKO in package):
                        params.append(PathParser._GECKO)
                self.controller.doFlash(params)
                self.packageList.select_clear(0, END)
                self.controller.transition(self)
        finally:
            self.mutex.release()

    def setDeviceList(self, device=[]):
        self.deviceList.delete(0, END)
        for li in device:
            self.deviceList.insert(END, li)

    def setVersionList(self, version=[]):
        if len(version) == 0:
            version = self.data[
                self.deviceList.get(self.deviceList.curselection())
                ]
        self.versionList.config(state="normal")
        self.engList.config(state="disabled")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.versionList.delete(0, END)
        for li in version:
            self.versionList.insert(END, li)

    def setEngList(self, eng=[]):
        if len(eng) == 0:
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.data[device][version]
        self.engList.config(state="normal")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.engList.delete(0, END)
        for li in eng:
            self.engList.insert(END, li)

    def refreshPackageList(self):
        self.mutex.acquire()
        try:
            self.packageList.config(state="normal")
            self.ok.config(state="normal")
            self.packageList.delete(0, END)
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.engList.get(self.engList.curselection())
            # if the value is '' or 'latest', the set the build_id option as ''.
            buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get()
            package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId)
            if len(package) == 0:
                package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES]
            for li in package:
                self.packageList.insert(END, li)
        finally:
            self.mutex.release()
示例#41
0
def run_a():
    """creates an analysis therad"""
    abortb.grid(row=20)
    plotb.grid_forget()
    run.grid_forget()
    progressbar.grid(row=21)
    global runpressed
    runpressed = True

    global latestThread
    latestThread = run_thread()
    latestThread.setDaemon(True)
    latestThread.start()


run.config(command=run_a)


#Function and button to plot results
def plotting():
    """shows plots on interface"""
    global listbuttons
    del listbuttons[:]
    if histograms == []:
        plots = glob.glob('Output/*.gif')
    else:
        plots = []
        for i in range(0, len(histograms)):
            name = imn.ImageDic[histograms[i]]
            plots.append(glob.glob('Output/' + name + '.gif'))
        plots = sum(plots, [])
示例#42
0
class Home(Frame):
    '''
    Frame for Home Screen.
    '''
    def __init__(self, master):
        Frame.__init__(self)
        self.pack()
        self.Name = 'Welcome ' + str(myname)
        self.label_1 = Label(self, text=self.Name, justify=Tkinter.LEFT)
        self.label_1.grid(row=0, pady=5)
        self.sync = Button(self, text="DLD Files", command=self.DLD)
        self.sync.grid(row=1, pady=5)
        self.pref = Button(self, text="Preferences", command=self.pref)
        self.pref.grid(row=3, pady=5)
        self.logout = Button(self, text="Logout", command=self.logout)
        self.logout.grid(row=4, pady=5)
        self.stop = Button(self, text="Stop DLD", command=self.stopDLD)
        self.stop.grid(row=2, pady=5)
        self.stop.config(state='disabled')

        #Download automatically on launch
        if auto_download is True:
            t.log(
                "Download automatically started. This can be disabled from preferences"
            )
            self.dld()

    def nfretrieve(self, url, directory, number):
        '''
        Retrieve from News Forum when passed nfurl i.e forum/view.php
        Passed arguments forum url, directory, course number (as appearing in Preferences)
        '''

        m.update()
        global t
        #array of all discussion urls
        self.urls = []
        #array of all downloadables
        self.nflinks = []
        global downloaded
        global downloadlinks

        br.open(url)

        #Read lines from Preferences. Obtain last visited discussion for course at index=number
        preferences = open("Preferences", "r")
        lines = preferences.readlines()
        lasturl = (lines[7 * number + 6])[:lines[7 * number + 6].index("\n")]
        preferences.close()

        #Set flag for checking if any new threads have been created since last run
        flag = 0

        #create an array of all discussion links (self.urls)
        #Newer threads come first in br.links()
        for link in br.links(
                url_regex="http://moodle.iitb.ac.in/mod/forum/discuss.php"):
            if link.url == lasturl:
                break
                #breaking loop once last visited discussion/thread is encountered
            if link.url not in self.urls:
                flag = 1
                self.urls.append(link.url)

        #iterating through every discussion
        for url in self.urls:
            m.update()

            br.open(url)

            #create an array of all downloadables
            for link in br.links(
                    url_regex="http://moodle.iitb.ac.in/pluginfile.php"):
                self.nflinks.append(link)

            #Download all downloadables
            for link in self.nflinks:
                if stop_DLD:
                    #Set flag 0 so that newlasturl is not updated, as all new threads may not be downloaded when force killed.
                    flag = 0
                    break
                else:
                    m.update()
                    br.open(link.url)
                    url_text = br.geturl()
                    if br.geturl().endswith('forcedownload=1'):
                        url_text = br.geturl()[:-16]
                    file_extension = '.' + url_text.rsplit('.', 1)[-1]
                    file_name = (url_text.rsplit('.', 1)[0]).rsplit('/', 1)[-1]
                    file_name = urllib.unquote_plus(file_name)
                    if file_name.endswith(file_extension):
                        file_name = file_name[:-len(file_extension)]
                    if file_extension in [
                            '.pdf', '.doc', '.ppt', '.pptx', '.docx', '.xls',
                            '.xlsx', '.cpp', '.h', '.html', '.py', '.css',
                            '.tex', '.java'
                    ]:
                        if not os.path.exists(directory + file_name +
                                              file_extension):
                            if not link.url in downloadlinks:
                                t.log('Downloading ' + file_name +
                                      file_extension + ' to ' + directory)
                                if not os.path.isdir(directory):
                                    os.makedirs(directory)
                                br.retrieve(
                                    link.url,
                                    directory + file_name + file_extension)
                                downloadlinks.append(link.url)

        #Find newlasturl (last visited disussion/thread)
        #(Order of threads is in reverse. i.e Newest first)
        if flag == 1:
            newlasturl = self.urls[0] + '\n'

            #Update Preferences with newlasturl
            lines[number * 7 + 6] = newlasturl
            preferences = open("Preferences", "w")
            preferences.writelines(lines)
            preferences.close()

    def retrieve(self, url, directory):
        '''
        Retrieve from course main page
        Arguments are main page url, directory
        '''

        m.update()
        global t
        global downloaded
        global downloadlinks
        self.links = []
        br.open(url)

        #Find all links inside given url and form array (self.links)
        for link in br.links(url_regex='.'):
            if (not link.url.startswith(
                    'http://moodle.iitb.ac.in/login/logout.php')
                    and not link.url.startswith(br.geturl())
                    and not link.url.startswith('#')
                    and not link.url.startswith(
                        'http://moodle.iitb.ac.in/mod/forum')
                    and not link.url.startswith('http://moodle.iitb.ac.in/my')
                    and
                    not link.url.startswith('http://moodle.iitb.ac.in/user')
                    and
                    not link.url.startswith('http://moodle.iitb.ac.in/badges')
                    and not link.url.startswith(
                        'http://moodle.iitb.ac.in/calendar') and
                    not link.url.startswith('http://moodle.iitb.ac.in/grade')
                    and
                    not link.url.startswith('http://moodle.iitb.ac.in/message')
                    and link.url not in downloaded):
                self.links.append(link)

        #Downlod all downloadables from self.links
        for link in self.links:
            if stop_DLD:
                break
            else:
                m.update()
                br.open(link.url)
                url_text = br.geturl()
                if br.geturl().endswith('forcedownload=1'):
                    url_text = br.geturl()[:-16]
                file_extension = '.' + url_text.rsplit('.', 1)[-1]
                if file_extension in [
                        '.pdf', '.doc', '.ppt', '.pptx', '.docx', '.xls',
                        '.xlsx', '.cpp', '.h', '.html', '.py', '.css', '.tex',
                        '.java'
                ]:

                    file_name = ""
                    if ']' in link.text:
                        file_name = link.text[link.text.index(']') + 1:]
                    else:
                        file_name = link.text

                    if file_name.endswith(file_extension):
                        file_name = file_name[:-len(file_extension)]

                    if not os.path.exists(directory + file_name +
                                          file_extension):
                        if not link.url in downloadlinks:
                            t.log('Downloading ' + file_name + file_extension +
                                  ' to ' + directory)
                            if not os.path.isdir(directory):
                                os.makedirs(directory)
                            br.retrieve(link.url,
                                        directory + file_name + file_extension)
                            downloadlinks.append(link.url)
                else:
                    #Retrieve from folders
                    if (br.geturl().startswith(
                            'http://moodle.iitb.ac.in/mod/folder')
                            and link.url not in downloaded
                            and link.text.startswith('[IMG]')):
                        foldername = br.title()[br.title().index(':') + 2:]
                        newpath = directory + foldername
                        if not os.path.exists(newpath):
                            os.makedirs(newpath)
                        t.log('Retrieving from ' + foldername + ' at ' +
                              newpath)
                        downloaded.append(link.url)
                        self.retrieve(link.url, newpath + '/')

                    #Retrieve Assignments
                    if br.geturl().startswith('http://moodle.iitb.ac.in/mod/assign') \
                                                and link.url not in downloaded:
                        downloaded.append(link.url)
                        if directory.endswith("Assignments/"):
                            newpath = directory[:-1]
                        else:
                            newpath = directory + "Assignments"
                        if not os.path.exists(newpath):
                            os.makedirs(newpath)
                        self.retrieve(link.url, newpath + '/')

            #br.back()
            self.pack()

    def stopDLD(self):
        '''
        On click of Stop DLD button
        '''

        global t, stop_DLD
        t.log('Terminating downloads.')
        stop_DLD = True

    def DLD(self):
        '''
        On click of DLD Files button
        '''

        global t, stop_DLD
        t.log('Downloading files, Please do not close until complete!')
        self.sync.config(state='disabled')
        self.pref.config(state='disabled')
        self.logout.config(state='disabled')
        self.stop.config(state='normal')
        urls = []
        nfurls = []
        directories = []
        stop_DLD = False

        #Open Preferences and call retrieve functions
        if os.path.exists('Preferences'):
            file_pref = open('Preferences', 'r')
            lines = file_pref.readlines()
            n = len(lines) / 7
            if len(lines):
                for number in range(n):
                    if stop_DLD:
                        break
                    else:
                        urls.append(lines[7 * number +
                                          2][:lines[7 * number +
                                                    2].index('\n')])
                        directories.append(lines[7 * number +
                                                 3][:lines[7 * number +
                                                           3].index('\n')])
                        nfurls.append(lines[7 * number +
                                            4][:lines[7 * number +
                                                      4].index("\n")])
                        if (lines[7 *
                                  number])[:lines[7 *
                                                  number].index('\n')] == '1':
                            t.log('Retrieving from ' +
                                  lines[7 * number +
                                        1][:lines[7 * number +
                                                  1].index('\n')] + ' at ' +
                                  directories[number])
                            self.retrieve(urls[number], directories[number])
                            t.log("Retrieving from " +
                                  lines[7 * number +
                                        1][:lines[7 * number +
                                                  1].index("\n")] +
                                  " News Forum at " + directories[number] +
                                  'News Forum/')
                            self.nfretrieve(
                                nfurls[number],
                                directories[number] + 'News Forum/', number)
            t.log("Successfully synced with Moodle!")
            self.sync.config(state='normal')
            self.pref.config(state='normal')
            self.logout.config(state='normal')
            self.stop.config(state='disabled')

            #If Preferences does not exist take user to Preferences screen
        else:
            t.log('Please set Preferences first!')
            self.sync.config(state='normal')
            self.pref.config(state='normal')
            self.logout.config(state='normal')
            self.destroy()
            self.newWindow = Pref_Screen(self.master)

    def pref(self):
        '''
        On Click Preferences button
        '''

        t.log(
            "Populating list of courses. This may take a while. Please be patient.."
        )
        m.update()
        self.destroy()
        self.newWindow = Pref_Screen(self.master)

    def logout(self):
        '''
        On Click Logout button
        '''
        lines = ["\n", "\n", "\n", "C:/", "\n", "1", "\n"]
        if os.path.exists("Cred"):
            file_cred = open('Cred', 'r')
            lines = file_cred.readlines()
            file_cred.close()

            lines[0] = '\n'
            lines[1] = '\n'
            lines[2] = '\n'

        file_cred = open('Cred', 'w')
        file_cred.writelines(lines)
        file_cred.close()
        t.log('Logout successful!')
        br.close()
        self.destroy()
        self.newWindow = LoginFrame(self.master)
示例#43
0
    def refreshWidget(self):
        #print "refresh"
        self.card_win.pack_forget()

        #Card window
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)

        #Create the name zone
        name_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar()
        name.set(self.name)
        from deck_creation import blocked_creature

        def modifName(*args):
            old = self.name in blocked_creature
            self.name = name.get()
            if old or self.name in blocked_creature:
                self.refreshWidget()

        name.trace("w", modifName)
        name_wid = Entry(name_zone, width=30, textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost = StringVar()
        self.stars = StringVar()
        cost_wid = Label(None,
                         textvariable=self.cost,
                         background='red',
                         width=5,
                         anchor=W)
        star_wid = Label(None,
                         textvariable=self.stars,
                         background='blue',
                         anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*" * self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)

        #Create an Image Zone
        image_zone = Button(self.card_win, command=self.choosePhoto)
        if hasattr(self, "photofile") and self.photofile:
            print "Image: ", self.photofile
            try:
                img = Image.open(self.photofile)
            except:
                decomp = self.photofile.split('/')
                for i in range(1, 6):
                    try:
                        fname = "/".join(decomp[-i:])
                        print "try to open", fname
                        img = Image.open(fname)
                        self.photofile = fname
                        break
                    except:
                        self.photofile = None
        if self.photofile:
            w, h = img.size
            if w > 300 or h > 200:
                img = img.resize((w / 2, h / 2), Image.LINEAR)
            image_zone.image = ImageTk.PhotoImage(img)
            image_zone.config(image=image_zone.image)
            #print "IMAGE CHANGED"
        else:
            from os import path
            fname = self.name.replace(" ", "_")
            if path.isfile("Cards/" + fname + ".png"):
                image_zone.config(text='image can be taken from\n' + "Cards/" +
                                  fname + ".png",
                                  background='white',
                                  anchor=CENTER)
            else:
                image_zone.config(text='clic to choose image',
                                  background='white',
                                  anchor=CENTER)

        image_zone.pack

        # POWER ZONE
        power_zone = PanedWindow(self.card_win, orient=VERTICAL)

        #fenetre=self.card_win.master
        def removePowerCreator(px):
            def removePower(*args):
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()

            return removePower

        for p in self.bonus:
            powline = PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid = p.initWidget(powline)
            powline.add(pow_wid)
            removepow = Button(powline,
                               text="X",
                               command=removePowerCreator(p),
                               anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline)

        def addPower(*args):
            name = addBonus.get()
            print "added :", name
            import cardPowers
            self.bonus += [eval('cardPowers.' + name + '()')]
            self.bonus[-1].parent = self.bonus
            self.bonus[-1].card = self
            #self.card_win.pack_forget()
            self.refreshWidget()

        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus")  # default value
        if not self.pv: addBonus_wid = getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus)
        addBonus.trace('w', addPower)
        if self.pv > 0 or len(self.bonus) == 0:
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)

        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        lv = int(localopen("progression", "r").read())
        if self.monster_type != "all" and not (lv < 8 and self.name
                                               in blocked_creature):
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        elif self.monster_type != "all":
            save_wid = Button(save_zone,
                              text="creature in campaign",
                              command=None)
        else:
            save_wid = Button(save_zone, text="nead type", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = Card.monster_list.keys()
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening, *choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)

        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = Card.monster_list.keys()
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete, *choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)

        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [
            file2name(t, "_monsters.sav")
            for t in glob.glob("CardFiles/*_monsters.sav")
        ]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category, *choice)
        self.category.trace('w', self.setFile)

        category_wid.pack()

        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)

        #Create a new Strength zone for att and pv
        strength_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        att = StringVar()
        att.set(str(self.att))
        pv = StringVar()
        pv.set(str(self.pv))

        def modifiedAttPv(*args):
            print "modifiedAttPv"
            self.pv = int(pv.get())
            if self.pv < 1 and self.is_spell == False:
                if len(self.bonus) == 0:
                    self.is_spell = True
                    self.refreshWidget()
                else:
                    self.pv = 1
                    self.refreshWidget()
            if self.pv > 0 and self.is_spell == True:
                if len(self.bonus) == 0:
                    self.is_spell = False
                    self.refreshWidget()
                else:
                    self.pv = 0
                    self.refreshWidget()
            self.att = int(att.get())
            self.getCost()

        att_wid = Spinbox(strength_zone,
                          from_=0,
                          to=1000,
                          textvariable=att,
                          command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(
            Label(strength_zone,
                  text='       ',
                  background='white',
                  anchor=CENTER))
        pv_wid = Spinbox(strength_zone,
                         from_=0,
                         to=1000,
                         textvariable=pv,
                         command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)

        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)

        self.card_win.pack()
示例#44
0
class Script_GUI(Frame):
    ''' Script creation graphical user interface.
        Since this page was crowding the main
        in order to neat
        this is a better place for it
    '''
    def __init__(self, master=None, **options):

        #if not master and options.get('parent'):
        #    master = options['parent']
        self.master = master
        Frame.__init__(self, master)

        # Just as an extension
        self._convertdata_ = self.master._convertdata_
        self.im_gear = self.master.im_gear

        self._container_ = self.master._script_

    def createWidgets(self):
        'create the script gui'

        #    first header row
        row = Frame(self)
        TEXT1 = "\nIn this section you can create scripts "
        Label(row, text=TEXT1, anchor='w').pack(side='top', padx=2, pady=1)
        row.pack(side='top', fill='x', padx=5)
        bottom_hline_deco(self)

        bottom_hline_deco(self, self.create_main_section)

        self.build_finalbuttons()

    def createWidgets_n_pack(self):
        self.createWidgets()
        self.pack()

    def create_main_section(self):
        '''Section for main input values    '''
        #=====================================================================
        '''  Create script section '''
        row2fill = Frame(self)
        row2fill_l = Frame(row2fill)
        self.s_entry_c = []
        _mainpage_ = self._container_['mainpage']
        _defvals_ = [
            '0.5', '1000', '1000', '300:293', '100', '1000', '-1:1', '1000',
            '293:300', '100'
        ]
        _def_dataname_ = './data.gro2lam'
        if _mainpage_ <> []:
            _def_dataname_ = _mainpage_[0]
            _defvals_ = _mainpage_[1:]

        _aux_c_ = [row2fill_l, 'Lammps data file to work', _def_dataname_]
        self.s_entry_c.append(self.master.createfileentry(*_aux_c_))

        _entries_ = [
            'Timestep [fs]', '-', 'NVE steps  [#ts]', '-', 'NVT steps  [#ts]',
            'Temperature at start:end [K]', 'Temperature damping [fs]', '-',
            'NPT steps  [#ts]', 'Presure at start:end  [atm]',
            'Presure damping [fs]', 'Temperature at start:end [K]',
            'Temperature damping [fs]'
        ]

        entr_maxlen = int(len(max(_entries_, key=len)) * 2.5 / 3)
        c = 0
        for e in range(len(_entries_)):
            if _entries_[e] == '-':
                bottom_hline_deco(row2fill_l)
                c += 1
            else:
                self.s_entry_c.append(
                    create_entry(row2fill_l, _entries_[e], _defvals_[e - c],
                                 entr_maxlen))
        row2fill_l.pack(side="left")
        # ====================
        row2fill.pack(side="top", padx=1, pady=5)

    def build_finalbuttons(self):
        '''    Final Buttons    '''
        row = Frame(self)
        ########          ADVANCED OPTIONS #################

        if self._container_['advanced'] == []:  # advanced _init_

            self._container_['advanced'] = [[], []]
            self._container_['advanced'][0] = [
                '10', 'array', 'lj/cut/coul/long', '8.5', '10', '1.9', 'pppm',
                '1e-4', '0.0:0.0:0.0', '1', '1', 'aniso', 'No',
                'NVE-NVT-NPT-NVT-R', '300'
            ]

        self.fcb = Button(row,
                          text='Advanced settings',
                          compound='left',
                          image=self.im_gear,
                          bg='gray86',
                          height=15,
                          width=145,
                          command=self.further_config_script)
        self.fcb.pack(side='left', padx=10, pady=0)

        ######           RESTRAIN GROUP         ##############

        self.resb = Button(row, text='Restrain', command=self.config_restrain)
        self.resb.pack(side='left', padx=10, pady=0)

        self.b1 = Button(
            row,
            text='Create',  # height=8,
            command=self.write_script)
        self.b1.pack(side='right', padx=2, pady=4)

        b2 = Button(row, text='Quit', command=self.quit)
        b2.pack(side='right', padx=20, pady=4)
        row.pack(side='top', fill='both', padx=5)

    def write_script(self):

        print 'Writing the lammps script'
        _mainpage_ = get_entriesvalue(self.s_entry_c)

        _flag_ = True  # data ok flag

        _entries_ = [
            'float', 'int', 'int', 'float:', 'float', 'int', 'float:', 'float',
            'float:', 'float'
        ]
        _flag_ *= self.check_datafile(bool)
        _flag_ *= min(check_vars(_mainpage_[1:], _entries_))

        if _flag_:
            self._container_['mainpage'] = _mainpage_
            _script_setup_ = [
                _mainpage_, self._container_['advanced'][0],
                self._container_['restrain']
            ]
            self.master._script_ = self._container_

            _flag_ = write_lammps_input(_script_setup_, self._convertdata_)

            if _flag_:
                print_dec_g('Lammps script done!')
                self.master.swapbody(3)

    def further_config_script(self):

        defvals = []
        title_txt = ' ' * 3 + '+ Simulation Parameters'
        instructions = 'Input further simulation parameters'
        askfor = [
            'Thermo output every  [#ts]',
            'Atom mapping',
            'Pairwise interactions',
            "L-J/Buck rcutoff  [" + u'\u00c5' + "]",
            "Coulomb rcutoff  [" + u'\u00c5' + "]",
            "Neighbor skin distance  [" + u'\u00c5' + "]",
            'Long-range solver',
            'Long-range relative error',
            'Interaction 1-2:1-3:1-4',
            'Neighbor delay  [#ts]',
            'Neighbor update  [#ts]',
            'Pressure control',
            'Force mixing rule',
            'Simulation order',
            'Velocity creation Temp  [K]',
        ]

        _pair_style_ = [
            'lj/cut/coul/long',
            'lj/cut/coul/cut',
            'lj/cut',
            'buck/coul/long',
            'buck',
            'buck/coul/cut',
            #'lj/cut/tip4p/cut', 'lj/cut/tip4p/long',
            #'lj/gromacs', 'lj/gromacs/coul/gromacs',
            'zero',
            'none'
        ]

        if self._convertdata_ <> None:
            buckorlj = int(self._convertdata_['defaults'][0])
            if buckorlj == 1:
                _pair_style_ = _pair_style_[:3] + _pair_style_[-2:]
            else:
                _pair_style_ = _pair_style_[3:]
                self._container_['advanced'][0][2] = _pair_style_[3]

        _kspace_ = [
            'pppm',
            'pppm/cg',
            'ewald',
            'pppm/disp',
            'ewald/disp',
            #'pppm/tip4p', 'pppm/disp/tip4p'
        ]

        _comb_rule_ = ['No', 'geometric', 'arithmetic', 'sixthpower']

        self._container_['advanced'][1] = [
            '', ['array', 'hash'], _pair_style_, '', '', '', _kspace_, '', '',
            '', '', ['aniso', 'iso', 'tri'], _comb_rule_, '', ''
        ]
        _defvals_ = []

        for _ad_ in range(len(self._container_['advanced'][0])):
            if self._container_['advanced'][1][_ad_] <> '':
                _def_ = self._container_['advanced'][0][_ad_]
                _dfli_ = self._container_['advanced'][1][_ad_]
                _defvals_.append([_def_, _dfli_])
            else:
                _defvals_.append(self._container_['advanced'][0][_ad_])

        self.fcb.config(bg='gray70')  #, width = 155) #cyan')
        self.master._aux_ = []
        pop = PromptPopUp(master=self.master,
                          title=title_txt,
                          briefing=instructions,
                          entries_txt=askfor,
                          entries_val=_defvals_,
                          width=400,
                          height=565)

        pop.wait_window()

        if self.master._aux_ <> []:
            _advanced_ = self.master._aux_

            _entries_ = [
                'int', '', '', 'float', 'float', 'float', '', 'float',
                'float::', 'int', 'int', '', '',
                [list, '-', 'NVE', 'NVT', 'NPT', 'R'], 'float'
            ]
            _flag_ = min(
                check_vars(_advanced_, _entries_,
                           'Advanced settings not saved!'))
            if _flag_:
                self._container_['advanced'][0] = _advanced_
                print_dec_g('Advanced settings saved')
        self.fcb.config(bg='gray86')  #, width = 145)

    def config_restrain(self):

        title_txt = ' ' * 28 + '+ Restrain Goups'
        instructions = 'Select the group to restrain'

        #============ grouping  ================
        max_index = self.check_datafile()

        if max_index:

            _defvals_ = self._container_['restrain']
            if _defvals_ == []:

                g_names = ['all_group']
                d_ids = ['{}:{}'.format(1, max_index)]
                kxyz_c = ['1:xyz']
                rest_ens = ['1-2']  #restrained_ensembles
                ck_init = [0]
                second_c = None

                if self._convertdata_ <> None:
                    _mol_niifi_ = self._convertdata_['atomsdata'][1]
                    for mt in range(len(_mol_niifi_)):
                        g_names.append(_mol_niifi_[mt][0])
                        d_ids.append('{}:{}'.format(*_mol_niifi_[mt][1:]))
                        kxyz_c += ['1:xyz']
                        rest_ens += ['1-2']
                        ck_init += [0]

            else:
                g_names, d_ids, kxyz_c, rest_ens, ck_init = _defvals_[0]
                #print g_names,'\n', d_ids,'\n', kxyz_c,'\n', ck_init
                if _defvals_[1] <> None:
                    second_c = _defvals_[1]
                else:
                    second_c = None

            self.resb.config(bg='gray70')  #, width = 45) #cyan')
            self.master._aux_ = []

            pop = PromptPopUp_wck(
                master=self.master,
                title=title_txt,
                briefing=instructions,
                entries_txt=g_names,
                entries_val=kxyz_c,
                width=530,
                #height = 365,
                range_id=d_ids,
                res_ens=rest_ens,
                chck_init=ck_init,
                extra_but=second_c,
            )

            pop.wait_window()

            if self.master._aux_ <> []:
                sim_len = 0
                for x in self._container_['advanced'][0][-2].split('-'):
                    if x.strip(' ') <> 'R':
                        sim_len += 1
                _res_flag_ = [[], []]
                _restrain_ = self.master._aux_[:]
                _, _d_ids, _kxyz_c, _runs_c, _res_flag_[0] = _restrain_[0]

                if _restrain_[1] <> None:
                    _, au2, au3, au4, au5 = _restrain_[1][:]
                    _restrain_aux = _d_ids + au2 + _kxyz_c + au3 + _runs_c + au4
                    _res_flag_[1] = au5
                else:
                    _restrain_aux = _d_ids + _kxyz_c + _runs_c
                _multi_ = len(_restrain_aux) / 3
                _entries_ = ([['<int:int<', 1, max_index]] * _multi_ +
                             ['float:xyz'] * _multi_ +
                             [['<int-x-int<:0', 1, sim_len]] * _multi_)

                _aux_ = check_vars(_restrain_aux, _entries_,
                                   'Restrain groups not saved!')
                #print _aux_
                _flag_ = min(_aux_)
                if _flag_:

                    if max(max(_res_flag_)):
                        self._container_['restrain'] = _restrain_
                        print_dec_g('Restrain data saved')
                    else:
                        print('Creating 0 groups, Restraining 0 atoms')
            self.resb.config(bg='gray86')  #, width = 45)

    def check_datafile(self, _bflag_=None):
        ''' function to get the max atom number 
            also is used in case of no gromacs direct data conversion
            to somehow make a check if that file is ok
        '''
        max_index = 0
        _flag_ = True
        if self._convertdata_ <> None:
            max_index = len(self._convertdata_['atomsdata'][0])
        else:
            _filename_ = self.s_entry_c[0].get()
            try:
                with open(_filename_, 'r') as indata:
                    for k_line in indata:
                        if not k_line.startswith('#'):
                            line_c = k_line.split()
                            if 'atoms' in line_c:
                                max_index = line_c[0]
                                break
            except IOError:
                pop_wrg_1('Data file not found!')
                print('Try performing a conversion first!')
                _flag_ = False

        if _bflag_ <> None:
            return _flag_
        return max_index
示例#45
0
class App:
    def __init__(self, master):
        self.master = master
        column0_padx = 24
        row_pady = 40
        self.imgck = IntVar()
        self.latck = IntVar()
        self.lonck = IntVar()
        self.timeck = IntVar()
        self.dateck = IntVar()
        self.datestate = int()
        self.imgval = StringVar()
        self.latval = StringVar()
        self.lonval = StringVar()
        self.timeval = StringVar()
        self.dateval = StringVar()
        self.headerVal = IntVar()
        self.rbv = IntVar()
        vcmd = (master.register(self.validate), '%d', '%i', '%P', '%s', '%S',
                '%v', '%V', '%W')

        self.entryExif = Entry(master, relief="sunken")
        self.entryExif.insert(0, "EXIF csv file")
        self.entryExif.grid(row=0, columnspan=4, sticky='EW', padx=5, pady=10)
        exifbtn = Button(master,
                         text="OPEN CSV file",
                         command=self.getEXIFfile)
        exifbtn.grid(row=1, column=0, padx=5, sticky='w')

        ##added to allow header line
        self.headerOpt = Checkbutton(master,
                                     text="Select if CSV file has header line",
                                     variable=self.headerVal)
        self.headerOpt.grid(row=2, column=0, padx=5, sticky='w')

        self.entryJPGS = Entry(master, relief="sunken")
        self.entryJPGS.insert(0, "JPEG folder")
        self.entryJPGS.grid(row=3, columnspan=4, sticky='EW', padx=5, pady=10)
        JPGbtn = Button(master,
                        text="OPEN JPEG folder",
                        command=self.getJPEGFolder)
        JPGbtn.grid(row=4, column=0, padx=5, sticky='w')

        self.paramFile = Entry(master, relief="sunken")
        self.paramFile.insert(0, "Param file")
        self.paramFile.grid(row=5, columnspan=4, sticky='EW', padx=5, pady=10)
        parambtn = Button(master,
                          text="OPEN PARAM file",
                          command=self.getParamfile)
        parambtn.grid(row=6, column=0, padx=5, sticky='w')

        lbl_exiftag = Label(master,
                            text="EXIF tag",
                            wraplength=100,
                            anchor='w',
                            justify='left')
        lbl_column = Label(master,
                           text="CSV column (zero based)",
                           wraplength=100,
                           anchor='w',
                           justify='left')
        cbImage = Checkbutton(master,
                              text='Image name',
                              variable=self.imgck,
                              command=self.imgcheck)
        cbLatitude = Checkbutton(master,
                                 text='Latitude',
                                 variable=self.latck,
                                 command=self.latcheck)
        cbLongitude = Checkbutton(master,
                                  text='Longitude',
                                  variable=self.lonck,
                                  command=self.loncheck)
        cbTime = Checkbutton(master,
                             text='GPSTime',
                             variable=self.timeck,
                             command=self.timecheck)
        cbDate = Checkbutton(master,
                             text='GPSDate',
                             variable=self.dateck,
                             command=self.datecheck)
        lblText = Label(master, text="Free text fields:")
        lblArtist = Label(master, text="Artist:")

        ##        lbl_analysis = Label(master, text="Analysis Library")
        self.entryImage = Entry(master,
                                validate='key',
                                validatecommand=vcmd,
                                width=5,
                                state='disabled')
        self.entryLat = Entry(master,
                              validate='key',
                              validatecommand=vcmd,
                              width=5,
                              state='disabled')
        self.entryLon = Entry(master,
                              validate='key',
                              validatecommand=vcmd,
                              width=5,
                              state='disabled')
        self.entryTime = Entry(master,
                               validate='key',
                               validatecommand=vcmd,
                               width=5,
                               state='disabled')
        self.entryDate = Entry(master,
                               validate='key',
                               validatecommand=vcmd,
                               width=5,
                               state='disabled')
        self.entryArtist = Entry(master, width=40)

        #lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w')
        lbl_exiftag.grid(row=7, column=0, padx=20, pady=12, sticky='w')
        lbl_column.grid(row=7, column=1, padx=10, pady=12, sticky='w')
        cbImage.grid(row=8, column=0, padx=20, sticky='w')
        cbLatitude.grid(row=9, column=0, padx=20, sticky='w')
        cbLongitude.grid(row=10, column=0, padx=20, sticky='w')
        cbTime.grid(row=11, column=0, padx=20, sticky='w')
        cbDate.grid(row=12, column=0, padx=20, sticky='w')
        lblText.grid(row=13, column=0, padx=30, sticky='w')
        lblArtist.grid(row=14, column=0, padx=20, sticky='w')
        self.entryImage.grid(row=8, column=1, padx=10, sticky='w')
        self.entryLat.grid(row=9, column=1, padx=10, sticky='w')
        self.entryLon.grid(row=10, column=1, padx=10, sticky='w')
        self.entryTime.grid(row=11, column=1, padx=10, sticky='w')
        self.entryDate.grid(row=12, column=1, padx=10, sticky='w')
        lbl_datefmt = Label(master,
                            text="Select date format:",
                            wraplength=500,
                            anchor='w',
                            justify='left')
        lbl_datefmt.grid(row=12, column=1, padx=50, sticky='w')
        self.entryArtist.grid(row=14, column=1, padx=10, sticky='w')
        ##        ##added to allow header line
        ##        self.dateOpt1 = Checkbutton(master, text="YYYYMMDD", variable=self.headerVal)
        ##        self.dateOpt1.grid(row=10, column=1, padx=160, sticky='w')
        ##        self.dateOpt2 = Checkbutton(master, text="YYYY:MM:DD", variable=self.headerVal)
        ##        self.dateOpt2.grid(row=10, column=1, padx=260, sticky='w')
        ##        self.dateOpt3 = Checkbutton(master, text="MM/DD/YYYY", variable=self.headerVal)
        ##        self.dateOpt3.grid(row=10, column=1, padx=360, sticky='w')

        #try radio buttons
        Radiobutton(master,
                    text="YYYYMMDD",
                    variable=self.rbv,
                    value=1,
                    command=self.rdioInvoke).grid(row=10,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="YYYY:MM:DD",
                    variable=self.rbv,
                    value=2,
                    command=self.rdioInvoke).grid(row=11,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="MM/DD/YYYY",
                    variable=self.rbv,
                    value=3,
                    command=self.rdioInvoke).grid(row=12,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="MM/DD/YY",
                    variable=self.rbv,
                    value=4,
                    command=self.rdioInvoke).grid(row=13,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')

        # buttons
        bottom_frame = Frame(master)
        bottom_frame.grid(row=30, column=1, columnspan=3, sticky='w')

        #I had to add the self to the prefix, otherwise my rdioInvoke wouldn't work.
        #I'm guessing the self is sort of the global aspect.
        #temporarily commenting this out so I can just test reading the param file
        self.btn_start = Button(bottom_frame,
                                text="Submit",
                                width=7,
                                command=self.MergeExif)
        #self.btn_start = Button(bottom_frame, text = "Submit", width=7, command=self.readParamfile)
        self.btn_start.pack(side='left', pady=20)
        self.btn_start.config(state='disabled')
        ##        btn_commit = Button(bottom_frame, text="Commit", width=7)
        ##        btn_commit.pack(side='left', padx=80)
        btn_exit = Button(bottom_frame,
                          text="Exit",
                          width=7,
                          command=self.cbtnClick)
        btn_exit.pack(side='left', padx=10)

    def rdioInvoke(self):
        print "rdioInvoke"
        self.btn_start.configure(state='normal')

    def cbtnClick(self):
        print "close button event handler"
        self.master.destroy()

    def imgcheck(self):
        print "check"
        if self.imgck.get() == 0:
            self.entryImage.configure(state='disabled')
        else:
            self.entryImage.configure(state='normal')

    def latcheck(self):
        print "check"
        if self.latck.get() == 0:
            self.entryLat.configure(state='disabled')
        else:
            self.entryLat.configure(state='normal')

    def loncheck(self):
        print "check"
        if self.lonck.get() == 0:
            self.entryLon.configure(state='disabled')
        else:
            self.entryLon.configure(state='normal')

    def timecheck(self):
        print "check"
        if self.timeck.get() == 0:
            self.entryTime.configure(state='disabled')
        else:
            self.entryTime.configure(state='normal')

    def datecheck(self):
        print "check"
        if self.dateck.get() == 0:
            self.entryDate.configure(state='disabled')
        else:
            self.entryDate.configure(state='normal')
            #self.datestate == 1
    def validate(self, action, index, value_if_allowed, prior_value, text,
                 validation_type, trigger_type, widget_name):
        if text in '0123456789':
            return True
        else:
            return False

    def getEXIFfile(self):
        EXIFcsvfile = tkFileDialog.askopenfilename(title='Image EXIF CSV file')
        #need to fix the next line
        self.entryExif.delete(0, END)
        if len(EXIFcsvfile) > 0:
            self.entryExif.insert(0, EXIFcsvfile)

    def getJPEGFolder(self):
        #by not specifying an intial directory, it starts where the script is located.
        JPGfolder = tkFileDialog.askdirectory(title='Pick JPEG folder')
        #need to clear anything that's there
        self.entryJPGS.delete(0, END)
        if len(JPGfolder) > 0:
            #print "now read JPEG folder %s" % JPGfolder
            #for entry widget
            self.entryJPGS.insert(0, JPGfolder)

    def getParamfile(self):
        PARAMtxtfile = tkFileDialog.askopenfilename(title='Paramter text file')
        self.paramFile.delete(0, END)
        if len(PARAMtxtfile) > 0:
            self.paramFile.insert(0, PARAMtxtfile)

    def readParamfile(self):
        params = self.paramFile.get()
        inputparams = open(params, "r")
        allparams = inputparams.read()
        for cmd3 in allparams.splitlines():
            if "-comment" in cmd3:
                ##                print cmd3
                ##                print " "
                val3 = cmd3
        for cmd4 in allparams.splitlines():
            if "-sep" in cmd4:
                ##                print cmd4
                ##                print " "
                #return cmd4
                val4 = cmd4

        for cmd6 in allparams.splitlines():
            if "-Caption=" in cmd6:
                ##                print cmd6
                ##                print " "
                #return cmd6
                val6 = cmd6

        for cmd9 in allparams.splitlines():
            if "-Caption-Abstract" in cmd9:
                ##                print cmd9
                ##                print " "
                #return cmd9
                val9 = cmd9

        for cmd10 in allparams.splitlines():
            if "-ImageDescription=" in cmd10:
                ##                print cmd10
                ##                print " "
                #return cmd10
                val10 = cmd10
##        print "read params"
##        print "val3"
##        print val3
        return (val3, val4, val6, val9, val10)

        #self.MergeExif()

    def MergeExif(self):
        try:
            test = self.entryExif.get()
            print test

            ##            print "date format"
            ##            print str(self.rbv.get())
            inputfile = open(test, "r")
            #print "made it here 1"
            imgval = int(self.entryImage.get())
            #print self.entryImage.get()
            #print str(imgval)
            if self.latck.get() <> 0:
                latval = int(self.entryLat.get())
            #print "made it here 1a"
            if self.lonck.get() <> 0:
                lonval = int(self.entryLon.get())
            print "made it here 1b"
            if self.timeck.get() <> 0:
                timeval = int(self.entryTime.get())
            print "made it here 1c"
            if self.dateck.get() <> 0:
                dateval = int(self.entryDate.get())
                print "got date"
                print str(dateval)
            print "made it here 2"
            ##add this if statement to deal with header value
            if self.headerVal.get() == 1:
                print "have a header value"
                line = inputfile.readline()
            else:
                print "no header value"
            print "getting return"
            ##            retcmd3, retcmd4, retcmd6, retcmd9, retcmd10 = self.readParamfile()
            ##            print "just cmd3"
            ##            print retcmd3
            allreturns = self.readParamfile()
            print "allreturns"
            print allreturns
            ##            print "first return"
            ##            print allreturns[0]
            while 1:
                line = inputfile.readline()
                print "made it here 3"
                values = str.split(line, ",")
                ##                print line
                ##                print "imgval"
                ##                print imgval
                ##if extension is included in text file
                img = values[imgval].strip()
                ##if extension is NOT included in text file
                ##img = values[imgval].strip() + '.JPG'
                vlat = values[latval].strip()
                vlon = values[lonval].strip()
                ingpsdate = values[dateval].strip()
                ##                #section to read date formats
                if self.rbv.get() == 1:
                    vyr = str(ingpsdate)[0:4]
                    vmm = str(ingpsdate)[4:6]
                    vdd = str(ingpsdate)[6:8]
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
                if self.rbv.get() == 2:
                    vgpsdate = ingpsdate
                if self.rbv.get() == 3:
                    vmm, vdd, vyr = ingpsdate.split("/")
                    if len(vmm) == 1:
                        vmm = "0" + vmm
                    if len(vdd) == 1:
                        vdd = "0" + vdd
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
                if self.rbv.get() == 4:
                    vmm, vdd, vyr = ingpsdate.split("/")
                    if len(vmm) == 1:
                        vmm = "0" + vmm
                    if len(vdd) == 1:
                        vdd = "0" + vdd
                    if int(vyr) < 50:
                        vyr = "20" + vyr
                    else:
                        vyr = "19" + vyr
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
##                if ingpsdate.find(':')==-1:
##                    vyr=str(ingpsdate)[0:4]
##                    vmm=str(ingpsdate)[4:6]
####                    print ingpsdate
####                    print "year"
####                    print vyr
####                    print "month"
####                    print vmm
##                    vdd=ingpsdate[6:8]
##                    vgpsdate=vyr+":"+vmm+":"+vdd
##                else:
##                    vgpsdate=ingpsdate
                print vgpsdate
                vgpstime = values[timeval].strip()
                imagefolder = self.entryJPGS.get()
                fullimg = os.path.join(imagefolder, img)
                fullimg = fullimg.replace('\\', '/')
                vartist = self.entryArtist.get()
                vartistquotes = '"' + vartist + '"'
                ##                print str(fullimg)
                ##                print str(vlat)
                ##                print str(vlon)
                ##                print str(vgpsdate)
                ##                print str(vgpstime)
                if (float(vlat)) > 0:
                    print "latref1"
                    vlatref = 'N'
                else:
                    print "latref2"
                    vlatref = 'S'
                if (float(vlon)) > 0:
                    vlonref = 'E'
                else:
                    vlonref = 'W'


##                print str(vlatref)
##                print str(vlonref)
                cmd = "exiftool -GPSDateStamp=" + vgpsdate + " -GPSTimeStamp="+vgpstime+" -GPSLatitude="+vlat+" -GPSLatitudeRef="+ vlatref+\
                      " -GPSLongitude="+vlon+" -GPSLongitudeRef="+vlonref+" "+ " -Artist=" +vartistquotes +" "+fullimg
                print cmd
                #print "made it past first os.system"
                subprocess.check_call(cmd, shell=True)
                print "executed"
                cmd2 = """exiftool -Credit="U.S. Geological Survey" -Contact="[email protected] " """ + fullimg
                subprocess.check_call(cmd2, shell=True)

                #jpeg comment
                print "in command 3 section"
                cmd3 = allreturns[0]
                cmd3new = cmd3 + " " + fullimg
                print cmd3new
                #print cmd3
                #cmd3 = """exiftool -comment="Photo from down-looking camera on the USGS SEABOSS deployed from the R/V Rafael during survey 2012-003-FA (http://woodshole.er.usgs.gov/operations/ia/public_ds_info.php?fa=2012-003-FA). Released as part of publication DOI:10.3133/ds937. " """+ fullimg
                subprocess.check_call(cmd3new, shell=True)
                #iptc info
                #cmd4 = """exiftool -sep ", " -keywords="Barnegat Bay, New Jersey, 2012-003-FA, SEABOSS, sea floor, USGS " """+ fullimg
                cmd4 = allreturns[1]
                cmd4new = cmd4 + " " + fullimg
                #subprocess.check_call(cmd4, shell=True)
                subprocess.check_call(cmd4new, shell=True)
                #cmd5 unused and skipped

                #xmp info
                #cmd6 = """exiftool -Caption="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd6 = allreturns[2]
                cmd6new = cmd6 + " " + fullimg
                #subprocess.check_call(cmd6, shell=True)
                subprocess.check_call(cmd6new, shell=True)
                print "did caption"
                #EXIF info
                cmd7 = """exiftool -Copyright="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd7, shell=True)
                print "did copyright"
                #iptc info
                cmd8 = """exiftool -CopyrightNotice="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd8, shell=True)
                #iptc info
                #cmd9 = """exiftool -Caption-Abstract="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd9 = allreturns[3]
                cmd9new = cmd9 + " " + fullimg
                #subprocess.check_call(cmd9, shell=True)
                subprocess.check_call(cmd9new, shell=True)
                #exif info - software such as Picasso use this as the caption
                #cmd10 = """exiftool -ImageDescription="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd10 = allreturns[4]
                cmd10new = cmd10 + " " + fullimg
                #subprocess.check_call(cmd10, shell=True)
                subprocess.check_call(cmd10new, shell=True)
        except:
            print "booboo maybe?"
        inputfile.close()
        print "done"
示例#46
0
class view(Tk):
    def mkStringVar(self, s):
        R = StringVar()
        R.set(s)
        return R

    def mkLabel(self, f, T, r, c, rs=1, cs=1):
        if isinstance(T, type(StringVar())):
            R = Label(f, textvariable=T, relief=GROOVE, borderwidth=2)
        else:
            R = Label(f, text=T, relief=GROOVE, borderwidth=2)
        R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens")
        return R

    def mkLabelList(self, f, SV, r):
        R = []
        for i in range(len(SV)):
            R.append(self.mkLabel(f, SV[i], r, i + 1))
        return R

    def mkButton(self, f, t, r, c, rs=1, cs=1):
        R = Button(f, text=t)
        R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens")
        return R

# ===== HALT et cetera =========================================================

    def mkHaltArea(self, f):
        self.HALTframe = Frame(f)
        self.HALTframe.config(relief=GROOVE)
        self.HALTframe.config(borderwidth=2)

        self.HALTbutton = Button(self.HALTframe, text="HALT", width=10)
        self.READMEbutton = Button(self.HALTframe, text="README", width=10)

        self.HALTbutton.config(borderwidth=2, relief=GROOVE, fg="red")
        self.HALTbutton.config(command=self.quit)
        self.READMEbutton.config(borderwidth=2, relief=GROOVE, fg="red")

        self.HALTbutton.pack(side=LEFT, fill=BOTH)
        self.READMEbutton.pack(side=RIGHT, fill=BOTH)

        self.HALTframe.grid(row=0,
                            column=9,
                            rowspan=1,
                            columnspan=4,
                            sticky="wens")

# ==============================================================================

    def mkProgramControl(self, f):
        self.PROGRAMCONTROLframe = Frame(f)
        self.PROGRAMCONTROLframe.config(relief=GROOVE)
        self.PROGRAMCONTROLframe.config(borderwidth=2)

        self.runButton = Button(self.PROGRAMCONTROLframe, text="RUN", width=10)
        self.runButton.grid(row=0, column=0, sticky="wens", padx=29, pady=7)

        self.stepButton = Button(self.PROGRAMCONTROLframe,
                                 text="STEP",
                                 width=10)
        self.stepButton.grid(row=1, column=0, sticky="wens", padx=29, pady=5)

        self.noStepButton = Button(self.PROGRAMCONTROLframe,
                                   text="NOSTEP",
                                   width=10)
        self.noStepButton.grid(row=2, column=0, sticky="wens", padx=29, pady=7)

        self.PROGRAMCONTROLframe.grid(row=17,
                                      column=11,
                                      rowspan=6,
                                      columnspan=2,
                                      sticky="wens")

# ==============================================================================

    def getPGMfileName(self):
        options = {'filetypes': [('pgm files', '.pgm')]}
        f = askopenfilename(**options)
        g = f.split('/')
        self.filenameVar.set(g[len(g) - 1])
        return f

    def mkProgramLoad(self, f):
        self.PROGRAMLOADframe = Frame(f)
        self.PROGRAMLOADframe.config(relief=GROOVE)
        self.PROGRAMLOADframe.config(borderwidth=2)

        self.loadPGMbutton = Button(self.PROGRAMLOADframe, text="Load PGM")
        self.loadPGMbutton.config(width=14)
        self.loadPGMbutton.pack(side=LEFT, fill=BOTH, padx=20, pady=5)

        self.filenameVar = StringVar()
        self.filenameVar.set("*****.pgm")

        self.fileNameLabel = Label(self.PROGRAMLOADframe,
                                   textvariable=self.filenameVar)
        self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=17)
        self.fileNameLabel.pack(side=RIGHT, fill=BOTH, padx=20, pady=5)

        self.PROGRAMLOADframe.grid(row=15,
                                   column=9,
                                   rowspan=2,
                                   columnspan=4,
                                   sticky="wens")

# ==============================================================================

    def mkMemory(self, f):
        self.MEMORYframe = Frame(f)
        self.MEMORYframe.config(relief=GROOVE)
        self.MEMORYframe.config(borderwidth=2)

        E = Frame(self.MEMORYframe)

        self.CLEAR = self.mkButton(E, "ClearMem", 0, 0)
        self.RANDOM = self.mkButton(E, "RandomMem", 0, 1)
        self.READ = self.mkButton(E, "ReadMem", 1, 0)
        self.WRITE = self.mkButton(E, "WriteMem", 1, 1)
        self.BUSTOMEM = self.mkButton(E, "BusToMem", 2, 0, 1, 2)

        F = Frame(self.MEMORYframe)

        for i in Range8:
            L = Label(F, textvariable=self.MEMORY[i])
            L.config(relief=GROOVE,
                     borderwidth=2,
                     bg="black",
                     fg="yellow",
                     height=1)
            L.grid(row=0, column=i, sticky="wens", ipadx=5)

        E.pack(side=TOP)
        F.pack(side=BOTTOM)

        self.MEMORYframe.grid(row=18,
                              column=9,
                              rowspan=5,
                              columnspan=2,
                              sticky="wens")

# ==============================================================================

    def mkDataBus(self, f):
        self.DBframe = Frame(f)
        self.DBframe.config(relief=GROOVE)
        self.DBframe.config(borderwidth=2, bg="red")
        self.DBframe.grid(row=0, column=0, rowspan=1, \
                          columnspan=9, sticky="wens")

        self.databusLabel = Label(self.DBframe, text="Data\nBus", width=10)
        self.databusLabel.pack(side=LEFT)

        self.DATABUSbuttons = []
        for i in Range8:
            b = Button(self.DBframe, textvariable=self.DATABUS[i])
            b.pack(side=LEFT, fill=BOTH)
            self.DATABUSbuttons.append(b)

    def mkAddressBus(self, f):
        self.ABframe = Frame(f)
        self.ABframe.config(relief=GROOVE)
        self.ABframe.config(borderwidth=2, bg="red")
        self.ABframe.grid(row=26,
                          column=0,
                          rowspan=1,
                          columnspan=13,
                          sticky="wens")

        self.AddressBusLabel = Label(self.ABframe,
                                     text="Address\nBus",
                                     width=12)
        self.AddressBusLabel.pack(side=LEFT)

        self.ADDRESSBUSbuttons = []
        for i in Range16:
            b = Button(self.ABframe, textvariable=self.ADDRESSBUS[i])
            b.pack(side=LEFT, fill=BOTH, ipadx=2)
            self.ADDRESSBUSbuttons.append(b)

# ==============================================================================

    def mkALU(self, f):
        self.ALUframe = Frame(f)
        self.ALUframe.config(relief=GROOVE)
        self.ALUframe.config(borderwidth=2)

        self.mkFunctionChoice(self.ALUframe)
        self.mkStates(self.ALUframe)

        self.ALUframe.grid(row=23,
                           column=9,
                           rowspan=3,
                           columnspan=4,
                           sticky="wens")

    def mkFunctionChoice(self, f):
        self.FUNCTIONframe = Frame(f)
        self.FUNCTIONframe.config(relief=GROOVE)
        self.FUNCTIONframe.config(borderwidth=2)

        self.F0label = Label(self.FUNCTIONframe,
                             text="F0",
                             borderwidth=2,
                             relief=GROOVE)
        self.F0label.grid(row=0, column=0, sticky="wens", padx=5)

        self.F1label = Label(self.FUNCTIONframe,
                             text="F1",
                             borderwidth=2,
                             relief=GROOVE)
        self.F1label.grid(row=0, column=1, sticky="wens", padx=8)

        self.F2label = Label(self.FUNCTIONframe,
                             text="F2",
                             borderwidth=2,
                             relief=GROOVE)
        self.F2label.grid(row=0, column=2, sticky="wens", padx=5)

        self.FUNCTIONbuttons = []

        self.F0button = Button(self.FUNCTIONframe)
        self.F0button.config(textvariable=self.FUNCTION[0],
                             borderwidth=2,
                             relief=GROOVE)
        self.F1button = Button(self.FUNCTIONframe)
        self.F1button.config(textvariable=self.FUNCTION[1],
                             borderwidth=2,
                             relief=GROOVE)
        self.F2button = Button(self.FUNCTIONframe)
        self.F2button.config(textvariable=self.FUNCTION[2],
                             borderwidth=2,
                             relief=GROOVE)

        self.FUNCTIONbuttons.append(self.F0button)
        self.FUNCTIONbuttons.append(self.F1button)
        self.FUNCTIONbuttons.append(self.F2button)

        for i in Range3:
            self.FUNCTIONbuttons[i].grid(row=1,
                                         column=i,
                                         sticky="wens",
                                         padx=5)

        self.FUNCTIONframe.pack(side=LEFT, padx=8, pady=3)

    def mkStates(self, f):
        self.STATESframe = Frame(f)
        self.STATESframe.config(relief=GROOVE)
        self.STATESframe.config(borderwidth=2)

        self.CARRYtag = Label(self.STATESframe,
                              text=" carry ",
                              borderwidth=2,
                              relief=GROOVE)
        self.CARRYtag.grid(row=0, column=0, padx=5, pady=2, sticky="wens")

        self.ZEROtag = Label(self.STATESframe,
                             text="  zero ",
                             borderwidth=2,
                             relief=GROOVE)
        self.ZEROtag.grid(row=0, column=1, padx=5, pady=1, sticky="wens")

        self.SIGNtag = Label(self.STATESframe,
                             text="  sign ",
                             borderwidth=2,
                             relief=GROOVE)
        self.SIGNtag.grid(row=0, column=2, padx=5, pady=2, sticky="wens")

        self.CARRY = self.mkStringVar("0")
        self.ZERO = self.mkStringVar("0")
        self.SIGN = self.mkStringVar("0")

        self.CARRYlabel = Label(self.STATESframe,
                                textvariable=self.CARRY,
                                borderwidth=2,
                                relief=GROOVE)
        self.CARRYlabel.grid(row=1, column=0, padx=5, pady=2, sticky="wens")

        self.ZEROlabel = Label(self.STATESframe,
                               textvariable=self.ZERO,
                               borderwidth=2,
                               relief=GROOVE)
        self.ZEROlabel.grid(row=1, column=1, padx=5, pady=1, sticky="wens")

        self.SIGNlabel = Label(self.STATESframe,
                               textvariable=self.SIGN,
                               borderwidth=2,
                               relief=GROOVE)
        self.SIGNlabel.grid(row=1, column=2, padx=5, pady=2, sticky="wens")

        self.STATESframe.pack(side=RIGHT, padx=8, pady=3)

# ==============================================================================

    def mkTagLabels(self, f):
        self.ALabel = self.mkLabel(f, "A", 1, 0)
        self.BLabel = self.mkLabel(f, "B", 2, 0)
        self.BLabel.config(bg="black", fg="yellow")
        self.CLabel = self.mkLabel(f, "C", 3, 0)
        self.CLabel.config(bg="black", fg="yellow")
        self.DLabel = self.mkLabel(f, "D", 4, 0)
        self.M1Label = self.mkLabel(f, "M1", 5, 0)
        self.M2Label = self.mkLabel(f, "M2", 6, 0)
        self.XLabel = self.mkLabel(f, "X", 7, 0)
        self.YLabel = self.mkLabel(f, "Y", 8, 0)
        self.J1Label = self.mkLabel(f, "J1", 9, 0)
        self.J2Label = self.mkLabel(f, "J2", 10, 0)
        self.PC1Label = self.mkLabel(f, "PC1", 11, 0)
        self.PC2Label = self.mkLabel(f, "PC2", 12, 0)
        self.Inc1Label = self.mkLabel(f, "Inc1", 13, 0)
        self.Inc2Label = self.mkLabel(f, "Inc2", 14, 0)
        self.IncUnit1Label = self.mkLabel(f, "IncUnit1", 15, 0)
        self.IncUnit2Label = self.mkLabel(f, "IncUnit2", 16, 0)
        self.InstLabel = self.mkLabel(f, "Inst", 17, 0)
        self.addLabel = self.mkLabel(f, "ADD", 18, 0)
        self.incLabel = self.mkLabel(f, "INC", 19, 0)
        self.andLabel = self.mkLabel(f, "AND", 20, 0)
        self.orLabel = self.mkLabel(f, "OR", 21, 0)
        self.xorLabel = self.mkLabel(f, "XOR", 22, 0)
        self.notLabel = self.mkLabel(f, "NOT", 23, 0)
        self.shlLabel = self.mkLabel(f, "SHL", 24, 0)
        self.clrLabel = self.mkLabel(f, "CLR", 25, 0)

        self.functionTagLabelDictionary = { (0,0,0) : self.addLabel, \
                                 (0,0,1) : self.incLabel, \
                                 (0,1,0) : self.andLabel, \
                                 (0,1,1) : self.orLabel, \
                                 (1,0,0) : self.xorLabel, \
                                 (1,0,1) : self.notLabel, \
                                 (1,1,0) : self.shlLabel, \
                                 (1,1,1) : self.clrLabel \
                                 }

        for i in self.functionTagLabelDictionary.values():
            i.config(bg="black", fg="yellow")

# ==============================================================================

    def mkRegisterStringVars(self):
        self.FUNCTION = [self.mkStringVar("0") for unused_i in Range3]
        self.DATABUS = [self.mkStringVar("0") for unused_i in Range8]
        self.Inst = [self.mkStringVar("0") for unused_i in Range8]
        self.A = [self.mkStringVar("0") for unused_i in Range8]
        self.B = [self.mkStringVar("0") for unused_i in Range8]
        self.C = [self.mkStringVar("0") for unused_i in Range8]
        self.D = [self.mkStringVar("0") for unused_i in Range8]
        self.M1 = [self.mkStringVar("0") for unused_i in Range8]
        self.M2 = [self.mkStringVar("0") for unused_i in Range8]
        self.X = [self.mkStringVar("0") for unused_i in Range8]
        self.Y = [self.mkStringVar("0") for unused_i in Range8]
        self.J1 = [self.mkStringVar("0") for unused_i in Range8]
        self.J2 = [self.mkStringVar("0") for unused_i in Range8]
        self.PC1 = [self.mkStringVar("0") for unused_i in Range8]
        self.PC2 = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc1 = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc2 = [self.mkStringVar("0") for unused_i in Range8]
        self.IncUnit1 = [self.mkStringVar("0") for unused_i in Range8]
        self.IncUnit2 = [self.mkStringVar("0") for unused_i in Range8]
        self.Add = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc = [self.mkStringVar("0") for unused_i in Range8]
        self.And = [self.mkStringVar("0") for unused_i in Range8]
        self.Or = [self.mkStringVar("0") for unused_i in Range8]
        self.Xor = [self.mkStringVar("0") for unused_i in Range8]
        self.Not = [self.mkStringVar("0") for unused_i in Range8]
        self.Shl = [self.mkStringVar("0") for unused_i in Range8]
        self.Clr = [self.mkStringVar("0") for unused_i in Range8]
        self.ADDRESSBUS = [self.mkStringVar("0") for unused_i in Range16]
        self.MEMORY = [self.mkStringVar("0") for unused_i in Range8]

# ==============================================================================

    def setRegisterLabelColor(self, L, bc, fc="black"):
        for i in L:
            i.config(bg=bc, fg=fc)

    def mkRegisterLabels(self, f):
        self.Alabels = self.mkLabelList(f, self.A, 1)
        self.setRegisterLabelColor(self.Alabels, "gray90")
        self.Blabels = self.mkLabelList(f, self.B, 2)
        self.setRegisterLabelColor(self.Blabels, "black", "yellow")
        self.Clabels = self.mkLabelList(f, self.C, 3)
        self.setRegisterLabelColor(self.Clabels, "black", "yellow")
        self.Dlabels = self.mkLabelList(f, self.D, 4)
        self.setRegisterLabelColor(self.Dlabels, "gray90")
        self.M1labels = self.mkLabelList(f, self.M1, 5)
        self.setRegisterLabelColor(self.M1labels, "gray90")
        self.M2labels = self.mkLabelList(f, self.M2, 6)
        self.setRegisterLabelColor(self.M2labels, "gray90")
        self.Xlabels = self.mkLabelList(f, self.X, 7)
        self.setRegisterLabelColor(self.Xlabels, "gray90")
        self.Ylabels = self.mkLabelList(f, self.Y, 8)
        self.setRegisterLabelColor(self.Ylabels, "gray90")

        self.J1labels = self.mkLabelList(f, self.J1, 9)
        self.J2labels = self.mkLabelList(f, self.J2, 10)
        self.PC1labels = self.mkLabelList(f, self.PC1, 11)
        self.PC2labels = self.mkLabelList(f, self.PC2, 12)

        self.Inc1labels = self.mkLabelList(f, self.Inc1, 13)
        self.setRegisterLabelColor(self.Inc1labels, "gray95")
        self.Inc2labels = self.mkLabelList(f, self.Inc2, 14)
        self.setRegisterLabelColor(self.Inc2labels, "gray95")

        self.IncUnit1labels = self.mkLabelList(f, self.IncUnit1, 15)
        self.setRegisterLabelColor(self.IncUnit1labels, "gray95")
        self.IncUnit2labels = self.mkLabelList(f, self.IncUnit2, 16)
        self.setRegisterLabelColor(self.IncUnit2labels, "gray95")

        self.Instlabels = self.mkLabelList(f, self.Inst, 17)

        self.addlabels = self.mkLabelList(f, self.Add, 18)
        self.setRegisterLabelColor(self.addlabels, "black", "red")
        self.inclabels = self.mkLabelList(f, self.Inc, 19)
        self.setRegisterLabelColor(self.inclabels, "black", "yellow")
        self.andlabels = self.mkLabelList(f, self.And, 20)
        self.setRegisterLabelColor(self.andlabels, "black", "yellow")
        self.orlabels = self.mkLabelList(f, self.Or, 21)
        self.setRegisterLabelColor(self.orlabels, "black", "yellow")
        self.xorlabels = self.mkLabelList(f, self.Xor, 22)
        self.setRegisterLabelColor(self.xorlabels, "black", "yellow")
        self.notlabels = self.mkLabelList(f, self.Not, 23)
        self.setRegisterLabelColor(self.notlabels, "black", "yellow")
        self.shllabels = self.mkLabelList(f, self.Shl, 24)
        self.setRegisterLabelColor(self.shllabels, "black", "yellow")
        self.clrlabels = self.mkLabelList(f, self.Clr, 25)
        self.setRegisterLabelColor(self.clrlabels, "black", "yellow")

        self.functionLabelsDictionary = { (0,0,0) : self.addlabels, \
                                 (0,0,1) : self.inclabels, \
                                 (0,1,0) : self.andlabels, \
                                 (0,1,1) : self.orlabels, \
                                 (1,0,0) : self.xorlabels, \
                                 (1,0,1) : self.notlabels, \
                                 (1,1,0) : self.shllabels, \
                                 (1,1,1) : self.clrlabels \
                                 }

# ===== Load & Select ==========================================================

    def mkLoad8Buttons(self, f):
        self.loadA = self.mkButton(f, "load A", 1, 9, 1, 2)
        self.loadB = self.mkButton(f, "load B", 2, 9, 1, 2)
        self.loadC = self.mkButton(f, "load C", 3, 9, 1, 2)
        self.loadD = self.mkButton(f, "load D", 4, 9, 1, 2)
        self.loadM1 = self.mkButton(f, "load M1", 5, 9, 1, 2)
        self.loadM2 = self.mkButton(f, "load M2", 6, 9, 1, 2)
        self.loadX = self.mkButton(f, "load X", 7, 9)
        self.loadY = self.mkButton(f, "load Y", 8, 9)
        self.loadJ1 = self.mkButton(f, "load J1", 9, 9, 1, 2)
        self.loadJ2 = self.mkButton(f, "load J2", 10, 9, 1, 2)

        self.loadInst = self.mkButton(f, "load Inst", 17, 9, 1, 2)

    def mkLoad16Buttons(self, f):
        self.loadXY = self.mkButton(f, "load XY", 7, 10, 2, 1)
        self.loadPC = self.mkButton(f, "load PC", 11, 9, 2, 2)
        self.loadINC = self.mkButton(f, "load INC", 13, 9, 2, 2)

    def mkSelect8Buttons(self, f):
        self.selectA = self.mkButton(f, "select A", 1, 11, 1, 2)
        self.selectB = self.mkButton(f, "select B", 2, 11, 1, 2)
        self.selectC = self.mkButton(f, "select C", 3, 11, 1, 2)
        self.selectD = self.mkButton(f, "select D", 4, 11, 1, 2)
        self.selectM1 = self.mkButton(f, "select M1", 5, 11)
        self.selectM2 = self.mkButton(f, "select M2", 6, 11)
        self.selectX = self.mkButton(f, "select X", 7, 11)
        self.selectY = self.mkButton(f, "select Y", 8, 11)

    def mkSelect16Buttons(self, f):
        self.selectM = self.mkButton(f, "select M", 5, 12, 2, 1)
        self.selectXY = self.mkButton(f, "select XY", 7, 12, 2, 1)
        self.selectJ = self.mkButton(f, "select J", 9, 11, 2, 2)
        self.selectPC = self.mkButton(f, "select PC", 11, 11, 2, 2)
        self.selectINC = self.mkButton(f, "select INC", 13, 11, 2, 2)

# ===== System Messages ========================================================

    def mkMessageArea(self, f):
        self.text = Text(f, height=36, width=64)
        self.text.configure(font=("Courier", 11, "bold"),
                            bg="black",
                            fg="green")
        self.scroll = Scrollbar(f, command=self.text.yview)
        self.text.configure(yscrollcommand=self.scroll.set)

        self.text.pack(side=LEFT, padx=3, pady=2)
        self.scroll.pack(side=RIGHT, fill=Y, padx=3, pady=2)

    def addText(self, text):
        self.text.insert(END, text + "\n")
        self.text.yview(END)

# ===== Initialization =========================================================

    def __init__(self):
        Tk.__init__(self)

        self.title("Virtual Machine")
        self.config(bg="blue")

        self.registers = LabelFrame(self, bg="blue")
        self.registers.config(relief=GROOVE)
        self.registers.config(borderwidth=2)
        self.registers.config(text="Virtual Machine: controls and states")
        self.registers.config(labelanchor="nw")
        self.registers.pack(side=LEFT, fill=BOTH)

        self.mkRegisterStringVars()

        self.mkTagLabels(self.registers)
        self.mkDataBus(self.registers)

        self.mkRegisterLabels(self.registers)

        self.mkLoad8Buttons(self.registers)
        self.mkLoad16Buttons(self.registers)
        self.mkSelect8Buttons(self.registers)
        self.mkSelect16Buttons(self.registers)

        self.mkAddressBus(self.registers)

        self.mkALU(self.registers)
        self.mkMemory(self.registers)
        self.mkProgramLoad(self.registers)
        self.mkProgramControl(self.registers)
        self.mkHaltArea(self.registers)

        self.messages = LabelFrame(self, bg="blue")
        self.messages.config(relief=GROOVE)
        self.messages.config(borderwidth=2)
        self.messages.config(text="Virtual Machine: system messages")
        self.messages.config(labelanchor="nw")
        self.messages.pack(side=RIGHT, fill=BOTH)

        self.mkMessageArea(self.messages)
示例#47
0
class Conversion(Frame):
    ''' Script creation graphical user interface.
        Since this page was crowding the main
        in order to neat
        this is a better place for it
    '''
    def __init__(self, master=None, **options):
        
        #if not master and options.get('parent'):
        #    master = options['parent']
        self.master  = master
        Frame.__init__(self, master)
        
        self.im_gear = self.master.im_gear
        
        # inner class object container
        self.objt_c = []
        

    def create_conversion_gui(self):
        
        #    first header row
        row = Frame(self)
        TEXT1= "\nSelect the parameters to perform the conversion: "
        Label(row, text=TEXT1, anchor='w').pack(side='top', padx=2, pady=10)
        row.pack( side='top', fill='x', padx=5)
        bottom_hline_deco(self)
        
        # file section
        #=======================       DEFAULTS       =========================
        ex_files=['./Examples/IONP/Original/SPIO_part-water-em.gro',
                  './Examples/IONP/Original/SPIO_part.top',
                  './Examples/IONP/Original/forcefield.itp',
                  './Examples/IONP/Original/ffoplsaaSI_FE_WATnb.itp',
                  './Examples/IONP/Original/ffoplsaaSI_FE_WATbon.itp'
                 ]
        #ex_files=['conf.gro','topol.top','forcefield.itp','nb.itp','bon.itp']
        _atomstyle_ = 'full'
        _radio_ = 1
        
        data_cont = self.master._convert_['setup']
        if data_cont <> []:
            ex_files = data_cont[:-2]
            _atomstyle_ = data_cont[-2]
            _radio_ = data_cont[-1]
        
        fi_txt=['Enter the gro file',
                'Enter the top file',
                'Enter the forcefield file',
                'Enter the non bonded file',
                'Enter the bonded file'
               ]
        
        for fi in range( len( ex_files)):
            self.objt_c.append( self.master.createfileentry( self, fi_txt[fi],
                                                           ex_files[fi],
                                                          )
                             )
        bottom_hline_deco( self)
        
        bottom_hline_deco( self, self.atomstyle)
        self.objt_c[-1].set( _atomstyle_)
        
        self.sol_buffer = _radio_
        bottom_hline_deco( self, self.build_solvation_section)
        self.objt_c[-1].set( _radio_)
        
        #    Final Buttons
        self.build_finalbuttons()

    def build_solvation_section( self):
        
        row = Frame(self)
        
        self.radio_part( row, 'Solvation atoms', [' yes',' no'])
        
        self.solv_b = Button( row, image= self.im_gear,
                             width = 25, height=23,
                             command= self.config_solvation
                            )
        self.solv_b.pack( side='right', padx=0)
        row.pack( side='top', fill='x', pady=3)

    def radio_part(self, _s_row_, _text_, _desc_=[''], _vals_=[]):
        
        _f_labels = format_dec([_s_row_, _text_])#, _pack_=False)
        
        radio_var = IntVar()
        for d in range( len( _desc_)):
            
            label_rb = Radiobutton(_s_row_, width=0, text= _desc_[d]
                                   ,variable = radio_var
                                   , value= len( _desc_)-1-d
                                   ,command = self.solvastuff
                                   , anchor='w'
                                  )
            label_rb.pack(side='left', padx=6)
        self.objt_c.append( radio_var)
        
    
    def solvastuff(self):
        '''If this point is reached, some button changed '''
        
        _solvation_ = self.objt_c[-1].get()
        if self.sol_buffer <> _solvation_:
            self.sol_buffer = _solvation_
            
            if _solvation_:
                self.solv_b.configure( state = 'normal')
            else:
                pop_wrg_1('You are choosing to not consider solvation.'
                                ,' If some solvent molecules are in the'
                                +' .gro file they will be ignored!', _i_=0)
                self.solv_b.configure( state = 'disabled')


    def atomstyle( self):
        ''' in this case just one, but could be modified 
        to be generic, accepting <row>, <text> and <options>'''
        a_mainrow= Frame( self)
        row_fst = Frame( a_mainrow)
        
        #from self-ttk import Combobox
        TEXT2=  'Choose an atom style'
        format_dec([row_fst, TEXT2])

        row_fsep = Frame(row_fst)
        
        atom_var = StringVar()
        atom_style_ddl = Drop_Down_List(row_fsep,
                                        textvariable = atom_var,
                                        #state="readonly"
                                       )
        atom_style_ddl['values'] = ('full', 'charge', 'molecular',
                                    'angle', 'bond','atomic')
        atom_style_ddl.bind("<Key>", lambda e: "break") # Magic
        atom_style_ddl.pack()
        self.objt_c.append( atom_var)
        
        row_fsep.pack(side='left', fill='x', pady=0)
        
        # row packing
        row_fst.pack(side='left', pady=0)
        
        a_mainrow.pack(side='top', fill='x', pady=3)

    def build_finalbuttons(self):
        
        Frame(self).pack(side="top", fill='x', pady=20) # Space
        
        _row_= self
        self.b1 = Button(_row_, text='Convert',
                         command = self.getdata_and_convert)
        self.b1.pack( side = 'right', padx=30, pady=15)
        
        b2 = Button(_row_, text = 'Quit', command = self.quit)
        b2.pack( side = 'right', padx=10, pady=4)

    def getdata_and_convert(self):
        _solvatedinfo_ = self.master._convert_['solvation']
        
        if ( self.objt_c[-1].get() and _solvatedinfo_ == []):
            pop_wrg_1( 'First perform the solvation configuration.'
                      + ' You can do it pressing in solvation settings gears',
                      _i_=0
                     )
            self.solv_b.invoke()
            
        elif self.get_entriesvalues():
            
            data_cont = self.master._convert_['setup']
            config = data_cont[-2:]+[0]
            
            sim_data, flag_done_ = extract_gromacs_data(data_cont[:-2],
                                                        _solvatedinfo_,
                                                        config[1:])
            if flag_done_:
                flag_done_ = write_lammps_data( sim_data, 'data.gro2lam',
                                               config
                                              )
            
            if flag_done_:
                print_dec_g( 'Data file generated as "data.gro2lam"' )
                
                self._convertdata_ = sim_data
                self._convertdata_['config'] = config
                
                # Returning the values
                self.master._convertdata_ = self._convertdata_
                self.master.swapbody(2)
                
        else:
            pop_wrg_1('The setup needs some further improvements'
                        +'to be runed. Please check your inputs')

    def get_entriesvalues(self):
        ''' ---   app entry getter   ----
        mainly to obtain values beside check buttons'''
        e_values=[]
        _flag_ = True
        ent_rang  =  range(len(self.objt_c))
        
        for ent in ent_rang:#[1:]:
            e_values.append(self.objt_c[ent].get())
            if ent <= 4:
                _flag_ *= check_file(e_values[-1])
            
        self.master._convert_['setup'] = e_values
        return _flag_

    def createWidgets(self):
        self.create_conversion_gui()

    def config_solvation( self):
            
        title_txt = ' '*15+'Input Water name'
        instructions = 'Enter the atom tag letters of:'
        askfor = ['O in the non bonded file',
                  'H in the non bonded file',
                  'O in the .gro file',
                  'H in the .gro file',
                  'H - O partial charge'
                  #'Na+ in the .gro file (if are present)',
                  #'Cl- in the .gro file (if are present)'
                 ]
        _solvatedinfo_ = self.master._convert_['solvation']
        
        if _solvatedinfo_ ==  []:
            defaultanswer = ['opls_116','opls_117','OW','HW1, HW2','0.4238'
                            #,'Na','Cl'
                           ]
        else:
            defaultanswer = _solvatedinfo_
            
        self.solv_b.config(bg = 'gray40', width = 45) #cyan')
        self.master._aux_ = []
        
        pop = PromptPopUp(master = self.master,
                          title = title_txt,
                          briefing = instructions, 
                          entries_txt = askfor, 
                          entries_val = defaultanswer
                         )
        
        pop.wait_window()
        
        if self.master._aux_ <> [] and self.get_entriesvalues():
            _app_aux_ = self.master._aux_
            #============ Check inputs =================
            _flag_ = 1
            nb_Ox, nbHy, gro_Oxs, gro_Hys, pch= _app_aux_
            _gro_f, _, _, _nbn_f, _, _, _= self.master._convert_['setup']
            _flags = check_in_file( _nbn_f, nb_Ox, nbHy)
            print ([nb_Ox, nbHy])
            list_aux = [Ox.strip(' ') for Ox in gro_Oxs.split(',')]
            list_aux += [Ox.strip(' ') for Ox in gro_Hys.split(',')]
            _flags += check_in_file( _gro_f, *list_aux)
            print (list_aux)
            
            try:
                x = float(pch)
                if -10<x<10:
                    _flags += [1]
                    partial_charges = 'Partial charges for H: {} and for O: {}'
                    print partial_charges.format( x, x*-2)
                else:
                    _flags += [0]
            except:
                _flags += [0]
            list_aux = [nb_Ox, nbHy] + list_aux
            for v in range(len(_flags)):
                err_txt = ''
                if not _flags[v] and v <> (len(_flags)-1):
                    filename = _nbn_f
                    if v>1:
                        filename = _gro_f
                    err_txt = 'Atom tag {} not found in {}'
                    if '/' in filename:
                        filename = filename.split('/')[-1]
                    err_txt = err_txt.format( list_aux[v], filename)
                    _flag_*=0
                
                elif not _flags[v]:
                    err_txt = 'Non valid partial charge {}'.format( pch)
                    _flag_*=0
                    
                if err_txt<>'':
                    pop_err_1(err_txt+'\nSetup not saved')
            #============       Done!  =================
            if _flag_:
                self.master._convert_['solvation'] = _app_aux_
                print_dec_g('Solvation setup saved!')
                #self.solv_b.focus()
        self.solv_b.config(bg = 'lightgrey', width = 28)
示例#48
0
class _Hatch_GUI(object):
    """
    create a Hatch object from
    hatch_supt and to then create a skeleton python project.
    """
    def __init__(self, master):
        self.initComplete = 0
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1

        # bind master to <Configure> in order to handle any resizing, etc.
        # postpone self.master.bind("<Configure>", self.Master_Configure)
        self.master.bind('<Enter>', self.bindConfigure)

        self.master.title("PyHatch GUI")
        self.master.resizable(0, 0)  # Linux may not respect this

        dialogframe = Frame(master, width=810, height=630)
        dialogframe.pack()

        self.Shortdesc_Labelframe = LabelFrame(
            dialogframe,
            text="Short Description (1-liner)",
            height="90",
            width="718")
        self.Shortdesc_Labelframe.place(x=60, y=127)

        helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold')

        self.Buildproject_Button = Button(dialogframe,
                                          text="Build Project",
                                          width="15",
                                          font=helv20)
        self.Buildproject_Button.place(x=492, y=10, width=263, height=68)
        self.Buildproject_Button.bind("<ButtonRelease-1>",
                                      self.Buildproject_Button_Click)

        self.Selectdir_Button = Button(dialogframe,
                                       text="<Select Directory>",
                                       width="15")
        self.Selectdir_Button.place(x=72, y=585, width=672, height=31)
        self.Selectdir_Button.bind("<ButtonRelease-1>",
                                   self.Selectdir_Button_Click)

        self.Author_Entry = Entry(dialogframe, width="15")
        self.Author_Entry.place(x=228, y=424, width=187, height=21)
        self.Author_Entry_StringVar = StringVar()
        self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar)
        self.Author_Entry_StringVar.set("John Doe")

        self.Classname_Entry = Entry(dialogframe, width="15")
        self.Classname_Entry.place(x=192, y=73, width=165, height=21)
        self.Classname_Entry_StringVar = StringVar()
        self.Classname_Entry.configure(
            textvariable=self.Classname_Entry_StringVar)
        self.Classname_Entry_StringVar.set("MyClass")

        self.Copyright_Entry = Entry(dialogframe, width="15")
        self.Copyright_Entry.place(x=228, y=478, width=461, height=21)
        self.Copyright_Entry_StringVar = StringVar()
        self.Copyright_Entry.configure(
            textvariable=self.Copyright_Entry_StringVar)
        self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe")

        self.Email_Entry = Entry(dialogframe, relief="sunken", width="15")
        self.Email_Entry.place(x=228, y=505, width=458, height=21)
        self.Email_Entry_StringVar = StringVar()
        self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar)
        self.Email_Entry_StringVar.set("*****@*****.**")

        self.GithubUserName_Entry = Entry(dialogframe,
                                          relief="sunken",
                                          width="15")
        self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21)
        self.GithubUserName_Entry_StringVar = StringVar()
        self.GithubUserName_Entry.configure(
            textvariable=self.GithubUserName_Entry_StringVar)
        self.GithubUserName_Entry_StringVar.set("github_user_name")

        self.Funcname_Entry = Entry(dialogframe, width="15")
        self.Funcname_Entry.place(x=192, y=100, width=157, height=21)
        self.Funcname_Entry_StringVar = StringVar()
        self.Funcname_Entry.configure(
            textvariable=self.Funcname_Entry_StringVar)
        self.Funcname_Entry_StringVar.set("my_function")

        # License values should be correct format
        LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys()))
        self.License_Entry_StringVar = StringVar()
        self.License_Entry = OptionMenu(dialogframe,
                                        self.License_Entry_StringVar,
                                        *LICENSE_OPTIONS)
        self.License_Entry.place(x=552, y=424, width=184, height=21)
        self.License_Entry_StringVar.set(LICENSE_OPTIONS[0])

        self.Mainpyname_Entry = Entry(dialogframe, width="15")
        self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21)
        self.Mainpyname_Entry_StringVar = StringVar()
        self.Mainpyname_Entry.configure(
            textvariable=self.Mainpyname_Entry_StringVar)
        self.Mainpyname_Entry_StringVar.set("main.py")

        self.Projname_Entry = Entry(dialogframe, width="15")
        self.Projname_Entry.place(x=168, y=10, width=194, height=21)
        self.Projname_Entry_StringVar = StringVar()
        self.Projname_Entry.configure(
            textvariable=self.Projname_Entry_StringVar)
        self.Projname_Entry_StringVar.set("MyProject")

        self.Shortdesc_Entry = Entry(dialogframe, width="15")
        self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48)
        self.Shortdesc_Entry_StringVar = StringVar()
        self.Shortdesc_Entry.configure(
            textvariable=self.Shortdesc_Entry_StringVar)
        self.Shortdesc_Entry_StringVar.set("My project does this")

        # Status must be correct format
        self.Status_Entry_StringVar = StringVar()
        self.Status_Entry = OptionMenu(dialogframe,
                                       self.Status_Entry_StringVar,
                                       *DEV_STATUS_OPTIONS)
        self.Status_Entry.place(x=228, y=451, width=183, height=21)
        self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0])

        self.Version_Entry = Entry(dialogframe, width="15")
        self.Version_Entry.place(x=552, y=451, width=184, height=21)
        self.Version_Entry_StringVar = StringVar()
        self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar)
        self.Version_Entry_StringVar.set("0.1.1")

        self.Author_Label = Label(dialogframe, text="Author", width="15")
        self.Author_Label.place(x=96, y=424, width=112, height=22)

        self.Classname_Label = Label(dialogframe,
                                     text="Class Name",
                                     width="15")
        self.Classname_Label.place(x=60, y=73, width=112, height=22)

        self.Copyright_Label = Label(dialogframe, text="Copyright", width="15")
        self.Copyright_Label.place(x=96, y=478, width=113, height=23)

        self.Email_Label = Label(dialogframe, text="Email", width="15")
        self.Email_Label.place(x=96, y=505, width=113, height=23)

        self.GithubUserName_Label = Label(dialogframe,
                                          text="GithubUserName",
                                          width="15")
        self.GithubUserName_Label.place(x=96, y=539, width=113, height=23)

        self.Funcname_Label = Label(dialogframe,
                                    text="Function Name",
                                    width="15")
        self.Funcname_Label.place(x=60, y=100, width=112, height=22)

        self.License_Label = Label(dialogframe, text="License", width="15")
        self.License_Label.place(x=432, y=424, width=113, height=23)

        self.Longdesc_Label = Label(dialogframe,
                                    text="Paragraph Description",
                                    width="15")
        self.Longdesc_Label.place(x=216, y=220, width=376, height=22)

        self.Mainpyname_Label = Label(dialogframe,
                                      text="Main Python File",
                                      width="15")
        self.Mainpyname_Label.place(x=48, y=37, width=112, height=22)

        self.Projname_Label = Label(dialogframe,
                                    text="Project Name",
                                    width="15")
        self.Projname_Label.place(x=48, y=10, width=112, height=22)

        self.Selectdir_Label = Label(
            dialogframe,
            text="Select the Directory Below Which to Place Your Project",
            width="15")
        self.Selectdir_Label.place(x=156, y=567, width=536, height=24)

        self.Status_Label = Label(dialogframe, text="Status", width="15")
        self.Status_Label.place(x=96, y=451, width=114, height=24)

        self.Version_Label = Label(dialogframe, text="Version", width="15")
        self.Version_Label.place(x=432, y=451, width=113, height=23)

        self.Isclass_Radiobutton = Radiobutton(dialogframe,
                                               text="Class Project",
                                               value="Class Project",
                                               width="15",
                                               anchor=W)
        self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("Class Project")
        self.RadioGroup1_StringVar_traceName = \
            self.RadioGroup1_StringVar.trace_variable("w",
                                                      self.RadioGroup1_StringVar_Callback)
        self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar)

        self.Isfunction_Radiobutton = Radiobutton(dialogframe,
                                                  text="Function Project",
                                                  value="Function Project",
                                                  width="15",
                                                  anchor=W)
        self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27)
        self.Isfunction_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        lbframe = Frame(dialogframe)
        self.Text_1_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Text_1 = Text(lbframe,
                           width="40",
                           height="6",
                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Text_1.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Text_1.pack(side=LEFT, fill=BOTH, expand=1)

        self.Text_1_frame.place(x=72, y=250, width=665, height=160)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.dirname = '<Select Directory>'
        self.Funcname_Entry.config(state=DISABLED)

        h = Hatch(projName='MyProject', mainDefinesClass='N')
        if h.author:
            self.Author_Entry_StringVar.set(h.author)
        if h.proj_license:
            self.License_Entry_StringVar.set(h.proj_license)
        if h.proj_copyright:
            self.Copyright_Entry_StringVar.set(h.proj_copyright)
        if h.email:
            self.Email_Entry_StringVar.set(h.email)
        if h.github_user_name:
            self.GithubUserName_Entry_StringVar.set(h.github_user_name)
        del h

    def build_result_dict(self):
        """Takes user inputs from GUI and builds a dictionary of results"""
        # pylint: disable=W0201
        self.result = {}  # return a dictionary of results

        self.result["author"] = self.Author_Entry_StringVar.get()
        self.result["status"] = self.Status_Entry_StringVar.get()
        self.result["proj_license"] = self.License_Entry_StringVar.get()
        self.result["version"] = self.Version_Entry_StringVar.get()
        self.result["proj_copyright"] = self.Copyright_Entry_StringVar.get()
        self.result["email"] = self.Email_Entry_StringVar.get()
        self.result[
            "github_user_name"] = self.GithubUserName_Entry_StringVar.get()

        self.result["main_py_name"] = self.Mainpyname_Entry_StringVar.get()
        self.result["proj_name"] = self.Projname_Entry_StringVar.get()
        self.result["class_name"] = self.Classname_Entry_StringVar.get()
        self.result["func_name"] = self.Funcname_Entry_StringVar.get()

        self.result["short_desc"] = self.Shortdesc_Entry_StringVar.get()
        self.result["para_desc"] = self.Text_1.get(1.0, END)
        self.result["parent_dir"] = self.dirname

        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.result["is_class_project"] = 'Y'
        else:
            self.result["is_class_project"] = 'N'

    def Buildproject_Button_Click(self, event):
        """When clicked, this method gathers all the user inputs
            and builds the project skeleton in the directory specified.
        """

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613

        # >>>>>>insert any user code below this comment for section "compID=29"
        # replace, delete, or comment-out the following
        #print "executed method Buildproject_Button_Click"

        if not os.path.isdir(self.dirname):
            ShowError(
                title='Need Parent Directory',
                message=
                'You need to choose a directory in which to place your project.'
            )
        else:
            self.build_result_dict()  # builds self.result dict
            r = self.result

            h = Hatch(projName=r["proj_name"],
                      mainDefinesClass=r["is_class_project"],
                      mainPyFileName=r["main_py_name"],
                      mainClassName=r["class_name"],
                      mainFunctionName=r["func_name"],
                      author=r["author"],
                      proj_copyright=r["proj_copyright"],
                      proj_license=r["proj_license"],
                      version=r["version"],
                      email=r["email"],
                      status=r["status"],
                      github_user_name=r["github_user_name"],
                      simpleDesc=r["short_desc"],
                      longDesc=r["para_desc"])

            call_result = h.save_project_below_this_dir(self.dirname)
            if call_result == 'Success':
                if AskYesNo(title='Exit Dialog',
                            message='Do you want to leave this GUI?'):
                    self.master.destroy()
            else:
                ShowWarning( title='Project Build Error',
                             message='Project did NOT build properly.\n'+\
                            'Warning Message = (%s)'%call_result)

    # return a string containing directory name
    def AskDirectory(self, title='Choose Directory', initialdir="."):
        """Simply wraps the tkinter function of the "same" name."""
        dirname = tkFileDialog.askdirectory(parent=self.master,
                                            initialdir=initialdir,
                                            title=title)
        return dirname  # <-- string

    def Selectdir_Button_Click(self, event):
        #  I don't care what the exception is, if there's a problem, bail
        #     Also, I want to redefine the dirname attribute here
        # pylint: disable=W0702, W0201

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Selects the directory in which to build project."""

        dirname = self.AskDirectory(title='Choose Directory For Nose Tests',
                                    initialdir='.')
        if dirname:
            try:
                dirname = os.path.abspath(dirname)
            except:
                self.dirname = '<Select Directory>'
                return  # let Alarm force dir selection

            self.dirname = dirname

            self.Selectdir_Button.config(text=self.dirname)

    def RadioGroup1_StringVar_Callback(self, varName, index, mode):
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Responds to changes in RadioGroup1_StringVar."""
        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.Funcname_Entry.config(state=DISABLED)
            self.Classname_Entry.config(state=NORMAL)
        else:
            self.Classname_Entry.config(state=DISABLED)
            self.Funcname_Entry.config(state=NORMAL)

    # tk_happy generated code. DO NOT EDIT THE FOLLOWING. section "Master_Configure"
    def bindConfigure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        if not self.initComplete:
            self.master.bind("<Configure>", self.Master_Configure)
            self.initComplete = 1

    def Master_Configure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        # >>>>>>insert any user code below this comment for section "Master_Configure"
        # replace, delete, or comment-out the following
        if event.widget != self.master:
            if self.w != -1:
                return
        x = int(self.master.winfo_x())
        y = int(self.master.winfo_y())
        w = int(self.master.winfo_width())
        h = int(self.master.winfo_height())
        if (self.x, self.y, self.w, self.h) == (-1, -1, -1, -1):
            self.x, self.y, self.w, self.h = x, y, w, h

        if self.w != w or self.h != h:
            print "Master reconfigured... make resize adjustments"
            self.w = w
            self.h = h
class QuizLetter(Frame):

    def __init__(self, parent):

        Frame.__init__(self, parent)
        self.parent = parent

        # generate the options of buttons
        keys = shuffle_dictionary(LETTERS)
        right_answer, answers = generate_letters(keys, NUM_LETTERS)
        # create window
        self.create_window()
        self.create_letter(right_answer)
        #self.create_button()
        self.create_play_button(answers)
        self.create_option_buttons(right_answer, answers)

    def create_window (self):

        self.parent.geometry(WINDOW_DIMENSIONS)
        self.parent.title(TITLE)

    def create_letter(self, right_answer):

        self.label = Label(self.parent, text=right_answer, font=("",80))
        self.label.pack()

    def create_play_button(self, answers):

        # create list of oggs
        list_oggs = []
        i= 0
        for i in range(0, NUM_LETTERS):
            list_oggs.append(LETTERS[answers[i]][1])
            i+=1
        self.play_image = PhotoImage(file=IMAGES_PATH + 'play.png')
        # create the button
        self.play_button = Button(self.parent,width=40,height=30,fg='black',
            image=self.play_image, command=lambda: play_ogg(list_oggs)).place(x=5,y=102)

    def right_button(self, button):
        """
        Button right green and sound
        """
        button.config(background = "green")
        button.config(activebackground="green")
        pygame.mixer.music.load(SOUNDS_PATH + 'right.ogg')
        pygame.mixer.music.play()

    def wrong_button(self, button):
        """
        Button wrong red and sound
        """
        button.config(background = "red")
        button.config(activebackground="red")
        pygame.mixer.music.load(SOUNDS_PATH + 'wrong.ogg')
        pygame.mixer.music.play()

    def create_option_buttons(self, right_answer, answers):

        # create buttons
        self.option_1 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[0]][0])
        self.option_1.place(x=5,y=140)
        self.option_2 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[1]][0])
        self.option_2.place(x=5,y=200) 
        self.option_3 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[2]][0])
        self.option_3.place(x=95,y=140)
        self.option_4 = Button(self.parent,width=7,height=3,fg='black',
                  text=LETTERS[answers[3]][0])
        self.option_4.place(x=95,y=200)
        self.option_1.config(command=lambda:
                             self.right_button(self.option_1) if answers[0] == right_answer
                             else self.wrong_button(self.option_1))
        self.option_2.config(command=lambda:
                             self.right_button(self.option_2) if answers[1] == right_answer
                             else self.wrong_button(self.option_2))
        self.option_3.config(command=lambda:
                             self.right_button(self.option_3) if answers[2] == right_answer
                             else self.wrong_button(self.option_3))
        self.option_4.config(command=lambda:
                             self.right_button(self.option_4) if answers[3] == right_answer
                             else self.wrong_button(self.option_4))
示例#50
0
class pump_ui(object):
    def __init__(self):
        master = Tk()
        master.style = ttk.Style()
        master.style.theme_use("default")
        master.config(bg=background_colour)
        master.resizable(
            0, 0
        )  # Disable resizing the UI to prevent having to make widget placing dynamic
        master.winfo_toplevel().title(frame_title)
        master.iconbitmap("bitcoin.ico")

        # Create pumper assistant to store data on the current BTC and alt holdings.
        self.pumper = pumper()

        self.create_title(master)
        self.create_api_info(master, previous_row=0)
        self.create_auto_sell(master, previous_row=3)
        self.create_stop_loss(master, previous_row=4)
        self.create_order_type(master, previous_row=6)
        self.create_fee_type(master, previous_row=7)
        self.create_btc_balance_picker(master, previous_row=8)
        self.create_alt_ticker(master, previous_row=10)
        self.create_pump_and_sell_buttons(master, previous_row=11)
        self.create_current_profit(master, previous_row=12)

        self.create_output_box(master, rightmost_column=1)

        # Can hardcode API key and Secret
        #self.api_key_entry.delete(0,END)
        #self.api_key_entry.insert(0,"KEY")
        #self.api_key_entry.config(state=DISABLED)
        #self.api_secret_entry.delete(0, END)
        #self.api_secret_entry.insert(0, "SECRET")
        #self.api_secret_entry.config(state=DISABLED)

        # Display the UI, this can only be called once per program.
        # Nothing in the main Python script will be run after creating the UI because of this.
        master.mainloop()

    def create_title(self, master, previous_row=-1, previous_column=-1):
        empty = Label(master, text=frame_title)
        empty.grid(row=previous_row + 1,
                   column=previous_column + 2,
                   columnspan=1)
        empty.config(bg=background_colour, fg=label_font_colour)

    def create_api_info(self, master, previous_row=-1, previous_column=-1):
        api_key_lbl = Label(master, text="API Key:")
        api_key_lbl.grid(row=previous_row + 1,
                         column=previous_column + 1,
                         columnspan=1,
                         sticky=E,
                         padx=(3, 0))
        api_key_lbl.config(bg=background_colour, fg=label_font_colour)

        self.api_key_entry = Entry(master,
                                   highlightthickness=0,
                                   bd=0,
                                   width=21,
                                   show="*")
        self.api_key_entry.config(borderwidth=2, relief=default_relief)
        self.api_key_entry.grid(row=previous_row + 1,
                                column=previous_column + 2)

        api_secret_lbl = Label(master, text="API Secret:")
        api_secret_lbl.grid(row=previous_row + 2,
                            column=previous_column + 1,
                            columnspan=1,
                            sticky=E,
                            padx=(3, 0))
        api_secret_lbl.config(bg=background_colour, fg=label_font_colour)

        self.api_secret_entry = Entry(master,
                                      highlightthickness=0,
                                      bd=0,
                                      width=21,
                                      show="*")
        self.api_secret_entry.config(borderwidth=2, relief=default_relief)
        self.api_secret_entry.grid(row=previous_row + 2,
                                   column=previous_column + 2)

        self.api_connect_btn = Button(master,
                                      text="Connect To Binance",
                                      command=self.on_connect_api)
        self.api_connect_btn.grid(row=previous_row + 3,
                                  column=previous_column + 2,
                                  columnspan=1,
                                  sticky=W + E,
                                  padx=10,
                                  pady=(0, 3))
        self.api_connect_btn.config(highlightbackground=background_colour)

    def create_auto_sell(self, master, previous_row=-1, previous_column=-1):
        auto_sell_lbl = Label(master, text="Auto Sell (%):")
        auto_sell_lbl.grid(row=previous_row + 1,
                           column=previous_column + 1,
                           columnspan=1,
                           sticky=E,
                           padx=(3, 0))
        auto_sell_lbl.config(bg=background_colour, fg=label_font_colour)

        self.auto_sell_spinbox = Spinbox(master,
                                         from_=1.0,
                                         to=300.0,
                                         increment=1.0,
                                         highlightbackground=background_colour)
        self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief)
        self.auto_sell_spinbox.grid(row=previous_row + 1,
                                    column=previous_column + 2)
        self.auto_sell_spinbox.delete(0, "end")
        self.auto_sell_spinbox.insert(0, 50)

    def create_stop_loss(self, master, previous_row=-1, previous_column=-1):
        stop_loss_lbl = Label(master, text="Stop Loss (%):")
        stop_loss_lbl.grid(row=previous_row + 1,
                           column=previous_column + 1,
                           columnspan=1,
                           sticky=E,
                           padx=(3, 0))
        stop_loss_lbl.config(bg=background_colour, fg=label_font_colour)

        self.stop_loss_spinbox = Spinbox(master,
                                         from_=-100.0,
                                         to=-10.0,
                                         increment=1.0,
                                         highlightbackground=background_colour)
        self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief)
        self.stop_loss_spinbox.grid(row=previous_row + 1,
                                    column=previous_column + 2)
        self.stop_loss_spinbox.delete(0, "end")
        self.stop_loss_spinbox.insert(0, -10)

    def create_btc_balance_picker(self,
                                  master,
                                  previous_row=-1,
                                  previous_column=-1):
        self.btc_balance_str = StringVar()
        btc_balance_lbl = Label(master, textvar=self.btc_balance_str)
        btc_balance_lbl.grid(row=previous_row + 1,
                             column=previous_column + 1,
                             columnspan=2,
                             sticky=W + E,
                             padx=(3, 0))
        btc_balance_lbl.config(bg=background_colour, fg=label_font_colour)
        self.set_available_btc_balance(Decimal(0))

        btc_to_use_label = Label(master,
                                 text="BTC to spend:",
                                 bg=background_colour,
                                 fg=label_font_colour)
        btc_to_use_label.grid(row=previous_row + 2,
                              column=previous_column + 1,
                              sticky=E,
                              padx=(3, 0))

        self.btc_to_use_spinbox = Spinbox(
            master,
            from_=minimum_trade,
            to=minimum_trade,
            increment=btc_to_use_increment,
            highlightbackground=background_colour)
        self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief)
        self.btc_to_use_spinbox.grid(row=previous_row + 2,
                                     column=previous_column + 2)

    def create_order_type(self, master, previous_row=-1, previous_column=-1):
        order_type_lbl = Label(master, text="Entry Type:")
        order_type_lbl.grid(row=previous_row + 1,
                            column=previous_column + 1,
                            sticky=E,
                            padx=(3, 0))
        order_type_lbl.config(bg=background_colour, fg=label_font_colour)

        self.is_entry_market = True

        def change_order_type(*args):
            self.is_entry_market = (self.order_type.get() == "Market Buy  \/")

        self.order_type = StringVar()
        self.order_type.trace(
            "w", change_order_type
        )  # Reduces how much work is done when the pump starts
        choices = {"Market Buy  \/", "Limit Buy     \/"}
        self.entry_type_option_menu = OptionMenu(master, self.order_type,
                                                 *choices)
        self.entry_type_option_menu.grid(row=previous_row + 1,
                                         column=previous_column + 2,
                                         sticky=W + E,
                                         padx=8)
        self.entry_type_option_menu.config(highlightthickness=0)
        self.entry_type_option_menu.configure(indicatoron=0)
        self.order_type.set("Market Buy  \/")

    def create_fee_type(self, master, previous_row=-1, previous_column=-1):
        fee_type_lbl = Label(master, text="Fee Type:")
        fee_type_lbl.grid(row=previous_row + 1,
                          column=previous_column + 1,
                          sticky=E,
                          padx=(3, 0))
        fee_type_lbl.config(bg=background_colour, fg=label_font_colour)

        self.is_using_bnb = True

        def change_fee_type(*args):
            self.is_using_bnb = (
                self.order_type.get() == "Binance Coin (BNB) \/")

        self.fee_type = StringVar()
        self.fee_type.trace(
            "w", change_fee_type
        )  # Reduces how much work is done when the pump starts
        choices = {"Binance Coin (BNB) \/", "0.1% Of All Trades    \/"}
        self.fee_type_option_menu = OptionMenu(master, self.fee_type, *choices)
        self.fee_type_option_menu.grid(row=previous_row + 1,
                                       column=previous_column + 2,
                                       sticky=W + E,
                                       padx=8)
        self.fee_type_option_menu.config(highlightthickness=0)
        self.fee_type_option_menu.configure(indicatoron=0)
        self.fee_type.set("Binance Coin (BNB) \/")

    def create_pump_and_sell_buttons(self,
                                     master,
                                     previous_row=-1,
                                     previous_column=-1):
        # Manual sell button can only be activated after initiating a pump.
        self.manual_sell_btn = Button(master,
                                      text="Sell",
                                      state=DISABLED,
                                      command=self.on_manual_sell)
        self.manual_sell_btn.grid(row=previous_row + 1,
                                  column=previous_column + 1,
                                  sticky=W + E,
                                  padx=(3, 0))
        self.manual_sell_btn.config(highlightbackground=background_colour)

        self.pump_btn = Button(master, text="Pump", command=self.on_pump)
        self.pump_btn.grid(row=previous_row + 1,
                           column=previous_column + 2,
                           sticky=W + E,
                           padx=8)
        self.pump_btn.config(highlightbackground=background_colour,
                             state=DISABLED)

    def create_alt_ticker(self, master, previous_row=-1, previous_column=-1):
        ticker_lbl = Label(master, text="Ticker To Pump:")
        ticker_lbl.grid(row=previous_row + 1,
                        column=previous_column + 1,
                        columnspan=1,
                        sticky=E,
                        padx=(3, 0),
                        pady=(0, 8))
        ticker_lbl.config(bg=background_colour, fg=label_font_colour)

        self.ticker_entry = Entry(master, highlightthickness=0, bd=0, width=21)
        self.ticker_entry.config(borderwidth=2, relief=default_relief)
        self.ticker_entry.grid(row=previous_row + 1,
                               column=previous_column + 2,
                               pady=8)
        self.ticker_entry.bind('<Return>', self.on_pump_shortcut)

    def create_current_profit(self,
                              master,
                              previous_row=-1,
                              previous_column=-1):
        self.current_profit_str = StringVar()
        current_profit_lbl = Label(master, textvar=self.current_profit_str)
        current_profit_lbl.grid(row=previous_row + 1,
                                column=previous_column + 1,
                                columnspan=2,
                                sticky=W + E,
                                padx=3,
                                pady=(0, 3))
        current_profit_lbl.config(bg=background_colour, fg=label_font_colour)
        self.current_profit_str.set("Current Profit: 0%")

    def create_output_box(self, master, rightmost_column):
        self.pump_output = StringVar()
        console_lbl = Label(master,
                            textvar=self.pump_output,
                            borderwidth=2,
                            relief=default_relief,
                            anchor=N)
        console_lbl.grid(row=0,
                         column=rightmost_column + 1,
                         columnspan=1,
                         rowspan=14,
                         padx=(10, 0),
                         pady=0)
        console_lbl.config(width=50,
                           height=22,
                           bg="black",
                           font=Font(family="Courier", size=9),
                           fg="white")
        self.lines = 0

    def disable_pre_pump_options(self):
        # Change the buttons that can be clicked to prevent the user
        # from trying to pump multiple coins with one bot.
        self.manual_sell_btn.config(state=NORMAL)
        self.pump_btn.config(state=DISABLED)
        self.btc_to_use_spinbox.config(state=DISABLED)
        self.ticker_entry.config(state=DISABLED)
        self.auto_sell_spinbox.config(state=DISABLED)
        self.stop_loss_spinbox.config(state=DISABLED)
        self.api_key_entry.config(
            state=DISABLED)  # Comment out if hardcoding key
        self.api_secret_entry.config(
            state=DISABLED)  # Comment out if hardcoding secret
        self.api_connect_btn.config(state=DISABLED)
        self.entry_type_option_menu.config(state=DISABLED)
        self.fee_type_option_menu.config(state=DISABLED)

    def enable_pump_options(self):
        # Change the buttons that can be clicked to prevent the user
        # from trying to pump multiple coins with one bot.
        self.manual_sell_btn.config(state=DISABLED)
        self.pump_btn.config(state=NORMAL)
        self.btc_to_use_spinbox.config(state=NORMAL)
        self.ticker_entry.config(state=NORMAL)
        self.auto_sell_spinbox.config(state=NORMAL)
        self.stop_loss_spinbox.config(state=NORMAL)
        self.api_key_entry.config(
            state=NORMAL)  # Comment out if hardcoding key
        self.api_secret_entry.config(
            state=NORMAL)  # Comment out if hardcoding secret
        self.api_connect_btn.config(state=NORMAL)
        self.entry_type_option_menu.config(state=NORMAL)
        self.fee_type_option_menu.config(state=NORMAL)

    def set_available_btc_balance(self, btc_balance):
        self.pumper.btc_balance = btc_balance
        self.btc_balance_str.set("Available Balance: " +
                                 readable_btc_balance(btc_balance))

    def set_current_profit(self, current_profit):
        self.current_profit_str.set(
            "Current Profit: " +
            '{0:.3f}'.format(round(current_profit * Decimal(100), 3)) + "%")

    def write_to_console(self, line):
        self.lines += 1
        if self.lines > max_lines_in_console:
            i = self.pump_output.get().index('\n')
            self.pump_output.set(self.pump_output.get()[i + 1:] + "\n" + line)
        elif self.lines == 1:
            self.pump_output.set(line)
        else:
            self.pump_output.set(self.pump_output.get() + "\n" + line)

    #### Button Behaviour ####
    def on_pump(self):
        try:
            api = self.api
            btc_to_use = Decimal(self.btc_to_use_spinbox.get())
        except InvalidOperation:
            # The BTC to spend box is empty.
            self.write_to_console("Stop!")
            self.write_to_console("BTC to spend cannot be empty.")
            return
        except AttributeError:
            # There is no API object.
            self.write_to_console(
                "You need to connect to Binance before pumping.")
            return

        if btc_to_use >= minimum_trade:
            if btc_to_use <= self.pumper.btc_balance:
                target_profit_percentage = Decimal(
                    float(self.auto_sell_spinbox.get()) / 100.0)

                # Validate auto-sell and stop loss
                if target_profit_percentage <= Decimal(0):
                    self.write_to_console("Auto sell has to be positive.")
                    return
                if Decimal(self.stop_loss_spinbox.get()) >= Decimal(0):
                    self.write_to_console("Stop loss has to be negative.")
                    return

                ticker = self.ticker_entry.get().upper()

                # Empty strings are False in Python
                if ticker:
                    full_ticker = api.full_ticker_for(ticker)

                    try:
                        alt = self.api.get_ticker(symbol=full_ticker)
                    except BinanceAPIException, e:
                        logging.debug(str(e))
                        self.write_to_console("Invalid ticker.")
                        return

                    alt_value = Decimal(alt["askPrice"])

                    # Used in console output
                    decimal_points = minimum_decimals_in_quantity.get(
                        full_ticker, 0)
                    self.pumper.decimal_points_in_alt = decimal_points

                    self.pumper.set_up(btc_to_use, target_profit_percentage,
                                       alt_value, ticker)
                    if self.is_entry_market:
                        self.pumper.alt_holdings = api.market_buy(
                            self.pumper.btc_to_use, full_ticker,
                            self.is_using_bnb)
                        self.write_to_console(
                            "Bought " + readable_alt_balance(
                                decimal_points, pumper=self.pumper) +
                            " with " + readable_btc_balance(btc_to_use) + ".")
                    else:
                        highest_bid = Decimal(alt["bidPrice"])

                        if alt_value - highest_bid <= Decimal(0.00000001):
                            to_bid = highest_bid
                        else:
                            # Bid between the highest bid and the lowest ask for the best odds of being filled.
                            to_bid = (alt_value -
                                      highest_bid) / 2 + highest_bid
                            to_bid = Decimal(
                                floor(to_bid * Decimal(100000000.0))
                            ) / Decimal(100000000.0)
                        self.pumper.starting_alt_value = to_bid

                        expected = api.limit_buy(
                            btc_to_alt(btc_to_use, alt_value), pumper,
                            full_ticker, to_bid, self.is_using_bnb)
                        self.write_to_console("Buying " + readable_alt_balance(
                            decimal_points, alt_amount=expected, ticker=ticker
                        ) + " for " + readable_btc_balance(btc_to_use) + ".")
                        self.write_to_console(
                            "This is a limit order, it may not get filled.")

                    self.disable_pre_pump_options()
                    self.set_stop_loss()
                    self.start_monitoring_orderbook(full_ticker)
                else:
                    # The user is trying to trade with more than they actually have.
                    self.write_to_console("You did not enter a ticker.")
            else:
                # The user is trying to trade with more than they actually have.
                self.write_to_console("Stop!")
                self.write_to_console(
                    "You are trying to spend more BTC than you have.")
        else:
示例#51
0
class Visualiser(object):
    '''
    Generic Offline Visualiser. Subclasses need to be used that specify
    how to handle a data source.
    '''
    
    ### Public functions ###

    def __init__(self,
                 title="Visualisation",
                 width=400,
                 height=400,
                 recording=False,
                 recordPattern=None,
                 paused=False,
                 source=None):
        '''
        Constructor.

        Params:
        title: string - Title of the visualisation window
        width: int - Width of the visualisation window
        height: int - Height of the visualisation window
        recording: boolean - Start with recording enabled?
        recordPattern: string - Pattern for recorded images,
          e.g., cylinders%05g.png
        paused: boolean - Start with playback paused?
        source:- The data source to read.
          What is required here varies by visualiser.
        '''

        # Visualisation options
        self.vis_features = []
        self.vis_frame = 0
        self.vis_frameStep = 1
        self.vis_jumping = False
        self.vis_recording = recording
        self.vis_recordPattern = recordPattern
        self.vis_paused = paused
        self.vis_source = source

        # VTK structures
        self.vtk_cells = vtkCellArray()
        self.vtk_renderer = vtkRenderer()

        # Tk structures
        self.tk_root = Tk()
        self.tk_root.title(title)
        self.tk_root.grid_rowconfigure(0, weight=1)
        self.tk_root.grid_columnconfigure(0, weight=3)
        self.tk_root.bind('<Destroy>', self.destroyed)
        if not self.vis_paused: self.tk_root.after(100, self.animate)            

        self.tk_renderWidget = vtkTkRenderWidget(self.tk_root,
                                                 width=width,
                                                 height=height)
        self.tk_renderWidget.grid(row=0, column=0, sticky=N+S+E+W)
        self.tk_renderWidget.GetRenderWindow().AddRenderer(self.vtk_renderer)

        self.tk_featureFrame = Frame(self.tk_root)
        self.tk_featureFrame.grid(row=0, column=1, rowspan=2)
        Label(self.tk_featureFrame, text='Features:').grid(row=0, column=0)

        self.tk_controlFrame = Frame(self.tk_root)
        self.tk_controlFrame.grid(row=1, column=0)

        self.tk_quit = Button(self.tk_controlFrame, text="Quit",
                              command=self.shutdown)
        self.tk_quit.grid(row=0, column=0, columnspan=2)

        def pause():
            if self.vis_paused:
                self.tk_pause.config(text='Pause')
                self.tk_root.after(100, self.animate)
            else:
                self.tk_pause.config(text='Resume')
            self.vis_paused ^= True
        self.tk_pause = Button(self.tk_controlFrame, text="Pause", command=pause)
        self.tk_pause.grid(row=0, column=2, columnspan=2)

        if self.vis_recordPattern is not None:
            def record():
                if self.vis_recording:
                    self.tk_record.config(text='Start Recording')
                else:
                    self.tk_record.config(text='Stop Recording')
                self.vis_recording ^= True
            self.tk_record = Button(self.tk_controlFrame, text="Start Recording", command=record)
            self.tk_record.grid(row=0, column=4, columnspan=2)
            if self.vis_recording:
                self.tk_record.config(text="Stop Recording")

        def make_seek_button(label, column, frame):
            def jump():
                self.jumpTo(frame)
            b = Button(self.tk_controlFrame,
                       text=label,
                       command=jump)
            b.grid(row=1, column=column, sticky=W+E)
            return b
        self.tk_seek_start = make_seek_button("|<", 0, 0)
        self.tk_seek_back10 = make_seek_button("<<", 1,
                                               lambda: self.vis_frame - 10)
        self.tk_seek_back1 = make_seek_button("<", 2,
                                              lambda: self.vis_frame - 1)
        self.tk_seek_forward1 = make_seek_button(">", 3,
                                                 lambda: self.vis_frame + 1)
        self.tk_seek_forward10 = make_seek_button(">>", 4,
                                                  lambda: self.vis_frame + 10)
        self.tk_seek_end = make_seek_button(">|", 5,
                                            self.getMaxFrameNumber)

        Label(self.tk_controlFrame, text='Frame').grid(row=2, column=0,
                                                       sticky=W+E)
        def changeFrame(frame):
            if not self.vis_jumping:
                self.vis_jumping = True
                self.jumpTo(self.tk_frame.get())
                self.vis_jumping = False
        self.tk_frame = Scale(self.tk_controlFrame, command=changeFrame,
                              from_=0, to=0, orient=HORIZONTAL)
        self.tk_frame.grid(row=2, column=1, columnspan=2, sticky=W+E)

        Label(self.tk_controlFrame, text='Step').grid(row=2, column=3,
                                                     sticky=W+E)
        def changeFrameStep(step):
            self.vis_frameStep = int(step)
        self.tk_frameStep = Scale(self.tk_controlFrame, command=changeFrameStep,
                                  from_=1, to=1, orient=HORIZONTAL)
        self.tk_frameStep.grid(row=2, column=4, columnspan=2, sticky=W+E)

        self.setupGrid()

    def add_feature(self, feature):
        '''Add a feature to this visualiser'''
        self.vis_features.append(feature)
        feature.button(self.tk_featureFrame).grid(row=len(self.vis_features),
                                                  column=0, sticky=W+E)
        feature.visualiser = self

    def run(self):
        '''Start the visualiser'''
        self.redraw()
        self.tk_root.mainloop()

    ### Private funcitions ###

    def resetSliders(self):
        '''
        Recalculate the upper bound on the frame and frameStep
        sliders.
        '''
        maxFrame = self.getMaxFrameNumber()
        self.tk_frame.config(to=maxFrame)
        self.tk_frameStep.config(to=maxFrame)

    def jumpTo(self, frame):
        '''
        Jump to a given frame. If frame is a function, jump to the
        return value of frame().
        '''
        oldFrame = self.vis_frame
        if hasattr(frame, '__call__'):
            self.vis_frame = frame()
        else:
            self.vis_frame = frame

        maxFrame = self.getMaxFrameNumber()

        if self.vis_frame < 0:
            self.vis_frame = 0
        elif self.vis_frame > maxFrame:
            self.vis_frame = maxFrame
            self.vis_paused = True
            self.tk_pause.config(text='Resume')

        self.tk_frame.set(self.vis_frame)
        self.redraw(oldFrame != self.vis_frame)

    def redraw(self, update=False):
        self.resetSliders()
        for feature in [ f for f in self.vis_features if not f.dynamic ]:
            feature.draw(self.vtk_renderer)
        if update:
            for feature in [ f for f in self.vis_features if f.dynamic]:
                f.redraw(self.vtk_renderer)
        self.tk_renderWidget.GetRenderWindow().Render()
        self.tk_root.update_idletasks()

    ### Gui events ###

    def destroyed(self, event):
        if event.widget == self.tk_root:
            self.shutdown()

    def shutdown(self):
        self.tk_root.withdraw()
        self.tk_root.destroy()

    def animate(self):
        if not self.vis_paused:
            self.jumpTo(self.vis_frame + self.vis_frameStep)
            if self.vis_recording and self.vis_recordPattern is not None:
                self.save_image()
            self.tk_root.after(100, self.animate)

    def save_image(self):
        extmap = {'.jpg' : vtkJPEGWriter,
                  '.jpeg' : vtkJPEGWriter,
                  '.png' : vtkPNGWriter,
                  '.pnm' : vtkPNMWriter}
        _, ext = splitext(self.vis_recordPattern)
        try: writer = extmap[ext.lower()]()
        except KeyError:
            print 'ERROR: Can\'t handle %s extension. Recording disabled.' % ext
            self.vis_recordPattern = None
            return

        win = self.vtk_renderer.GetRenderWindow()
        w2i = vtkWindowToImageFilter()
        w2i.SetInput(win)
        w2i.Update()
        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(self.vis_recordPattern % self.vis_frame)
        win.Render()
        writer.Write()

    ### Things subclasses need to override ###

    def setupGrid(self):
        '''
        Populate the vtkCellArray instance at
        self.vtk_cells. Subclasses are required to override this
        function to read from their source as appropriate.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::setupGrid!')

    def getMaxFrameNumber(self):
        '''
        Return the maximum frame number. This will need to be defined
        by a subclass.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getMaxFrameNumber!')

    def getQuantityPoints(self, quantityName, dynamic=True, frameNumber=0):
        '''
        Return the points of a quantity at a given frame as a list
        [float]. Subclasses need to override this.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getQuantityPoints!')

    def getQuantityDict(self):
        '''
        Return the values of all quantities at a given time as a
        dictionary. Sublclasses need to override this.
        '''
        raise NotImplementedError('Subclass needs to override Visualiser::getQuantityDict!')
示例#52
0
class MyPoti(Tkinter.Tk):
    def __init__(self, master):
        Tkinter.Tk.__init__(self,master)
        self.master = master
        self.initialize()

    def initialize(self):
		#create canvas with specified size and add 
        w = Canvas(self, width=700, height=600)
        w.pack()
	
		#Declare two lists, one for front labels, anthoer for answer labels
        self.flabels = []
        self.alabels = []
		#Define x and y cordinates for lables
        self.flblx = 280
        self.flbly = 40
        self.alblx = 380
        self.albly = 40

		#Dummy list1
        self.my_list = []
	
		#Text to set on front lables
        self.str_label = ['POTI0', 'POTI1','POTI2','POTI3','POTI4']
	
		#Trigger to check if we want to program or pause
        self.running = True
        
		#Define environment varibales for input text fields
		#We can change/update this during runtime
        self.entry_pot_var = Tkinter.StringVar()
        self.entry_res_var = Tkinter.StringVar()
		
		#Define text areas for input onr for poti selection and one for resistence value
        self.entry_pot = Entry(self,textvariable=self.entry_pot_var, validate="focusout")
        self.entry_res = Entry(self,textvariable=self.entry_res_var, validate="focusout")

		#Initial text to display on above text fields
        self.entry_pot_var.set("Enter Pot selection")
        self.entry_res_var.set("Enter resistor value - 2000 to 100000") 

		#Set pot selection entry as highlighted
        self.entry_pot.selection_range(0,Tkinter.END)
        #self.entry_res.selection_range(0,Tkinter.END)

		#Set keyboard focus on pot text field
        self.entry_pot.focus_set()

		#Add pot text field to canvas
        self.entry_pot.pack()
		
		#ToDO
		#validate input for pot selection
        #self.entry_pot["validatecommand"] = (self.register(self.check_pot), "%P")
		
		#Add resistence text field to canvas
        self.entry_res.pack()
        
		#Create two text on the canvas with x and y coodrinates
        w.create_window(120, 40, window=self.entry_pot)
        w.create_window(120, 70,window=self.entry_res)

		#We declare 5 front lables and add them to canvas with x and y co ordinates
        for x in range(5):
            print self.str_label[x]
            self.label = Label(self, text=self.str_label[x], fg='white', bg='black')
            self.label.pack()
            self.flabels.append(self.label)

		#We declare 5 answer lables and add them to canvas with x and y co ordinates
        for x in range(5):
            self.label = Label(self, text='values', fg='white', bg='blue')
            self.label.pack()
            self.alabels.append(self.label)

		#Create front label in canvas
        for label in self.flabels:
            w.create_window(self.flblx,self.flbly,window=label)
            self.flbly = self.flbly + 19

		#Create answer label in cavas
        for label in self.alabels:
            w.create_window(self.alblx,self.albly,window=label)
            self.albly = self.albly + 20

		###
		#Button definitions
		###
		#Start button, and add callback to start_app function when this button is clicked
        self.start_button = Button(self, text="Set", height=2, width=10, command=self.start_app)
        self.start_button.pack()

		#Clear button, and add callback to clear_app function when this button is clicked
        self.clear_button = Button(self, text="Clear", height=2, width=10, command=self.clear_app, state="disabled")
        self.clear_button.pack()

		#Clear button, and add quit function of tkinter master when this button is clicked
        self.close_button = Button(self, text="Close", height=2, width=10, command=self.quit)
        self.close_button.pack()

        #Add buttons to canvas
        w.create_window(70, 170, window=self.start_button)
        w.create_window(190, 170, window=self.close_button)
        w.create_window(310, 170, window=self.clear_button)
	
	#Input validation for pot selection text field
    def check_pot(self, txt):
        print("POT validate!")
        #pot = self.entry_pot_var.get()
        if int(txt):
            if txt < 0 or txt > 4 :
                return False
            else:
                return True
        else:
            print("Not integer")
            self.entry_pot.focus_set()
            self.entry_pot.delete(0, END)

            return False
	#Input validation for resistence text field
    def check_res(self):
        print("Greetings!")

    def start_app(self):
        """ 
        Start the application when start button pressed
        """
        #Disable start button after presed
        global running
        self.running = True
        #self.start_button.config(state="disabled")
        self.clear_button.config(state="normal")
        print "Starting app!"
		#call update values function
        self.update_values()

    def clear_app(self):
        """
        Clear the answer lable fields 
        """
        print "Clear"
        global running
        self.running = False
        self.start_button.config(state="normal")
        self.clear_button.config(state="disabled")
        for i in range(5):
            self.alabels[i].config(text=str("values"))
		
		#Clear the text fields and set default vaule
        self.entry_pot_var.set("Enter Pot selection")
        self.entry_res_var.set("Enter resistor value - 2000 to 100000")
		
		#set keyboard focus
        self.entry_pot.focus_set()

    def stop_app(self):
        """
        Stop the app
        """
        print "Stopping"
        self.quit()

    def update_values(self):
        """
        Helper function to trigger label values after reading pot and res values
        """
        #if self.running:
        #    self.after(1000, self.update_values)

		#Read input value given for pot selection text field
        pot = self.entry_pot.get()
        ###if pot < 0 or pot > 4 : ###
        if int(pot) < 0 or int(pot) > 4 :
			tkMessageBox.showerror("wrong input","wrong input, pot selection must be 0-4, current selection: %s" % pot)
			return 
        res = self.entry_res.get()

		
		#Read input value given for  resistence text field
        res = self.entry_res.get()
		
		#call update text value function which converts values and send data to MCP
        self.update_text_values(pot, res)

    def update_text_values(self, pot, res):
        """
        Update the answer lables values with resistence
        """
        #resisitor to data conversion
        byte = 256
        local_pot = 100000
        local_res = 125
        #rw = int(res) * 1000
        #rw = int(rw) - int(local_res)
        #lev = float((rw * byte) / local_pot)
        #level =round(lev)
        #level = int(level)
        #level = int(res) - int(local_res)
        if float(res):
            level = float(res) - int(local_res)
        else:
            level = int(res) - int(local_res)
        level = (level * byte) / local_pot
		level = int(level)
        print(level)
        b = 0

        if int(pot) == 0:
            b = "0001" "0001" "{0:08b}".format(level)
        if int(pot) == 1:
            b = "0001" "0001" "{0:08b}" '{0:016b}'.format(level)
        if int(pot) == 2:
            b = "0001" "0001" "{0:08b}" '{0:032b}'.format(level)
        if int(pot) == 3:
            b = "0001" "0001" "{0:08b}" '{0:048b}'.format(level)
        if int(pot) == 4:
            b = "0001" "0001" "{0:08b}" '{0:064b}'.format(level)

        print b 
		#update answer label based on poti selection
        self.alabels[int(pot)].config(text=str(level))
		
        for x in b:
            GPIO.output(SPI_SDI_PIN, int(x))
            print(int(x))
            GPIO.output(SPI_CLK_PIN, True)
            GPIO.output(SPI_CLK_PIN, False)
            GPIO.output(SPI_CS_PIN, True)
        self.update_idletasks()
示例#53
0
class TopoConsole(tk.AppWindow,tk.TkParameterized):
    """
    Main window for the Tk-based GUI.
    """

    def _getmenubar(self):
        return self.master.menubar

    menubar = property(_getmenubar)

    def __getitem__(self,menu_name):
        """Allow dictionary-style access to the menu bar."""
        return self.menubar[menu_name]

    def __init__(self, root,exit_on_quit=True, **params):
        tk.AppWindow.__init__(self,root,status=True)
        tk.TkParameterized.__init__(self,root,**params)

        # Instead of displaying tracebacks on the commandline, try to display
        # them on the originating window.
        # CEBALERT: on destroy(), ought to revert this
        Tkinter.Misc._report_exception=_tkinter_report_exception

        self.exit_on_quit = exit_on_quit
        self.auto_refresh_panels = []
        self._init_widgets()
        self.title(topo.sim.name) # If -g passed *before* scripts on commandline, this is useless.
                                  # So topo.misc.commandline sets the title as its last action (if -g)



        # catch click on the 'x': offers choice to quit or not
        self.protocol("WM_DELETE_WINDOW",self.quit_topographica)


        ##########
        ### Make cascade menus open automatically on linux when the mouse
        ### is over the menu title.
        ### [Tkinter-discuss] Cascade menu issue
        ### http://mail.python.org/pipermail/tkinter-discuss/2006-August/000864.html
        if topo.tkgui.system_platform is 'linux':
            activate_cascade = """\
            if {[%W cget -type] != {menubar} && [%W type active] == {cascade}} {
                %W postcascade active
               }
            """
            self.bind_class("Menu", "<<MenuSelect>>", activate_cascade)
        ##########

        # Install warning and message handling
        from param.parameterized import Parameterized
        self.__orig_P_warning = Parameterized.warning
        #self.__orig_P_message = Parameterized.message
        type.__setattr__(Parameterized,'warning',self.gui_warning)
        #type.__setattr__(Parameterized,'message',self.gui_message)

    def gui_warning(self,msg,*args,**kw):
        stat = self.__get_status_bar()
        stat.warn(msg%args)
        self.__orig_P_warning(self,msg,*args,**kw)

    def gui_message(self,msg,*args,**kw):
        stat = self.__get_status_bar()
        stat.message(msg%args)
        self.__orig_P_message(self,*args)


    def title(self,t=None):
        newtitle = "Topographica"
        if t: newtitle+=": %s" % t
        tk.AppWindow.title(self,newtitle)


    def _init_widgets(self):

        ## CEBALERT: now we can have multiple operations at the same time,
        ## status bar could be improved to show all tasks?

        # CEBALERT
        self.messageBar = self.status

        self.some_area = DockManager(self)
        self.some_area.pack(fill="both", expand=1)

        ### Balloon, for pop-up help
        self.balloon = tk.Balloon(self.content)

        ### Top-level (native) menu bar
        #self.menubar = tk.ControllableMenu(self.content)
        self.configure(menu=self.menubar)

        #self.menu_balloon = Balloon(topo.tkgui.root)

        # no menubar in tile yet
        # http://news.hping.org/comp.lang.tcl.archive/4679.html

        self.__simulation_menu()
        self.__create_plots_menu()
        self.refresh_plots_menu()
        self.__help_menu()


        ### Running the simulation
        run_frame = Frame(self.content)
        run_frame.pack(side='top',fill='x',padx=4,pady=8)

        self.run_frame = run_frame

        Label(run_frame,text='Run for: ').pack(side=LEFT)

        self.run_for_var=DoubleVar()
        self.run_for_var.set(1.0)

        run_for = tk.TaggedSlider(run_frame,
                               variable=self.run_for_var,
                               tag_width=11,
                               slider_length=150,
                               bounds=(0,20000))
        self.balloon.bind(run_for,"Duration to run the simulation, e.g. 0.0500, 1.0, or 20000.")
        run_for.pack(side=LEFT,fill='x',expand=YES)
        run_for.tag.bind("<Return>",self.run_simulation)

        # When return is pressed, the TaggedSlider updates itself...but we also want to run
        # the simulation in this case.
        run_frame.optional_action=self.run_simulation

        go_button = Button(run_frame,text="Go",
                           command=self.run_simulation)
        go_button.pack(side=LEFT)

        self.balloon.bind(go_button,"Run the simulation for the specified duration.")

        self.step_button = Button(run_frame,text="Step",command=self.run_step)
        self.balloon.bind(self.step_button,"Run the simulation through the time at which the next events are processed.")
        self.step_button.pack(side=LEFT)

        self.sizeright()


    def __simulation_menu(self):
        """Add the simulation menu options to the menubar."""
        simulation_menu = ControllableMenu(self.menubar,tearoff=0)

        self.menubar.add_cascade(label='Simulation',menu=simulation_menu)

        simulation_menu.add_command(label='Run script',command=self.run_script)
        simulation_menu.add_command(label='Save script',command=self.save_script_repr)
        simulation_menu.add_command(label='Load snapshot',command=self.load_snapshot)
        simulation_menu.add_command(label='Save snapshot',command=self.save_snapshot)
        #simulation_menu.add_command(label='Reset',command=self.reset_network)
        simulation_menu.add_command(label='Test Pattern',command=self.open_test_pattern)

        simulation_menu.add_command(label='Model Editor',command=self.open_model_editor)
        simulation_menu.add_command(label='Quit',command=self.quit_topographica)



    def open_test_pattern(self):
        return open_plotgroup_panel(TestPattern)






    def __create_plots_menu(self):
        """
        Add the plot menu to the menubar, with Basic plots on the menu itself and
        others in cascades by category (the plots come from plotgroup_templates).
        """
        plots_menu = ControllableMenu(self.menubar,tearoff=0)
        self.menubar.add_cascade(label='Plots',menu=plots_menu)


    # CEBALERT: should split other menus in same way as plots (create/refresh)
    def refresh_plots_menu(self):
        plots_menu = self['Plots']
        plots_menu.delete(0,'end')

        # create menu entries, and get list of categories
        entries=OrderedDict() # keep the order of plotgroup_templates (which is also KL)
        categories = []
        for label,plotgroup in plotgroups.items():
            entries[label] = PlotsMenuEntry(plotgroup)
            categories.append(plotgroup.category)
        categories = sorted(set(categories))


        # The Basic category items appear on the menu itself.
        assert 'Basic' in categories, "'Basic' is the category for the standard Plots menu entries."
        for label,entry in entries.items():
            if entry.plotgroup.category=='Basic':
                    plots_menu.add_command(label=label,command=entry.__call__)

        categories.remove('Basic')

        plots_menu.add_separator()

        # Add the other categories to the menu as cascades, and the plots of each category to
        # their cascades.
        for category in categories:
            category_menu = ControllableMenu(plots_menu,tearoff=0)
            plots_menu.add_cascade(label=category,menu=category_menu)

            # could probably search more efficiently than this
            for label,entry in entries.items():
                if entry.plotgroup.category==category:
                    category_menu.add_command(label=label,command=entry.__call__)


        plots_menu.add_separator()

        plots_menu.add_command(label="Help",command=(lambda x=plotting_help_locations: self.open_location(x)))


    def __help_menu(self):
        """Add the help menu options."""

        help_menu = ControllableMenu(self.menubar,tearoff=0,name='help')
        self.menubar.add_cascade(label='Help',menu=help_menu)

        help_menu.add_command(label='About',command=self.new_about_window)
        help_menu.add_command(label="User Manual",
                              command=(lambda x=user_manual_locations: self.open_location(x)))

        help_menu.add_command(label="Tutorials",
                              command=(lambda x=tutorials_locations: self.open_location(x)))

        help_menu.add_command(label="Examples",
                              command=self.run_example_script)

        help_menu.add_command(label="Reference Manual",
                              command=(lambda x=reference_manual_locations: self.open_location(x)))

        help_menu.add_command(label="Topographica.org",
                              command=(lambda x=topo_www_locations: self.open_location(x)))

        help_menu.add_command(label="Python documentation",
                              command=(lambda x=python_doc_locations: self.open_location(x)))




    def quit_topographica(self,check=True,exit_status=0):
        """Quit topographica."""
        if not check or (check and tk.askyesno("Quit Topographica","Really quit?")):
            self.destroy()

            # matplotlib's tk backend starts its own Tk instances; we
            # need to close these ourselves (at least to avoid error
            # message about 'unusual termination' in Windows).
            try: # not that there should be an error, but just in case...
                import matplotlib._pylab_helpers
                for figman in matplotlib._pylab_helpers.Gcf.get_all_fig_managers():
                    figman.destroy()
            except:
                pass

            self.message("Quit selected%s" % ("; exiting" if  self.exit_on_quit else ""))

            # Workaround for obscure problem on some UNIX systems
            # as of 4/2007, probably including Fedora Core 5.
            # On these systems, if Topographica is started from a
            # bash prompt and then quit from the Tkinter GUI (as
            # opposed to using Ctrl-D in the terminal), the
            # terminal would suppress echoing of all future user
            # input.  stty sane restores the terminal to sanity,
            # but it is not clear why this is necessary.
            # For more info:
            # http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d0f33c8eb2e02d
            if topo.tkgui.system_platform=="linux" and os.getenv('EMACS')!='t':
                try: os.system("stty sane")
                except: pass
            # CEBALERT: re. above. Shouldn't we be able to store the
            # output of "stty --save" before starting the gui, then
            # ensure that when the gui exits (however badly it
            # happens) run "stty saved_settings"?

            # CEBALERT: there was no call to self.master.destroy()
            if  self.exit_on_quit:
                sys.exit(exit_status)


    def run_script(self):
        """
        Dialog to run a user-selected script

        The script is exec'd in __main__.__dict__ (i.e. as if it were specified on the commandline.)
        """
        script = askopenfilename(initialdir=normalize_path(),filetypes=SCRIPT_FILETYPES)
        if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('Run canceled')
        else:
            execfile(script,__main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)

    # CEBALERT: duplicates most of run_script()
    def run_example_script(self):


        script = askopenfilename(initialdir=topo.misc.genexamples.find_examples(),
                                 filetypes=SCRIPT_FILETYPES)

        if script in ('',(),None): # (representing the various ways no script was selected in the dialog)
            self.messageBar.response('No example opened')
        else:
            execfile(script,__main__.__dict__)
            self.messageBar.response('Ran ' + script)
            sim_name_from_filename(script)
            self.title(topo.sim.name)



    def save_script_repr(self):
        script_name = asksaveasfilename(filetypes=SCRIPT_FILETYPES,
                                        initialdir=normalize_path(),
                                        initialfile=topo.sim.basename()+"_script_repr.ty")

        if script_name:
            topo.command.save_script_repr(script_name)
            self.messageBar.response('Script saved to ' + script_name)


    def load_snapshot(self):
        """
        Dialog to load a user-selected snapshot (see topo.command.load_snapshot() ).
        """
        snapshot_name = askopenfilename(initialdir=normalize_path(),filetypes=SAVED_FILETYPES)

        if snapshot_name in ('',(),None):
            self.messageBar.response('No snapshot loaded.')
        else:
            self.messageBar.dynamicinfo('Loading snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.load_snapshot(snapshot_name)
            self.messageBar.response('Loaded snapshot ' + snapshot_name)
            self.title(topo.sim.name)

        self.auto_refresh()


    def save_snapshot(self):
        """
        Dialog to save a snapshot (see topo.command.save_snapshot() ).

        Adds the file extension .typ if not already present.
        """
        snapshot_name = asksaveasfilename(filetypes=SAVED_FILETYPES,
                                          initialdir=normalize_path(),
                                          initialfile=topo.sim.basename()+".typ")

        if snapshot_name in ('',(),None):
            self.messageBar.response('No snapshot saved.')
        else:
            if not snapshot_name.endswith('.typ'):
                snapshot_name = snapshot_name + SAVED_FILE_EXTENSION

            self.messageBar.dynamicinfo('Saving snapshot (may take some time)...')
            self.update_idletasks()
            topo.command.save_snapshot(snapshot_name)
            self.messageBar.response('Snapshot saved to ' + snapshot_name)


    def auto_refresh(self, update=True):
        """
        Refresh all windows in auto_refresh_panels.

        Panels can add and remove themselves to the list; those in the list
        will have their refresh() method called whenever this console's
        autorefresh() is called.
        """
        for win in self.auto_refresh_panels:
            win.refresh(update)

        self.set_step_button_state()
        self.update_idletasks()


    ### CEBERRORALERT: why doesn't updatecommand("display=True") for an
    ### orientation preference map measurement work with the
    ### hierarchical example? I guess this is the reason I thought the
    ### updating never worked properly (or I really did break it
    ### recently - or I'm confused)...
    def refresh_activity_windows(self):
        """
        Update any windows with a plotgroup_key ending in 'Activity'.

        Used primarily for debugging long scripts that present a lot of activity patterns.
        """
        for win in self.auto_refresh_panels:
            if re.match('.*Activity$',win.plotgroup.name):
                win.refresh()
                self.update_idletasks()


    def open_model_editor(self):
        """Start the Model editor."""
        return ModelEditor(self)


    def new_about_window(self):
        win = tk.AppWindow(self)
        win.withdraw()
        win.title("About Topographica")
        text = Label(win,text=topo.about(display=False),justify=LEFT)
        text.pack(side=LEFT)
        win.deiconify()
        #self.messageBar.message('state', 'OK')

    def open_location(self, locations):
        """
        Try to open one of the specified locations in a new window of the default
        browser. See webbrowser module for more information.

        locations should be a tuple.
        """
        # CB: could have been a list. This is only here because if locations is set
        # to a string, it will loop over the characters of the string.
        assert isinstance(locations,tuple),"locations must be a tuple."

        for location in locations:
            try:
                existing_location = resolve_path(location)
                webbrowser.open(existing_location,new=2,autoraise=True)
                self.messageBar.response('Opened local file '+existing_location+' in browser.')
                return ###
            except:
                pass

        for location in locations:
            if location.startswith('http'):
                try:
                    webbrowser.open(location,new=2,autoraise=True)
                    self.messageBar.response('Opened remote location '+location+' in browser.')
                    return ###
                except:
                    pass

        self.messageBar.response("Could not open any of %s in a browser."%locations)


    # CEBALERT: need to take care of removing old messages automatically?
    # (Otherwise callers might always have to pass 'ok'.)
    def status_message(self,m):
        self.messageBar.response(m)


    def run_simulation(self,event=None): # event=None allows use as callback
        """
        Run the simulation for the duration specified in the
        'run for' taggedslider.
        """
        fduration = self.run_for_var.get()
        self.open_progress_window(timer=topo.sim.timer)
        topo.sim.run_and_time(fduration)
        self.auto_refresh()


    # CEBERRORALERT: Step button does strange things at time==0.
    # E.g. for lissom_oo_or, nothing appears to happen. For
    # hierarchical, runs to time==10.
    def run_step(self):

        if not topo.sim.events:
            # JP: step button should be disabled if there are no events,
            # but just in case...
            return

        # JPALERT: This should really use .run_and_time() but it doesn't support
        # run(until=...)
        topo.sim.run(until=topo.sim.events[0].time)
        self.auto_refresh()

    def set_step_button_state(self):
        if topo.sim.events:
            self.step_button.config(state=NORMAL)
        else:
            self.step_button.config(state=DISABLED)


    def __get_status_bar(self,i=2):
        # Hack to find appropriate status bar: Go back through frames
        # until a widget with a status bar is found, and return it.
        try:
            while True:
                f = sys._getframe(i)
                if hasattr(f,'f_locals'):
                    if 'self' in f.f_locals:
                        o = f.f_locals['self']
                        # (temporary hack til ScrolledFrame cleaned up)
                        if o.__class__.__name__!='ScrolledFrame':
                            if hasattr(o,'messageBar'):
                                return o.messageBar
                            elif hasattr(o,'status'):
                                return o.status
                    i+=1
        except:
            pass

        #print "GUI INTERNAL WARNING: failed to determine window on which to display message."
        return self.messageBar


    def open_progress_window(self,timer,title=None):
        """
        Provide a convenient link to progress bars.
        """
        stat = self.__get_status_bar()
        return stat.open_progress_window(timer=timer,sim=topo.sim)
示例#54
0
class wm_seg:
    """
    Simple GUI application
    If the application inside a container, automatic updates are removed.

    The application uses two frames (tabs):
    - training
    - testing
    """
    def __init__(self, master, container):

        self.master = master
        master.title("nicMSlesions")

        # running on a container
        self.container = container

        # gui attributes
        self.path = os.getcwd()
        self.default_config = None
        self.user_config = None
        self.current_folder = os.getcwd()
        self.list_train_pretrained_nets = []
        self.list_test_nets = []
        self.version = __version__
        if self.container is False:
            # version_number
            self.commit_version = subprocess.check_output(
                ['git', 'rev-parse', 'HEAD'])

        # queue and thread parameters. All processes are embedded
        # inside threads to avoid freezing the application
        self.train_task = None
        self.test_task = None
        self.test_queue = Queue.Queue()
        self.train_queue = Queue.Queue()

        # --------------------------------------------------
        # parameters. Mostly from the config/*.cfg files
        # --------------------------------------------------

        # data parameters
        self.param_training_folder = StringVar()
        self.param_test_folder = StringVar()
        self.param_FLAIR_tag = StringVar()
        self.param_T1_tag = StringVar()
        self.param_MOD3_tag = StringVar()
        self.param_MOD4_tag = StringVar()
        self.param_mask_tag = StringVar()
        self.param_model_tag = StringVar()
        self.param_register_modalities = BooleanVar()
        self.param_skull_stripping = BooleanVar()
        self.param_denoise = BooleanVar()
        self.param_denoise_iter = IntVar()
        self.param_save_tmp = BooleanVar()
        self.param_debug = BooleanVar()

        # train parameters
        self.param_net_folder = os.path.join(self.current_folder, 'nets')
        self.param_use_pretrained_model = BooleanVar()
        self.param_pretrained_model = StringVar()
        self.param_inference_model = StringVar()
        self.param_num_layers = IntVar()
        self.param_net_name = StringVar()
        self.param_net_name.set('None')
        self.param_balanced_dataset = StringVar()
        self.param_fract_negatives = DoubleVar()

        # model parameters
        self.param_pretrained = None
        self.param_min_th = DoubleVar()
        self.param_patch_size = IntVar()
        self.param_weight_paths = StringVar()
        self.param_load_weights = BooleanVar()
        self.param_train_split = DoubleVar()
        self.param_max_epochs = IntVar()
        self.param_patience = IntVar()
        self.param_batch_size = IntVar()
        self.param_net_verbose = IntVar()
        self.param_t_bin = DoubleVar()
        self.param_l_min = IntVar()
        self.param_min_error = DoubleVar()
        self.param_mode = BooleanVar()
        self.param_gpu_number = IntVar()

        # load the default configuration from the conf file
        self.load_default_configuration()

        # self frame (tabbed notebook)
        self.note = Notebook(self.master)
        self.note.pack()

        os.system('cls' if platform.system() == 'Windows' else 'clear')
        print "##################################################"
        print "# ------------                                   #"
        print "# nicMSlesions                                   #"
        print "# ------------                                   #"
        print "# MS WM lesion segmentation                      #"
        print "#                                                #"
        print "# -------------------------------                #"
        print "# (c) Sergi Valverde 2018                        #"
        print "# Neuroimage Computing Group                     #"
        print "# -------------------------------                #"
        print "##################################################\n"
        print "Please select options for training or inference in the menu..."

        # --------------------------------------------------
        # training tab
        # --------------------------------------------------
        self.train_frame = Frame()
        self.note.add(self.train_frame, text="Training")
        self.test_frame = Frame()
        self.note.add(self.test_frame, text="Inference")

        # label frames
        cl_s = 5
        self.tr_frame = LabelFrame(self.train_frame, text="Training images:")
        self.tr_frame.grid(row=0,
                           columnspan=cl_s,
                           sticky='WE',
                           padx=5,
                           pady=5,
                           ipadx=5,
                           ipady=5)
        self.model_frame = LabelFrame(self.train_frame, text="CNN model:")
        self.model_frame.grid(row=5,
                              columnspan=cl_s,
                              sticky='WE',
                              padx=5,
                              pady=5,
                              ipadx=5,
                              ipady=5)

        # training options
        self.inFolderLbl = Label(self.tr_frame, text="Training folder:")
        self.inFolderLbl.grid(row=0, column=0, sticky='E', padx=5, pady=2)
        self.inFolderTxt = Entry(self.tr_frame)
        self.inFolderTxt.grid(row=0,
                              column=1,
                              columnspan=5,
                              sticky="W",
                              pady=3)
        self.inFileBtn = Button(self.tr_frame,
                                text="Browse ...",
                                command=self.load_training_path)
        self.inFileBtn.grid(row=0,
                            column=5,
                            columnspan=1,
                            sticky='W',
                            padx=5,
                            pady=1)

        self.optionsBtn = Button(self.tr_frame,
                                 text="Other options",
                                 command=self.parameter_window)
        self.optionsBtn.grid(row=0,
                             column=10,
                             columnspan=1,
                             sticky="W",
                             padx=(100, 1),
                             pady=1)

        # setting input modalities: FLAIR + T1 are mandatory
        # Mod 3 / 4 are optional
        self.flairTagLbl = Label(self.tr_frame, text="FLAIR tag:")
        self.flairTagLbl.grid(row=1, column=0, sticky='E', padx=5, pady=2)
        self.flairTxt = Entry(self.tr_frame, textvariable=self.param_FLAIR_tag)
        self.flairTxt.grid(row=1, column=1, columnspan=1, sticky="W", pady=1)

        self.t1TagLbl = Label(self.tr_frame, text="T1 tag:")
        self.t1TagLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2)
        self.t1Txt = Entry(self.tr_frame, textvariable=self.param_T1_tag)
        self.t1Txt.grid(row=2, column=1, columnspan=1, sticky="W", pady=1)

        self.mod3TagLbl = Label(self.tr_frame, text="mod 3 tag:")
        self.mod3TagLbl.grid(row=3, column=0, sticky='E', padx=5, pady=2)
        self.mod3Txt = Entry(self.tr_frame, textvariable=self.param_MOD3_tag)
        self.mod3Txt.grid(row=3, column=1, columnspan=1, sticky="W", pady=1)

        self.mod4TagLbl = Label(self.tr_frame, text="mod 4 tag:")
        self.mod4TagLbl.grid(row=4, column=0, sticky='E', padx=5, pady=2)
        self.mod4Txt = Entry(self.tr_frame, textvariable=self.param_MOD4_tag)
        self.mod4Txt.grid(row=4, column=1, columnspan=1, sticky="W", pady=1)

        self.maskTagLbl = Label(self.tr_frame, text="MASK tag:")
        self.maskTagLbl.grid(row=5, column=0, sticky='E', padx=5, pady=2)
        self.maskTxt = Entry(self.tr_frame, textvariable=self.param_mask_tag)
        self.maskTxt.grid(row=5, column=1, columnspan=1, sticky="W", pady=1)

        # model options
        self.modelTagLbl = Label(self.model_frame, text="Model name:")
        self.modelTagLbl.grid(row=6, column=0, sticky='E', padx=5, pady=2)
        self.modelTxt = Entry(self.model_frame,
                              textvariable=self.param_net_name)
        self.modelTxt.grid(row=6, column=1, columnspan=1, sticky="W", pady=1)

        self.checkPretrain = Checkbutton(self.model_frame,
                                         text="use pretrained",
                                         var=self.param_use_pretrained_model)
        self.checkPretrain.grid(row=6, column=3, padx=5, pady=5)

        self.update_pretrained_nets()

        self.pretrainTxt = OptionMenu(self.model_frame,
                                      self.param_pretrained_model,
                                      *self.list_train_pretrained_nets)
        self.pretrainTxt.grid(row=6, column=5, sticky='E', padx=5, pady=5)

        # START button links
        self.trainingBtn = Button(self.train_frame,
                                  state='disabled',
                                  text="Start training",
                                  command=self.train_net)
        self.trainingBtn.grid(row=7, column=0, sticky='W', padx=1, pady=1)

        # --------------------------------------------------
        # inference tab
        # --------------------------------------------------
        self.tt_frame = LabelFrame(self.test_frame, text="Inference images:")
        self.tt_frame.grid(row=0,
                           columnspan=cl_s,
                           sticky='WE',
                           padx=5,
                           pady=5,
                           ipadx=5,
                           ipady=5)
        self.test_model_frame = LabelFrame(self.test_frame, text="CNN model:")
        self.test_model_frame.grid(row=5,
                                   columnspan=cl_s,
                                   sticky='WE',
                                   padx=5,
                                   pady=5,
                                   ipadx=5,
                                   ipady=5)

        # testing options
        self.test_inFolderLbl = Label(self.tt_frame, text="Testing folder:")
        self.test_inFolderLbl.grid(row=0, column=0, sticky='E', padx=5, pady=2)
        self.test_inFolderTxt = Entry(self.tt_frame)
        self.test_inFolderTxt.grid(row=0,
                                   column=1,
                                   columnspan=5,
                                   sticky="W",
                                   pady=3)
        self.test_inFileBtn = Button(self.tt_frame,
                                     text="Browse ...",
                                     command=self.load_testing_path)
        self.test_inFileBtn.grid(row=0,
                                 column=5,
                                 columnspan=1,
                                 sticky='W',
                                 padx=5,
                                 pady=1)

        self.test_optionsBtn = Button(self.tt_frame,
                                      text="Other options",
                                      command=self.parameter_window)
        self.test_optionsBtn.grid(row=0,
                                  column=10,
                                  columnspan=1,
                                  sticky="W",
                                  padx=(100, 1),
                                  pady=1)

        self.test_flairTagLbl = Label(self.tt_frame, text="FLAIR tag:")
        self.test_flairTagLbl.grid(row=1, column=0, sticky='E', padx=5, pady=2)
        self.test_flairTxt = Entry(self.tt_frame,
                                   textvariable=self.param_FLAIR_tag)
        self.test_flairTxt.grid(row=1,
                                column=1,
                                columnspan=1,
                                sticky="W",
                                pady=1)

        self.test_t1TagLbl = Label(self.tt_frame, text="T1 tag:")
        self.test_t1TagLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2)
        self.test_t1Txt = Entry(self.tt_frame, textvariable=self.param_T1_tag)
        self.test_t1Txt.grid(row=2, column=1, columnspan=1, sticky="W", pady=1)

        self.test_mod3TagLbl = Label(self.tt_frame, text="mod 3 tag:")
        self.test_mod3TagLbl.grid(row=3, column=0, sticky='E', padx=5, pady=2)
        self.test_mod3Txt = Entry(self.tt_frame,
                                  textvariable=self.param_MOD3_tag)
        self.test_mod3Txt.grid(row=3,
                               column=1,
                               columnspan=1,
                               sticky="W",
                               pady=1)

        self.test_mod4TagLbl = Label(self.tt_frame, text="mod 4 tag:")
        self.test_mod4TagLbl.grid(row=4, column=0, sticky='E', padx=5, pady=2)
        self.test_mod4Txt = Entry(self.tt_frame,
                                  textvariable=self.param_MOD4_tag)
        self.test_mod4Txt.grid(row=4,
                               column=1,
                               columnspan=1,
                               sticky="W",
                               pady=1)

        self.test_pretrainTxt = OptionMenu(self.test_model_frame,
                                           self.param_inference_model,
                                           *self.list_test_nets)

        self.param_inference_model.set('None')
        self.test_pretrainTxt.grid(row=5, column=0, sticky='E', padx=5, pady=5)

        # START button links cto docker task
        self.inferenceBtn = Button(self.test_frame,
                                   state='disabled',
                                   text="Start inference",
                                   command=self.infer_segmentation)
        self.inferenceBtn.grid(row=7, column=0, sticky='W', padx=1, pady=1)

        # train / test ABOUT button
        self.train_aboutBtn = Button(self.train_frame,
                                     text="about",
                                     command=self.about_window)
        self.train_aboutBtn.grid(row=7,
                                 column=4,
                                 sticky='E',
                                 padx=(1, 1),
                                 pady=1)

        self.test_aboutBtn = Button(self.test_frame,
                                    text="about",
                                    command=self.about_window)
        self.test_aboutBtn.grid(row=7,
                                column=4,
                                sticky='E',
                                padx=(1, 1),
                                pady=1)

        # Processing state
        self.process_indicator = StringVar()
        self.process_indicator.set(' ')
        self.label_indicator = Label(master,
                                     textvariable=self.process_indicator)
        self.label_indicator.pack(side="left")

        # Closing processing events is implemented via
        # a master protocol
        self.master.protocol("WM_DELETE_WINDOW", self.close_event)

    def parameter_window(self):
        """
        Setting other parameters using an emerging window
        CNN parameters, CUDA device, post-processing....

        """
        t = Toplevel(self.master)
        t.wm_title("Other parameters")

        # data parameters
        t_data = LabelFrame(t, text="data options:")
        t_data.grid(row=0, sticky="WE")
        checkPretrain = Checkbutton(t_data,
                                    text="Register modalities",
                                    var=self.param_register_modalities)
        checkPretrain.grid(row=0, sticky='W')
        checkSkull = Checkbutton(t_data,
                                 text="Skull-strip modalities",
                                 var=self.param_skull_stripping)
        checkSkull.grid(row=1, sticky="W")
        checkDenoise = Checkbutton(t_data,
                                   text="Denoise masks",
                                   var=self.param_denoise)
        checkDenoise.grid(row=2, sticky="W")

        denoise_iter_label = Label(t_data,
                                   text=" Denoise iter:               ")
        denoise_iter_label.grid(row=3, sticky="W")
        denoise_iter_entry = Entry(t_data,
                                   textvariable=self.param_denoise_iter)
        denoise_iter_entry.grid(row=3, column=1, sticky="E")

        check_tmp = Checkbutton(t_data,
                                text="Save tmp files",
                                var=self.param_save_tmp)
        check_tmp.grid(row=4, sticky="W")
        checkdebug = Checkbutton(t_data,
                                 text="Debug mode",
                                 var=self.param_debug)
        checkdebug.grid(row=5, sticky="W")

        # model parameters
        t_model = LabelFrame(t, text="Model:")
        t_model.grid(row=5, sticky="EW")

        maxepochs_label = Label(t_model, text="Max epochs:                  ")
        maxepochs_label.grid(row=6, sticky="W")
        maxepochs_entry = Entry(t_model, textvariable=self.param_max_epochs)
        maxepochs_entry.grid(row=6, column=1, sticky="E")

        trainsplit_label = Label(t_model, text="Validation %:           ")
        trainsplit_label.grid(row=7, sticky="W")
        trainsplit_entry = Entry(t_model, textvariable=self.param_train_split)
        trainsplit_entry.grid(row=7, column=1, sticky="E")

        batchsize_label = Label(t_model, text="Test batch size:")
        batchsize_label.grid(row=8, sticky="W")
        batchsize_entry = Entry(t_model, textvariable=self.param_batch_size)
        batchsize_entry.grid(row=8, column=1, sticky="E")

        mode_label = Label(t_model, text="Verbosity:")
        mode_label.grid(row=9, sticky="W")
        mode_entry = Entry(t_model, textvariable=self.param_net_verbose)
        mode_entry.grid(row=9, column=1, sticky="E")

        #gpu_mode = Checkbutton(t_model,
        #                         text="GPU:",
        #                         var=self.param_mode)
        #gpu_mode.grid(row=10, sticky="W")

        gpu_number = Label(t_model, text="GPU number:")
        gpu_number.grid(row=10, sticky="W")
        gpu_entry = Entry(t_model, textvariable=self.param_gpu_number)
        gpu_entry.grid(row=10, column=1, sticky="W")

        # training parameters
        tr_model = LabelFrame(t, text="Training:")
        tr_model.grid(row=12, sticky="EW")

        balanced_label = Label(tr_model, text="Balanced dataset:    ")
        balanced_label.grid(row=13, sticky="W")
        balanced_entry = Entry(tr_model,
                               textvariable=self.param_balanced_dataset)
        balanced_entry.grid(row=13, column=1, sticky="E")

        fraction_label = Label(tr_model, text="Fraction negative/positives: ")
        fraction_label.grid(row=14, sticky="W")
        fraction_entry = Entry(tr_model,
                               textvariable=self.param_fract_negatives)
        fraction_entry.grid(row=14, column=1, sticky="E")

        # postprocessing parameters
        t_post = LabelFrame(t, text="Post-processing:  ")
        t_post.grid(row=15, sticky="EW")
        t_bin_label = Label(t_post, text="Out probability th:      ")
        t_bin_label.grid(row=16, sticky="W")
        t_bin_entry = Entry(t_post, textvariable=self.param_t_bin)
        t_bin_entry.grid(row=16, column=1, sticky="E")

        l_min_label = Label(t_post, text="Min out region size:         ")
        l_min_label.grid(row=17, sticky="W")
        l_min_entry = Entry(t_post, textvariable=self.param_l_min)
        l_min_entry.grid(row=17, column=1, sticky="E")

        vol_min_label = Label(t_post, text="Min vol error (ml):   ")
        vol_min_label.grid(row=18, sticky="W")
        vol_min_entry = Entry(t_post, textvariable=self.param_min_error)
        vol_min_entry.grid(row=18, column=1, sticky="E")

    def load_default_configuration(self):
        """
        load the default configuration from /config/default.cfg
        This method assign each of the configuration parameters to
        class attributes
        """

        default_config = ConfigParser.SafeConfigParser()
        default_config.read(os.path.join(self.path, 'config', 'default.cfg'))

        # dastaset parameters
        self.param_training_folder.set(
            default_config.get('database', 'train_folder'))
        self.param_test_folder.set(
            default_config.get('database', 'inference_folder'))
        self.param_FLAIR_tag.set(default_config.get('database', 'flair_tags'))
        self.param_T1_tag.set(default_config.get('database', 't1_tags'))
        self.param_MOD3_tag.set(default_config.get('database', 'mod3_tags'))
        self.param_MOD4_tag.set(default_config.get('database', 'mod4_tags'))
        self.param_mask_tag.set(default_config.get('database', 'roi_tags'))
        self.param_register_modalities.set(
            default_config.get('database', 'register_modalities'))
        self.param_denoise.set(default_config.get('database', 'denoise'))
        self.param_denoise_iter.set(
            default_config.getint('database', 'denoise_iter'))
        self.param_skull_stripping.set(
            default_config.get('database', 'skull_stripping'))
        self.param_save_tmp.set(default_config.get('database', 'save_tmp'))
        self.param_debug.set(default_config.get('database', 'debug'))

        # train parameters
        self.param_use_pretrained_model.set(
            default_config.get('train', 'full_train'))
        self.param_pretrained_model.set(
            default_config.get('train', 'pretrained_model'))
        self.param_inference_model.set("      ")
        self.param_balanced_dataset.set(
            default_config.get('train', 'balanced_training'))
        self.param_fract_negatives.set(
            default_config.getfloat('train', 'fraction_negatives'))

        # model parameters
        self.param_net_folder = os.path.join(self.current_folder, 'nets')
        self.param_net_name.set(default_config.get('model', 'name'))
        self.param_train_split.set(
            default_config.getfloat('model', 'train_split'))
        self.param_max_epochs.set(default_config.getint('model', 'max_epochs'))
        self.param_patience.set(default_config.getint('model', 'patience'))
        self.param_batch_size.set(default_config.getint('model', 'batch_size'))
        self.param_net_verbose.set(default_config.get('model', 'net_verbose'))
        self.param_gpu_number.set(default_config.getint('model', 'gpu_number'))
        # self.param_mode.set(default_config.get('model', 'gpu_mode'))

        # post-processing
        self.param_l_min.set(default_config.getint('postprocessing', 'l_min'))
        self.param_t_bin.set(default_config.getfloat('postprocessing',
                                                     't_bin'))
        self.param_min_error.set(
            default_config.getfloat('postprocessing', 'min_error'))

    def write_user_configuration(self):
        """
        write the configuration into config/configuration.cfg
        """
        user_config = ConfigParser.RawConfigParser()

        # dataset parameters
        user_config.add_section('database')
        user_config.set('database', 'train_folder',
                        self.param_training_folder.get())
        user_config.set('database', 'inference_folder',
                        self.param_test_folder.get())
        user_config.set('database', 'flair_tags', self.param_FLAIR_tag.get())
        user_config.set('database', 't1_tags', self.param_T1_tag.get())
        user_config.set('database', 'mod3_tags', self.param_MOD3_tag.get())
        user_config.set('database', 'mod4_tags', self.param_MOD4_tag.get())
        user_config.set('database', 'roi_tags', self.param_mask_tag.get())

        user_config.set('database', 'register_modalities',
                        self.param_register_modalities.get())
        user_config.set('database', 'denoise', self.param_denoise.get())
        user_config.set('database', 'denoise_iter',
                        self.param_denoise_iter.get())
        user_config.set('database', 'skull_stripping',
                        self.param_skull_stripping.get())
        user_config.set('database', 'save_tmp', self.param_save_tmp.get())
        user_config.set('database', 'debug', self.param_debug.get())

        # train parameters
        user_config.add_section('train')
        user_config.set('train', 'full_train',
                        not (self.param_use_pretrained_model.get()))
        user_config.set('train', 'pretrained_model',
                        self.param_pretrained_model.get())
        user_config.set('train', 'balanced_training',
                        self.param_balanced_dataset.get())
        user_config.set('train', 'fraction_negatives',
                        self.param_fract_negatives.get())
        # model parameters
        user_config.add_section('model')
        user_config.set('model', 'name', self.param_net_name.get())
        user_config.set('model', 'pretrained', self.param_pretrained)
        user_config.set('model', 'train_split', self.param_train_split.get())
        user_config.set('model', 'max_epochs', self.param_max_epochs.get())
        user_config.set('model', 'patience', self.param_patience.get())
        user_config.set('model', 'batch_size', self.param_batch_size.get())
        user_config.set('model', 'net_verbose', self.param_net_verbose.get())
        # user_config.set('model', 'gpu_mode', self.param_mode.get())
        user_config.set('model', 'gpu_number', self.param_gpu_number.get())

        # postprocessing parameters
        user_config.add_section('postprocessing')
        user_config.set('postprocessing', 't_bin', self.param_t_bin.get())
        user_config.set('postprocessing', 'l_min', self.param_l_min.get())
        user_config.set('postprocessing', 'min_error',
                        self.param_min_error.get())

        # Writing our configuration file to 'example.cfg'
        with open(os.path.join(self.path, 'config', 'configuration.cfg'),
                  'wb') as configfile:
            user_config.write(configfile)

    def load_training_path(self):
        """
        Select training path from disk and write it.
        If the app is run inside a container,
        link the iniitaldir with /data
        """
        initialdir = '/data' if self.container else os.getcwd()
        fname = askdirectory(initialdir=initialdir)
        if fname:
            try:
                self.param_training_folder.set(fname)
                self.inFolderTxt.delete(0, END)
                self.inFolderTxt.insert(0, self.param_training_folder.get())
                self.trainingBtn['state'] = 'normal'
            except:
                pass

    def load_testing_path(self):
        """
        Selecet the inference path from disk and write it
        If the app is run inside a container,
        link the iniitaldir with /data
        """
        initialdir = '/data' if self.container else os.getcwd()
        fname = askdirectory(initialdir=initialdir)
        if fname:
            try:
                self.param_test_folder.set(fname)
                self.test_inFolderTxt.delete(0, END)
                self.test_inFolderTxt.insert(0, self.param_test_folder.get())
                self.inferenceBtn['state'] = 'normal'
            except:
                pass

    def update_pretrained_nets(self):
        """
        get a list of the  different net configuration present in the system.
        Each model configuration is represented by a folder containing the network
        weights for each of the networks. The baseline net config is always
        included by default

        """
        folders = os.listdir(self.param_net_folder)
        self.list_train_pretrained_nets = folders
        self.list_test_nets = folders

    def write_to_console(self, txt):
        """
        to doc:
        important method
        """
        self.command_out.insert(END, str(txt))

    def write_to_test_console(self, txt):
        """
        to doc:
        important method
        """
        self.test_command_out.insert(END, str(txt))

    def infer_segmentation(self):
        """
        Method implementing the inference process:
        - Check network selection
        - write the configuration to disk
        - Run the process on a new thread
        """

        if self.param_inference_model.get() == 'None':
            print "ERROR: Please, select a network model before starting...\n"
            return
        if self.test_task is None:
            self.inferenceBtn.config(state='disabled')
            self.param_net_name.set(self.param_inference_model.get())
            self.param_use_pretrained_model.set(False)
            self.write_user_configuration()
            print "\n-----------------------"
            print "Running configuration:"
            print "-----------------------"
            print "Inference model:", self.param_model_tag.get()
            print "Inference folder:", self.param_test_folder.get(), "\n"

            print "Method info:"
            print "------------"
            self.test_task = ThreadedTask(self.write_to_test_console,
                                          self.test_queue,
                                          mode='testing')
            self.test_task.start()
            self.master.after(100, self.process_container_queue)

    def train_net(self):
        """
        Method implementing the training process:
        - write the configuration to disk
        - Run the process on a new thread
        """

        if self.param_net_name.get() == 'None':
            print "ERROR: Please, define network name before starting...\n"
            return

        self.trainingBtn['state'] = 'disable'

        if self.train_task is None:
            self.trainingBtn.update()
            self.write_user_configuration()
            print "\n-----------------------"
            print "Running configuration:"
            print "-----------------------"
            print "Train model:", self.param_net_name.get()
            print "Training folder:", self.param_training_folder.get(), "\n"

            print "Method info:"
            print "------------"

            self.train_task = ThreadedTask(self.write_to_console,
                                           self.test_queue,
                                           mode='training')
            self.train_task.start()
            self.master.after(100, self.process_container_queue)

    def check_update(self):
        """
            check update version and propose to download it if differnt
            So far, a rudimentary mode is used to check the last version.
            """

        # I have to discard possible local changes :(
        print "---------------------------------------"
        print "Updating software"
        print "current version:", self.commit_version

        remote_commit = subprocess.check_output(['git', 'stash'])
        remote_commit = subprocess.check_output(['git', 'fetch'])
        remote_commit = subprocess.check_output(
            ['git', 'rev-parse', 'origin/master'])

        if remote_commit != self.commit_version:
            proc = subprocess.check_output(['git', 'pull', 'origin', 'master'])
            self.check_link.config(text="Updated")
            self.commit_version = remote_commit
            print "updated version:", self.commit_version
        else:
            print "This software is already in the latest version"
        print "---------------------------------------"

    def about_window(self):
        """
        Window showing information about the software and
        version number, including auto-update. If the application
        is run from a container, then auto-update is disabled
        """
        def callback(event):
            """
            open webbrowser when clicking links
            """
            webbrowser.open_new(event.widget.cget("text"))

        # main window
        t = Toplevel(self.master, width=500, height=500)
        t.wm_title("About")

        # NIC logo + name
        title = Label(t,
                      text="nicMSlesions v" + self.version + "\n"
                      "Multiple Sclerosis White Matter Lesion Segmentation")
        title.grid(row=2, column=1, padx=20, pady=10)
        img = ImageTk.PhotoImage(Image.open('./logonic.png'))
        imglabel = Label(t, image=img)
        imglabel.image = img
        imglabel.grid(row=1, column=1, padx=10, pady=10)
        group_name = Label(t,
                           text="Copyright Sergi Valverde (2018-) \n " +
                           "NeuroImage Computing Group")
        group_name.grid(row=3, column=1)
        group_link = Label(t,
                           text=r"http://atc.udg.edu/nic",
                           fg="blue",
                           cursor="hand2")
        group_link.grid(row=4, column=1)
        group_link.bind("<Button-1>", callback)

        license_content = "Licensed under the BSD 2-Clause license. \n" + \
                          "A copy of the license is present in the root directory."

        license_label = Label(t, text=license_content)
        license_label.grid(row=5, column=1, padx=20, pady=20)

        # if self.container is False:
        #     # check version and updates
        #     version_number = Label(t, text="commit: " + self.commit_version)
        #     version_number.grid(row=6, column=1, padx=20, pady=(1, 1))
        #
        #     self.check_link = Button(t,
        #                         text="Check for updates",
        #                         command=self.check_update)
        #     self.check_link.grid(row=7, column=1)

    def process_container_queue(self):
        """
        Process the threading queue. When the threaded processes are
        finished, buttons are reset and a message is shown in the app.
        """
        self.process_indicator.set('Running... please wait')
        try:
            msg = self.test_queue.get(0)
            self.process_indicator.set('Done. See log for more details.')
            self.inferenceBtn['state'] = 'normal'
            self.trainingBtn['state'] = 'normal'
        except Queue.Empty:
            self.master.after(100, self.process_container_queue)

    def close_event(self):
        """
        Stop the thread processes using OS related calls.
        """
        if self.train_task is not None:
            self.train_task.stop_process()
        if self.test_task is not None:
            self.test_task.stop_process()
        os.system('cls' if platform.system == "Windows" else 'clear')
        root.destroy()
示例#55
0
文件: gui.py 项目: imcj/pybbs
class LintGui:
    """Build and control a window to interact with pylint"""

    def __init__(self, root=None):
        """init"""
        self.root = root or Tk()
        self.root.title('Pylint')
        #reporter
        self.reporter = None
        #message queue for output from reporter
        self.msg_queue = Queue.Queue()
        self.msgs = []
        self.filenames = []
        self.rating = StringVar()
        self.tabs = {}
        self.report_stream = BasicStream(self)
        #gui objects
        self.lbMessages = None
        self.showhistory = None
        self.results = None
        self.btnRun = None
        self.information_box = None
        self.convention_box = None
        self.refactor_box = None
        self.warning_box = None
        self.error_box = None
        self.fatal_box = None
        self.txtModule = None
        self.status = None
        self.msg_type_dict = None
        self.init_gui()

    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white")
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                    yscrollcommand=rightscrollbar2.set,
                    xscrollcommand=bottomscrollbar2.set,
                    bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white", font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window)
        c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window)
        r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window)
        w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window)
        e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window)
        f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window)
        dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window)
        ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window)
        stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window)
        msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=E)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, columnspan=2, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I' : lambda : self.information_box.get() == 1,
            'C' : lambda : self.convention_box.get() == 1,
            'R' : lambda : self.refactor_box.get() == 1,
            'E' : lambda : self.error_box.get() == 1,
            'W' : lambda : self.warning_box.get() == 1,
            'F' : lambda : self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()


    def select_recent_file(self, event):
        """adds the selected file in the history listbox to the Module box"""
        if not self.showhistory.size():
            return

        selected = self.showhistory.curselection()
        item = self.showhistory.get(selected)
        #update module
        self.txtModule.delete(0, END)
        self.txtModule.insert(0, item)

    def refresh_msg_window(self):
        """refresh the message window with current output"""
        #clear the window
        self.lbMessages.delete(0, END)
        for msg in self.msgs:
            if (self.msg_type_dict.get(msg[0])()):
                msg_str = self.convert_to_string(msg)
                self.lbMessages.insert(END, msg_str)
                fg_color = COLORS.get(msg_str[:3], 'black')
                self.lbMessages.itemconfigure(END, fg=fg_color)

    def refresh_results_window(self):
        """refresh the results window with current output"""
        #clear the window
        self.results.delete(0, END)
        try:
            for res in self.tabs[self.box.get()]:
                self.results.insert(END, res)
        except:
            pass

    def convert_to_string(self, msg):
        """make a string representation of a message"""
        if (msg[2] != ""):
            return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4]
        else:
            return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4]

    def process_incoming(self):
        """process the incoming messages from running pylint"""
        while self.msg_queue.qsize():
            try:
                msg = self.msg_queue.get(0)
                if msg == "DONE":
                    self.report_stream.output_contents()
                    return False

                #adding message to list of msgs
                self.msgs.append(msg)

                #displaying msg if message type is selected in check box
                if (self.msg_type_dict.get(msg[0])()):
                    msg_str = self.convert_to_string(msg)
                    self.lbMessages.insert(END, msg_str)
                    fg_color = COLORS.get(msg_str[:3], 'black')
                    self.lbMessages.itemconfigure(END, fg=fg_color)

            except Queue.Empty:
                pass
        return True

    def periodic_call(self):
        """determine when to unlock the run button"""
        if self.process_incoming():
            self.root.after(100, self.periodic_call)
        else:
            #enabling button so it can be run again
            self.btnRun.config(state=NORMAL)

    def mainloop(self):
        """launch the mainloop of the application"""
        self.root.mainloop()

    def quit(self, _=None):
        """quit the application"""
        self.root.quit()

    def halt(self):
        """program halt placeholder"""
        return

    def file_open(self, package=False, _=None):
        """launch a file browser"""
        if not package:
            filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'),
                                                    ('allfiles', '*')], title='Select Module')
        else:
            filename = askdirectory(title="Select A Folder", mustexist=1)

        if filename == ():
            return

        self.txtModule.delete(0, END)
        self.txtModule.insert(0, filename)

    def update_filenames(self):
        """update the list of recent filenames"""
        filename = self.txtModule.get()
        if not filename:
            filename = os.getcwd()
        if filename+'\n' in self.filenames:
            index = self.filenames.index(filename+'\n')
            self.filenames.pop(index)

        #ensure only 10 most recent are stored
        if len(self.filenames) == 10:
            self.filenames.pop()
        self.filenames.insert(0, filename+'\n')

    def set_history_window(self):
        """update the history window with info from the history file"""
        #clear the window
        self.showhistory.delete(0, END)
        # keep the last 10 most recent files
        try:
            view_history = open(HOME+HISTORY, 'r')
            for hist in view_history.readlines():
                if not hist in self.filenames:
                    self.filenames.append(hist)
                self.showhistory.insert(END, hist.split('\n')[0])
            view_history.close()
        except IOError:
            # do nothing since history file will be created later
            return

    def run_lint(self, _=None):
        """launches pylint"""
        self.update_filenames()
        self.root.configure(cursor='watch')
        self.reporter = GUIReporter(self, output=self.report_stream)
        module = self.txtModule.get()
        if not module:
            module = os.getcwd()

        #cleaning up msgs and windows
        self.msgs = []
        self.lbMessages.delete(0, END)
        self.tabs = {}
        self.results.delete(0, END)
        self.btnRun.config(state=DISABLED)

        #setting up a worker thread to run pylint
        worker = Thread(target=lint_thread, args=(module, self.reporter, self,))
        self.periodic_call()
        worker.start()

        # Overwrite the .pylint-gui-history file with all the new recently added files
        # in order from filenames but only save last 10 files
        write_history = open(HOME+HISTORY, 'w')
        write_history.writelines(self.filenames)
        write_history.close()
        self.set_history_window()

        self.root.configure(cursor='')
示例#56
0
class gui:

    def __init__(self, sonar):
        self.tk = Tk()
        self.canvas = Canvas(self.tk, height=800, width=800)
        self.canvas.pack()
        self.next = Button(self.tk, text='next', command=self.step)
        self.next.pack()
        self.rb = Button(self.tk, text='run', command=self.run)
        self.rb.pack()
        self.sonar = sonar
        self.draw_map()
        self.draw_move_points()
        self.delete_old = True
        #self.tk.after(20,self.redraw)

        self.tk.mainloop()

    def run(self):
        self.next.config(state='disabled')
        self.rb.config(state='disabled')
        self.manual = False
        self.tk.after(50, self.redraw)

    def step(self):
        self.manual = True
        self.redraw()
        
    def redraw(self):
        check = self.sonar.sim_step()
        if self.delete_old:
            self.canvas.delete('scan')
            self.canvas.delete('intersect')
            self.canvas.delete('particle')
            self.canvas.delete('mvln')
            
        self.draw_sonar_data()
        self.draw_particle_data()
        if check is not -1 and self.manual is False:
            self.tk.after(50, self.redraw)
        
    def draw_sonar_data(self):
        #print 'data'
        #for line in self.sonar.scan_lines:
            #draw_line(self.canvas, line, tag='scan')
            
        #for point in self.sonar.intersection_points:
            #draw_point(self.canvas, point, tag='intersect')
        draw_point(self.canvas, self.sonar.loc, tag='sonar', colour='red')

    def draw_particle_data(self):
        particles = self.sonar.particles.list()
        for particle in particles:
            draw_point(self.canvas, particle.loc, weight=particle.wt, tag='particle')
            if particle.move_line:
                draw_line(self.canvas, particle.move_line, tag='mvln')
            #for line in particle.scan:
             #   draw_line(self.canvas, line, tag='scan')
            #for intersect in particle.int:
                #draw_point(self.canvas, intersect, tag='intersect')
        
    def draw_map(self):
        #print 'map'
        for line in self.sonar.map.lines:
            draw_line(self.canvas, line, tag='map')

    def draw_move_points(self):
        for point in self.sonar.get_move_list():
            draw_point(self.canvas, point[0], tag='mvpt')
示例#57
-1
class ResultList(Frame):
    """
    Result List widget
    """

    def __init__(self, master=None):
        Frame.__init__(self, master, padx=3, pady=3)
        self.columnconfigure(0, weight=1, minsize=50)
        self.columnconfigure(1, weight=1000)
        self.columnconfigure(2, weight=1, minsize=10)
        self.__createWidgets()
        self.show()

    def __createWidgets(self):
        self.lbl = Label(text="")
        self.lbl.grid(row=1, column=0, columnspan=2, in_=self)
        self.__hide_button = Button(text="Hide", command=self.hide)
        self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self)
        self.__yScroll = Scrollbar(orient=VERTICAL)
        self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE)
        self.__yScroll.config(command=self.list.yview)

    def show(self):
        self.__hide_button.config(text="Hide", command=self.hide)
        self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self)
        self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self)

    def hide(self):
        self.__hide_button.config(text="Show", command=self.show)
        self.list.grid_forget()
        self.__yScroll.grid_forget()

    def clear(self):
        self.list.delete(0, END)

    def fill(self, valList):
        self.clear()
        for v in valList:
            self.list.insert(END, v)
        self.list.see(0)
        self.select(0)

    def append(self, val):
        self.list.insert(END, val)
        self.list.see(END)

    def select(self, index=0):
        self.list.selection_set(index)

    def selected(self):
        return int(self.list.curselection()[0])

    def width(self, width):
        self.list.config(width=width)