예제 #1
0
class channel_plot:
    '''
    '''

    def __init__(self, interface, toplevel=False, start_t=False, stop_t=False):
        '''
        '''
        self.abort = False
        if not start_t:
            start_t = datetime.utcnow() - timedelta(hours=2)
        if not stop_t:
            stop_t = datetime.utcnow()
        self.update_pending = False
        self.pype = interface
        self.plot_dicts = {}
        if isinstance(start_t, datetime):
            self.start_t = StringVar(value=start_t.strftime(time_format))
        elif isinstance(start_t, str):
            self.start_t = StringVar(value=start_t)
        else:
            raise TypeError('start_t must be string or datetime')
        if isinstance(stop_t, datetime):
            self.stop_t = StringVar(value=stop_t.strftime(time_format))
        elif isinstance(stop_t, str):
            self.stop_t = StringVar(value=stop_t)
        else:
            raise TypeError('stop_t must be string or datetime')
        self.time_interval = [self.start_t.get(), self.stop_t.get()]
        self.ymin = DoubleVar()
        self.ymax = DoubleVar()
        if toplevel:
            self.toplevel = toplevel
        else:
            self.toplevel = Tk.Tk()
        self.status_var = StringVar(value='initializing')
        self._SetupCanvas()
        self._BuildGui()
        if not toplevel:
            Tk.mainloop()

    def _BuildGui(self):
        '''
        '''
        self.removei = IntVar(value=0)
        self.relative_start_time = BooleanVar(value=False)
        self.relative_stop_time = BooleanVar(value=False)
        self.continuous_updates = BooleanVar(value=False)
        self.ManualLimits = BooleanVar(value=False)
        self.LogYScale = BooleanVar(value=False)
        self.ShowGrid = BooleanVar(value=False)
        self.ConnectedPts = BooleanVar(value=True)
        Button(self.toplevel, text="Add Line", command=self._AddSubplot
               ).grid(row=0, column=1)
        self._AddSubplot()
        Button(self.toplevel, text="Gas Line Temps", command=self._PlotGasLines
               ).grid(row=0, column=2)
        Button(self.toplevel, text="Amps+Cell Temps", command=self._PlotCell
               ).grid(row=0, column=3)

        Label(self.toplevel, text='Start Time').grid(row=4, column=1)
        start_entry = Entry(self.toplevel, textvariable=self.start_t)
        start_entry.bind('<Return>', self.Update)
        start_entry.bind('<KP_Enter>', self.Update, '+')
        start_entry.grid(row=4, column=2, columnspan=2)
        Checkbutton(self.toplevel, text='Hours ago',
                    variable=self.relative_start_time).grid(row=4, column=4,
                                                            sticky='W')

        Label(self.toplevel, text='Stop Time').grid(row=5, column=1)
        stop_entry = Entry(self.toplevel, textvariable=self.stop_t)
        stop_entry.bind('<Return>', self.Update)
        stop_entry.bind('<KP_Enter>', self.Update, '+')
        stop_entry.grid(row=5, column=2, columnspan=2)
        Checkbutton(self.toplevel, text='Now',
                    variable=self.relative_stop_time).grid(row=5, column=4,
                                                           sticky='W')

        Label(self.toplevel, text='Y limits (min-max)').grid(row=7, column=1)
        ymin = Entry(self.toplevel, textvariable=self.ymin)
        ymin.grid(row=7, column=2)
        ymin.bind('<Return>', self.Update)
        ymin.bind('<KP_Enter>', self.Update, '+')
        ymax = Entry(self.toplevel, textvariable=self.ymax)
        ymax.grid(row=7, column=3)
        ymax.bind('<Return>', self.Update)
        ymax.bind('<KP_Enter>', self.Update, '+')
        Checkbutton(self.toplevel, text='Manual Y-limits', variable=self.ManualLimits
                    ).grid(row=8, column=1)
        Checkbutton(self.toplevel, text='Log Y-scale', variable=self.LogYScale
                    ).grid(row=8, column=2)
        Checkbutton(self.toplevel, text='Show Grid', variable=self.ShowGrid
                    ).grid(row=9, column=1)
        Checkbutton(self.toplevel, text='Connected Points', variable=self.ConnectedPts
                    ).grid(row=9, column=2)

        Button(self.toplevel, text="Update All", command=self.Update
               ).grid(row=10, column=1)
        Button(self.toplevel, text="Save Plot", command=self.SaveFigure
               ).grid(row=10, column=2)
        Button(self.toplevel, text="Save Json", command=self.SaveJson
               ).grid(row=10, column=3)
        Checkbutton(self.toplevel, text='Continuous (Button above to start)',
                    variable=self.continuous_updates
                    ).grid(row=11, column=1, columnspan=2)
        self.status_var.set('done')

        Label(self.toplevel, textvariable=self.status_var).grid(row=20,
                                                                column=1,
                                                                columnspan=2)

    def _SetupCanvas(self):
        '''
        '''
        self.figure = Figure()
        self.figure.subplots_adjust(left=0.15, bottom=0.2)
        self.subfigure = self.figure.add_subplot(1,1,1)
        self.notebook = Notebook(self.toplevel)
        self.notebook.grid(row=1, column=1, rowspan=3, columnspan=3, sticky='nsew')
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.toplevel)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0, column=0, rowspan=10)

    def _AddSubplot(self):
        '''
        '''
        plotnum = len(self.notebook.tabs())
        self.plot_dicts[plotnum] = {}
        frame = Frame(self.notebook)
        frame.pack(side='top', fill='both', expand='y')
        self.plot_dicts[plotnum]['xname'] = StringVar(value='None')
        self.plot_dicts['xunit'] = False
        self.plot_dicts[plotnum]['yname'] = StringVar(value='None')
        self.plot_dicts['yunit'] = False
        Label(frame, text='X Channel').grid(row=0, column=0)
        Label(frame, text='Y Channel').grid(row=1, column=0)
        OptionMenu(frame, self.plot_dicts[plotnum]['xname'],
                   "None", "time", "dpph_field", *self.pype.EligibleLoggers()
                   ).grid(row=0, column=1, sticky='ew')
        OptionMenu(frame, self.plot_dicts[plotnum]['yname'],
                   "None", "dpph_field", *self.pype.EligibleLoggers()
                   ).grid(row=1, column=1, sticky='ew')
        self.notebook.add(frame, text='line:'+str(plotnum))

    def _SetStartStop(self, event=None):
        '''
        '''
        try:
            if self.relative_stop_time.get():
                stop_time = datetime.utcnow()
            else:
                stop_time = datetime.strptime(self.stop_t.get(), time_format)
            if self.relative_start_time.get():
                hours = float(self.start_t.get())
                start = datetime.utcnow() - timedelta(hours=hours)
            else:
                start = datetime.strptime(self.start_t.get(), time_format)
            assert (start < stop_time)
            self.time_interval[0] = start.strftime(time_format)
            self.time_interval[1] = stop_time.strftime(time_format)
        except ValueError:
            showwarning('Warning', 'invalid time format, must match yyyy-mm-ddThh:mm:ssZ')
            raise TimeFormatError("invalid start or stop time format")
        except AssertionError:
            showwarning('Warning', 'time order error, stop time must be after start time')
            raise TimeOrderError("stop time must be after start time")

    def Update(self, event=None, tab='All', unpend=False):
        '''
            Call whatever sequence is needed to update local data and redraw
            the plot
        '''
        if self.abort:
            self.abort = False
            return
        if unpend:
            self.update_pending = False
        self.status_var.set('updating!')
        if tab == 'All':
            tab = range(len(self.notebook.tabs()))
        elif isinstance(tab, int):
            tab = [tab]
        else:
            raise ValueError('tab should be "All" or an int')
        try:
            self._SetStartStop(event=None)
        except:
            print('SetStartStop problems')
            self.abort = True
            
        self.subfigure.clear()
        for tabi in tab:
            if tabi > len(self.subfigure.get_lines()):
                print('wtf')
            elif tabi == len(self.subfigure.get_lines()):
                self._UpdateData(tab=tabi)
                self._MakePlot(tab=tabi)
            else:
                self._UpdateExisting(tab=tabi)
        self.figure.legends = []
        self.figure.legend(*self.subfigure.get_legend_handles_labels())
        self.figure.legends[0].draggable(True)
        self.canvas.draw()
        self.status_var.set('updated at: ' +
                            datetime.utcnow().strftime(time_format))
        if (self.continuous_updates.get() and self.relative_stop_time.get() and
                 not self.update_pending):
            self.update_pending = True
            self.toplevel.after(10000, lambda: self.Update(unpend=True))

    def _UpdateData(self, tab=0):
        '''
        '''
        try:
            yname = self.plot_dicts[tab]['yname'].get()
            ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0],
                                             self.time_interval[1])
            if self.plot_dicts[tab]['xname'].get() == 'time':
                xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0]))
            else:
                xname = self.plot_dicts[tab]['xname'].get()
                xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0],
                                                 self.time_interval[1])
            if tab > 0 and ychdat[0]:
                assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units'
                assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units'

            self.xdata = []
            self.ydata = []
            if ychdat[0]:
                for tx, x in zip(xchdat[0], xchdat[1]):
                    xtmp = False
                    ytmp = False
                    dt = timedelta(seconds=60)
                    for ty, y in zip(ychdat[0], ychdat[1]):
                        if abs(ty - tx) < dt:
                            dt = abs(ty - tx)
                            xtmp = x
                            ytmp = y
                    if xtmp and ytmp:
                        self.xdata.append(xtmp)
                        self.ydata.append(ytmp)
                [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata,
                                                           self.ydata)))
                self.plot_dicts['xunit'] = xchdat[2][0]
                self.plot_dicts['yunit'] = ychdat[2][0]
        except AssertionError as e:
            print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60)

    def _UpdateExisting(self, tab=0):
        '''
        '''
        try:
            yname = self.plot_dicts[tab]['yname'].get()
            ychdat = self.pype.GetTimeSeries(yname, self.time_interval[0],
                                             self.time_interval[1])
            if self.plot_dicts[tab]['xname'].get() == 'time':
                xchdat = (ychdat[0], ychdat[0], 'time' * len(ychdat[0]))
            else:
                xname = self.plot_dicts[tab]['xname'].get()
                xchdat = self.pype.GetTimeSeries(xname, self.time_interval[0],
                                                 self.time_interval[1])
            if tab > 0 and ychdat[0]:
                assert xchdat[2][0] == self.plot_dicts['xunit'], 'x units'
                assert ychdat[2][0] == self.plot_dicts['yunit'], 'y units'

            self.xdata = []
            self.ydata = []
            if ychdat[0]:
                for tx, x in zip(xchdat[0], xchdat[1]):
                    xtmp = False
                    ytmp = False
                    dt = timedelta(seconds=60)
                    for ty, y in zip(ychdat[0], ychdat[1]):
                        if abs(ty - tx) < dt:
                            dt = abs(ty - tx)
                            xtmp = x
                            ytmp = y
                    if xtmp and ytmp:
                        self.xdata.append(xtmp)
                        self.ydata.append(ytmp)
                [self.xdata, self.ydata] = zip(*sorted(zip(self.xdata,
                                                           self.ydata)))
                self.plot_dicts['xunit'] = xchdat[2][0]
                self.plot_dicts['yunit'] = ychdat[2][0]
            this_line = self.subfigure.get_lines()[tab]
            this_line.set_xdata(array(self.xdata))
            this_line.set_ydata(array(self.ydata))

        except AssertionError as e:
            print('*'*60, '\n the', e[0], 'do not match the 0th line', '*'*60)

    def _MakePlot(self, tab=0):
        '''
        '''
        if self.ConnectedPts.get():
            plotformat='o-'
        else:
            plotformat='o'
        if self.plot_dicts[tab]['xname'].get() == 'time':
            self.subfigure.plot_date(self.xdata, self.ydata, plotformat,
                                          label=self.plot_dicts[tab]['yname'].get())
            self.subfigure.set_xticklabels(self.subfigure.get_xticklabels(),
                                           rotation=-45)
            self.subfigure.xaxis.set_major_formatter(dates.DateFormatter(
                "%m/%d %H:%M"))
            self.subfigure.yaxis.set_major_formatter(ticker.ScalarFormatter(
                useOffset=False))
        else:
            self.subfigure.plot(self.xdata, self.ydata, plotformat,
                                label=self.plot_dicts[tab]['yname'].get())
        self.subfigure.set_title(self.plot_dicts[tab]['yname'].get() +
                                 ' vs ' +
                                 self.plot_dicts[tab]['xname'].get() +
                                 '\n from ' + self.time_interval[0] +
                                 ' to ' + self.time_interval[1])
        xname = self.plot_dicts[tab]['xname'].get().replace('_', ' ')
        xunit = '[' + str(self.plot_dicts['xunit']) + ']'
        self.subfigure.set_xlabel(xname + ' ' + xunit)
        yname = self.plot_dicts[tab]['yname'].get().replace('_', ' ')
        yunit = '[' + str(self.plot_dicts['yunit']) + ']'
        self.subfigure.set_ylabel(yname + ' ' + yunit)
        tickformat = ticker.ScalarFormatter(useOffset=False)
        if self.ManualLimits.get():
            self.subfigure.set_ylim(bottom=self.ymin.get(), top=self.ymax.get())
        if self.LogYScale.get():
            self.subfigure.set_yscale('log')
        if self.ShowGrid.get():
            self.subfigure.grid(b=True, which='major')
            self.subfigure.grid(b=True, which='minor')

    def _PlotGasLines(self):
        '''
        '''
        gas_lines = ['left_gas_line_lower_t',
                     'left_gas_line_upper_t',
                     'right_gas_line_lower_t',
                     'right_gas_line_upper_t']
        self._PlotSet(gas_lines)

    def _PlotCell(self):
        '''
        '''
        sensors = ['kh2_temp', 'kh3_temp', 'waveguide_cell_body_temp',
                   'coldhead_temp']
        self._PlotSet(sensors)

    def _PlotSet(self, channels):
        '''
            Plots a set of channels on common axes
        '''
        for plotn, channel in enumerate(channels):
            if (len(self.plot_dicts)-2) <= plotn:
                self._AddSubplot()
            self.plot_dicts[plotn]['xname'].set('time')
            self.plot_dicts[plotn]['yname'].set(channel)
        self.start_t.set('3')
        self.relative_start_time.set(True)
        self.relative_stop_time.set(True)
        self.continuous_updates.set(True)
        self.Update()

    def SaveFigure(self):
        '''
        '''
        file_extensions = [('vectorized', '.eps'), ('adobe', '.pdf'),
                           ('image', '.png'), ('all', '.*')]
        outfile = asksaveasfilename(defaultextension='.pdf',
                                    filetypes=file_extensions)
        self.figure.savefig(outfile)


    def SaveJson(self):
        '''
        '''
        outfile = asksaveasfile(defaultextension='.json')
        outdict = {'xunit':self.plot_dicts['xunit'],
                   'yunit':self.plot_dicts['yunit']
                  }
        for tab in range(len(self.plot_dicts)-2):
            outdict[tab] = {}
            outdict[tab]['xname']=self.plot_dicts[tab]['xname'].get()
            outdict[tab]['yname']=self.plot_dicts[tab]['yname'].get()
            this_line = self.subfigure.get_lines()[tab]
            if outdict['xunit'] == 't':
                outdict[tab]['xdata'] = [str(t) for t in this_line.get_xdata()]
            else:
                outdict[tab]['xdata'] = list(this_line.get_xdata())
            outdict[tab]['ydata'] = list(this_line.get_ydata())

        dump(outdict, outfile, indent=4)
        outfile.close()
