Exemple #1
0
class FilamentReport(Toplevel):
	def __init__(self, app, printer, settings, logger, *arg):
		self.app = app
		self.printer = printer
		self.settings = settings
		self.logger = logger
		
		layers = self.app.gcodeInfo.layerOrder
		usage = self.app.gcodeInfo.filLayers

		self.selection = None
		
		Toplevel.__init__(self, app, *arg)
		self.title("Layer by Layer Filament Usage")
		self.protocol("WM_DELETE_WINDOW", self.doCancel)

		f = Frame(self)
		f.grid(row=1, column=1, rowspan=1, padx=10)

		self.tree = Treeview(self, height=12, selectmode='browse')
		self.sb = Scrollbar(self)
		self.sb.config(command=self.tree.yview)
		self.tree.config(yscrollcommand=self.sb.set)

		ln = []
		for l in layerinfo:
			ln.append(l[0])
		del ln[0]
		self.tree.config(columns=ln)
		
		for l in layerinfo:
			self.tree.column(l[0], width=l[1], anchor=l[2])
			self.tree.heading(l[0], text=l[3])

		self.sb.pack(side=RIGHT, fill=Y)
		self.tree.pack(side=LEFT, fill=BOTH, expand=1)

		prev = 0.0	
		tl = layers[-1]
		total = usage[tl]		
		for l in layers:
			n = usage[l]
			self.tree.insert('', 'end', text=l, values=("%7.3f" % (n-prev), "%9.3f" % n, "%9.3f" % (total-n)))
			prev = n

	def doCancel(self):
		self.app.closeFilamentReport()
Exemple #2
0
class MacroFrame(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.numStates = 0
        self.initUI()

    def initUI(self):
        self.columnconfigure(0, weight=0)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        self.rowconfigure(0, weight=1)

        self.commandFrame = Frame(self, background="white")
        self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W+E)
        self.commandFrame.columnconfigure(1, weight=1)

        self.btnCommand = Button(self.commandFrame, text="Run")
        self.btnCommand.grid(row=0, column=0)

        self.strCommand = StringVar()
        self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand)
        self.entCommand.grid(row=0, column=1, sticky=W+E)
        
        self.lstMacro = Listbox(self)
        self.lstMacro.grid(row=1, column=0, sticky=N+S+W+E)
        
        self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse")
        self.treeview.grid(row=1, column=1, columnspan=4, sticky=N+S+W+E)
        self.treeScrollbar = Scrollbar(self)
        self.treeScrollbar.grid(row=1, column=5, sticky=N+S)
        self.treeview.config(yscrollcommand=self.treeScrollbar.set)
        self.treeScrollbar.config(command=self.treeview.yview)

        self.btnFrame = Frame(self, background="white")
        self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W+E)

        self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro)
        self.btnRun.grid(row=0, column=0)
        
        self.btnStop = Button(self.btnFrame, text="Stop")
        self.btnStop.grid(row=0, column=1)

        self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro)
        self.btnSaveMacro.grid(row=0, column=2)

        self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro")
        self.btnDeleteMacro.grid(row=0, column=3)

        self.btnDeleteState = Button(self.btnFrame, text="Delete State")
        self.btnDeleteState.grid(row=0, column=4)

    def addState(self, robot):
        stateName = "state" + str(self.numStates)
        self.treeview.insert("", END, iid=stateName, text=stateName)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            self.treeview.insert(stateName, END, iid=stateName + "_" + limbName, text=limbName)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    self.treeview.insert(stateName + "_" + limbName,
                                         END,
                                         iid=stateName + "_" + limbName + "_" + partName,
                                         text=partName,
                                         values=[part.angle])
                    partNum += 1
            limbNum += 1
        self.numStates += 1

    def getState(self, stateNum, robot):
        stateName = "state" + str(stateNum)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    part.setAngle(int(self.treeview.item(stateName + "_" + limbName + "_" + partName, "values")[0]))
                    partNum += 1
            limbNum += 1

    def runMacro(self):
        thread = threading.Thread(target=self.updateState)
        thread.start()
            
    def updateState(self):
        for i in range(self.numStates):
            self.getState(i, self.parent.robotFrame.robot)
            time.sleep(.1)

    def saveMacro(self):
        pass