예제 #2
0
class View(Toplevel):
    def __init__(self, model):
        self.model = model
        self.model_config = self.model.get_config()
        self.channels_num = 0
        self.channels_amount = 0

        self.root = Tk()
        self.root.resizable(width=FALSE, height=FALSE)
        self.root.title("RaaS. event_proxy configurator")
        #: self.root.iconbitmap('resourse/vit.ico')
        self.config_route = self.model.get_config_route()

        self.panelFrame = Frame(self.root, height=60)
        self.canvas = Canvas(self.root, borderwidth=0)
        self.textFrame = Frame(self.canvas, height=340, width=600)
        self.mainFrame = LabelFrame(self.root, width=200, text="Main:",
                                    height=340, relief=RAISED, borderwidth=1)
        self.chanelFrame = LabelFrame(self.root, width=370, text="Channels:",
                                      height=340, relief=RAISED, borderwidth=1)

        #: self.vsb = Scrollbar(self.root, orient="horizontal",
        #:                     command=self.canvas.xview)
        #:self.canvas.configure(xscrollcommand=self.vsb.set)
        #:self.vsb.pack(side="bottom", fill="x")
        self.canvas.pack(side="bottom", fill="both", expand=True)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        self.root.protocol("WM_DELETE_WINDOW", self.quit_handler)

        self.tabs = Notebook(self.root)
        self.in_channel_text = []
        self.out_port_text = []
        self.out_channel_text = []

        self.c = self.model.get_channels().keys()
        self.channels_len = len(self.model.get_channels())
        #:print self.model.get_channels()
        self.panelFrame.pack(side='top', fill='x')
        self.textFrame.pack(side='bottom', fill='both', expand=1)
        self.mainFrame.place(x=10, y=60)
        self.chanelFrame.place(x=220, y=60)
        self.tabs.place(x=230, y=80)

        x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2
        y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2
        self.root.geometry("+%d+%d" % (x-150, y-150))

        for i in range(self.channels_len):
            self.channels_num += 1
            self.channels_amount += 1

            self.f1 = Frame(self.tabs, height=290, width=350)
            self.tabs.add(self.f1, text='Channel {0}'.format(i + 1))

            self.in_channel = Label(self.f1, text="In channel")
            self.out_port = Label(self.f1, text="Out port")
            self.out_channel = Label(self.f1, text="Out channel")

            self.in_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.in_channel_text[i].insert(0, self.c[i])

            self.out_port_text.append(Entry(self.f1, width=20, bd=3))
            self.out_port_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_port)

            self.out_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.out_channel_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_channel)

            self.in_channel.place(x=5, y=10)
            self.in_channel_text[i].place(x=5, y=30)

            self.out_port.place(x=5, y=50)
            self.out_port_text[i].place(x=5, y=70)

            self.out_channel.place(x=5, y=90)
            self.out_channel_text[i].place(x=5, y=110)

            self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format(
                self.channels_amount),
                                     command=
                                     lambda: self.del_channel(i))
            self.del_ch_btn.bind("<Button-1>")
            self.del_ch_btn.place(x=5, y=140, width=100, height=30)

        self.server_host_label = Label(self.root, text="Server host")
        self.server_port_label = Label(self.root, text="Server port")
        self.raas_port_label = Label(self.root, text="Raas port")
        self.encoding_label = Label(self.root, text='Encoding')
        self.levenshtein_distance_label = Label(self.root,
                                                text='Levenshtein distance')
        self.window_time_label = Label(self.root, text='Window time')

        self.server_host_entity = Entry(self.root, width=20, bd=3)
        self.server_host_entity.insert(0, self.model_config['server_host'])

        self.server_port_entity = Entry(self.root, width=20, bd=3)
        self.server_port_entity.insert(0, self.model_config['server_port'])

        self.raas_port_entity = Entry(self.root, width=20, bd=3)
        self.raas_port_entity.insert(0, self.model_config['raas_port'])

        self.encoding_entry = Entry(self.root, width=20, bd=3)
        self.encoding_entry.insert(0, self.model_config['encoding'])

        self.levenshtein_distance_entry = Entry(self.root, width=20, bd=3)
        self.levenshtein_distance_entry.insert(0, self.model_config[
            'levenshtein_distance'])

        self.window_time_entry = Entry(self.root, width=20, bd=3)
        self.window_time_entry.insert(0, self.model_config['window_time'])

        self.var = IntVar()
        self.cfg_debug = self.model_config['debug']
        if self.cfg_debug == 'True':
            self.var.set(1)
        else:
            self.var.set(0)
        self.check_debug = Checkbutton(self.root, text='Debug',
                                       variable=self.var)

        self.filter_var = IntVar()
        self.cfg_use_filter = self.model_config['use_filter']
        if self.cfg_use_filter == 'True':
            self.filter_var.set(1)
        else:
            self.filter_var.set(0)
        self.check_use_filter = Checkbutton(self.root, text='Use filter',
                                            variable=self.filter_var)

        self.addBtn = Button(self.panelFrame, text='Add channel')
        self.saveBtn = Button(self.panelFrame, text='Save')
        self.quitBtn = Button(self.panelFrame, text='Quit')

        self.saveBtn.bind("<Button-1>", self.SaveFile)
        self.quitBtn.bind("<Button-1>", self.Quit)
        self.addBtn.bind("<Button-1>", self.add_channel)

        self.saveBtn.place(x=10, y=10, width=40, height=40)
        self.quitBtn.place(x=60, y=10, width=40, height=40)
        self.addBtn.place(x=220, y=10, width=80, height=40)

        self.server_host_label.place(x=20, y=80)
        self.server_host_entity.place(x=20, y=100)

        self.server_port_label.place(x=20, y=120)
        self.server_port_entity.place(x=20, y=140)

        self.raas_port_label.place(x=20, y=160)
        self.raas_port_entity.place(x=20, y=180)

        self.encoding_label.place(x=20, y=200)
        self.encoding_entry.place(x=20, y=220)

        self.check_debug.place(x=20, y=250)
        self.f = Frame(self.root, height=1, width=190, bg='grey')
        self.f.place(x=15, y=275)

        self.levenshtein_distance_label.place(x=20, y=280)
        self.levenshtein_distance_entry.place(x=20, y=300)

        self.window_time_label.place(x=20, y=320)
        self.window_time_entry.place(x=20, y=340)

        self.check_use_filter.place(x=20, y=370)

    def del_channel(self, numb):
        rwidth = self.root.winfo_width()
        rheight = self.root.winfo_height()
        if self.channels_num > 6:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 65)
            self.root.geometry("%dx%d" % (rwidth - 65, rheight))

        if self.channels_num == 6:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 20)
            self.root.geometry("%dx%d" % (rwidth - 20, rheight))

        dvar = self.tabs.tabs().index(self.tabs.select())

        self.in_channel_text.pop(dvar)
        self.out_channel_text.pop(dvar)
        self.out_port_text.pop(dvar)
        self.channels_num -= 1
        self.tabs.forget(self.tabs.select())

        tabs_list = self.tabs.tabs()
        self.root.update()

    def add_channel(self, env):
        if self.channels_num > 15:
            tkMessageBox.showerror('Error',
                                   'You can not add more than 16 channels')
            return False

        rwidth = self.root.winfo_width()
        rheight = self.root.winfo_height()

        if self.channels_num == 5:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 20)
            self.root.geometry("%dx%d" % (rwidth + 20, rheight))

        if self.channels_num > 5:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 65)
            self.root.geometry("%dx%d" % (rwidth + 65, rheight))

        self.f1 = Frame(self.tabs, height=290, width=350)
        self.tabs.add(self.f1,
                      text='Channel {0}'.format(self.channels_amount + 1))

        self.in_channel = Label(self.f1, text="In channel")
        self.out_port = Label(self.f1, text="Out port")
        self.out_channel = Label(self.f1, text="Out channel")

        self.in_channel_text.append(Entry(self.f1, width=20, bd=3))

        self.out_port_text.append(Entry(self.f1, width=20, bd=3))

        self.out_channel_text.append(Entry(self.f1, width=20, bd=3))

        self.in_channel.place(x=5, y=10)
        self.in_channel_text[self.channels_num].place(x=5, y=30)

        self.out_port.place(x=5, y=50)
        self.out_port_text[self.channels_num].place(x=5, y=70)

        self.out_channel.place(x=5, y=90)
        self.out_channel_text[self.channels_num].place(x=5, y=110)

        self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format(
            self.channels_num + 1),
                                 command=
                                 lambda: self.del_channel(self.channels_num))
        self.del_ch_btn.bind("<Button-1>")
        self.del_ch_btn.place(x=5, y=140, width=100, height=30)

        self.channels_num += 1
        self.channels_amount += 1

    def Quit(self, env):
        if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'):
            self.SaveFile(env)
        self.root.destroy()

    def quit_handler(self):
        if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'):
            self.save_handler()
        self.root.destroy()

    def validate_int(self, var, text, channel):
        if not var.isdigit():
            tkMessageBox.showerror("Error",
                                   "Error in {1}. Value of field '{0}' must be int.".format(text, channel))
            return False
        return True

    def validate_empty(self, var, text):
        if not var:
            tkMessageBox.showerror("Error",
                                   "Field {0} must be not empty.".format(text))
            return False
        return True

    def validate_channels(self):
        if not self.channels_num:
            tkMessageBox.showerror("Error",
                                   "You must add at least one channel")
            return False
        return True

    def validate_change_field(self):
        self.validating_config = self.model.get_updated_config()
        self.flag = False
        if self.server_host_entity.get() != str(self.validating_config['server_host']):
            self.flag = True
        if self.server_port_entity.get() != str(self.validating_config['server_port']):
            self.flag = True
        if self.raas_port_entity.get() != str(self.validating_config['raas_port']):
            self.flag = True
        if self.encoding_entry.get() != str(self.validating_config['encoding']):
            self.flag = True
        if str(self.levenshtein_distance_entry.get()) != str(self.validating_config['levenshtein_distance']):
            self.flag = True
        if str(self.window_time_entry.get()) != str(self.validating_config['window_time']):
            self.flag = True
        self.tmp = IntVar()
        if self.validating_config['debug'] == 'True':
            self.tmp.set(1)
        else:
            self.tmp.set(0)
        if self.tmp.get() != self.var.get():
            self.flag = True
        self.tmp_filter = IntVar()
        if self.validating_config['use_filter'] == 'True':
            self.tmp_filter.set(1)
        else:
            self.tmp_filter.set(0)
        if self.tmp_filter.get() != self.filter_var.get():
            self.flag = True
        #TODO: add validating of channels
        if self.channels_num != self.channels_amount or self.channels_len != self.channels_num:
            return True
        for i in range(self.channels_num):
            if self.in_channel_text[i].get() != str(self.c[i]):
                self.flag = True
            if self.out_port_text[i].get() != str(self.model.get_channels()[
                self.c[i]].out_port):
                self.flag = True
            if self.out_channel_text[i].get() != str(self.model.get_channels()[
                self.c[i]].out_channel):
                self.flag = True
        return self.flag

    def validate_all(self):
        #if not self.validate_change_field():
        #    return False
        if not self.validate_channels():
            return False
        if not self.validate_empty(self.server_host_entity.get(),
                                   'Server host'):
            return False
        if not self.validate_empty(self.encoding_entry.get(), 'Encoding'):
            return False
        if not self.validate_empty(self.levenshtein_distance_entry.get(),
                                   'Levenshtein distance'):
            return False
        if not self.validate_int(self.server_port_entity.get(), 'Server port',
                                 ''):
            return False
        if not self.validate_int(self.raas_port_entity.get(), 'Raas port', ''):
            return False
        if not self.validate_int(self.levenshtein_distance_entry.get(),
                                 'Levenshtein distance', ''):
            return False
        if not self.validate_int(self.window_time_entry.get(), 'Window time',
                                 ''):
            return False
        for i in range(self.channels_num):
            if not self.validate_int(self.in_channel_text[i].get(),
                                     'In channel',
                                     ' Channel {0}'.format(i + 1)):
                return False
            if not self.validate_int(self.out_port_text[i].get(), 'Out port',
                                     ' Channel {0}'.format(i + 1)):
                return False
            if not self.validate_int(self.out_channel_text[i].get(),
                                     'Out channel',
                                     ' Channel {0}'.format(i + 1)):
                return False
        return True

    def SaveFile(self, env):
        self.save_handler()

    def save_handler(self):
        if not self.validate_all():
            return False

        config = ConfigParser.RawConfigParser()
        config.add_section('Main')
        config.set('Main', 'server_host', self.server_host_entity.get())
        config.set('Main', 'server_port', self.server_port_entity.get())
        config.set('Main', 'raas_port', self.raas_port_entity.get())
        result = 'False'
        if self.var.get():
            result = 'True'
        config.set('Main', 'debug', result)
        config.set('Main', 'encoding', self.encoding_entry.get())
        config.set('Main', 'levenshtein_distance',
                   self.levenshtein_distance_entry.get())
        config.set('Main', 'window_time', self.window_time_entry.get())
        result_filter = 'False'
        if self.filter_var.get():
            result_filter = 'True'
        config.set('Main', 'use_filter', result_filter)

        for i in range(self.channels_num):
            config.add_section('Channel{0}'.format(i + 1))
            config.set('Channel{0}'.format(i + 1), 'in_channel',
                       self.in_channel_text[i].get())
            config.set('Channel{0}'.format(i + 1), 'out_port',
                       self.out_port_text[i].get())
            config.set('Channel{0}'.format(i + 1), 'out_channel',
                       self.out_channel_text[i].get())

        with open(self.config_route, 'wb') as configfile:
            config.write(configfile)
        tkMessageBox.showinfo("Info", "Successfully saved.")

    def run(self):
        self.root.mainloop()