class Gui(Frame):
    """ Gui class for Graphical User Interface"""
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.searcher = Searcher()
        self.initUI()

    def initUI(self):
        self.pack(fill=BOTH, expand=True)
        Grid.columnconfigure(self, 0, weight=1)
        Label(self,
              text='Classroom Finder',
              font=('Arial', 20, 'bold'),
              bg='cyan',
              fg='white').grid(sticky=W + E,
                               columnspan=3)  # classroom finder header
        Label(self, text='Url:').grid(column=0, row=1, pady=10, padx=(50, 0))
        self.urlentry = Entry(self, width=100)  # url entry to get url
        self.urlentry.grid(column=1, row=1, padx=(0, 80))
        self.color_label = Label(
            self, bg='red', width=10)  # color label to make red,yellow,green
        self.color_label.grid(column=0,
                              row=2,
                              sticky=E,
                              columnspan=2,
                              padx=(120),
                              pady=(0, 40))
        self.fetchbtn = Button(self,
                               text='Fetch',
                               height=2,
                               width=10,
                               command=self.dynamic)  # fetch button
        self.fetchbtn.grid(column=1,
                           row=2,
                           sticky=E,
                           padx=(0, 30),
                           pady=(10, 50))
        Label(self,
              text='Filters',
              bg='cyan',
              fg='white',
              font=('Arial', 20, 'bold'),
              width=10).grid(column=0, row=3, padx=10)
        self.frame = Frame(self, borderwidth=3,
                           relief=GROOVE)  # frame to keep filters part
        self.frame.grid(column=0,
                        row=4,
                        columnspan=3,
                        sticky=W + E + S + N,
                        pady=10,
                        padx=10)
        Label(self.frame, text='Where am I?').grid(sticky=W)
        self.where_combo = Combobox(self.frame,
                                    state='readonly')  # where am i combobox
        self.where_combo.grid(column=1, row=0, pady=20)
        self.where_combo.bind(
            '<<ComboboxSelected>>',
            self.change_build)  # to update room button wrt where combo
        Label(self.frame, text='Room').grid(sticky=W)
        self.room_combo = Combobox(self.frame,
                                   state='readonly')  # rooms combobox
        self.room_combo.grid(column=1, row=1)
        Label(self.frame, text='Start').grid(sticky=W)
        self.start_combo = Combobox(self.frame, state='readonly',
                                    width=7)  # start time combobox
        self.start_combo.grid(column=1, row=2, pady=20, sticky=W)
        Label(self.frame, text='End').grid(column=2, row=2, sticky=W)
        self.end_combo = Combobox(self.frame, state='readonly',
                                  width=7)  # end time combobox
        self.end_combo.grid(column=3, row=2, sticky=W)
        Label(self.frame, text='Day').grid(sticky=W)
        self.day_combo = Combobox(self.frame,
                                  state='readonly')  # days combobox
        self.day_combo.grid(column=1, row=3, pady=(0, 20))
        self.search = Button(self.frame,
                             text='Search',
                             width=10,
                             height=2,
                             command=self.add_treeview)  # seach button
        self.search.grid(padx=(0, 50), columnspan=2)
        Label(self.frame, text='Classroom results', bg='gray',
              fg='white').grid(sticky=N + E + W,
                               column=4,
                               row=0,
                               rowspan=5,
                               padx=(55, 0))
        self.scroll = Scrollbar(
            self.frame, orient='vertical')  # vertical scrollbar for treeview
        self.tree = Treeview(self.frame,
                             columns=('', '', '', '', ''),
                             selectmode='extended',
                             show='headings')
        listofcolumn = [
            'Room', 'Traffic', 'Availability %', 'Closeness', 'Overall Score'
        ]  # colums to treeview
        counter = 1
        for column in listofcolumn:
            self.tree.column('#' + str(counter), width=90)  # to resize columns
            self.tree.heading('#' + str(counter), text=column,
                              anchor=CENTER)  # to set headings
            counter += 1
        self.scroll.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll.set)
        self.tree.grid(column=4, row=0, rowspan=5, padx=(40, 0), pady=(30, 0))
        self.scroll.grid(column=5,
                         row=0,
                         rowspan=5,
                         sticky=N + S,
                         pady=(30, 0))
        self.urlentry.insert(
            0,
            'https://www.sehir.edu.tr/en/announcements/2018-2019-bahar-donemi-ders-programi'
        )

    def dynamic(self):
        self.color_label.configure(
            bg='yellow'
        )  # make color label yellow at the beginning of the process
        self.update_idletasks()
        self.searcher.fetch(self.urlentry.get(
        ))  # to call fetch method in searcher class to start process
        self.color_label.configure(bg='green')
        room_num = [
            room.room_num
            for room in self.searcher.buildings['ACAD BUILD 1'].classrooms
        ]
        self.where_combo.configure(
            values=[build for build in sorted(self.searcher.buildings)])
        self.where_combo.current(
            0)  # to get values in combobox and set value 0 as a default
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)
        self.start_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.start_combo.current(
            0)  # start and end combo both have the same interval from 9 to 19
        self.end_combo.configure(
            values=["{}:00".format(time) for time in range(9, 20)])
        self.end_combo.current(len(self.end_combo['values']) - 1)
        self.day_combo.configure(
            values=["Monday", 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])
        self.day_combo.current(0)

    def change_build(
            self, event
    ):  # when where am i combobox chance, room combobox also chance
        building = self.where_combo.get()
        room_num = [
            room.room_num
            for room in self.searcher.buildings[building].classrooms
        ]
        self.room_combo.configure(values=[room for room in sorted(room_num)])
        self.room_combo.current(0)

    def add_treeview(self):  # to add scores in treeview
        self.tree.delete(*self.tree.get_children())
        self.overall_scores = self.searcher.search(
            self.day_combo.get(),
            self.where_combo.get(), self.room_combo.get(),
            self.start_combo.get(), self.end_combo.get()
        )  # key operator for the sorted dict by values which overall score
        for item, score in sorted(self.overall_scores.items(),
                                  key=operator.itemgetter(1),
                                  reverse=True):
            if item.availability_score == 0:  # to avoid from availability score 0
                continue
            room = str(item.classroom.building_num) + str(
                item.classroom.room_num)
            self.tree.insert('',
                             'end',
                             values=(room, item.traffic_score,
                                     item.availability_score,
                                     item.closeness_score, score))
class SleepableThreadManagerGUI:
    ui = None  # Main UI Window

    top = None  # Top UI frame
    bottom = None  # Bottom UI frame

    allow_scroll = True

    manager = None  # Sleepable thread manager

    iidList = []

    ui_update_thread = None  # UI Update thread

    thread_dropdown = None  # Dropdown to select threads
    function_dropdown = None  # Dropdown to select functions

    thread_selected = None  # Variable for the thread selection
    threads_selected = []
    function_selected = None  # Variable for the function selection

    function_menu = None
    selection_context_menu = None
    empty_selection_context_menu = None

    info_tree_view = None  # Tree view for thread info
    output_textbox = None  # Output textbox for the UI thread to write to

    def __init__(self):
        self.manager = SleepableThreadManager()

        self.ui = Tk()
        self.ui.title('Sleepable Thread Manager')
        self.ui.geometry('550x600')

        self.function_selected = StringVar(self.ui)
        self.thread_selected = StringVar(self.ui)

        self.thread_selected.set('Select a Thread...')
        self.function_selected.set('Select a Function...')

        # create all of the main containers
        self.top = Frame(self.ui, width=300, height=50, pady=5)
        self.bottom = Frame(self.ui, bg='orange', width=300, height=20, pady=0)

        # main window
        self.ui.grid_columnconfigure(
            0, weight=1)  # expand main column when main ui resizes
        self.top.grid(row=0, sticky="ew")  # Stick top frame to east/west
        self.bottom.grid(
            row=1,
            sticky="nsew")  # Stick bottom frame to north/south/easy/west
        self.ui.grid_rowconfigure(
            1, weight=1)  # Expand bottom panel when main ui resizes

        # top frame component config
        self.top.grid_rowconfigure(
            0, weight=1)  # Expand first row when top frame resizes
        self.top.grid_rowconfigure(
            1, weight=1)  # Expand second row when top frame resizes
        self.top.grid_columnconfigure(
            1, weight=1)  # Expand second column when top frame resizes

        # bottom frame component config
        self.bottom.grid_rowconfigure(
            0, weight=1)  # Expand row 1 when bottom frame resizes
        self.bottom.grid_rowconfigure(
            1, weight=1)  # Expand row 2 when bottom frame resizes
        self.bottom.grid_columnconfigure(
            0, weight=1)  # Expand column 1 when bottom frame resizes
        self.bottom.grid_columnconfigure(0, weight=1)

        # create widgets for top frame
        function_label = Label(self.top, text='Function name:')
        self.function_dropdown = OptionMenu(
            self.top, self.function_selected,
            *self.manager.function_mappings.keys())

        # layout the widgets in the top frame
        function_label.grid(row=1, column=0)
        self.function_dropdown.grid(row=1, column=1, columnspan=3, sticky="ew")

        # create widgets for bottom frame
        self.selection_context_menu = Menu(self.info_tree_view)
        createMultiple = Menu(self.info_tree_view)
        functionMenu = Menu(self.selection_context_menu)
        functionMenu.add_command(
            label='Square', command=lambda: self.set_thread_function('Square'))
        functionMenu.add_command(
            label='Cube', command=lambda: self.set_thread_function('Cube'))

        self.selection_context_menu.add_cascade(label='Create...',
                                                menu=createMultiple)
        self.selection_context_menu.add_cascade(label='Set function...',
                                                menu=functionMenu)

        self.selection_context_menu.add_command(label='Start',
                                                command=self.start_thread)
        self.selection_context_menu.add_command(label='Sleep',
                                                command=self.sleep_thread)
        self.selection_context_menu.add_command(label='Wake',
                                                command=self.wake_thread)
        self.selection_context_menu.add_command(label='Stop',
                                                command=self.stop_thread)
        self.selection_context_menu.add_command(label='Restart',
                                                command=self.restart_thread)
        self.selection_context_menu.add_command(label='Remove',
                                                command=self.remove_thread)

        self.empty_selection_context_menu = Menu(self.info_tree_view)

        createMultiple.add_command(label='1', command=self.create_thread)
        createMultiple.add_command(
            label='5', command=lambda: self.create_thread(amount=5))
        createMultiple.add_command(
            label='10', command=lambda: self.create_thread(amount=10))
        createMultiple.add_command(
            label='20', command=lambda: self.create_thread(amount=20))

        self.empty_selection_context_menu.add_cascade(label='Create',
                                                      menu=createMultiple)

        self.info_tree_view = Treeview(self.bottom,
                                       columns=('Function', 'Status'))
        self.info_tree_view.heading('#0', text='Thread Name')
        self.info_tree_view.heading('#1', text='Function Name')
        self.info_tree_view.heading('#2', text='Status')
        self.info_tree_view.column('#0', width=100, stretch=NO)
        self.info_tree_view.column('#1', width=75)
        self.info_tree_view.column('#2', width=100, stretch=NO)
        self.info_tree_view.bind('<Button-3>', self.popup)
        self.output_textbox = Text(self.bottom,
                                   background="white",
                                   font=("Helvetica", 8))

        self.output_scrollbar = Scrollbar(self.bottom,
                                          command=self.output_textbox.yview)
        self.info_scrollbar = Scrollbar(self.bottom,
                                        command=self.info_tree_view.yview)

        # layout for the widgets in the bottom frame
        self.info_tree_view.grid(row=0, column=0, sticky='nsew')
        self.info_scrollbar.grid(row=0, column=1, sticky="nse")
        self.info_tree_view.config(yscrollcommand=self.info_scrollbar.set)

        self.output_textbox.grid(row=1, column=0, sticky='nsew')
        self.output_scrollbar.grid(row=1, column=1, sticky="nse")
        self.output_textbox.config(yscrollcommand=self.output_scrollbar.set)

        self.ui_update_thread = SleepableThread(work_wait=0.5)
        self.ui_update_thread.set_thread_work(self.refresh_output)
        self.ui_update_thread.start_thread()

        # Mainloop
        self.ui.mainloop()

    # UI refresh
    def refresh_tree_view(self):
        self.info_tree_view.delete(*self.info_tree_view.get_children())
        for item in self.manager.threads.items():
            self.info_tree_view.insert(
                '',
                'end',
                text=item[0],
                values=(str(item[1].work_function),
                        item[1].thread_state_mappings[item[1].thread_state]))

    def refresh_output(self):
        # function passed to ui thread, change to labels/gridview? need independent message queue on threads
        if self.manager.functions.MessageQueue.__len__() > 0:
            while self.manager.functions.MessageQueue.__len__() != 0:
                item = self.manager.functions.MessageQueue.pop()
                if len(item) >= 400:
                    raise Exception('Output too large')
                else:
                    self.output_textbox.delete('1.0', END)
                    self.output_textbox.insert(END, '{}\n'.format(item))
                    if self.manager.thread_stats(
                    )[1] > 0 and self.allow_scroll:
                        self.output_textbox.see('end')

    def popup(self, event):
        self.allow_scroll = False
        #iid = self.info_tree_view.identify_row(event.y)
        self.iidList = self.info_tree_view.selection()
        if self.iidList:
            if self.iidList > 0:
                for i in self.iidList:
                    self.threads_selected.append(
                        self.info_tree_view.item(i)['text'])
            # self.info_tree_view.selection_set(iid)
            # self.thread_selected.set(self.info_tree_view.item(iid)['text'])
            self.selection_context_menu.post(event.x_root, event.y_root)
        else:
            self.empty_selection_context_menu.post(event.x_root, event.y_root)
            pass
        self.manager.functions.MessageQueue = []
        self.allow_scroll = True

    # Button functions
    def create_thread(self, amount=1):
        i = 0
        while i != amount:
            self.manager.control(command='create')
            i += 1
        self.refresh_tree_view()

    def remove_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='remove')
        self.refresh_tree_view()

    def start_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='start')
        self.refresh_tree_view()

    def restart_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='restart')
        self.refresh_tree_view()

    def sleep_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='sleep')
        self.refresh_tree_view()

    def wake_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='wake')
        self.refresh_tree_view()

    def stop_thread(self):
        while self.threads_selected.__len__() != 0:
            self.manager.control(thread=self.threads_selected.pop(),
                                 command='stop')
        self.refresh_tree_view()

    def set_thread_function(self, funct):
        while self.threads_selected.__len__() != 0:
            self.manager.set_function(self.threads_selected.pop(), funct)
        self.refresh_tree_view()