예제 #3
0
    def __init__(self):

        self.tasks = None
        self.mainTerminated = None
        self.results = None
        self.awaited = None

        self.reqParser = RawQueryParser()

        self.defaultCfg = defaultCfg
        self.stlist = STAT_TYPES.keys()

        # set main window parameters
        mainWindow = SmartTk()
        mainWindow.title(_WindowLabels.window_title)
        self.root = mainWindow
        mainWindow.minsize(650, 450)

        # there are two frames with different finctions.
        # In fact, they work separately but use the same set of settings.
        generalframe = SettingHybrid(mainWindow)
        tabframe = Frame(mainWindow)

        self.settings = generalframe

        nb = Notebook(tabframe)
        nbUrlTab = Frame()
        nbFileEditingTab = Frame()
        nbStatTab = StatTypeFrame()
        self.statTab = nbStatTab
        self.homeDir = None


        qField = ParameterInputText(nbFileEditingTab)
        self.qField = qField
        qReadingButton = Button(nbFileEditingTab, text = u'OK', command = self.get_request_from_raw_query_window)

        self.urlText = CopyPasteText(nbUrlTab)
        urlButton = Button(nbUrlTab, text = u'OK', command = self.get_query_from_url_window)

        self.urlText.pack(fill=BOTH, expand=1)
        urlButton.pack()

        self.b1 = urlButton
        self.b2 = qReadingButton

        nb.add(nbFileEditingTab, text = tabs['file'])
        nb.add(nbUrlTab, text = tabs['url'])
        nb.add(nbStatTab, text = tabs['st'])

        minTabFrameWidth = 0
        for tab in nb.tabs():
            minTabFrameWidth += len(nb.tab(tab)['text'])

        self.root.config(width = minTabFrameWidth + 200)

        qField.pack(fill=BOTH, expand=1)
        qReadingButton.pack()
        #nbUrlTab.pack()
        nb.pack(fill=BOTH, expand=1)

        self.nb = nb # to manage tabs

        generalframe.pack(expand=0, side = 'left')
        tabframe.pack(fill=BOTH, expand=1)

        generalframe.bind_to_statistics_frame(nbStatTab)

        self.enable_keyboard_managing()
        self._add_menu()