Exemple #5
0
class SDCard: 
	def __init__(self, root, prtr, settings, log):
		self.app = root
		self.printer = prtr
		self.settings = settings
		self.log = log
		self.top = None

	def isActive(self):
		return self.top != None

	def start(self):
		self.app.sdchecking = True
		self.printer.send_now("M21")
		
	def sdCheckComplete(self, ready):
		if not ready:
			self.log.logMsg("Error initializing SD card")
		else:
			self.app.sdlisting = True
			self.printer.send_now("M20")
			
	def refresh(self):
		self.top.destroy()
		self.app.sdlisting = True
		self.printer.send_now("M20")
			
	def sdListComplete(self, sdlist):
		top = self.top = Toplevel(self.app) 
		top.title("SD Card Control")
		top.protocol('WM_DELETE_WINDOW', self.delTop)
		f = Frame(top, height=150, width=150)
		f.grid(row=1, column=1);
		self.tree = Treeview(f, height=12, selectmode='browse') 
		self.tree.column("#0", minwidth=100)
		self.tree.bind("<<TreeviewSelect>>", self.treeSelect)
		self.sb = Scrollbar(f)
		self.sb.config(command=self.tree.yview)
		self.tree.config(yscrollcommand=self.sb.set)
			
		self.sb.pack(side=RIGHT, fill=Y)
		self.tree.pack(side=LEFT, fill=BOTH, expand=1)

		SDroot = SDDir('')
		for item in sdlist:
			if item.startswith('/'):
				cd = SDroot
				l = item[1:].split('/')
				for d in l[:-1]:
					ncd = cd.getDir(d)
					if ncd == None:
						ncd = cd.addDir(d)
			
					cd = ncd
				cd.addFile(l[-1], fqn=item)
					
			else:
				SDroot.addFile(item)
				
		SDroot.sortAll()
		
		self.fileMap = {}
		self.startFile = None
		self.loadDir(SDroot, '')
		bf = Frame(top, width=50)
		bf.grid(column=3, row=1)
		
		blf = LabelFrame(bf, text="Print from SD Card", width=48, height=40)
		
		self.bPrint = Button(blf, text='Print', command=self.doPrint, width = 6) 
		self.bPrint.pack()
		blf.pack(fill='x')
		
		blf = LabelFrame(bf, text="Delete from SD Card", width=48, height=40)
		
		self.bDelete = Button(blf, text="Delete", command=self.doDelete, width=6)
		self.bDelete.pack()
		blf.pack(fill='x')
		
		blf = LabelFrame(bf, text="Upload to SD Card", width=48, height=180)

		self.upDir = Label(blf, text="Dir:", justify=LEFT)
		self.upDir.pack()

		ef = Frame(blf)

		l = Label(ef, text="File:", justify=LEFT)
		l.pack(side=LEFT)

		self.entry = Entry(ef, width=12)
		self.entry.pack(side=LEFT)
		fn = 'untitled.g'
		if self.app.GCodeFile:
			fn = os.path.basename(self.app.GCodeFile)
			if len(fn) > 8:
				fn = fn[0:8]
			fn += ".g"
		self.entry.delete(0, END)
		self.entry.insert(0, fn)
		ef.pack()
		
		self.bUpload = Button(blf, text="Upload", command=self.doUpload, width=6)
		self.bUpload.pack()

		blf.pack(fill='x')
		
		if self.app.printing or self.app.sdprinting:
			self.bPrint.config(state=DISABLED)
			self.bUpload.config(state=DISABLED)
			
		if not self.app.GCodeFile:
			self.bUpload.config(state=DISABLED)
			
		blf = Frame(bf)
		self.bExit = Button(blf, text='Exit', command=self.doExit, width=6) 
		self.bExit.pack()
		blf.pack()

		if self.startFile:
			self.tree.selection_set(self.startFile)
			
		self.top.geometry("360x300+100+100")

	def delTop(self):
		self.top.destroy()
		self.top = None
	
	def treeSelect(self, *arg):
		s = self.tree.selection()[0]
		
		try:
			d = s.split(':')[0]
		except:
			d = ""
			
		if len(d) == 0:
			d = '(root)'
			
		self.upDir.config(text="Dir: " + d)
		
		if self.app.printing or self.app.sdprinting or not self.app.GCodeFile:
			self.bUpload.config(state=DISABLED)
		else:
			self.bUpload.config(state=NORMAL)
			
		if ':' in s: # a file is chosen
			if self.app.printing or self.app.sdprinting:
				self.bPrint.config(state=DISABLED)
			else:
				self.bPrint.config(state=NORMAL)
			self.bDelete.config(state=NORMAL)
			
		else: # a directory is chosen
			self.bPrint.config(state=DISABLED)
			self.bDelete.config(state=DISABLED)


	def loadDir(self, d, did):
		d.resetDir()
		nd = d.nextDir()
		while (nd):
			myid = did + '/' + nd.dirName()
			self.tree.insert(did, 'end', myid, text=nd.dirName())
			self.loadDir(nd, myid)
			nd = d.nextDir()
			
		d.resetFile()
		f = d.nextFile()
		while (f):
			myid = did + ':' + f[0]
			self.fileMap[myid] = f[1]
			self.tree.insert(did, 'end', myid, text=f[0])
			if self.startFile == None:
				self.startFile = myid
			f = d.nextFile()		
		
	def doExit(self): 
		self.top.destroy()
		self.top = None

	def doPrint(self): 
		s = self.tree.selection()[0]
		if s in self.fileMap:
			fn = self.fileMap[s].lower()
			self.log.logMsg("Starting print of SD file %s" % fn)
			self.printer.send_now("M23 %s" % fn)  # select the file
			self.printer.send_now("M24") # start the print
			self.app.sdprinting = True
			self.app.setToolbarSDPrint()
			self.top.destroy()
			self.top = None
		
	def doDelete(self):
		s = self.tree.selection()[0]
		if s in self.fileMap:
			fn = self.fileMap[s].lower()
			self.log.logMsg("Deleting file %s" % fn)
			self.printer.send_now("M30 %s" % fn)
			self.refresh()
		
	def doUpload(self):
		bn = self.entry.get()

		try:		
			d = self.tree.selection()[0].split(':')[0]
		except:
			d = ""
			
		if len(d) != 0:
			d += '/'
		
		fn = (d + bn).lower()
		self.log.logMsg("Starting upload to SD file %s" % fn)
		self.printer.send_now("M28 %s" % fn)  # select the file
		self.app.startUpload()
		self.top.destroy()
		self.top = None
Exemple #6
0
class MacroFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.numStates = 0
        self.initUI()

    def initUI(self):
        self.columnconfigure(0, weight=0)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        self.rowconfigure(0, weight=1)

        self.commandFrame = Frame(self, background="white")
        self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W + E)
        self.commandFrame.columnconfigure(1, weight=1)

        self.btnCommand = Button(self.commandFrame, text="Run")
        self.btnCommand.grid(row=0, column=0)

        self.strCommand = StringVar()
        self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand)
        self.entCommand.grid(row=0, column=1, sticky=W + E)

        self.lstMacro = Listbox(self)
        self.lstMacro.grid(row=1, column=0, sticky=N + S + W + E)

        self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse")
        self.treeview.grid(row=1, column=1, columnspan=4, sticky=N + S + W + E)
        self.treeScrollbar = Scrollbar(self)
        self.treeScrollbar.grid(row=1, column=5, sticky=N + S)
        self.treeview.config(yscrollcommand=self.treeScrollbar.set)
        self.treeScrollbar.config(command=self.treeview.yview)

        self.btnFrame = Frame(self, background="white")
        self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W + E)

        self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro)
        self.btnRun.grid(row=0, column=0)

        self.btnStop = Button(self.btnFrame, text="Stop")
        self.btnStop.grid(row=0, column=1)

        self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro)
        self.btnSaveMacro.grid(row=0, column=2)

        self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro")
        self.btnDeleteMacro.grid(row=0, column=3)

        self.btnDeleteState = Button(self.btnFrame, text="Delete State")
        self.btnDeleteState.grid(row=0, column=4)

    def addState(self, robot):
        stateName = "state" + str(self.numStates)
        self.treeview.insert("", END, iid=stateName, text=stateName)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            self.treeview.insert(stateName, END, iid=stateName + "_" + limbName, text=limbName)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    self.treeview.insert(
                        stateName + "_" + limbName,
                        END,
                        iid=stateName + "_" + limbName + "_" + partName,
                        text=partName,
                        values=[part.angle],
                    )
                    partNum += 1
            limbNum += 1
        self.numStates += 1

    def getState(self, stateNum, robot):
        stateName = "state" + str(stateNum)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    part.setAngle(int(self.treeview.item(stateName + "_" + limbName + "_" + partName, "values")[0]))
                    partNum += 1
            limbNum += 1

    def runMacro(self):
        thread = threading.Thread(target=self.updateState)
        thread.start()

    def updateState(self):
        for i in range(self.numStates):
            self.getState(i, self.parent.robotFrame.robot)
            time.sleep(0.1)

    def saveMacro(self):
        pass
Exemple #7
0
class ProjectVenster (ZoekVenster):

    TITLE = 'Projecten'

    def fill(self):
        super(self.__class__, self).fill()
        #Basisvelden
        self.identry = EntryField(self.veldenFrame, 'Projectnummer', row=0)
        self.naamentry = EntryField(self.veldenFrame, 'Projectnaam', row=1)
        self.jaarentry = EntryField(self.veldenFrame, 'Jaar', row=2)
        self.budgetentry = EntryField(self.veldenFrame, 'Budget', row=3)
        self.keywordLabel = Label(self.veldenFrame, text='Trefwoorden:')
        self.keywordLabel.grid(row=4, column=0, sticky=W)
        self.keywordText = Text(self.veldenFrame, relief=SUNKEN, wrap=WORD, width=60, height=3)
        self.keywordText.grid(row=4, column=1, sticky=W)

        #Partners
        self.partnersLabel = Label(self.veldenFrame, text='Relaties:')
        self.partnersLabel.grid(row=5, column=0)
        self.partnersFrame = Frame(self.veldenFrame)
        self.partnersFrame.grid(row=5, column=1, sticky=W+E)
        self.partnersListBox = Treeview(self.partnersFrame, columns=('Relatie', 'Rol'), height=3, show='headings', selectmode=BROWSE)
        self.partnersListBox.grid(row=0, column=0, sticky=W+E)

        self.partnersKnopFrame = Frame(self.veldenFrame)
        self.partnersKnopFrame.grid(row=6, column=1, sticky=E)
        self.pScrollbar = Scrollbar(self.partnersFrame)
        self.pScrollbar.grid(row=0, column=1, sticky=N+S+E)

        self.partnersListBox.config(yscrollcommand=self.pScrollbar.set)
        self.pScrollbar.config(command=self.partnersListBox.yview)

        self.partnersToevoegenKnop = Button(self.partnersKnopFrame, text='Toevoegen...', command=self.partnerToevoegen)
        self.partnersToevoegenKnop.grid()
        self.partnersVerwijderenKnop = Button (self.partnersKnopFrame, text='Verwijderen', command=self.partnerVerwijderen)
        self.partnersVerwijderenKnop.grid(row=0, column=1)
        self.partnersListBox.bind('<<TreeviewSelect>>', self.nieuwePartnerSelectie)

        #Bestanden
        self.bestandenHoofdFrame = Frame(self.resultaatframe)
        self.bestandenHoofdFrame.grid(row=2)
        self.bestandenLabel = Label(self.bestandenHoofdFrame, text='Bestanden:')
        self.bestandenLabel.grid(row=7, column=0, sticky=W)
        self.bestandenFrame = Frame(self.bestandenHoofdFrame)
        self.bestandenFrame.grid(row=7, column=1, sticky=W+E)
        self.bestandenListBox = Listbox(self.bestandenFrame, selectmode=EXTENDED, width=50, height=10)
        self.bestandenListBox.grid(row=0, column=0, sticky=W+E)
        self.bScrollbar = Scrollbar(self.bestandenFrame)
        self.bScrollbar.grid(row=0, column=1, sticky=N+S+E)
        self.bestandenListBox.config(yscrollcommand=self.bScrollbar.set)
        self.bScrollbar.config(command=self.bestandenListBox.yview)
        self.bestandenKnopFrame = Frame(self.bestandenHoofdFrame)
        self.bestandenKnopFrame.grid(row=8, column=1, sticky=E)
        self.bestandenToevoegKnop = Button(self.bestandenKnopFrame, text='Bestanden toevoegen...', command=self.bestandenToevoegen)
        self.bestandenToevoegKnop.grid(row=0, column=0, sticky=E)
        self.mapToevoegenKnop = Button(self.bestandenKnopFrame, text='Map toevoegen...', command=self.mapToevoegen)
        self.mapToevoegenKnop.grid(row=0, column=1, sticky=E)
        self.bestandenOphaalKnop = Button(self.bestandenKnopFrame, text='Ophalen...', command=self.bestandenOphalen)
        self.bestandenOphaalKnop.grid(row=0, column=2, sticky=E)
        self.bestandenVerwijderKnop = Button(self.bestandenKnopFrame, text='Verwijderen', command=self.bestandenVerwijderen)
        self.bestandenVerwijderKnop.grid(row=0, column=3, sticky=E)
        self.pollBestandenLijst()
        self.curid=-1


    def disableResultaat(self):
        self.identry.label.config(state=DISABLED)
        self.identry.entry.config(state=DISABLED)
        self.identry.setValue('')
        self.naamentry.label.config(state=DISABLED)
        self.naamentry.entry.config(state=DISABLED)
        self.naamentry.setValue('')
        self.jaarentry.label.config(state=DISABLED)
        self.jaarentry.entry.config(state=DISABLED)
        self.jaarentry.setValue('')
        self.budgetentry.label.config(state=DISABLED)
        self.budgetentry.entry.config(state=DISABLED)
        self.budgetentry.setValue('')
        self.keywordLabel.config(state=DISABLED)
        self.keywordText.delete(1.0, END)
        self.keywordText.config(state=DISABLED)
        self.partnersLabel.config(state=DISABLED)
        self.partnersListBox.delete(*self.partnersListBox.get_children())
        self.partnersToevoegenKnop.config(state=DISABLED)
        self.partnersVerwijderenKnop.config(state=DISABLED)
        self.bestandenLabel.config(state=DISABLED)
        self.bestandenListBox.delete(0, END)
        self.bestandenListBox.config(state=DISABLED)
        self.bestandenToevoegKnop.config(state=DISABLED)
        self.mapToevoegenKnop.config(state=DISABLED)
        self.bestandenOphaalKnop.config(state=DISABLED)
        self.bestandenVerwijderKnop.config(state=DISABLED)

    def enableResultaat(self):
        self.identry.label.config(state=NORMAL)
        self.identry.entry.config(state=NORMAL)
        self.naamentry.label.config(state=NORMAL)
        self.naamentry.entry.config(state=NORMAL)
        self.jaarentry.label.config(state=NORMAL)
        self.jaarentry.entry.config(state=NORMAL)
        self.budgetentry.label.config(state=NORMAL)
        self.budgetentry.entry.config(state=NORMAL)
        self.keywordLabel.config(state=NORMAL)
        self.keywordText.config(state=NORMAL)
        self.partnersLabel.config(state=NORMAL)
        self.partnersToevoegenKnop.config(state=NORMAL)
        self.bestandenLabel.config(state=NORMAL)
        self.bestandenListBox.config(state=NORMAL)
        self.bestandenToevoegKnop.config(state=NORMAL)
        self.mapToevoegenKnop.config(state=NORMAL)

    def disableContent(self):
        super(self.__class__, self).disableContent()
        self.disableResultaat()

    def enableContent(self):
        super(self.__class__, self).enableContent()
        if self.curid > -1:
            self.enableResultaat()

    def refresh(self):
        super(self.__class__, self).refresh()
        self.disableResultaat()

    def queryLijst(self, searchstring):
        words = self.splitKeywords(searchstring)
        if len(words) > 0:
            lijst = []
            for word in words:
                sql = ('\n'
                       '                SET @key := "%s";\n'
                       '                SELECT p.project_id, p.name_project FROM project AS p\n'
                       '                LEFT JOIN project_relation AS r ON p.project_id=r.project_id\n'
                       '                LEFT JOIN company AS c ON r.company_id=c.company_id\n'
                       '                LEFT JOIN keyword AS k ON p.project_id=k.project_id\n'
                       '                WHERE p.Project_ID LIKE @key\n'
                        'OR c.name LIKE @key OR r.role_name LIKE @key '
                       '                OR c.Name LIKE @key\n'
                       '                OR c.Street LIKE @key\n'
                       '                OR c.Street_Nr LIKE @key\n'
                       '                OR c.ZIP_Code LIKE @key\n'
                       '                OR c.City LIKE @key\n'
                       '                OR c.Country LIKE @key\n'
                       '                OR k.keyword LIKE @key\n'
                       '                OR p.Name_project LIKE @key\n'
                       '                OR CONCAT(p.Total_Costs) LIKE @key\n'
                       '                OR CONCAT(p.date_of_order) LIKE @key\n'
                       '                ') % ('%' + word + '%')
                if self.app.verbinding.verbind():
                    try:
                        c = self.app.verbinding.selectAll(sql, multi=True)
                        lijst.append(set([(int(k), v) for k, v in c]))
                    except Exception, e:
                        print '%s: %s' % (e.__class__.__name__, e.message)
                        raise
                    finally:
                        self.app.verbinding.sluit()