Example #1
0
class DlgLogin(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.site = StringVar()
        self.site.set(cfg.get("site", ""))
        self.login = StringVar()
        self.login.set(cfg.get("user", ""))
        self.password = StringVar()
        self.password.set(str(cfg.get("password", "")))
        site = Entry(master, width=15, textvariable=self.site)
        site.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Site:")).grid(column=0, row=0, sticky="w")
        loge = Entry(master, width=15, textvariable=self.login)
        loge.grid(column=1, row=1, sticky="e")
        Label(master, text=_("Username:"******"w")
        pase = Entry(master, width=15, textvariable=self.password, show="*")
        pase.grid(column=1, row=2, sticky="e")
        Label(master, text=_("Password:"******"w")
        self.to_remember = IntVar()
        self.to_remember.set(cfg.get("remember_passwd", 1))
        chk1 = Checkbutton(master, text="Remember",
                           variable=self.to_remember)
        chk1.grid(column=0, row=3, sticky="w", columnspan=2)
        self.resizable(width=0, height=0)
        return loge

    def apply(self):
        "On ok button pressed"
        self.config["remember_passwd"] = self.to_remember.get()
        self.config["site"] = self.site.get()
        self.config["user"] = self.login.get()
        self.config["password"].set_password(self.password.get())
        self.config["OK button"] = True
class NetworkPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.generalnavframe = ttk.Frame(self)
        self.generalnavframe.grid(row=0, column=0, sticky="nsew")

        self.generalpagebutt = tk.Button(self.generalnavframe, text="General", width=10, height=3, command=lambda: controller.show_frame(GeneralPage))
        self.generalpagebutt.grid(row=0, column=0)

        self.filesyspagebutt = tk.Button(self.generalnavframe, text="File System", width=10, height=3, command=lambda: controller.show_frame(FileSYSPage))
        self.filesyspagebutt.grid(row=0, column=1)

        self.serialpagebutt = tk.Button(self.generalnavframe, text="Serial", width=10, height=3, command=lambda: controller.show_frame(SerialPage))
        self.serialpagebutt.grid(row=0, column=2)

        self.networkpagebutt = tk.Button(self.generalnavframe, text="Network", width=10, height=3, bg='gray', command=lambda: controller.show_frame(NetworkPage))
        self.networkpagebutt.grid(row=0, column=3)

        self.generalcontrollsframe = ttk.Frame(self)  # secondary frame with page controlls
        self.generalcontrollsframe.grid(row=1, column=0, sticky="nsew")

        self.var = IntVar()
        self.var.set(2)

        self.dhcp = ttk.Radiobutton(self.generalcontrollsframe, text="Dhcp", variable=self.var, value=2)
        self.dhcp.grid(row=0, column=1)

        self.static = ttk.Radiobutton(self.generalcontrollsframe, text="Static", variable=self.var, value=1)
        self.static.grid(row=0, column=0)

        self.ipaddress = ttk.Label(self.generalcontrollsframe, text="Ip Address")
        self.ipaddress.grid(row=1, column=0)
        self.ipaddrv4 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.ipaddrv4.grid(row=1, column=1)

        self.subnetlbl = ttk.Label(self.generalcontrollsframe, text="Subnet")
        self.subnetlbl.grid(row=2, column=0)
        self.subnet = ttk.Entry(self.generalcontrollsframe, width=16)
        self.subnet.grid(row=2, column=1)

        self.gatewaylbl = ttk.Label(self.generalcontrollsframe, text="Gateway")
        self.gatewaylbl.grid(row=3, column=0)
        self.gateway = ttk.Entry(self.generalcontrollsframe, width=16)
        self.gateway.grid(row=3, column=1)

        self.dns1lbl = ttk.Label(self.generalcontrollsframe, text="Dns1")
        self.dns1lbl.grid(row=4, column=0)
        self.dns1 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.dns1.grid(row=4, column=1)

        self.dns2lbl = ttk.Label(self.generalcontrollsframe, text="Dns2")
        self.dns2lbl.grid(row=5, column=0)
        self.dns2 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.dns2.grid(row=5, column=1)

        self.setnetwork = ttk.Button(self.generalcontrollsframe, text="Set", width=16)
        self.setnetwork.grid(row=7, column=0, columnspan=2)
Example #3
0
class Checkbox(Checkbutton):
    def __init__(self, master, text, default=None, **args):
        self.var = IntVar()
        Checkbutton.__init__(self, master, text=text, variable=self.var, **args)
        if default is not None:
            self.var.set(default)

    def get(self):
        return self.var.get()
Example #4
0
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, "%P"))

        self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply"))
        # self.divide_button = Button(master, text="/", command=lambda: self.update("divide"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
        return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        elif method == "multiply":
            self.total *= self.entered_number
        elif method == "divide":
            self.total /= self.entered_number
        else:  # reset
            self.total = 0
        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
Example #5
0
class FrameKSPObject(Frame):
    
    
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        frame = Frame(self)
        frame.pack()
        self.string_var0 = StringVar()
        self.string_var1 = StringVar()
        self.int_var = IntVar()
        self.entry0 = Entry(frame, textvariable=self.string_var0)
        self.entry0.pack(side='left')
        Entry(frame, textvariable=self.string_var1).pack(side='left')
        frame = Frame(self)
        frame.pack()
        Button(frame, width=8, text='Accept', command=self.accept).pack(side='left')
        Button(frame, width=8, text='Cancel', command=self.cancel).pack(side='left')
        Button(frame, width=8, text='Delete', command=self.delete).pack(side='left')
        
        
    def populate(self, kspobject):
        self._kspobject = kspobject
        self.string_var0.set(kspobject.name)
        self.string_var1.set(kspobject.value)
        self.int_var.set(kspobject.id_)
        
        
    def accept(self):
        name = self.string_var0.get()
        value = self.string_var1.get()
        id_ = self.int_var.get()
        self.master.master.update_kspobject(name, value, id_)
        self.master.destroy()
    
    
    def cancel(self):
        self.master.destroy()
    
    
    def delete(self):
        id_ = self.int_var.get()
        self.master.master.delete_kspobject(id_)
        self.master.destroy()
        
        
        
        
        
        
        
        
        
        
        
        
        
Example #6
0
class DiceTab(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        #Sides of Dice
        labelSides=Label(self,text="Sides")
        labelSides.grid(row=0,column=0)
        self.sides=StringVar()
        self.sides.set(20)
        spinboxSides=Spinbox(self,from_=1,to=20,increment=1,width=4)
        spinboxSides.config(textvariable=self.sides, font="sans 24", justify="center")
        spinboxSides.grid(row=0,column=1)
        #Number of Dices
        labelNumber=Label(self,text="Number")
        labelNumber.grid(row=1,column=0)
        self.number=StringVar()
        self.number.set(1)
        spinboxNumber=Spinbox(self,from_=1,to=30,increment=1,width=4)
        spinboxNumber.config(textvariable=self.number, font="sans 24", justify="center")
        spinboxNumber.grid(row=1,column=1)
        #Modifier
        labelModifier=Label(self,text="Modifier")
        labelModifier.grid(row=2,column=0)
        self.modifier=StringVar()
        self.modifier.set(0)
        spinboxModifier=Spinbox(self,from_=-5,to=5,increment=1,width=4)
        spinboxModifier.config(textvariable=self.modifier, font="sans 24", justify="center")
        spinboxModifier.grid(row=2,column=1)
        #Hide Checkbox
        labelHide=Label(self, text="Hide")
        labelHide.grid(row=2, column=2)
        self.hide=IntVar()
        self.hide.set(0)
        checkbuttonHide=Checkbutton(self,variable=self.hide)
        checkbuttonHide.grid(row=2,column=3)
        #Result display
        self.result=StringVar()
        self.result.set("")
        labelResult1=Label(self,text="Result")
        labelResult1.grid(row=1, column=4)
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN,width=4)
        labelResult2.grid(row=1,column=5)
        #Button to roll
        buttonRoll=Button(self,text="Roll!", command=self.roll)
        buttonRoll.grid(row=2,column=5)
        

    def roll(self):
        self.throws=[]
        numberOfDices=int(self.number.get())
        sidesOfDice=int(self.sides.get())
        modifierOfDice=int(self.modifier.get())
        
        for i in range(numberOfDices):
            self.throws.append(rd.randint(1,sidesOfDice))
        self.result.set(str(sum(self.throws)+modifierOfDice))
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN, width=4)
        labelResult2.grid(row=1,column=5)
Example #7
0
class ProgressCheckButton(Frame, Observable):
    def __init__(self, parent, model, index, status_model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self.model = model
        self.index = index
        self.status_model = status_model
        self.var = IntVar()
        self.var.set(model.get_checked())
        self.progress_var = IntVar()
        self.progress_status = ProgressStatus.undefined
        self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self.model.add_listener(self._model_changed)

    def _model_changed(self, new_status):
        model_state = self.model.get_checked()
        gui_state = self.var.get()
        if model_state is not gui_state:
            self.model.set_checked(gui_state)

    def refresh_check(self):
        if self.status_model.is_checked_force_reload():
            self.check_button.select()
        else:
            self.check_button.deselect()

    def is_checked(self):
        return self.var.get()

    def _progress_status_changed(self, new_status):
        self._refresh_progress()

    def _refresh_progress(self):
        status = self.status_model.get_status()
        if not status == self.progress_status:
            if status == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _check_changed(self):
        new_checked = self.var.get()
        if new_checked is not self.model.get_checked():
            self.model.set_checked(new_checked)
        if new_checked is not self.status_model.is_checked():
            self._notify(self.index, new_checked)
Example #8
0
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)

    def _model_changed(self):
        self.update()

    def _update(self):
        # Update check status
        model_check_state = self._model.get_check_status()
        if model_check_state is not self._current_gui_checked_state:
            self._current_gui_checked_state = model_check_state
            # if self.status_model.is_checked_force_reload():
            if model_check_state:
                self.check_button.select()
            else:
                self.check_button.deselect()

        # Update progress status
        model_progress_state = self._model.get_progress_status
        if not model_progress_state == self._current_gui_progress_state:
            self._current_gui_progress_state = model_progress_state
            if model_progress_state == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
Example #9
0
class Options(Frame):
    def __init__(self, master, ordinances=False, **kwargs):
        super(Options, self).__init__(master, **kwargs)
        self.ancestors = IntVar()
        self.ancestors.set(4)
        self.descendants = IntVar()
        self.spouses = IntVar()
        self.ordinances = IntVar()
        self.contributors = IntVar()
        self.start_indis = StartIndis(self)
        self.fid = StringVar()
        btn = Frame(self)
        entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16)
        entry_fid.bind('<Key>', self.enter)
        label_ancestors = Label(self, text=_('Number of generations to ascend'))
        entry_ancestors = EntryWithMenu(self, textvariable=self.ancestors, width=5)
        label_descendants = Label(self, text=_('Number of generations to descend'))
        entry_descendants = EntryWithMenu(self, textvariable=self.descendants, width=5)
        btn_add_indi = Button(btn, text=_('Add a FamilySearch ID'), command=self.add_indi)
        btn_spouses = Checkbutton(self, text='\t' + _('Add spouses and couples information'), variable=self.spouses)
        btn_ordinances = Checkbutton(self, text='\t' + _('Add Temple information'), variable=self.ordinances)
        btn_contributors = Checkbutton(self, text='\t' + _('Add list of contributors in notes'), variable=self.contributors)
        self.start_indis.grid(row=0, column=0, columnspan=3)
        entry_fid.grid(row=0, column=0, sticky='w')
        btn_add_indi.grid(row=0, column=1, sticky='w')
        btn.grid(row=1, column=0, columnspan=2, sticky='w')
        entry_ancestors.grid(row=2, column=0, sticky='w')
        label_ancestors.grid(row=2, column=1, sticky='w')
        entry_descendants.grid(row=3, column=0, sticky='w')
        label_descendants.grid(row=3, column=1, sticky='w')
        btn_spouses.grid(row=4, column=0, columnspan=2, sticky='w')
        if ordinances:
            btn_ordinances.grid(row=5, column=0, columnspan=3, sticky='w')
        btn_contributors.grid(row=6, column=0, columnspan=3, sticky='w')
        entry_ancestors.focus_set()

    def add_indi(self):
        if self.start_indis.add_indi(self.fid.get()):
            self.fid.set('')

    def enter(self, evt):
        if evt.keysym in {'Return', 'KP_Enter'}:
            self.add_indi()
Example #10
0
class VariableLabel:
    def __init__(self,parent,col,row,genre):

        """

        :param parent: fenetre root
        :param col: colonne pour placer le label
        :param row: ligne pour placer le label
        :param genre: type de label (int ou str)
        """
        self.val=StringVar()
        self.val.set("RED")
        if (genre=="integer"):
            self.val=IntVar()
            self.val.set(0)
        label=Label(parent,textvariable=self.val,bg="bisque")
        label.grid(column=col,row=row)

    def getVar(self):
        return(self.val)

    def setVar(self,valeur):
        """

        :param valeur: nouvelle valeur du Label
        """
        self.val.set(valeur)
Example #11
0
class Status_Bar(Frame):
    """
    The status bar visualizes progress and status.
    """
    task = None

    def __init__(self, _master):
        super(Status_Bar, self).__init__(_master, bd=1, relief=SUNKEN)

        self.task = StringVar()
        self.progress = IntVar()
        self.init_widgets()

    def update_task(self, _task, _progress):
        """ This function is used as an endpoint for for the
        bubbling notify_task call of the BPMFrame class.
        :param _task: Text that defines the task
        :param _progress: Text that describes the degree of progress
        """
        if _progress < 0:
            self.pb_progress.mode = 'indeterminate'
        else:
            self.pb_progress.mode = 'determinate'

        self.task.set(_task)
        self.progress.set(_progress)
        self.update_idletasks()

    def init_widgets(self):
        """
        Initialize visual elements.
        """

        self.l_task = ttk.Label(self, textvariable=self.task, width=70)
        self.l_task.pack(side=LEFT, fill=X)

        self.pb_progress = ttk.Progressbar(self, variable=self.progress, length=150)
        self.pb_progress.pack(side=RIGHT)
    def _create_frame_with_radio_btns(self, parent, name, text, row_index,
                                      column_index, add_both=True):
        ''' Creates frame with one set of Radiobuttons.

            Args:
                parent (Tk object): parent of the frame.
                name (str): name of the parameter that will a key in options
                    dictionary.
                text (list of str): list with two parameter values that should
                    be displayed next to the first two Radiobuttons.
                row_index (int): index of the row where the frame should
                    be placed using grid method.
                column_index (int): index of the column where the frame
                    should be placed using grid method.
                add_both (bool, optional): True if the third Radiobutton
                    with text "both" must be displayed, False otherwise,
                    defaults to True.
        '''
        assert len(text) == 2
        v = IntVar()
        self.options[name] = v
        self.options[name].trace(
            'w', (lambda *args: self.radio_btn_change(name)))
        frame_with_radio_btns = Frame(parent)
        first_option = Radiobutton(frame_with_radio_btns,
                                   text=text[0], variable=v, value=1)
        first_option.grid(row=0, column=0, sticky=W+N, padx=2)
        v.set(1)
        second_option = Radiobutton(frame_with_radio_btns,
                                    text=text[1], variable=v, value=2)
        second_option.grid(row=1, column=0, sticky=W+N, padx=2)
        if add_both:
            both = Radiobutton(frame_with_radio_btns, text='Both',
                               variable=v, value=3)
            both.grid(row=3, column=0, sticky=W+N, padx=2)
        frame_with_radio_btns.grid(row=row_index, column=column_index,
                                   padx=1, pady=5, sticky=W+N)
Example #13
0
class MainMenu():
    def main(self):
        '''Function to run on game start'''
        self.mainMenu=Tk()
        self.mainMenu.geometry('200x300+200+200')
        self.mainMenu.title("Minesweeper")
        playButton=Button(self.mainMenu,text='Play',command=lambda:self.startPlay(None))

        self.height= IntVar()
        self.width= IntVar()
        self.minesAmount= IntVar()

        self.height.set(10)
        self.width.set(10)
        self.minesAmount.set(10)

        playButton.pack()
        
        xSlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Height',sliderlength=20,from_=1,to=15,tickinterval=0,variable=self.height).pack()
        ySlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Width',sliderlength=20,from_=1,to=15,tickinterval=0,variable=self.width).pack()      
        minesSlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Mines',sliderlength=20,from_=0,to=15*15-1,tickinterval=0,variable=self.minesAmount).pack()
        
        aboutButton=Button(self.mainMenu,text='About',command=self.about)
        quitButton=Button(self.mainMenu,text='Quit',command=self.quitApp)

        
        
        aboutButton.pack()
        quitButton.pack()

    def startPlay(self,event):
        play=Play()
        minesAmount=self.minesAmount.get()
        height=self.height.get()
        width=self.width.get()
        if minesAmount>width*height-1:
            messagebox.showerror(title='Error',message="Amount of mines can't be bigger than total size of the field. Plese try again.")
            return
        self.mainMenu.destroy()
        play.StartGame(minesAmount,height,width)

    def about(self):
        messagebox.showinfo(title='About',message='Author:Marcel Salmič.')
        
    def quitApp(self):
        self.mainMenu.destroy()
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title("DRT Glue Demo")

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.self._error = None
        self._init_fonts(self._top)

        self._examples = examples
        self._readingCache = [None for example in examples]

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Set the data to None
        self._curExample = -1
        self._readings = []
        self._drs = None
        self._drsWidget = None
        self._error = None

        self._init_glue()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_exampleListbox(self._top)
        self._init_readingListbox(self._top)
        self._init_canvas(self._top)

        # Resize callback
        self._canvas.bind("<Configure>", self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_glue(self):
        tagger = RegexpTagger(
            [
                ("^(David|Mary|John)$", "NNP"),
                ("^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$", "VB"),
                ("^(go|order|vanish|find|approach)$", "VB"),
                ("^(a)$", "ex_quant"),
                ("^(every)$", "univ_quant"),
                ("^(sandwich|man|dog|pizza|unicorn|cat|senator)$", "NN"),
                ("^(big|gray|former)$", "JJ"),
                ("^(him|himself)$", "PRP"),
            ]
        )

        depparser = MaltParser(tagger=tagger)
        self._glue = DrtGlue(depparser=depparser, remove_duplicates=False)

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())
        if self._size.get() < 0:
            big = self._size.get() - 2
        else:
            big = self._size.get() + 2
        self._bigfont = Font(family="helvetica", weight="bold", size=big)

    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill="both", side="left", padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text="Examples")
        self._exampleList_label.pack()
        self._exampleList = Listbox(
            self._exampleFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._exampleList.pack(side="right", fill="both", expand=1)

        for example in self._examples:
            self._exampleList.insert("end", ("  %s" % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame, orient="vertical")
            self._exampleList.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a example, apply it.
        self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select)

    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill="both", side="left", padx=2)
        self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings")
        self._readingList_label.pack()
        self._readingList = Listbox(
            self._readingFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._readingList.pack(side="right", fill="both", expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame, orient="vertical")
        self._readingList.config(yscrollcommand=listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side="right", fill="y")

        self._populate_readingListbox()

    def _populate_readingListbox(self):
        # Populate the listbox with integers
        self._readingList.delete(0, "end")
        for i in range(len(self._readings)):
            self._readingList.insert("end", ("  %s" % (i + 1)))
        self._readingList.config(height=min(len(self._readings), 25), width=5)

        # If they select a example, apply it.
        self._readingList.bind("<<ListboxSelect>>", self._readingList_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind("<Control-q>", self.destroy)
        self._top.bind("<Control-x>", self.destroy)
        self._top.bind("<Escape>", self.destroy)
        self._top.bind("n", self.next)
        self._top.bind("<space>", self.next)
        self._top.bind("p", self.prev)
        self._top.bind("<BackSpace>", self.prev)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill="none", side="bottom", padx=3, pady=2)
        Button(buttonframe, text="Prev", background="#90c0d0", foreground="black", command=self.prev).pack(side="left")
        Button(buttonframe, text="Next", background="#90c0d0", foreground="black", command=self.next).pack(side="left")

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas["scrollregion"] = "%d %d %d %d" % (x1, y1, x2, y2)
        self._redraw()

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background="white",
            # width=525, height=250,
            closeenough=10,
            border=2,
            relief="sunken",
        )
        self._cframe.pack(expand=1, fill="both", side="top", pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="q")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        actionmenu = Menu(menubar, tearoff=0)
        actionmenu.add_command(label="Next", underline=0, command=self.next, accelerator="n, Space")
        actionmenu.add_command(label="Previous", underline=0, command=self.prev, accelerator="p, Backspace")
        menubar.add_cascade(label="Action", underline=0, menu=actionmenu)

        optionmenu = Menu(menubar, tearoff=0)
        optionmenu.add_checkbutton(
            label="Remove Duplicates",
            underline=0,
            variable=self._glue.remove_duplicates,
            command=self._toggle_remove_duplicates,
            accelerator="r",
        )
        menubar.add_cascade(label="Options", underline=0, menu=optionmenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize)
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old DRS, widgets, etc.
        if self._drsWidget is not None:
            self._drsWidget.clear()

        if self._drs:
            self._drsWidget = DrsWidget(self._canvas, self._drs)
            self._drsWidget.draw()

        if self._error:
            self._drsWidget = DrsWidget(self._canvas, self._error)
            self._drsWidget.draw()

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None:
            return
        self._top.destroy()
        self._top = None

    def prev(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or before) the first item
                if index <= 0:
                    self._select_previous_example()
                else:
                    self._readingList_store_selection(index - 1)

            else:
                # select its first reading
                self._readingList_store_selection(readingListSize - 1)

        else:
            self._select_previous_example()

    def _select_previous_example(self):
        # if the current example is not the first example
        if self._curExample > 0:
            self._exampleList_store_selection(self._curExample - 1)
        else:
            # go to the last example
            self._exampleList_store_selection(len(self._examples) - 1)

    def next(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # if there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or past) the last item
                if index >= (readingListSize - 1):
                    self._select_next_example()
                else:
                    self._readingList_store_selection(index + 1)

            else:
                # select its first reading
                self._readingList_store_selection(0)

        else:
            self._select_next_example()

    def _select_next_example(self):
        # if the current example is not the last example
        if self._curExample < len(self._examples) - 1:
            self._exampleList_store_selection(self._curExample + 1)
        else:
            # go to the first example
            self._exampleList_store_selection(0)

    def about(self, *e):
        ABOUT = "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n" + "Written by Daniel H. Garrette"
        TITLE = "About: NLTK DRT Glue Demo"
        try:
            from tkMessageBox import Message

            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle():
            return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None:
            self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size + 2)))
        self._redraw()

    def _toggle_remove_duplicates(self):
        self._glue.remove_duplicates = not self._glue.remove_duplicates

        self._exampleList.selection_clear(0, "end")
        self._readings = []
        self._populate_readingListbox()
        self._readingCache = [None for ex in self._examples]
        self._curExample = -1
        self._error = None

        self._drs = None
        self._redraw()

    def _exampleList_select(self, event):
        selection = self._exampleList.curselection()
        if len(selection) != 1:
            return
        self._exampleList_store_selection(int(selection[0]))

    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, "end")
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception as e:
                    self._readings = []
                    self._error = DrtVariableExpression(Variable("Error: " + str(e)))
                    self._readingCache[index] = self._error

                    # add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ("  %s *" % example))
                    self._exampleList.config(height=min(len(self._examples), 25), width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()

    def _readingList_select(self, event):
        selection = self._readingList.curselection()
        if len(selection) != 1:
            return
        self._readingList_store_selection(int(selection[0]))

    def _readingList_store_selection(self, index):
        reading = self._readings[index]

        self._readingList.selection_clear(0, "end")
        if reading:
            self._readingList.selection_set(index)

            self._drs = reading.simplify().normalize().resolve_anaphora()

            self._redraw()
Example #15
0
class OperatePanel(Frame):
    def __init__(self, parent, searchCallback, resetCallback):
        super().__init__(parent)
        self.icSelected = IntVar()
        self.mwwSelected = IntVar()
        self.urSelected = IntVar()
        self.ifnSelected = IntVar()
        self.searchCallback = searchCallback
        self.resetCallback = resetCallback
        self.searchBtn = Button(self,
                                text="Search",
                                command=self.onClickSearch,
                                padx=3)
        self.resetBtn = Button(self,
                               text="Reset",
                               command=self.onClickReset,
                               padx=3)
        self.icBtn = Checkbutton(self,
                                 text="Ignore Case",
                                 command=self.onSelectIgnoreCase,
                                 variable=self.icSelected)
        self.mwwBtn = Checkbutton(self,
                                  text="Match Whole Word",
                                  command=self.onSelectMatchWholeWord,
                                  variable=self.mwwSelected)
        self.urBtn = Checkbutton(self,
                                 text="Use Regular",
                                 command=self.onSelectUseRegular,
                                 variable=self.urSelected)
        self.ifnBtn = Checkbutton(self,
                                  text="Ignore Folder Name",
                                  variable=self.ifnSelected)
        self.icBtn.grid(row=0, column=0, sticky="W")
        self.mwwBtn.grid(row=0, column=1, sticky="W")
        self.ifnBtn.grid(row=1, column=0, sticky="W")
        self.urBtn.grid(row=1, column=1, sticky="W")
        self.resetBtn.grid(row=2, column=0)
        self.searchBtn.grid(row=2, column=1)

    def getFlags(self):
        flags = []
        if self.icSelected.get() == 1:
            flags.append("-ic")
        if self.mwwSelected.get() == 1:
            flags.append("-mww")
        if self.urSelected.get() == 1:
            flags.append("-r")
        if self.ifnSelected.get() == 1:
            flags.append("-ifn")
        return flags

    def onClickSearch(self):
        if self.searchCallback is not None:
            self.searchCallback()

    def onClickReset(self):
        self.urSelected.set(0)
        self.icSelected.set(0)
        self.mwwSelected.set(0)
        self.ifnSelected.set(0)
        if self.resetCallback is not None:
            self.resetCallback()

    def onSelectIgnoreCase(self):
        self.urSelected.set(0)

    def onSelectMatchWholeWord(self):
        self.urSelected.set(0)

    def onSelectUseRegular(self):
        self.icSelected.set(0)
        self.mwwSelected.set(0)
Example #16
0
class MainApp():
    def __init__(self):
        self.File_name = None
        self.Programe_Name = "CHE-Editor"
        self.WDG = Tk()
        self.WDG.title(self.Programe_Name)
        self.WDG.iconbitmap("icons/icon_editor.ico")
        self.WDG.geometry("860x620")
        self.WDG.maxsize(width=1340, height=700)
        self.WDG.minsize(width=860, height=620)
        self.Main_UI()

    def Main_UI(self):
        self.MenuBar = Menu(self.WDG)

        #1      #MenuBar
        #File_menu
        self.File_menu = Menu(self.MenuBar, tearoff=0, title="File")
        self.MenuBar.add_cascade(label="File", menu=self.File_menu)
        #Edit_menu
        self.Edit_menu = Menu(self.MenuBar, tearoff=0, title="Edit")
        self.MenuBar.add_cascade(label="Edit", menu=self.Edit_menu)
        #View_menu
        self.View_menu = Menu(self.MenuBar, tearoff=0, title="View")
        self.MenuBar.add_cascade(label="View", menu=self.View_menu)
        #Theme_menu in View
        self.Theme_menu = Menu(self.View_menu, tearoff=0, title="Theme")
        self.View_menu.add_cascade(label="Theme", menu=self.Theme_menu)
        #Option_menu
        self.Options_menu = Menu(self.MenuBar, tearoff=0, title="Options")
        self.MenuBar.add_cascade(label="Options", menu=self.Options_menu)
        #Help_menu
        self.Help_menu = Menu(self.MenuBar, tearoff=0, title="Help")
        self.MenuBar.add_cascade(label="Help", menu=self.Help_menu)

        #2      #Icons Variables
        #Edit_Menu Icons
        Undo = PhotoImage(file="icons/Undo.gif")
        Redo = PhotoImage(file="icons/redo.gif")
        Paste = PhotoImage(file="icons/paste.gif")
        Copy = PhotoImage(file="icons/copy.gif")
        Cut = PhotoImage(file="icons/cut.gif")
        #Help_Menu_Icons
        Help = PhotoImage(file="icons/help.gif")
        About = PhotoImage(file="icons/about.gif")
        #File_Menu_Icons
        New = PhotoImage(file="icons/new.gif")
        Open = PhotoImage(file="icons/open.gif")
        Save = PhotoImage(file="icons/save.gif")
        Save_As = PhotoImage(file="icons/save_as.gif")
        Exit = PhotoImage(file="icons/exit.gif")

        #Appear menubar in app
        self.WDG.config(menu=self.MenuBar)
        #self.WDG.config(menu=self.IconBar)

        #3      #Set commands in menus
        #File_Menu
        self.File_menu.add_command(label="New",
                                   accelerator="Ctrl+N",
                                   compound="left",
                                   underline=0,
                                   command=self.New)
        self.File_menu.add_command(label="Open",
                                   accelerator="Ctrl+O",
                                   compound="left",
                                   underline=0,
                                   command=self.Open)
        self.File_menu.add_command(label="Save",
                                   accelerator="Ctrl+S",
                                   compound="left",
                                   underline=0,
                                   command=self.Save)
        self.File_menu.add_command(label="Save as",
                                   accelerator="Shift+Ctrl+S",
                                   compound="left",
                                   underline=0,
                                   command=self.Save_As)
        self.File_menu.add_separator()
        self.File_menu.add_command(label="Exit",
                                   accelerator="F4",
                                   compound="left",
                                   underline=0,
                                   command=self.Exit)
        #Edit_Menu
        self.Edit_menu.add_command(label="Undo",
                                   accelerator="Ctrl+Z",
                                   compound="left",
                                   underline=0,
                                   command=self.Undo)
        self.Edit_menu.add_command(label="Redo",
                                   accelerator='Ctrl+Y',
                                   compound='left',
                                   underline=0,
                                   command=self.Redo)
        self.Edit_menu.add_command(label="Select all",
                                   accelerator='Ctrl+A',
                                   compound='left',
                                   underline=0,
                                   command=self.Select)
        self.Edit_menu.add_command(label="Cut",
                                   accelerator='Ctrl+X',
                                   compound='left',
                                   underline=7,
                                   command=self.Cut)
        self.Edit_menu.add_command(label="Copy",
                                   accelerator='Ctrl+C',
                                   compound='left',
                                   underline=0,
                                   command=self.Copy)
        self.Edit_menu.add_command(label="Paste",
                                   accelerator='Ctrl+V',
                                   compound='left',
                                   underline=0,
                                   command=self.Paste)
        self.Edit_menu.add_command(label="Search",
                                   accelerator='Ctrl+F',
                                   compound='left',
                                   underline=0,
                                   command=self.Search)
        #Help_Menu
        self.Help_menu.add_command(label="Help",
                                   accelerator="F1",
                                   compound="left",
                                   underline=0,
                                   command=self.Help)
        self.Help_menu.add_command(label="About",
                                   compound="left",
                                   underline=0,
                                   command=self.About)
        #View_Menu
        self.Show_line_number = IntVar()
        self.Show_line_number.set(1)
        self.theme_name = StringVar()
        self.View_menu.add_checkbutton(label="Show Line Number",
                                       variable=self.Show_line_number)
        self.Highlightline = BooleanVar()
        self.View_menu.add_checkbutton(label='Highlight Current Line',
                                       onvalue=1,
                                       offvalue=0,
                                       variable=self.Highlightline,
                                       command=self.Toggle_highlight)
        self.cursorcoord = BooleanVar()
        self.View_menu.add_checkbutton(label='Show Cursor Location',
                                       variable=self.cursorcoord,
                                       command=self.Show_cursor_coord)
        self.Theme_menu.add_radiobutton(label="Default",
                                        variable=self.theme_name)

        #4      #add Shortcut_Bar & Row_Number_Bar
        #Shortcut_Bar
        self.Shortcut_Bar = Frame(self.WDG, height=25)
        self.Shortcut_Bar.pack(expand='no', fill='x')
        Icons = ['New', 'Open', 'Save', 'Copy', 'Cut', 'Paste', 'Undo', 'Redo']
        for i, icon in enumerate(Icons):
            Tool_icon = PhotoImage(file='icons/{}.gif'.format(icon))
            #c_var = 'self.{}'.format(icon)
            cmd = eval('self.{}'.format(icon))
            self.Tool_bar_btn = Button(self.Shortcut_Bar,
                                       image=Tool_icon,
                                       command=cmd)
            self.Tool_bar_btn.image = Tool_icon
            self.Tool_bar_btn.pack(side='left')
        #Row_Number_Bar
        self.Row_Number_Bar = Text(self.WDG,
                                   width=3,
                                   padx=3,
                                   takefocus=0,
                                   border=0,
                                   background='khaki',
                                   state='disabled',
                                   wrap='none')
        self.Row_Number_Bar.pack(side='left', fill='y')

        #5      #add Content_Text
        self.Content_Text = Text(self.WDG, wrap='word', undo=1)
        self.Content_Text.pack(expand='yes', fill='both')
        self.Content_Text.tag_configure('active_line', background='ivory2')
        self.Scroll_Bar = Scrollbar(self.Content_Text)
        self.Content_Text.configure(yscrollcommand=self.Scroll_Bar.set)
        self.Scroll_Bar.config(command=self.Content_Text.yview)
        self.Scroll_Bar.pack(side='right', fill='y')

        #6      #add_Cursor_Coord_Bar
        self.Cursor_Coord_Bar = Label(self.Content_Text,
                                      text='Row: 1 | Column: 1')
        self.Cursor_Coord_Bar.pack(fill=None,
                                   expand='no',
                                   side='right',
                                   anchor='se')

        #7      #Binding
        self.Content_Text.bind("<Control-o>", self.Open)
        self.Content_Text.bind("<Control-O>", self.Open)
        self.Content_Text.bind("<Control-s>", self.Save)
        self.Content_Text.bind("<Control-S>", self.Save)
        self.Content_Text.bind("<Shift-Control-KeyPress-s>", self.Save_As)
        self.Content_Text.bind("<Shift-Control-KeyPress-S>", self.Save_As)
        self.Content_Text.bind("<Control-n>", self.New)
        self.Content_Text.bind("<Control-N>", self.New)
        self.Content_Text.bind("<Control-z>", self.Undo)
        self.Content_Text.bind("<Control-Z>", self.Undo)
        self.Content_Text.bind("<Control-y>", self.Redo)
        self.Content_Text.bind("<Control-Y>", self.Redo)
        self.Content_Text.bind("<Control-x>", self.Cut)
        self.Content_Text.bind("<Control-X>", self.Cut)
        self.Content_Text.bind("<Control-a>", self.Select)
        self.Content_Text.bind("<Control-A>", self.Select)
        self.Content_Text.bind("<Control-c>", self.Copy)
        self.Content_Text.bind("<Control-C>", self.Copy)
        self.Content_Text.bind("<Control-v>", self.Paste)
        self.Content_Text.bind("<Control-V>", self.Paste)
        self.Content_Text.bind("<Control-f>", self.Search)
        self.Content_Text.bind("<Control-F>", self.Search)
        self.Content_Text.bind("<Any-KeyPress>", self.Content_changed)
        self.WDG.bind_all("<KeyPress-F1>", self.Help)
        self.WDG.bind_all("<KeyPress-F4>", self.Exit)


#8  #Built In Finctions
#File_Menu_Functions

    def New(self, event=None):
        self.Content_Text.delete(1., 'end')
        self.WDG.title('{} - {}'.format('Untitled', self.Programe_Name))

    ##
    def Open(self, event=None):
        self.Open_file_name = filedialog.askopenfilename(
            defaultextension=".txt",
            filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
        if self.Open_file_name:
            self.File_name = self.Open_file_name
            self.WDG.title("{} - {}".format(os.path.basename(self.File_name),
                                            self.Programe_Name))
            self.Content_Text.delete(1.0, 'end')
            with open(self.File_name) as _File:
                self.Content_Text.insert(1.0, _File.read())

    ##
    def Save(self, event=None):
        if not self.File_name:
            self.Save_As()
        else:
            self.Write_to_file(self.File_name)
        return "break"

    ##
    def Save_As(self, event=None):
        self.Save_file_name = filedialog.asksaveasfilename(
            defaultextension='.txt',
            filetypes=[('All Files', '*.*'), ('Text Documents', '*.txt')])
        if self.Save_file_name:
            self.File_name = self.Save_file_name
            self.Write_to_file(self.File_name)
            self.WDG.title('{} - {}'.format(os.path.basename(self.File_name),
                                            self.Programe_Name))
        return "break"

    ##
    def Write_to_file(self, filename):
        try:
            self.content = self.Content_Text.get(1.0, 'end')
            with open(self.File_name, 'w') as the_file:
                the_file.write(self.content)
        except IOError as er:
            print(er)

    ##
    def Exit(self, event=None):
        self.msg_exit = messagebox.askyesno('Exit Editor',
                                            'Do you want to exit?')
        if self.msg_exit:
            self.WDG.destroy()

    #Edit_Menu_Functions
    ##
    def Select(self, event=None):
        self.Content_Text.tag_add("sel", 1.0, "end")
        print("Done1")
        return "breake"

    ##
    def Cut(self, event=None):
        self.Content_Text.event_generate("<<Cut>>")
        return "breake"

    ##
    def Copy(self, event=None):
        self.Content_Text.event_generate("<<Copy>>")
        return "breake"

    ##
    def Paste(self, event=None):
        self.Content_Text.event_generate("<<Paste>>")
        return "breake"

    ##
    def Undo(self, event=None):
        self.Content_Text.event_generate("<<Undo>>")
        return "breake"

    ##
    def Redo(self, event=None):
        self.Content_Text.event_generate("<<Redo>>")
        return "breake"

    ##
    def Search(self, event=None):
        self.Search_Window = Toplevel(self.WDG)
        self.Search_Window.title("Search About...")
        self.Search_Window.transient(self.WDG)
        self.Search_Window.resizable(False, False)
        self.S_lbl_1 = Label(self.Search_Window, text='Search About :')
        self.S_lbl_1.grid(row=0, column=0, sticky='e')
        self.S_ent_1 = Entry(self.Search_Window, width=28)
        self.S_ent_1.grid(row=0, column=1, padx=2, pady=2, sticky='we')
        self.S_ent_1.focus_set()
        Ignore_case_value = IntVar()
        self.S_chk_1 = Checkbutton(self.Search_Window,
                                   text='Ignor Case',
                                   variable=Ignore_case_value)
        self.S_chk_1.grid(row=1, column=1, padx=2, pady=2, sticky='e')
        self.S_btn_1 = Button(
            self.Search_Window,
            text='Find',
            underline=0,
            command=lambda: self.Search_results(self.S_ent_1.get(
            ), Ignore_case_value.get(), self.Content_Text, self.Search_Window,
                                                self.S_ent_1))
        self.S_btn_1.grid(row=0, column=2, padx=2, pady=2, sticky='e' + 'w')
        self.S_btn_2 = Button(self.Search_Window,
                              text='Cancel',
                              underline=0,
                              command=self.Close_Search_Window)
        self.S_btn_2.grid(row=1, column=2, padx=2, pady=2, sticky='e' + 'w')

    ##
    def Search_results(self, Keyword, IfIgnoreCase, Content, Output, Input):
        Content.tag_remove('match', '1.0', 'end')
        matches_found = 0
        if Keyword:
            start_pos = '1.0'
            while True:
                start_pos = Content.search(Keyword,
                                           start_pos,
                                           nocase=IfIgnoreCase,
                                           stopindex='end')
                if not start_pos:
                    break
                end_pos = "{} + {}c".format(start_pos, len(Keyword))
                Content.tag_add('match', start_pos, end_pos)
                matches_found += 1
                start_pos = end_pos
            Content.tag_config('match', foreground='red', background='yellow')
            Input.focus_set()
            Output.title("{} matches found".format(matches_found))

    ##
    def Close_Search_Window(self):
        self.Content_Text.tag_remove('match', '1.0', 'end')
        self.Search_Window.destroy()
        #self.Search_Window.protocol('WM_DELETE_WINDOW',self.Close_Search_Window)
        return "break"

    #View_Menu_Functions
    ##
    def Content_changed(self, event=None):
        self.Update_line_numbers()
        self.Update_cursor_coord()

    ##
    def Get_line_numbers(self, event=None):
        self.Number = ""
        if self.Show_line_number.get():
            self.Row, self.Column = self.Content_Text.index('end').split('.')
            for i in range(1, int(self.Row)):
                self.Number += str(i) + "\n"
        return self.Number

    ##
    def Update_line_numbers(self):
        self.Line_Number = self.Get_line_numbers()
        self.Row_Number_Bar.config(state='normal')
        self.Row_Number_Bar.delete(1.0, 'end')
        self.Row_Number_Bar.insert(1.0, self.Line_Number)
        self.Row_Number_Bar.config(state='disabled')

    ##
    def Toggle_highlight(self, event=None):
        if self.Highlightline.get():
            self.Highlight_line()
        else:
            self.Undo_highlight()

    ##
    def Highlight_line(self, interval=100):
        self.Content_Text.tag_remove('active_line', 1.0, 'end')
        self.Content_Text.tag_add('active_line', "insert linestart",
                                  "insert lineend+1c")
        self.Content_Text.after(interval, self.Toggle_highlight)

    ##
    def Undo_highlight(self):
        self.Content_Text.tag_remove('active_line', 1.0, 'end')

    ##
    def Show_cursor_coord(self):
        self.cursor_coord_checked = self.cursorcoord.get()
        if self.cursor_coord_checked:
            self.Cursor_Coord_Bar.pack(expand='no',
                                       fill=None,
                                       side='right',
                                       anchor='se')
        else:
            self.Cursor_Coord_Bar.pack_forget()

    ##
    def Update_cursor_coord(self):
        self.Row_2, self.Column_2 = self.Content_Text.index('insert').split(
            '.')
        self.row_num, self.col_num = str(int(
            self.Row_2)), str(int(self.Column_2) + 1)
        self.Coord = "Row: {} | Column: {}".format(self.row_num, self.col_num)
        self.Cursor_Coord_Bar.config(text=self.Coord)

    #Help_Menu_Functions
    ##
    def About(self, event=None):
        messagebox.showinfo(
            'About', '{} {}'.format(self.Programe_Name,
                                    '\nDeveloped by \n TaReK'))

    ##
    def Help(self, event=None):
        messagebox.showinfo('Help',
                            'Text Editor building in python',
                            icon='question')
Example #17
0
def guiMain(args=None):
    mainWindow = Tk()
    mainWindow.wm_title("OoT Randomizer %s" % ESVersion)

    set_icon(mainWindow)

    notebook = ttk.Notebook(mainWindow)
    randomizerWindow = ttk.Frame(notebook)
    adjustWindow = ttk.Frame(notebook)
    customWindow = ttk.Frame(notebook)
    notebook.add(randomizerWindow, text='Randomize')
    notebook.pack()

    # Shared Controls

    farBottomFrame = Frame(mainWindow)

    def open_output():
        open_file(output_path(''))

    openOutputButton = Button(farBottomFrame, text='Open Output Directory', command=open_output)

    if os.path.exists(local_path('README.html')):
        def open_readme():
            open_file(local_path('README.html'))
        openReadmeButton = Button(farBottomFrame, text='Open Documentation', command=open_readme)
        openReadmeButton.pack(side=LEFT)

    farBottomFrame.pack(side=BOTTOM, fill=X, padx=5, pady=5)

    # randomizer controls

    topFrame = Frame(randomizerWindow)
    rightHalfFrame = Frame(topFrame)
    checkBoxFrame = Frame(rightHalfFrame)

    createSpoilerVar = IntVar()
    createSpoilerCheckbutton = Checkbutton(checkBoxFrame, text="Create Spoiler Log", variable=createSpoilerVar)
    suppressRomVar = IntVar()
    suppressRomCheckbutton = Checkbutton(checkBoxFrame, text="Do not create patched Rom", variable=suppressRomVar)
    compressRomVar = IntVar()
    compressRomCheckbutton = Checkbutton(checkBoxFrame, text="Compress patched Rom", variable=compressRomVar)
    openForestVar = IntVar()
    openForestCheckbutton = Checkbutton(checkBoxFrame, text="Open Forest", variable=openForestVar)
    openDoorVar = IntVar()
    openDoorCheckbutton = Checkbutton(checkBoxFrame, text="Open Door of Time", variable=openDoorVar)
    dungeonItemsVar = IntVar()
    dungeonItemsCheckbutton = Checkbutton(checkBoxFrame, text="Place Dungeon Items (Compasses/Maps)", onvalue=0, offvalue=1, variable=dungeonItemsVar)
    beatableOnlyVar = IntVar()
    beatableOnlyCheckbutton = Checkbutton(checkBoxFrame, text="Only ensure seed is beatable, not all items must be reachable", variable=beatableOnlyVar)
    hintsVar = IntVar()
    hintsCheckbutton = Checkbutton(checkBoxFrame, text="Gossip Stone Hints with Stone of Agony", variable=hintsVar)

    createSpoilerCheckbutton.pack(expand=True, anchor=W)
    suppressRomCheckbutton.pack(expand=True, anchor=W)
    compressRomCheckbutton.pack(expand=True, anchor=W)
    openForestCheckbutton.pack(expand=True, anchor=W)
    openDoorCheckbutton.pack(expand=True, anchor=W)
    dungeonItemsCheckbutton.pack(expand=True, anchor=W)
    beatableOnlyCheckbutton.pack(expand=True, anchor=W)
    hintsCheckbutton.pack(expand=True, anchor=W)

    fileDialogFrame = Frame(rightHalfFrame)

    romDialogFrame = Frame(fileDialogFrame)
    baseRomLabel = Label(romDialogFrame, text='Base Rom')
    romVar = StringVar()
    romEntry = Entry(romDialogFrame, textvariable=romVar)

    def RomSelect():
        rom = filedialog.askopenfilename(filetypes=[("Rom Files", (".z64", ".n64")), ("All Files", "*")])
        romVar.set(rom)
    romSelectButton = Button(romDialogFrame, text='Select Rom', command=RomSelect)

    baseRomLabel.pack(side=LEFT)
    romEntry.pack(side=LEFT)
    romSelectButton.pack(side=LEFT)

    romDialogFrame.pack()

    checkBoxFrame.pack()
    fileDialogFrame.pack()

    drowDownFrame = Frame(topFrame)


    bridgeFrame = Frame(drowDownFrame)
    bridgeVar = StringVar()
    bridgeVar.set('medallions')
    bridgeOptionMenu = OptionMenu(bridgeFrame, bridgeVar, 'medallions', 'vanilla', 'dungeons', 'open')
    bridgeOptionMenu.pack(side=RIGHT)
    bridgeLabel = Label(bridgeFrame, text='Rainbow Bridge Requirement')
    bridgeLabel.pack(side=LEFT)

    bridgeFrame.pack(expand=True, anchor=E)

    bottomFrame = Frame(randomizerWindow)

    seedLabel = Label(bottomFrame, text='Seed #')
    seedVar = StringVar()
    seedEntry = Entry(bottomFrame, textvariable=seedVar)
    countLabel = Label(bottomFrame, text='Count')
    countVar = StringVar()
    countSpinbox = Spinbox(bottomFrame, from_=1, to=100, textvariable=countVar)

    def generateRom():
        guiargs = Namespace
        guiargs.seed = int(seedVar.get()) if seedVar.get() else None
        guiargs.count = int(countVar.get()) if countVar.get() != '1' else None
        guiargs.bridge = bridgeVar.get()
        guiargs.create_spoiler = bool(createSpoilerVar.get())
        guiargs.suppress_rom = bool(suppressRomVar.get())
        guiargs.compress_rom = bool(compressRomVar.get())
        guiargs.open_forest = bool(openForestVar.get())
        guiargs.open_door_of_time = bool(openDoorVar.get())
        guiargs.nodungeonitems = bool(dungeonItemsVar.get())
        guiargs.beatableonly = bool(beatableOnlyVar.get())
        guiargs.hints = bool(hintsVar.get())
        guiargs.rom = romVar.get()
        try:
            if guiargs.count is not None:
                seed = guiargs.seed
                for _ in range(guiargs.count):
                    main(seed=seed, args=guiargs)
                    seed = random.randint(0, 999999999)
            else:
                main(seed=guiargs.seed, args=guiargs)
        except Exception as e:
            messagebox.showerror(title="Error while creating seed", message=str(e))
        else:
            messagebox.showinfo(title="Success", message="Rom patched successfully")

    generateButton = Button(bottomFrame, text='Generate Patched Rom', command=generateRom)

    seedLabel.pack(side=LEFT)
    seedEntry.pack(side=LEFT)
    countLabel.pack(side=LEFT, padx=(5, 0))
    countSpinbox.pack(side=LEFT)
    generateButton.pack(side=LEFT, padx=(5, 0))

    openOutputButton.pack(side=RIGHT)

    drowDownFrame.pack(side=LEFT)
    rightHalfFrame.pack(side=RIGHT)
    topFrame.pack(side=TOP)
    bottomFrame.pack(side=BOTTOM)

    if args is not None:
        # load values from commandline args
        createSpoilerVar.set(int(args.create_spoiler))
        suppressRomVar.set(int(args.suppress_rom))
        compressRomVar.set(int(args.compress_rom))
        if args.nodungeonitems:
            dungeonItemsVar.set(int(not args.nodungeonitems))
        openForestVar.set(int(args.open_forest))
        openDoorVar.set(int(args.open_door_of_time))
        beatableOnlyVar.set(int(args.beatableonly))
        hintsVar.set(int(args.hints))
        if args.count:
            countVar.set(str(args.count))
        if args.seed:
            seedVar.set(str(args.seed))
        bridgeVar.set(args.bridge)
        romVar.set(args.rom)

    mainWindow.mainloop()
Example #18
0
class CollectorGUI:
    def __init__(self, master):
        self.master = master
        self.master.title('Mouse Movement Collection')
        self.master.bind('<Motion>', self.track_movement)
        self.master.bind('<Button-1>', self.track_click)

        self.FRAME_WIDTH = 1000
        self.FRAME_HEIGHT = 500
        master.geometry('{}x{}'.format(self.FRAME_WIDTH,
                                       self.FRAME_HEIGHT))  # width x height

        self.start_button = Button(master,
                                   text='Start Collection',
                                   command=self.spawn_random_button)
        self.start_button.pack()

        self.collected = IntVar(value=0)
        self.collected_total = IntVar(value=0)
        self.num_to_collect = 50

        self.counter = Label(master, textvariable=self.collected)
        self.counter.place(x=10, y=10)
        self.counter_total = Label(master, textvariable=self.collected_total)
        self.counter_total.place(x=10, y=30)

        self.current_button = {}

        # self.button_log = {}
        date = str(datetime.now().date())

        data_dir = 'data\\'
        # make the directory if the folder does not exist
        if not os.path.exists(data_dir):
            os.mkdir(data_dir)
        filename = data_dir + 'button_log_{}.csv'.format(date)

        print('Output will be written to {}'.format(filename))
        self.button_log_file = open(filename, 'a+')

        self.last_updated = time()

        self.START_TIME = None
        if self.START_TIME is None:
            self.START_TIME = time()
            #print(self.START_TIME)

    # clears the GUI of existing buttons
    def clear_buttons(self):

        buttons = self.master.pack_slaves()
        for b in buttons:
            b.destroy()
        buttons = self.master.place_slaves()
        for b in buttons:
            if isinstance(b, Button):
                b.destroy()
        return

    # creates a new button of random size in a random location on the window
    def spawn_random_button(self):

        self.collected.set(value=(self.collected.get() +
                                  1))  # increment counter
        # CLOSE WINDOW AFTER N BUTTONS PRESSED
        if self.collected.get() > self.num_to_collect:
            self.clear_buttons()
            sleep(.5)
            self.restart()
            return
        self.collected_total.set(value=(self.collected_total.get() +
                                        1))  # increment counter
        self.last_updated = time()
        self.clear_buttons()  # clear previous button
        n = self.collected.get()

        new_button = Button(self.master,
                            text='CLICK ME',
                            command=self.spawn_random_button,
                            bg='red')

        # randomize button dimensions and location
        w = random.randint(15, 100)
        h = random.randint(15, 100)
        x = random.randint(w, self.FRAME_WIDTH - w)
        y = random.randint(w, self.FRAME_HEIGHT - h)

        # log button
        this_button = {"x": x, "y": y, "width": w, "height": h}

        self.current_button = this_button
        # self.button_log[n] = this_button

        # sleep(.1)  # short break before next button appears
        new_button.place(x=x, y=y, height=h, width=w)

    # when an iteration is complete, spawn a button to restart the collection process
    def restart(self):
        w = 20
        h = 80
        x = random.randint(w, self.FRAME_WIDTH - w)
        y = random.randint(w, self.FRAME_HEIGHT - h)
        self.start_button = Button(self.master,
                                   text='Start Collection',
                                   command=self.spawn_random_button,
                                   bg='blue')
        self.start_button.place(x=x, y=y)
        self.collected.set(0)

    # collects information on movement events (position and time)
    def track_movement(self, event):
        x = event.x_root - self.master.winfo_rootx()
        y = event.y_root - self.master.winfo_rooty()
        # print('({}, {})'.format(x, y), 'button:', self.current_button)
        t = time() - self.last_updated

        if self.collected.get() > 0:
            self.log_action('MOVE', x, y, t, self.current_button)

    # collects information on click events (position and time)
    def track_click(self, event):
        x = event.x_root - self.master.winfo_rootx()
        y = event.y_root - self.master.winfo_rooty()
        t = time() - self.last_updated

        if self.collected.get() > 0:
            self.log_action('CLICK', x, y, t, self.current_button)

    # writes collected event information to the CSV specified in the initialization of the GUI
    def log_action(self, action, x, y, t, b):
        self.button_log_file.write(
            '{}, {}, {}, {}, {}, {}, {}, {}, {}\n'.format(
                self.collected.get(), action, x, y, t, b['x'], b['y'],
                b['width'], b['height']))
Example #19
0
class MLNQueryGUI(object):
    def __init__(self, master, gconf, directory=None):
        self.master = master

        self.initialized = False

        self.master.bind('<Return>', self.infer)
        self.master.bind('<Escape>', lambda a: self.master.quit())
        self.master.protocol('WM_DELETE_WINDOW', self.quit)

        self.dir = os.path.abspath(
            ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)
        self.frame.columnconfigure(1, weight=1)

        row = 0
        # pracmln project options
        Label(self.frame, text='PRACMLN Project: ').grid(row=row,
                                                         column=0,
                                                         sticky='ES')
        project_container = Frame(self.frame)
        project_container.grid(row=row, column=1, sticky="NEWS")

        # new proj file
        self.btn_newproj = Button(project_container,
                                  text='New Project...',
                                  command=self.new_project)
        self.btn_newproj.grid(row=0, column=1, sticky="WS")

        # open proj file
        self.btn_openproj = Button(project_container,
                                   text='Open Project...',
                                   command=self.ask_load_project)
        self.btn_openproj.grid(row=0, column=2, sticky="WS")

        # save proj file
        self.btn_updateproj = Button(project_container,
                                     text='Save Project...',
                                     command=self.noask_save_project)
        self.btn_updateproj.grid(row=0, column=3, sticky="WS")

        # save proj file as...
        self.btn_saveproj = Button(project_container,
                                   text='Save Project as...',
                                   command=self.ask_save_project)
        self.btn_saveproj.grid(row=0, column=4, sticky="WS")

        # grammar selection
        row += 1
        Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E')
        grammars = ['StandardGrammar', 'PRACGrammar']
        self.selected_grammar = StringVar()
        self.selected_grammar.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars))
        l.grid(row=row, column=1, sticky='NWE')

        # logic selection
        row += 1
        Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E')
        logics = ['FirstOrderLogic', 'FuzzyLogic']
        self.selected_logic = StringVar()
        self.selected_logic.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics))
        l.grid(row=row, column=1, sticky='NWE')

        # mln section
        row += 1
        Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE')
        self.mln_container = FileEditBar(self.frame,
                                         directory=self.dir,
                                         filesettings={
                                             'extension': '.mln',
                                             'ftypes': [('MLN files', '.mln')]
                                         },
                                         defaultname='*unknown{}',
                                         importhook=self.import_mln,
                                         deletehook=self.delete_mln,
                                         projecthook=self.save_proj,
                                         filecontenthook=self.mlnfilecontent,
                                         fileslisthook=self.mlnfiles,
                                         updatehook=self.update_mln,
                                         onchangehook=self.project_setdirty)
        self.mln_container.editor.bind("<FocusIn>", self._got_focus)
        self.mln_container.grid(row=row, column=1, sticky="NEWS")
        self.mln_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        row += 1
        self.use_emln = IntVar()
        self.use_emln.set(0)
        self.cb_use_emln = Checkbutton(self.frame,
                                       text="use model extension",
                                       variable=self.use_emln,
                                       command=self.onchange_use_emln)
        self.cb_use_emln.grid(row=row, column=1, sticky="W")

        # mln extension section
        row += 1
        self.emlncontainerrow = row
        self.emln_label = Label(self.frame, text="EMLN: ")
        self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE')
        self.emln_container = FileEditBar(self.frame,
                                          directory=self.dir,
                                          filesettings={
                                              'extension':
                                              '.emln',
                                              'ftypes':
                                              [('MLN extension files', '.emln')
                                               ]
                                          },
                                          defaultname='*unknown{}',
                                          importhook=self.import_emln,
                                          deletehook=self.delete_emln,
                                          projecthook=self.save_proj,
                                          filecontenthook=self.emlnfilecontent,
                                          fileslisthook=self.emlnfiles,
                                          updatehook=self.update_emln,
                                          onchangehook=self.project_setdirty)
        self.emln_container.grid(row=self.emlncontainerrow,
                                 column=1,
                                 sticky="NEWS")
        self.emln_container.editor.bind("<FocusIn>", self._got_focus)
        self.emln_container.columnconfigure(1, weight=2)
        self.onchange_use_emln(dirty=False)
        self.frame.rowconfigure(row, weight=1)

        # db section
        row += 1
        Label(self.frame, text="Evidence: ").grid(row=row,
                                                  column=0,
                                                  sticky='NE')
        self.db_container = FileEditBar(self.frame,
                                        directory=self.dir,
                                        filesettings={
                                            'extension': '.db',
                                            'ftypes':
                                            [('Database files', '.db')]
                                        },
                                        defaultname='*unknown{}',
                                        importhook=self.import_db,
                                        deletehook=self.delete_db,
                                        projecthook=self.save_proj,
                                        filecontenthook=self.dbfilecontent,
                                        fileslisthook=self.dbfiles,
                                        updatehook=self.update_db,
                                        onchangehook=self.project_setdirty)
        self.db_container.grid(row=row, column=1, sticky="NEWS")
        self.db_container.editor.bind("<FocusIn>", self._got_focus)
        self.db_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        # inference method selection
        row += 1
        self.list_methods_row = row
        Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E)
        self.selected_method = StringVar()
        self.selected_method.trace('w', self.select_method)
        methodnames = sorted(InferenceMethods.names())
        self.list_methods = OptionMenu(*(self.frame, self.selected_method) +
                                       tuple(methodnames))
        self.list_methods.grid(row=self.list_methods_row,
                               column=1,
                               sticky="NWE")

        # options
        row += 1
        option_container = Frame(self.frame)
        option_container.grid(row=row, column=1, sticky="NEWS")

        # Multiprocessing
        self.multicore = IntVar()
        self.cb_multicore = Checkbutton(option_container,
                                        text="Use all CPUs",
                                        variable=self.multicore,
                                        command=self.settings_setdirty)
        self.cb_multicore.grid(row=0, column=2, sticky=W)

        # profiling
        self.profile = IntVar()
        self.cb_profile = Checkbutton(option_container,
                                      text='Use Profiler',
                                      variable=self.profile,
                                      command=self.settings_setdirty)
        self.cb_profile.grid(row=0, column=3, sticky=W)

        # verbose
        self.verbose = IntVar()
        self.cb_verbose = Checkbutton(option_container,
                                      text='verbose',
                                      variable=self.verbose,
                                      command=self.settings_setdirty)
        self.cb_verbose.grid(row=0, column=4, sticky=W)

        # options
        self.ignore_unknown_preds = IntVar()
        self.cb_ignore_unknown_preds = Checkbutton(
            option_container,
            text='ignore unkown predicates',
            variable=self.ignore_unknown_preds,
            command=self.settings_setdirty)
        self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W")

        # queries
        row += 1
        Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E)
        self.query = StringVar()
        self.query.trace('w', self.settings_setdirty)
        Entry(self.frame, textvariable=self.query).grid(row=row,
                                                        column=1,
                                                        sticky="NEW")

        # additional parameters
        row += 1
        Label(self.frame, text="Add. params: ").grid(row=row,
                                                     column=0,
                                                     sticky="NE")
        self.params = StringVar()
        self.params.trace('w', self.settings_setdirty)
        self.entry_params = Entry(self.frame, textvariable=self.params)
        self.entry_params.grid(row=row, column=1, sticky="NEW")

        # closed-world predicates
        row += 1
        Label(self.frame, text="CW preds: ").grid(row=row,
                                                  column=0,
                                                  sticky="E")

        cw_container = Frame(self.frame)
        cw_container.grid(row=row, column=1, sticky='NEWS')
        cw_container.columnconfigure(0, weight=1)

        self.cwPreds = StringVar()
        self.cwPreds.trace('w', self.settings_setdirty)
        self.entry_cw = Entry(cw_container, textvariable=self.cwPreds)
        self.entry_cw.grid(row=0, column=0, sticky="NEWS")

        self.closed_world = IntVar()
        self.cb_closed_world = Checkbutton(cw_container,
                                           text="CW Assumption",
                                           variable=self.closed_world,
                                           command=self.onchange_cw)
        self.cb_closed_world.grid(row=0, column=1, sticky='W')

        # output filename
        row += 1
        output_cont = Frame(self.frame)
        output_cont.grid(row=row, column=1, sticky='NEWS')
        output_cont.columnconfigure(0, weight=1)

        # - filename
        Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE")
        self.output_filename = StringVar()
        self.entry_output_filename = Entry(output_cont,
                                           textvariable=self.output_filename)
        self.entry_output_filename.grid(row=0, column=0, sticky="NEW")

        # - save option
        self.save = IntVar()
        self.cb_save = Checkbutton(output_cont,
                                   text="save",
                                   variable=self.save)
        self.cb_save.grid(row=0, column=1, sticky=W)

        # start button
        row += 1
        start_button = Button(self.frame,
                              text=">> Start Inference <<",
                              command=self.infer)
        start_button.grid(row=row, column=1, sticky="NEW")

        self.settings_dirty = IntVar()
        self.project_dirty = IntVar()

        self.gconf = gconf
        self.project = None
        self.project_dir = os.path.abspath(
            ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))
        if gconf['prev_query_project':self.project_dir] is not None:
            self.load_project(
                os.path.join(self.project_dir,
                             gconf['prev_query_project':self.project_dir]))
        else:
            self.new_project()

        self.config = self.project.queryconf
        self.project.addlistener(self.project_setdirty)

        self.mln_container.dirty = False
        self.emln_container.dirty = False
        self.db_container.dirty = False
        self.project_setdirty(dirty=False)

        self.master.geometry(gconf['window_loc_query'])

        self.initialized = True

    def _got_focus(self, *_):
        if self.master.focus_get() == self.mln_container.editor:
            if not self.project.mlns and not self.mln_container.file_buffer:
                self.mln_container.new_file()
        elif self.master.focus_get() == self.db_container.editor:
            if not self.project.dbs and not self.db_container.file_buffer:
                self.db_container.new_file()
        elif self.master.focus_get() == self.emln_container.editor:
            if not self.project.emlns and not self.emln_container.file_buffer:
                self.emln_container.new_file()

    def quit(self):
        if self.settings_dirty.get() or self.project_dirty.get():
            savechanges = messagebox.askyesnocancel(
                "Save changes",
                "You have unsaved project changes. Do you want to save them before quitting?"
            )
            if savechanges is None:
                return
            elif savechanges:
                self.noask_save_project()
            self.master.destroy()
        else:
            # write gui settings and destroy
            self.write_gconfig()
            self.master.destroy()

    ####################### PROJECT FUNCTIONS #################################

    def new_project(self):
        self.project = MLNProject()
        self.project.addlistener(self.project_setdirty)
        self.project.name = DEFAULTNAME.format('.pracmln')
        self.reset_gui()
        self.set_config(self.project.queryconf)
        self.mln_container.update_file_choices()
        self.emln_container.update_file_choices()
        self.db_container.update_file_choices()
        self.project_setdirty(dirty=True)

    def project_setdirty(self, dirty=False, *args):
        self.project_dirty.set(dirty or self.mln_container.dirty
                               or self.db_container.dirty
                               or self.emln_container.dirty)
        self.changewindowtitle()

    def settings_setdirty(self, *args):
        self.settings_dirty.set(1)
        self.changewindowtitle()

    def changewindowtitle(self):
        title = (WINDOWTITLEEDITED if
                 (self.settings_dirty.get() or self.project_dirty.get()) else
                 WINDOWTITLE).format(self.project_dir, self.project.name)
        self.master.title(title)

    def ask_load_project(self):
        filename = askopenfilename(initialdir=self.dir,
                                   filetypes=[('PRACMLN project files',
                                               '.pracmln')],
                                   defaultextension=".pracmln")
        if filename and os.path.exists(filename):
            self.load_project(filename)
        else:
            logger.info('No file selected.')
            return

    def load_project(self, filename):
        if filename and os.path.exists(filename):
            projdir, _ = ntpath.split(filename)
            self.dir = os.path.abspath(projdir)
            self.project_dir = os.path.abspath(projdir)
            self.project = MLNProject.open(filename)
            self.project.addlistener(self.project_setdirty)
            self.reset_gui()
            self.set_config(self.project.queryconf.config)
            self.mln_container.update_file_choices()
            self.db_container.update_file_choices()
            if len(self.project.mlns) > 0:
                self.mln_container.selected_file.set(
                    self.project.queryconf['mln']
                    or list(self.project.mlns.keys())[0])
            self.mln_container.dirty = False
            if len(self.project.emlns) > 0:
                self.emln_container.selected_file.set(
                    self.project.queryconf['emln']
                    or list(self.project.emlns.keys())[0])
            self.emln_container.dirty = False
            if len(self.project.dbs) > 0:
                self.db_container.selected_file.set(
                    self.project.queryconf['db']
                    or list(self.project.dbs.keys())[0])
            self.db_container.dirty = False
            self.write_gconfig(savegeometry=False)
            self.settings_dirty.set(0)
            self.project_setdirty(dirty=False)
            self.changewindowtitle()
        else:
            logger.error(
                'File {} does not exist. Creating new project...'.format(
                    filename))
            self.new_project()

    def noask_save_project(self):
        if self.project.name and not self.project.name == DEFAULTNAME.format(
                '.pracmln'):
            self.save_project(os.path.join(self.project_dir,
                                           self.project.name))
        else:
            self.ask_save_project()

    def ask_save_project(self):
        fullfilename = asksaveasfilename(initialdir=self.project_dir,
                                         confirmoverwrite=True,
                                         filetypes=[('PRACMLN project files',
                                                     '.pracmln')],
                                         defaultextension=".pracmln")
        self.save_project(fullfilename)

    def save_project(self, fullfilename):
        if fullfilename:
            fpath, fname = ntpath.split(fullfilename)
            fname = fname.split('.')[0]
            self.project.name = fname
            self.dir = os.path.abspath(fpath)
            self.project_dir = os.path.abspath(fpath)

            self.mln_container.save_all_files()
            self.emln_container.save_all_files()
            self.db_container.save_all_files()

            self.update_config()
            self.project.save(dirpath=self.project_dir)
            self.write_gconfig()

            self.load_project(fullfilename)
            self.settings_dirty.set(0)

    def save_proj(self):
        self.project.save(dirpath=self.project_dir)
        self.write_gconfig()
        self.project_setdirty(dirty=False)

    ####################### MLN FUNCTIONS #####################################

    def import_mln(self, name, content):
        self.project.add_mln(name, content)

    def delete_mln(self, fname):
        if fname in self.project.mlns:
            self.project.rm_mln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.mlns:
            self.project.rm_mln(fnamestr)

    def update_mln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.mln_container.selected_file.get()
        if new is None:
            new = self.mln_container.selected_file.get().strip('*')
        if content is None:
            content = self.mln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno(
                "Save changes",
                "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.mlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.mlns[old] = content
        else:
            if new in self.project.mlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno(
                        "Save changes",
                        "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.mlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.mlns[new] = content
        return 1

    def mlnfiles(self):
        return list(self.project.mlns.keys())

    def mlnfilecontent(self, filename):
        return self.project.mlns.get(filename, '').strip()

    # /MLN FUNCTIONS #####################################

    ####################### EMLN FUNCTIONS #####################################

    def import_emln(self, name, content):
        self.project.add_emln(name, content)

    def delete_emln(self, fname):
        if fname in self.project.emlns:
            self.project.rm_emln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.emlns:
            self.project.rm_emln(fnamestr)

    def update_emln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.emln_container.selected_file.get()
        if new is None:
            new = self.emln_container.selected_file.get().strip('*')
        if content is None:
            content = self.emln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno(
                "Save changes",
                "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.emlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.emlns[old] = content
        else:
            if new in self.project.emlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno(
                        "Save changes",
                        "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.emlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.emlns[new] = content
        return 1

    def emlnfiles(self):
        return list(self.project.emlns.keys())

    def emlnfilecontent(self, filename):
        return self.project.emlns.get(filename, '').strip()

    # /EMLN FUNCTIONS #####################################

    # DB FUNCTIONS #####################################
    def import_db(self, name, content):
        self.project.add_db(name, content)

    def delete_db(self, fname):
        if fname in self.project.dbs:
            self.project.rm_db(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.dbs:
            self.project.rm_db(fnamestr)

    def update_db(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.db_container.selected_file.get()
        if new is None:
            new = self.db_container.selected_file.get().strip('*')
        if content is None:
            content = self.db_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno(
                "Save changes",
                "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.dbs[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.dbs[old] = content
        else:
            if new in self.project.dbs:
                if askoverwrite:
                    savechanges = messagebox.askyesno(
                        "Save changes",
                        "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.dbs[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.dbs[new] = content
        return 1

    def dbfiles(self):
        return list(self.project.dbs.keys())

    def dbfilecontent(self, filename):
        return self.project.dbs.get(filename, '').strip()

    # /DB FUNCTIONS #####################################

    # GENERAL FUNCTIONS #################################

    def select_method(self, *args):
        self.set_outputfilename()
        self.settings_setdirty()

    def onchange_use_emln(self, dirty=True, *args):
        if not self.use_emln.get():
            self.emln_label.grid_forget()
            self.emln_container.grid_forget()
        else:
            self.emln_label.grid(row=self.emlncontainerrow,
                                 column=0,
                                 sticky="NE")
            self.emln_container.grid(row=self.emlncontainerrow,
                                     column=1,
                                     sticky="NWES")
        if dirty:
            self.settings_setdirty()

    def onchange_cw(self, *args):
        if self.closed_world.get():
            self.entry_cw.configure(state=DISABLED)
        else:
            self.entry_cw.configure(state=NORMAL)
        self.settings_setdirty()

    def reset_gui(self):
        self.set_config({})
        self.db_container.clear()
        self.emln_container.clear()
        self.mln_container.clear()

    def set_config(self, newconf):
        self.config = newconf
        self.selected_grammar.set(ifnone(newconf.get('grammar'),
                                         'PRACGrammar'))
        self.selected_logic.set(ifnone(newconf.get('logic'),
                                       'FirstOrderLogic'))
        self.mln_container.selected_file.set(ifnone(newconf.get('mln'), ''))
        if self.use_emln.get():
            self.emln_container.selected_file.set(
                ifnone(newconf.get('mln'), ''))
        self.db_container.selected_file.set(ifnone(newconf.get('db'), ""))
        self.selected_method.set(
            ifnone(newconf.get("method"),
                   InferenceMethods.name('MCSAT'),
                   transform=InferenceMethods.name))
        self.multicore.set(ifnone(newconf.get('multicore'), 0))
        self.profile.set(ifnone(newconf.get('profile'), 0))
        self.params.set(ifnone(newconf.get('params'), ''))
        self.use_emln.set(ifnone(newconf.get('use_emln'), 0))
        self.verbose.set(ifnone(newconf.get('verbose'), 1))
        self.ignore_unknown_preds.set(
            ifnone(newconf.get('ignore_unknown_preds'), 0))
        self.output_filename.set(ifnone(newconf.get('output_filename'), ''))
        self.cwPreds.set(ifnone(newconf.get('cw_preds'), ''))
        self.closed_world.set(ifnone(newconf.get('cw'), 0))
        self.save.set(ifnone(newconf.get('save'), 0))
        self.query.set(ifnone(newconf.get('queries'), ''))
        self.onchange_cw()

    def set_outputfilename(self):
        if not hasattr(self, "output_filename") or not hasattr(
                self, "db_filename") or not hasattr(self, "mln_filename"):
            return
        mln = self.mln_container.selected_file.get()
        db = self.db_container.selected_file.get()
        if "" in (mln, db):
            return
        if self.selected_method.get():
            method = InferenceMethods.clazz(self.selected_method.get())
            methodid = InferenceMethods.id(method)
            filename = config.query_output_filename(mln, methodid, db)
            self.output_filename.set(filename)

    def update_config(self):

        self.config = PRACMLNConfig()
        self.config["use_emln"] = self.use_emln.get()
        self.config['mln'] = self.mln_container.selected_file.get().strip(
        ).lstrip('*')
        self.config['emln'] = self.emln_container.selected_file.get().strip(
        ).lstrip('*')
        self.config["db"] = self.db_container.selected_file.get().strip(
        ).lstrip('*')
        self.config["method"] = InferenceMethods.id(
            self.selected_method.get().strip())
        self.config["params"] = self.params.get().strip()
        self.config["queries"] = self.query.get()
        self.config["output_filename"] = self.output_filename.get().strip()
        self.config["cw"] = self.closed_world.get()
        self.config["cw_preds"] = self.cwPreds.get()
        self.config['profile'] = self.profile.get()
        self.config['logic'] = self.selected_logic.get()
        self.config['grammar'] = self.selected_grammar.get()
        self.config['multicore'] = self.multicore.get()
        self.config['save'] = self.save.get()
        self.config['ignore_unknown_preds'] = self.ignore_unknown_preds.get()
        self.config['verbose'] = self.verbose.get()
        self.config['window_loc'] = self.master.winfo_geometry()
        self.config['dir'] = self.dir
        self.project.queryconf = PRACMLNConfig()
        self.project.queryconf.update(self.config.config.copy())

    def write_gconfig(self, savegeometry=True):
        self.gconf['prev_query_path'] = self.dir
        self.gconf['prev_query_project':self.dir] = self.project.name

        # save geometry
        if savegeometry:
            self.gconf['window_loc_query'] = self.master.geometry()
        self.gconf.dump()

    def infer(self, savegeometry=True, options={}, *args):
        mln_content = self.mln_container.editor.get("1.0", END).strip()
        db_content = self.db_container.editor.get("1.0", END).strip()

        # create conf from current gui settings
        self.update_config()

        # write gui settings
        self.write_gconfig(savegeometry=savegeometry)

        # hide gui
        self.master.withdraw()

        try:
            print((headline('PRACMLN QUERY TOOL')))
            print()

            if options.get('mlnarg') is not None:
                mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')),
                             logic=self.config.get('logic', 'FirstOrderLogic'),
                             grammar=self.config.get('grammar', 'PRACGrammar'))
            else:
                mlnobj = parse_mln(
                    mln_content,
                    searchpaths=[self.dir],
                    projectpath=os.path.join(self.dir, self.project.name),
                    logic=self.config.get('logic', 'FirstOrderLogic'),
                    grammar=self.config.get('grammar', 'PRACGrammar'))

            if options.get('emlnarg') is not None:
                emln_content = mlnpath(options.get('emlnarg')).content
            else:
                emln_content = self.emln_container.editor.get("1.0",
                                                              END).strip()

            if options.get('dbarg') is not None:
                dbobj = Database.load(mlnobj,
                                      dbfiles=[options.get('dbarg')],
                                      ignore_unknown_preds=self.config.get(
                                          'ignore_unknown_preds', True))
            else:
                out(self.config.get('ignore_unknown_preds', True))
                dbobj = parse_db(mlnobj,
                                 db_content,
                                 ignore_unknown_preds=self.config.get(
                                     'ignore_unknown_preds', True))

            if options.get('queryarg') is not None:
                self.config["queries"] = options.get('queryarg')

            infer = MLNQuery(config=self.config,
                             mln=mlnobj,
                             db=dbobj,
                             emln=emln_content)
            result = infer.run()

            # write to file if run from commandline, otherwise save result to project results
            if options.get('outputfile') is not None:
                output = io.StringIO()
                result.write(output)
                with open(os.path.abspath(options.get('outputfile')),
                          'w') as f:
                    f.write(output.getvalue())
                logger.info('saved result to {}'.format(
                    os.path.abspath(options.get('outputfile'))))
            elif self.save.get():
                output = io.StringIO()
                result.write(output)
                fname = self.output_filename.get()
                self.project.add_result(fname, output.getvalue())
                self.project.save(dirpath=self.dir)
                logger.info(
                    'saved result to file results/{} in project {}'.format(
                        fname, self.project.name))
            else:
                logger.debug(
                    'No output file given - results have not been saved.')
        except:
            traceback.print_exc()

        # restore main window
        sys.stdout.flush()
        self.master.deiconify()
Example #20
0
class waitWindowProgressBar(Toplevel):
    def __init__(self, parent=None):
        """
        Initialises the calculate wait window. Waits for other processes to finish, then packs everything. 
        messages, setup_dataset and stop are the functions that change the layout of the frame.
        """
        super().__init__(parent)
        self.title("Setting up.......")
        #self.attributes("-topmost", True)
        self.pb_val = IntVar(self)
        self.pb_val.set(0)
        self.pb = Progressbar(self, length=400, variable=self.pb_val)
        self.pb.pack(pady=20, padx=20)
        self.pb.configure(maximum=10)
        self.labeltext = StringVar()
        self.labeltext.set("Waiting for other process.....")
        self.waiting_label = Label(self, textvariable=self.labeltext)
        self.waiting_label.configure(anchor="center")
        self.waiting_label.pack(pady=20, padx=20, fill='both', expand=True)
        self.stopbutton = Button(self,
                                 text="Stop!",
                                 compound="bottom",
                                 command=self.stop)
        self.stopbutton.pack(side="left", fill="x", expand=True)
        self.stopflag = 0
        self.update()

    def stop(self):
        """
        Sets the stopflag to 1, thus stopping the calculation.
        """
        self.stopflag = 1

    def setup_dataset(self, dataset):
        """
        Sets up the calculation wait window for the different stages of calculation.
        """
        self.dataset = dataset
        self.title("Calculating Dataset %s" % os.path.basename(dataset.path))
        self.waiting_label.pack(pady=20, padx=20)
        self.update()

    def errormessage(self, dataset):
        messagebox.showwarning(
            "Invalid parameters",
            "Dataset %s was skipped in the computation because of invalid parameters. Please configure Cut-off frequency and / or Filter type."
            % os.path.basename(dataset.path))

    def return_function(self):
        """
        Returns two functions for further use in the model.
        """
        @ri.rternalize
        def messages(i, r, each):
            """
            Messages function given to the R environment.
            Gives feedback on the state of the Monte-Carlo simulation. 
            """
            self.pb.step()
            count = np.asarray((i, r))
            if (count[0] == -1):
                self.title("Computation for Dataset %s" %
                           os.path.basename(self.dataset.path))
                self.pb.pack(pady=20, padx=20)
                self.pb_val.set(0)
                self.stopbutton["state"] = "normal"
                if self.dataset.metadata[
                        "Method"] == "HILDE-Homogeneous" or self.dataset.metadata[
                            "Method"] == "HILDE-Heterogeneous":
                    self.pb.configure(maximum=int(
                        self.dataset.metadata["Repetitions_Hilde"]))
                else:
                    self.pb.configure(
                        maximum=int(self.dataset.metadata["Repetitions"]))
                self.labeltext.set(
                    "Currently computing quantile for Dataset:\n%s \n Press Stop! button to stop computation for current dataset."
                    % os.path.basename(self.dataset.path))
            if (count[0] == -2):
                self.pb.pack_forget()
                self.labeltext.set(
                    "Calculating fit for Dataset:\n%s\nThis computation cannot be interrupted and may take a few minutes."
                    % os.path.basename(self.dataset.path))
                self.stopbutton["state"] = "disabled"
                self.waiting_label.pack(pady=20, padx=20)
            self.update()
            return self.stopflag

        return messages, self.setup_dataset, self.errormessage
Example #21
0
class MLNQueryGUI(object):
    def __init__(self, master, gconf, directory=None):
        self.master = master

        self.initialized = False

        self.master.bind('<Return>', self.infer)
        self.master.bind('<Escape>', lambda a: self.master.quit())
        self.master.protocol('WM_DELETE_WINDOW', self.quit)

        self.dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)
        self.frame.columnconfigure(1, weight=1)

        row = 0
        # pracmln project options
        Label(self.frame, text='PRACMLN Project: ').grid(row=row, column=0,
                                                         sticky='ES')
        project_container = Frame(self.frame)
        project_container.grid(row=row, column=1, sticky="NEWS")

        # new proj file
        self.btn_newproj = Button(project_container, text='New Project...', command=self.new_project)
        self.btn_newproj.grid(row=0, column=1, sticky="WS")

        # open proj file
        self.btn_openproj = Button(project_container, text='Open Project...', command=self.ask_load_project)
        self.btn_openproj.grid(row=0, column=2, sticky="WS")

        # save proj file
        self.btn_updateproj = Button(project_container, text='Save Project...', command=self.noask_save_project)
        self.btn_updateproj.grid(row=0, column=3, sticky="WS")

        # save proj file as...
        self.btn_saveproj = Button(project_container, text='Save Project as...', command=self.ask_save_project)
        self.btn_saveproj.grid(row=0, column=4, sticky="WS")

        # grammar selection
        row += 1
        Label(self.frame, text='Grammar: ').grid(row=row, column=0, sticky='E')
        grammars = ['StandardGrammar', 'PRACGrammar']
        self.selected_grammar = StringVar()
        self.selected_grammar.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_grammar) + tuple(grammars))
        l.grid(row=row, column=1, sticky='NWE')

        # logic selection
        row += 1
        Label(self.frame, text='Logic: ').grid(row=row, column=0, sticky='E')
        logics = ['FirstOrderLogic', 'FuzzyLogic']
        self.selected_logic = StringVar()
        self.selected_logic.trace('w', self.settings_setdirty)
        l = OptionMenu(*(self.frame, self.selected_logic) + tuple(logics))
        l.grid(row=row, column=1, sticky='NWE')

        # mln section
        row += 1
        Label(self.frame, text="MLN: ").grid(row=row, column=0, sticky='NE')
        self.mln_container = FileEditBar(self.frame, directory=self.dir,
                                         filesettings={'extension': '.mln', 'ftypes': [('MLN files', '.mln')]},
                                         defaultname='*unknown{}',
                                         importhook=self.import_mln,
                                         deletehook=self.delete_mln,
                                         projecthook=self.save_proj,
                                         filecontenthook=self.mlnfilecontent,
                                         fileslisthook=self.mlnfiles,
                                         updatehook=self.update_mln,
                                         onchangehook=self.project_setdirty)
        self.mln_container.editor.bind("<FocusIn>", self._got_focus)
        self.mln_container.grid(row=row, column=1, sticky="NEWS")
        self.mln_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        row += 1
        self.use_emln = IntVar()
        self.use_emln.set(0)
        self.cb_use_emln = Checkbutton(self.frame, text="use model extension",
                                       variable=self.use_emln,
                                       command=self.onchange_use_emln)
        self.cb_use_emln.grid(row=row, column=1, sticky="W")

        # mln extension section
        row += 1
        self.emlncontainerrow = row
        self.emln_label = Label(self.frame, text="EMLN: ")
        self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky='NE')
        self.emln_container = FileEditBar(self.frame,
                                          directory=self.dir,
                                          filesettings={'extension': '.emln', 'ftypes': [('MLN extension files','.emln')]},
                                          defaultname='*unknown{}',
                                          importhook=self.import_emln,
                                          deletehook=self.delete_emln,
                                          projecthook=self.save_proj,
                                          filecontenthook=self.emlnfilecontent,
                                          fileslisthook=self.emlnfiles,
                                          updatehook=self.update_emln,
                                          onchangehook=self.project_setdirty)
        self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NEWS")
        self.emln_container.editor.bind("<FocusIn>", self._got_focus)
        self.emln_container.columnconfigure(1, weight=2)
        self.onchange_use_emln(dirty=False)
        self.frame.rowconfigure(row, weight=1)

        # db section
        row += 1
        Label(self.frame, text="Evidence: ").grid(row=row, column=0, sticky='NE')
        self.db_container = FileEditBar(self.frame, directory=self.dir,
                                        filesettings={'extension': '.db', 'ftypes': [('Database files', '.db')]},
                                        defaultname='*unknown{}',
                                        importhook=self.import_db,
                                        deletehook=self.delete_db,
                                        projecthook=self.save_proj,
                                        filecontenthook=self.dbfilecontent,
                                        fileslisthook=self.dbfiles,
                                        updatehook=self.update_db,
                                        onchangehook=self.project_setdirty)
        self.db_container.grid(row=row, column=1, sticky="NEWS")
        self.db_container.editor.bind("<FocusIn>", self._got_focus)
        self.db_container.columnconfigure(1, weight=2)
        self.frame.rowconfigure(row, weight=1)

        # inference method selection
        row += 1
        self.list_methods_row = row
        Label(self.frame, text="Method: ").grid(row=row, column=0, sticky=E)
        self.selected_method = StringVar()
        self.selected_method.trace('w', self.select_method)
        methodnames = sorted(InferenceMethods.names())
        self.list_methods = OptionMenu(*(self.frame, self.selected_method) + tuple(methodnames))
        self.list_methods.grid(row=self.list_methods_row, column=1, sticky="NWE")

        # options
        row += 1
        option_container = Frame(self.frame)
        option_container.grid(row=row, column=1, sticky="NEWS")

        # Multiprocessing
        self.multicore = IntVar()
        self.cb_multicore = Checkbutton(option_container, text="Use all CPUs",
                                        variable=self.multicore,
                                        command=self.settings_setdirty)
        self.cb_multicore.grid(row=0, column=2, sticky=W)

        # profiling
        self.profile = IntVar()
        self.cb_profile = Checkbutton(option_container, text='Use Profiler',
                                      variable=self.profile,
                                      command=self.settings_setdirty)
        self.cb_profile.grid(row=0, column=3, sticky=W)

        # verbose
        self.verbose = IntVar()
        self.cb_verbose = Checkbutton(option_container, text='verbose',
                                      variable=self.verbose,
                                      command=self.settings_setdirty)
        self.cb_verbose.grid(row=0, column=4, sticky=W)

        # options
        self.ignore_unknown_preds = IntVar()
        self.cb_ignore_unknown_preds = Checkbutton(option_container,
                                                   text='ignore unkown predicates',
                                                   variable=self.ignore_unknown_preds,
                                                   command=self.settings_setdirty)
        self.cb_ignore_unknown_preds.grid(row=0, column=5, sticky="W")

        # queries
        row += 1
        Label(self.frame, text="Queries: ").grid(row=row, column=0, sticky=E)
        self.query = StringVar()
        self.query.trace('w', self.settings_setdirty)
        Entry(self.frame, textvariable=self.query).grid(row=row, column=1, sticky="NEW")

        # additional parameters
        row += 1
        Label(self.frame, text="Add. params: ").grid(row=row, column=0, sticky="NE")
        self.params = StringVar()
        self.params.trace('w', self.settings_setdirty)
        self.entry_params = Entry(self.frame, textvariable=self.params)
        self.entry_params.grid(row=row, column=1, sticky="NEW")

        # closed-world predicates
        row += 1
        Label(self.frame, text="CW preds: ").grid(row=row, column=0, sticky="E")

        cw_container = Frame(self.frame)
        cw_container.grid(row=row, column=1, sticky='NEWS')
        cw_container.columnconfigure(0, weight=1)

        self.cwPreds = StringVar()
        self.cwPreds.trace('w', self.settings_setdirty)
        self.entry_cw = Entry(cw_container, textvariable=self.cwPreds)
        self.entry_cw.grid(row=0, column=0, sticky="NEWS")

        self.closed_world = IntVar()
        self.cb_closed_world = Checkbutton(cw_container, text="CW Assumption",
                                           variable=self.closed_world,
                                           command=self.onchange_cw)
        self.cb_closed_world.grid(row=0, column=1, sticky='W')

        # output filename
        row += 1
        output_cont = Frame(self.frame)
        output_cont.grid(row=row, column=1, sticky='NEWS')
        output_cont.columnconfigure(0, weight=1)

        # - filename
        Label(self.frame, text="Output: ").grid(row=row, column=0, sticky="NE")
        self.output_filename = StringVar()
        self.entry_output_filename = Entry(output_cont, textvariable=self.output_filename)
        self.entry_output_filename.grid(row=0, column=0, sticky="NEW")

        # - save option
        self.save = IntVar()
        self.cb_save = Checkbutton(output_cont, text="save", variable=self.save)
        self.cb_save.grid(row=0, column=1, sticky=W)

        # start button
        row += 1
        start_button = Button(self.frame, text=">> Start Inference <<", command=self.infer)
        start_button.grid(row=row, column=1, sticky="NEW")

        self.settings_dirty = IntVar()
        self.project_dirty = IntVar()

        self.gconf = gconf
        self.project = None
        self.project_dir = os.path.abspath(ifnone(directory, ifnone(gconf['prev_query_path'], os.getcwd())))
        if gconf['prev_query_project': self.project_dir] is not None:
            self.load_project(os.path.join(self.project_dir, gconf['prev_query_project':self.project_dir]))
        else:
            self.new_project()

        self.config = self.project.queryconf
        self.project.addlistener(self.project_setdirty)

        self.mln_container.dirty = False
        self.emln_container.dirty = False
        self.db_container.dirty = False
        self.project_setdirty(dirty=False)

        self.master.geometry(gconf['window_loc_query'])

        self.initialized = True

    def _got_focus(self, *_):
        if self.master.focus_get() == self.mln_container.editor:
            if not self.project.mlns and not self.mln_container.file_buffer:
                self.mln_container.new_file()
        elif self.master.focus_get() == self.db_container.editor:
            if not self.project.dbs and not self.db_container.file_buffer:
                self.db_container.new_file()
        elif self.master.focus_get() == self.emln_container.editor:
            if not self.project.emlns and not self.emln_container.file_buffer:
                self.emln_container.new_file()

    def quit(self):
        if self.settings_dirty.get() or self.project_dirty.get():
            savechanges = messagebox.askyesnocancel("Save changes", "You have unsaved project changes. Do you want to save them before quitting?")
            if savechanges is None:
                return
            elif savechanges:
                self.noask_save_project()
            self.master.destroy()
        else:
            # write gui settings and destroy
            self.write_gconfig()
            self.master.destroy()


    ####################### PROJECT FUNCTIONS #################################

    def new_project(self):
        self.project = MLNProject()
        self.project.addlistener(self.project_setdirty)
        self.project.name = DEFAULTNAME.format('.pracmln')
        self.reset_gui()
        self.set_config(self.project.queryconf)
        self.mln_container.update_file_choices()
        self.emln_container.update_file_choices()
        self.db_container.update_file_choices()
        self.project_setdirty(dirty=True)


    def project_setdirty(self, dirty=False, *args):
        self.project_dirty.set(dirty or self.mln_container.dirty or self.db_container.dirty or
            self.emln_container.dirty)
        self.changewindowtitle()


    def settings_setdirty(self, *args):
        self.settings_dirty.set(1)
        self.changewindowtitle()


    def changewindowtitle(self):
        title = (WINDOWTITLEEDITED if (self.settings_dirty.get() or self.project_dirty.get()) else WINDOWTITLE).format(self.project_dir, self.project.name)
        self.master.title(title)


    def ask_load_project(self):
        filename = askopenfilename(initialdir=self.dir, filetypes=[('PRACMLN project files', '.pracmln')], defaultextension=".pracmln")
        if filename and os.path.exists(filename):
            self.load_project(filename)
        else:
            logger.info('No file selected.')
            return


    def load_project(self, filename):
        if filename and os.path.exists(filename):
            projdir, _ = ntpath.split(filename)
            self.dir = os.path.abspath(projdir)
            self.project_dir = os.path.abspath(projdir)
            self.project = MLNProject.open(filename)
            self.project.addlistener(self.project_setdirty)
            self.reset_gui()
            self.set_config(self.project.queryconf.config)
            self.mln_container.update_file_choices()
            self.db_container.update_file_choices()
            if len(self.project.mlns) > 0:
                self.mln_container.selected_file.set(self.project.queryconf['mln'] or list(self.project.mlns.keys())[0])
            self.mln_container.dirty = False
            if len(self.project.emlns) > 0:
                self.emln_container.selected_file.set(self.project.queryconf['emln'] or list(self.project.emlns.keys())[0])
            self.emln_container.dirty = False
            if len(self.project.dbs) > 0:
                self.db_container.selected_file.set(self.project.queryconf['db'] or list(self.project.dbs.keys())[0])
            self.db_container.dirty = False
            self.write_gconfig(savegeometry=False)
            self.settings_dirty.set(0)
            self.project_setdirty(dirty=False)
            self.changewindowtitle()
        else:
            logger.error('File {} does not exist. Creating new project...'.format(filename))
            self.new_project()


    def noask_save_project(self):
        if self.project.name and not self.project.name == DEFAULTNAME.format('.pracmln'):
            self.save_project(os.path.join(self.project_dir, self.project.name))
        else:
            self.ask_save_project()


    def ask_save_project(self):
        fullfilename = asksaveasfilename(initialdir=self.project_dir,
                                         confirmoverwrite=True,
                                         filetypes=[('PRACMLN project files','.pracmln')],
                                         defaultextension=".pracmln")
        self.save_project(fullfilename)


    def save_project(self, fullfilename):
        if fullfilename:
            fpath, fname = ntpath.split(fullfilename)
            fname = fname.split('.')[0]
            self.project.name = fname
            self.dir = os.path.abspath(fpath)
            self.project_dir = os.path.abspath(fpath)

            self.mln_container.save_all_files()
            self.emln_container.save_all_files()
            self.db_container.save_all_files()

            self.update_config()
            self.project.save(dirpath=self.project_dir)
            self.write_gconfig()

            self.load_project(fullfilename)
            self.settings_dirty.set(0)


    def save_proj(self):
        self.project.save(dirpath=self.project_dir)
        self.write_gconfig()
        self.project_setdirty(dirty=False)


    ####################### MLN FUNCTIONS #####################################

    def import_mln(self, name, content):
        self.project.add_mln(name, content)


    def delete_mln(self, fname):
        if fname in self.project.mlns:
            self.project.rm_mln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.mlns:
            self.project.rm_mln(fnamestr)


    def update_mln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.mln_container.selected_file.get()
        if new is None:
            new = self.mln_container.selected_file.get().strip('*')
        if content is None:
            content = self.mln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.mlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.mlns[old] = content
        else:
            if new in self.project.mlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.mlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.mlns[new] = content
        return 1


    def mlnfiles(self):
        return list(self.project.mlns.keys())


    def mlnfilecontent(self, filename):
        return self.project.mlns.get(filename, '').strip()

    # /MLN FUNCTIONS #####################################


    ####################### EMLN FUNCTIONS #####################################

    def import_emln(self, name, content):
        self.project.add_emln(name, content)


    def delete_emln(self, fname):
        if fname in self.project.emlns:
            self.project.rm_emln(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.emlns:
            self.project.rm_emln(fnamestr)


    def update_emln(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.emln_container.selected_file.get()
        if new is None:
            new = self.emln_container.selected_file.get().strip('*')
        if content is None:
            content = self.emln_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.emlns[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.emlns[old] = content
        else:
            if new in self.project.emlns:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.emlns[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.emlns[new] = content
        return 1


    def emlnfiles(self):
        return list(self.project.emlns.keys())


    def emlnfilecontent(self, filename):
        return self.project.emlns.get(filename, '').strip()

    # /EMLN FUNCTIONS #####################################

    # DB FUNCTIONS #####################################
    def import_db(self, name, content):
        self.project.add_db(name, content)


    def delete_db(self, fname):
        if fname in self.project.dbs:
            self.project.rm_db(fname)
        fnamestr = fname.strip('*')
        if fnamestr in self.project.dbs:
            self.project.rm_db(fnamestr)


    def update_db(self, old=None, new=None, content=None, askoverwrite=True):
        if old is None:
            old = self.db_container.selected_file.get()
        if new is None:
            new = self.db_container.selected_file.get().strip('*')
        if content is None:
            content = self.db_container.editor.get("1.0", END).strip()

        if old == new and askoverwrite:
            savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
            if savechanges:
                self.project.dbs[old] = content
            else:
                logger.error('no name specified!')
                return -1
        elif old == new and not askoverwrite:
            self.project.dbs[old] = content
        else:
            if new in self.project.dbs:
                if askoverwrite:
                    savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new))
                    if savechanges:
                        self.project.dbs[new] = content
                    else:
                        logger.error('no name specified!')
                        return -1
            else:
                self.project.dbs[new] = content
        return 1


    def dbfiles(self):
        return list(self.project.dbs.keys())


    def dbfilecontent(self, filename):
        return self.project.dbs.get(filename, '').strip()

    # /DB FUNCTIONS #####################################

    # GENERAL FUNCTIONS #################################

    def select_method(self, *args):
        self.set_outputfilename()
        self.settings_setdirty()


    def onchange_use_emln(self, dirty=True, *args):
        if not self.use_emln.get():
            self.emln_label.grid_forget()
            self.emln_container.grid_forget()
        else:
            self.emln_label.grid(row=self.emlncontainerrow, column=0, sticky="NE")
            self.emln_container.grid(row=self.emlncontainerrow, column=1, sticky="NWES")
        if dirty:
            self.settings_setdirty()


    def onchange_cw(self, *args):
        if self.closed_world.get():
            self.entry_cw.configure(state=DISABLED)
        else:
            self.entry_cw.configure(state=NORMAL)
        self.settings_setdirty()


    def reset_gui(self):
        self.set_config({})
        self.db_container.clear()
        self.emln_container.clear()
        self.mln_container.clear()


    def set_config(self, newconf):
        self.config = newconf
        self.selected_grammar.set(ifnone(newconf.get('grammar'), 'PRACGrammar'))
        self.selected_logic.set(ifnone(newconf.get('logic'), 'FirstOrderLogic'))
        self.mln_container.selected_file.set(ifnone(newconf.get('mln'), ''))
        if self.use_emln.get():
            self.emln_container.selected_file.set(ifnone(newconf.get('mln'), ''))
        self.db_container.selected_file.set(ifnone(newconf.get('db'), ""))
        self.selected_method.set(ifnone(newconf.get("method"), InferenceMethods.name('MCSAT'), transform=InferenceMethods.name))
        self.multicore.set(ifnone(newconf.get('multicore'), 0))
        self.profile.set(ifnone(newconf.get('profile'), 0))
        self.params.set(ifnone(newconf.get('params'), ''))
        self.use_emln.set(ifnone(newconf.get('use_emln'), 0))
        self.verbose.set(ifnone(newconf.get('verbose'), 1))
        self.ignore_unknown_preds.set(ifnone(newconf.get('ignore_unknown_preds'), 0))
        self.output_filename.set(ifnone(newconf.get('output_filename'), ''))
        self.cwPreds.set(ifnone(newconf.get('cw_preds'), ''))
        self.closed_world.set(ifnone(newconf.get('cw'), 0))
        self.save.set(ifnone(newconf.get('save'), 0))
        self.query.set(ifnone(newconf.get('queries'), ''))
        self.onchange_cw()


    def set_outputfilename(self):
        if not hasattr(self, "output_filename") or not hasattr(self, "db_filename") or not hasattr(self, "mln_filename"):
            return
        mln = self.mln_container.selected_file.get()
        db = self.db_container.selected_file.get()
        if "" in (mln, db):
            return
        if self.selected_method.get():
            method = InferenceMethods.clazz(self.selected_method.get())
            methodid = InferenceMethods.id(method)
            filename = config.query_output_filename(mln, methodid, db)
            self.output_filename.set(filename)


    def update_config(self):

        self.config = PRACMLNConfig()
        self.config["use_emln"] = self.use_emln.get()
        self.config['mln'] = self.mln_container.selected_file.get().strip().lstrip('*')
        self.config['emln'] = self.emln_container.selected_file.get().strip().lstrip('*')
        self.config["db"] = self.db_container.selected_file.get().strip().lstrip('*')
        self.config["method"] = InferenceMethods.id(self.selected_method.get().strip())
        self.config["params"] = self.params.get().strip()
        self.config["queries"] = self.query.get()
        self.config["output_filename"] = self.output_filename.get().strip()
        self.config["cw"] = self.closed_world.get()
        self.config["cw_preds"] = self.cwPreds.get()
        self.config['profile'] = self.profile.get()
        self.config['logic'] = self.selected_logic.get()
        self.config['grammar'] = self.selected_grammar.get()
        self.config['multicore'] = self.multicore.get()
        self.config['save'] = self.save.get()
        self.config['ignore_unknown_preds'] = self.ignore_unknown_preds.get()
        self.config['verbose'] = self.verbose.get()
        self.config['window_loc'] = self.master.winfo_geometry()
        self.config['dir'] = self.dir
        self.project.queryconf = PRACMLNConfig()
        self.project.queryconf.update(self.config.config.copy())


    def write_gconfig(self, savegeometry=True):
        self.gconf['prev_query_path'] = self.dir
        self.gconf['prev_query_project': self.dir] = self.project.name

        # save geometry
        if savegeometry:
            self.gconf['window_loc_query'] = self.master.geometry()
        self.gconf.dump()


    def infer(self, savegeometry=True, options={}, *args):
        mln_content = self.mln_container.editor.get("1.0", END).strip()
        db_content = self.db_container.editor.get("1.0", END).strip()

        # create conf from current gui settings
        self.update_config()

        # write gui settings
        self.write_gconfig(savegeometry=savegeometry)

        # hide gui
        self.master.withdraw()

        try:
            print((headline('PRACMLN QUERY TOOL')))
            print()

            if options.get('mlnarg') is not None:
                mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')),
                             logic=self.config.get('logic', 'FirstOrderLogic'),
                             grammar=self.config.get('grammar', 'PRACGrammar'))
            else:
                mlnobj = parse_mln(mln_content, searchpaths=[self.dir],
                                   projectpath=os.path.join(self.dir, self.project.name),
                                   logic=self.config.get('logic', 'FirstOrderLogic'),
                                   grammar=self.config.get('grammar', 'PRACGrammar'))

            if options.get('emlnarg') is not None:
                emln_content = mlnpath(options.get('emlnarg')).content
            else:
                emln_content = self.emln_container.editor.get("1.0", END).strip()

            if options.get('dbarg') is not None:
                dbobj = Database.load(mlnobj, dbfiles=[options.get('dbarg')], ignore_unknown_preds=self.config.get('ignore_unknown_preds', True))
            else:
                out(self.config.get('ignore_unknown_preds', True))
                dbobj = parse_db(mlnobj, db_content, ignore_unknown_preds=self.config.get('ignore_unknown_preds', True))

            if options.get('queryarg') is not None:
                self.config["queries"] = options.get('queryarg')

            infer = MLNQuery(config=self.config, mln=mlnobj, db=dbobj, emln=emln_content)
            result = infer.run()


            # write to file if run from commandline, otherwise save result to project results
            if options.get('outputfile') is not None:
                output = io.StringIO()
                result.write(output)
                with open(os.path.abspath(options.get('outputfile')), 'w') as f:
                    f.write(output.getvalue())
                logger.info('saved result to {}'.format(os.path.abspath(options.get('outputfile'))))
            elif self.save.get():
                output = io.StringIO()
                result.write(output)
                fname = self.output_filename.get()
                self.project.add_result(fname, output.getvalue())
                self.project.save(dirpath=self.dir)
                logger.info('saved result to file results/{} in project {}'.format(fname, self.project.name))
            else:
                logger.debug('No output file given - results have not been saved.')
        except:
            traceback.print_exc()

        # restore main window
        sys.stdout.flush()
        self.master.deiconify()
Example #22
0
class IntegerEntry(StringEntry):
    """Integer class for entry
        super

    Parameters
    ----------
    parent : str
        parent handle
    lf_text : str
        text on LabelFrame
    l_limit : int
        lower limit
    u_limit : int
        upper limit
    def_inp : str
        default text
    colour : str
        frame colour
    mod : str
        enable or disable state switch

    Returns
    -------
    integer
    """
    def __init__(self,
                 parent,
                 lf_text,
                 l_limit,
                 u_limit,
                 def_inp="",
                 colour='brown',
                 mod=False):
        '''
        #self.parent = parent
        #self.lf_text = lf_text
        #self.mod = mod
        #self.colour = colour
        '''
        super().__init__(parent, lf_text, def_inp, colour, mod)  # added
        #       StringEntry.__init__(self,fr,lf_text,def_inp,colour,mod)
        self.l_limit = l_limit
        self.u_limit = u_limit

        self.out_var = IntVar()
        self.out_var.set(def_inp)

        self.construct(colour)
        self.limits()
        self.make_entry()

    def limits(self):
        """limit logic

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        self.ulab = Label(self,
                          text=str(self.u_limit) + "  upper limit",
                          style='brown.TLabel')  # self.lf1
        self.ulab.grid(row=0, column=1, padx=10)
        self.llab = Label(self,
                          text=str(self.l_limit) + "  lower limit",
                          style='brown.TLabel')  # self.lf1
        self.llab.grid(row=1, column=1, padx=10)

    def end_input(self, evt):
        """limit on integer, float

        Parameters
        ----------
        evt : str
            bind handle

        Returns
        -------
        None
        """
        self.ulab['style'] = 'brown.TLabel'
        self.llab['style'] = 'brown.TLabel'
        if self.l_limit < self.out_var.get() < self.u_limit:
            self.messlbl['text'] = "That's OK"
        elif self.l_limit >= self.out_var.get():
            self.messlbl['text'] = "Input below or at lower limit"
            self.llab['style'] = 'lowr.TLabel'
        else:
            self.messlbl['text'] = "Input above or at  upper limit"
            self.ulab['style'] = 'upr.TLabel'

    def is_okay(self, text, inp, ind):
        """ validation function

        Parameters
        ----------
        text : str
            text if allowed
        inp : str
            current input

        Returns
        -------
        boolean
        """
        if text in ("", "-"):
            return True
        try:
            int(text)
        except ValueError:
            return False
        return True
Example #23
0
class sideWindow(AppShell):
    #################################################################
    # sideWindow(AppShell)
    # This class will open a side window wich contains a scene graph and
    # a world setting page.
    #################################################################
    appversion      = '1.0'
    appname         = 'Navigation Window'
    frameWidth      = 325
    frameHeight     = 580
    frameIniPosX    = 0
    frameIniPosY    = 110
    padx            = 0
    pady            = 0

    lightEnable = 0
    ParticleEnable = 0
    basedriveEnable = 0
    collision = 0
    backface = 0
    texture = 1
    wireframe = 0

    enableBaseUseDrive = 0

    def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision,
                 backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw):
        self.worldColor = worldColor
        self.lightEnable = lightEnable
        self.ParticleEnable = ParticleEnable
        self.basedriveEnable = basedriveEnable
        self.collision = collision
        self.backface = backface
        self.texture = texture
        self.wireframe = wireframe
        self.grid = grid
        self.enableAutoCamera = enableAutoCamera
        self.widgetVis = widgetVis

        # Define the megawidget options.
        optiondefs = (
            ('title',       self.appname,       None),
            )
        self.defineoptions(kw, optiondefs)

        if parent == None:
            self.parent = Toplevel()
        else:
            self.parent = parent

        AppShell.__init__(self, self.parent)
        self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY))

        self.parent.resizable(False,False) ## Disable the ability to resize for this Window.

    def appInit(self):
        print('----SideWindow is Initialized!!')

    def createInterface(self):
        # The interior of the toplevel panel
        interior = self.interior()
        mainFrame = Frame(interior)
        ## Creat NoteBook
        self.notebookFrame = Pmw.NoteBook(mainFrame)
        self.notebookFrame.pack(fill=tkinter.BOTH,expand=1)
        sgePage = self.notebookFrame.add('Tree Graph')
        envPage = self.notebookFrame.add('World Setting')
        self.notebookFrame['raisecommand'] = self.updateInfo

        ## Tree Grapgh Page
        self.SGE = seSceneGraphExplorer.seSceneGraphExplorer(
            sgePage, nodePath = render,
            scrolledCanvas_hull_width = 270,
            scrolledCanvas_hull_height = 570)
        self.SGE.pack(fill = tkinter.BOTH, expand = 0)

        ## World Setting Page
        envPage = Frame(envPage)
        pageFrame = Frame(envPage)
        self.LightingVar = IntVar()
        self.LightingVar.set(self.lightEnable)
        self.LightingButton = Checkbutton(
            pageFrame,
            text = 'Enable Lighting',
            variable = self.LightingVar,
            command = self.toggleLights)
        self.LightingButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.CollisionVar = IntVar()
        self.CollisionVar.set(self.collision)
        self.CollisionButton = Checkbutton(
            pageFrame,
            text = 'Show Collision Object',
            variable = self.CollisionVar,
            command = self.showCollision)
        self.CollisionButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.ParticleVar = IntVar()
        self.ParticleVar.set(self.ParticleEnable)
        self.ParticleButton = Checkbutton(
            pageFrame,
            text = 'Show Particle Dummy',
            variable = self.ParticleVar,
            command = self.enableParticle)
        self.ParticleButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.baseUseDriveVar = IntVar()
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.baseUseDriveButton = Checkbutton(
            pageFrame,
            text = 'Enable base.usedrive',
            variable = self.baseUseDriveVar,
            command = self.enablebaseUseDrive)
        self.baseUseDriveButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backfaceVar = IntVar()
        self.backfaceVar.set(self.backface)
        self.backfaceButton = Checkbutton(
            pageFrame,
            text = 'Enable BackFace',
            variable = self.backfaceVar,
            command = self.toggleBackface)
        self.backfaceButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.textureVar = IntVar()
        self.textureVar.set(self.texture)
        self.textureButton = Checkbutton(
            pageFrame,
            text = 'Enable Texture',
            variable = self.textureVar,
            command = self.toggleTexture)
        self.textureButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.wireframeVar = IntVar()
        self.wireframeVar.set(self.wireframe)
        self.wireframeButton = Checkbutton(
            pageFrame,
            text = 'Enable Wireframe',
            variable = self.wireframeVar,
            command = self.toggleWireframe)
        self.wireframeButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.gridVar = IntVar()
        self.gridVar.set(self.grid)
        self.gridButton = Checkbutton(
            pageFrame,
            text = 'Enable Grid',
            variable = self.gridVar,
            command = self.toggleGrid)
        self.gridButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.widgetVisVar = IntVar()
        self.widgetVisVar.set(self.widgetVis)
        self.widgetVisButton = Checkbutton(
            pageFrame,
            text = 'Enable WidgetVisible',
            variable = self.widgetVisVar,
            command = self.togglewidgetVis)
        self.widgetVisButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.enableAutoCameraVar = IntVar()
        self.enableAutoCameraVar.set(self.enableAutoCamera)
        self.enableAutoCameraButton = Checkbutton(
            pageFrame,
            text = 'Enable Auto Camera Movement for Loading Objects',
            variable = self.enableAutoCameraVar,
            command = self.toggleAutoCamera)
        self.enableAutoCameraButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backgroundColor = ColorEntry(
            pageFrame, text = 'BG Color', value=self.worldColor)
        self.backgroundColor['command'] = self.setBackgroundColorVec
        self.backgroundColor['resetValue'] = [0,0,0,0]
        self.backgroundColor.pack(side=tkinter.LEFT, expand=False)
        self.bind(self.backgroundColor, 'Set background color')
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        envPage.pack(expand=False)

        ## Set all stuff done
        self.notebookFrame.setnaturalsize()
        mainFrame.pack(fill = 'both', expand = 1)


    def createMenuBar(self):
        # We don't need menu bar here.
        self.menuBar.destroy()

    def onDestroy(self, event):
        #################################################################
        # onDestroy(self, event)
        # This function will be called when user closed the side window.
        # Here we will send out a message with whole data set we will need
        # for the next time user open the side window.
        #################################################################
        messenger.send('SW_close',[self.worldColor,
                                   self.lightEnable,
                                   self.ParticleEnable,
                                   self.basedriveEnable,
                                   self.collision,
                                   self.backface,
                                   self.texture,
                                   self.wireframe,
                                   self.grid,
                                   self.widgetVis,
                                   self.enableAutoCamera])
        '''
        If you have open any thing, please rewrite here!
        '''
        pass

    ###############################
    def updateInfo(self, page = 'Tree Graph'):
        #################################################################
        # updateInfo(self, page = 'Tree Graph')
        # This function will be called when each time user change the main
        # page of the window.
        # What it dose is to call right function to restore the data for current selected page.
        #################################################################
        if page=='Tree Graph':
            self.updateTreeGraph()
        elif page == 'World Setting':
            self.updateWorldSetting()

    def updateTreeGraph(self):
        #################################################################
        # updateTreeGraph(self)
        # When scene graoh page has been opend, call sceneGraphExplorer to
        # updata the tree.
        #################################################################
        self.SGE.update()
        pass

    def updateWorldSetting(self):
        #################################################################
        # updateWorldSetting(self)
        # When world setting page has been selected, this function will
        # reset those check box in the page to reflect the current world setting.
        #################################################################
        self.LightingVar.set(self.lightEnable)

        self.CollisionVar.set(self.collision)
        self.ParticleVar.set(self.ParticleEnable)
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.backgroundColor.set(value = self.worldColor)
        pass

    def toggleLights(self):
        #################################################################
        # toggleLights(self)
        # send out a message to let sceneEditor know we need to toggle the light.
        # Then, sceneEditor will pass the message to dataHolder to disable/enable
        # the lights. (lightManager is inside the dataHolder)
        #################################################################
        self.lightEnable = (self.lightEnable+1)%2
        messenger.send('SW_lightToggle')
        pass

    def showCollision(self):
        #################################################################
        # showCollision(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of collision objects.
        #################################################################
        self.collision = (self.collision+1)%2
        messenger.send('SW_collisionToggle', [self.collision])
        pass

    def enableParticle(self):
        #################################################################
        # enableParticle(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of particle objects.
        #################################################################
        self.ParticleEnable = (self.ParticleEnable+1)%2
        messenger.send('SW_particleToggle', [self.ParticleEnable])
        pass

    def enablebaseUseDrive(self):
        #################################################################
        # enablebaseUseDrive(self)
        # This function will toggle the usage of base.useDrive.
        # Well, it may not usefull at all.
        #
        # We won't send out any message in this time to notice
        # the sceneEditor this event happend.
        # In the other hand, we will restore it back when
        # the side window has been closed.
        #
        #################################################################
        if self.enableBaseUseDrive==0:
            print('Enabled')
            base.useDrive()
            self.enableBaseUseDrive = 1
        else:
            print('disabled')
            #base.useTrackball()
            base.disableMouse()
            self.enableBaseUseDrive = 0
        self.basedriveEnable = (self.basedriveEnable+1)%2
        pass

    def toggleBackface(self):
        #################################################################
        # toggleBackface(self)
        # This function will toggle the back face setting. so it will
        # render the polygon with two sides.
        #################################################################
        base.toggleBackface()
        self.backface = (self.backface+1)%2
        return

    def toggleBackfaceFromMainW(self):
        #################################################################
        # toggleBackfaceFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the back face setting in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.backface = (self.backface+1)%2
        self.backfaceButton.toggle()
        return

    def toggleTexture(self):
        #################################################################
        # toggleTexture(self)
        # This function will toggle the txture using option for the whole scene.
        #################################################################
        base.toggleTexture()
        self.texture = (self.texture+1)%2
        return

    def toggleTextureFromMainW(self):
        #################################################################
        # toggleTextureFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the texture usage from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.texture = (self.texture+1)%2
        self.textureButton.toggle()
        return

    def toggleWireframe(self):
        #################################################################
        # toggleWireframe(self)
        # This function will toggle the wire frame mode.
        #################################################################
        base.toggleWireframe()
        self.wireframe = (self.wireframe+1)%2
        return

    def toggleWireframeFromMainW(self):
        #################################################################
        # toggleWireframeFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the wire frame mode in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.wireframe = (self.wireframe+1)%2
        self.wireframeButton.toggle()
        return

    def toggleGrid(self):
        #################################################################
        # toggleGrid(self)
        # This function will toggle the usage of the grid.
        #################################################################
        self.grid = (self.grid+1)%2
        if self.grid==1:
            SEditor.grid.enable()
        else:
            SEditor.grid.disable()

    def togglewidgetVis(self):
        #################################################################
        # togglewidgetVis(self)
        # This function will toggle the visibility of the widget of the grid.
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        SEditor.toggleWidgetVis()
        if SEditor.widget.fActive:
                messenger.send('shift-f')
        return

    def toggleWidgetVisFromMainW(self):
        #################################################################
        # toggleWidgetVisFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the visibility of widgets ('v') from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        self.widgetVisButton.toggle()
        return

    def setBackgroundColorVec(self,color):
        #################################################################
        # setBackgroundColorVec(self,color)
        # Call back function
        # This will be called from the colorEntry on the world setting page.
        # The "color" here is a list containing three integer data, R, G and B.
        #################################################################
        base.setBackgroundColor(color[0]/255.0,
                                color[1]/255.0,
                                color[2]/255.0)
        self.worldColor = [color[0],color[1],color[2],0]

    def toggleAutoCamera(self):
        #################################################################
        # toggleAutoCamera(self)
        # This function will toggle the usage of the auto-camera movement
        # when user loaded model or actor into the scene.
        #################################################################
        self.enableAutoCamera = (self.enableAutoCamera+1)%2
        SEditor.toggleAutoCamera()
        return

    def selectPage(self,page='Tree Graph'):
        #################################################################
        #################################################################
        self.notebookFrame.selectpage(page)
Example #24
0
class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def generate(self):
        n = int(self.menu_gen.get())
        seed = self.inp_seed.get()
        self.output = Generator.convert(seed, n)
        if len(self.output) > 0:
            self.generated = True
            self.butt_draw.config(    state= 'normal')
            self.chek_fullscrn.config(state= 'normal')
            self.clearOutput(self.output)

    def draw(self, n, step=False):
        p1, p2 = Draw.move(n)
        self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick)
        if step:
            self.curr_canvas.update_idletasks()

    def do(self, action, step, rainbow):
        if len(action) > 1:
            p = action[1]
        else:
            p = 1.0

        self.timebuff += step
        cmd = action[0].lower()
        if cmd == "draw":
            if rainbow:
                self.incColor()
                if self.incThickYN:
                    self.incThick(self.reverseThick, False)
            elif self.incThickYN:
                self.incThick(self.reverseThick, True)
            if self.timebuff > 1.0:
                truncate = int(self.timebuff)
                self.after(truncate, self.draw(float(p), True))
                self.timebuff -= truncate
            else:
                self.draw(float(p))
        elif cmd == "turn":
            Draw.turn(float(p))
        elif cmd == "skip":
            Draw.skip(float(p))
        elif cmd == "back":
            Draw.back(float(p))
        elif cmd == "color":
            if not rainbow:
                self.color = Color.getHexString(p)
        elif cmd == "thick":
            self.thick = int(p)
        else:
            print("Unknown command " + cmd)

    def drawAll(self, newWindow= True):
        if self.generated == True:
            self.butt_print.config(state= 'disabled')
            self.timebuff = 0.0
            self.color = Color.white()
            self.thick = 2
            l = float(self.slid_linesize.get())
            a = float(self.slid_angle.get())
            Draw.init(self.startingPoint, l, a)
            if self.fullScreen.get() == 1:
                if newWindow:
                    self.curr_canvas = dc.BigCanvas(self).canvas
                self.canvas.delete("all")
            else:
                self.curr_canvas = self.canvas
            self.curr_canvas.delete("all")
            self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get()))
            rainbow = self.rainbowCheck.get() == 1
            if rainbow or self.incThickYN:
                self.incStep = 1.0/float(self.getDrawCount(self.output))
                self.percent = 0.0
            for c in self.output:
                if c == '[':
                    Draw.push()
                elif c == ']':
                    Draw.pop()
                else:
                    for r in Rule.getDrawings():
                        if c == r[0]:
                            if len(r) > 2:
                                params = (r[1], r[2])
                            else:
                                params = (r[1],)
                            s = float(self.slid_timer.get())
                            self.do(params, s, rainbow)
                            break
            self.butt_print.config(state= 'normal')

    def incColor(self):
        self.color    = Color.getValueByPercent(self.percent)
        self.percent += self.incStep

    def incThick(self, reverse, incYN):
        maxthick = 5
        minthick = 1
        diff = maxthick - minthick
        if reverse:
            result = maxthick - int(diff * self.percent)
        else:
            result = minthick + int(diff * self.percent)
        self.thick = result
        if incYN:
            self.percent += self.incStep

    def getDrawCount(self, s):
        draw_commands = []
        for r in Rule.getDrawings():
            if r[1].lower() == "draw":
                draw_commands.append(r[0])
        draw_count = 0;
        for c in s:
            for d in draw_commands:
                if c == d:
                    draw_count += 1
                    break
        return draw_count

    def clearOutput(self, replacement=None):
        self.text_output.config(state= 'normal')
        self.text_output.delete(1.0, END)
        if replacement:
            self.text_output.insert(END, replacement)
        self.text_output.config(state= 'disabled')

    def formatRules(self, rules):
        ret = []
        for r in rules:
            entry = r[0] + " | " + r[1]
            if len(r) > 2:
                entry += " " + r[2]
            ret.append(entry)
        return ret

    def getRuleFromFormatted(self, s):
        if s:
            rule = s.split('|')
            rule[0] = rule[0].strip()
            rule[1] = rule[1].strip()
            prod = rule[1].split(" ")
            if len(prod) == 1:
                return (rule[0], prod[0])
            else:
                return (rule[0], prod[0], prod[1])

    def RefreshLists(self):
        self.list_prod.delete(0, END)
        self.list_draw.delete(0, END)

        l = self.formatRules(Rule.getProductions())
        for p in l:
            self.list_prod.insert(END, p)

        l = self.formatRules(Rule.getDrawings())
        for d in l:
            self.list_draw.insert(END, d)




    def AddProductionRule(self, edit=None):
        rule = dp.AddProductionRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeProd(edit[0])
            Rule.AddProduction(rule)
            self.RefreshLists()

    def AddDrawingRule(self, edit=None):
        rule = dd.AddDrawingRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeDraw(edit[0])
            Rule.AddDrawing(rule)
            self.RefreshLists()

    def EditProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_prod.get(idx))
            if rule:
                self.AddProductionRule(rule)

    def EditDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_draw.get(idx))
            if rule:
                self.AddDrawingRule(rule)

    def DeleteProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            Rule.removeProd(s[0])
            self.RefreshLists()

    def DeleteDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            Rule.removeDraw(s[0])
            self.RefreshLists()


    def packOutput(self):
        ret = ""
        ret += self.packAxiom()
        ret += self.packProdRules()
        ret += self.packDrawRules()
        return ret

    def packAxiom(self):
        return "@" + str(self.inp_seed.get()).strip()

    def packRules(self, rules):
        ret = "@"
        for r in rules:
            ret += "$" + str(r[0]) + "|" + str(r[1])
            if len(r) > 2:
                ret += ":" + str(r[2])
        return ret

    def packProdRules(self):
        return self.packRules(Rule.getProductions())

    def packDrawRules(self):
        return self.packRules(Rule.getDrawings())


    def parseProdRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                Rule.AddProduction((r[0], r[1]))

    def parseDrawRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                p = r[1].split(':')
                if len(p) == 1:
                    tup = (r[0], p[0])
                else:
                    tup = (r[0], p[0], p[1])
                Rule.AddDrawing(tup)


    def parseSaveFile(self, s):
        Rule.wipe()
        settings = s.split('@')
        self.inp_seed.set(str(settings[1]))
        self.parseProdRules(settings[2])
        self.parseDrawRules(settings[3])
        self.RefreshLists()


    def save(self):
        try:
            filename = filedialog.asksaveasfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'w')
                f.write(self.packOutput())
                f.close()
        except Exception as e:
            print("File IO error in save\n", e)

    def load(self):
        try:
            filename = filedialog.askopenfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'r')
                self.parseSaveFile(f.read())
                f.close()
                self.slid_linesize.set(1.0)
                self.slid_timer.set(0.0)
                self.menu_gen.set(1)
                self.clearOutput()

        except Exception as e:
            print("File IO error in load\n" + e)

    def help(self):
        help.HelpDialog(self)


    def saveImage(self):
        filename = filedialog.asksaveasfilename(**self.file_options['ps'])
        self.curr_canvas.postscript(file=filename, colormode='color')

    def click(self, event):
        self.startingPoint = (event.x, event.y)

    def clickAndRedraw(self, event):
        self.click(event)
        self.drawAll(False)

    def fileOptions(self):
        self.file_options = {}
        txt_options  = {}
        ps_options  = {}
        txt_options['defaultextension'] = '.txt'
        txt_options['filetypes'] = [('Plaintext', '.txt')]
        txt_options['initialdir'] = 'Patterns'
        ps_options['defaultextension'] = '.ps'
        ps_options['filetypes'] = [('Postscript Image', '.ps')]
        ps_options['initialdir'] = 'Images'
        self.file_options['txt'] = txt_options
        self.file_options['ps'] = ps_options

    def makeMenuBar(self):
        self.menubar = Menu(self);
        self.menubar.add_command(label="Save", command= self.save)
        self.menubar.add_command(label="Load", command= self.load)
        self.menubar.add_command(label="Help", command= self.help)
        root.config(menu= self.menubar)

    def makeInputFrame(self):
        self.inp_seed         = String()
        self.bgColor          = String()
        self.gen_value        = Int()
        self.rainbowCheck     = Int()
        self.fram_input       = Frame(self,              bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height)
        self.fram_seed        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_prod        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_draw        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_drawParams  = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_gen         = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_output      = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.menu_gen         = DropDown(self.fram_gen,  textvariable= self.gen_value, state= 'readonly')
        self.entr_seed        = Input(self.fram_seed,    textvariable= self.inp_seed)
        self.text_output      = Output(self.fram_output, width= 35, height= 10)
        self.scrl_output      = Scrollbar(self.fram_output)
        self.list_prod        = List(self.fram_prod,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.list_draw        = List(self.fram_draw,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.slid_linesize    = Slider(self.fram_drawParams,  from_= 0.1, to= 10.0,     orient= HORIZONTAL, resolution= 0.1, length= 180)
        self.slid_timer       = Slider(self.fram_drawParams,  from_= 0, to= 2,          orient= HORIZONTAL, resolution= 0.02, length= 180)
        self.slid_angle       = Slider(self.fram_drawParams,  from_= 0, to= 359,        orient= HORIZONTAL, length= 180)
        self.entr_bgcolor     = Input (self.fram_drawParams, textvariable= self.bgColor)
        self.butt_prodAdd     = Button(self.fram_prod,   text= "Add",    width=8, command= self.AddProductionRule)
        self.butt_prodEdit    = Button(self.fram_prod,   text= "Edit",   width=8, command= self.EditProductionRule)
        self.butt_prodDelete  = Button(self.fram_prod,   text= "Delete", width=8, command= self.DeleteProductionRule)
        self.butt_drawAdd     = Button(self.fram_draw,   text= "Add",    width=8, command= self.AddDrawingRule)
        self.butt_drawEdit    = Button(self.fram_draw,   text= "Edit",   width=8, command= self.EditDrawingRule)
        self.butt_drawDelete  = Button(self.fram_draw,   text= "Delete", width=8, command= self.DeleteDrawingRule)
        self.chek_incColor    = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck)
        Label(self.fram_seed,       text= "Axiom:", width=8).grid             (row=0, column=0)
        Label(self.fram_prod,       text= "Production\nRules:", width=8).grid (row=0, column=0)
        Label(self.fram_draw,       text= "Drawing\nRules:", width=8).grid    (row=0, column=0)
        Label(self.fram_drawParams, text= "Line Size:").grid                  (row=0, column=0)
        Label(self.fram_drawParams, text= "Delay (ms):").grid                 (row=1, column=0)
        Label(self.fram_drawParams, text= "Starting Angle:").grid             (row=2, column=0)
        Label(self.fram_drawParams, text= "Background Color:").grid           (row=3, column=0)
        Label(self.fram_output,     text= "Output:").grid                     (row=0, column=0)
        Label(self.fram_gen,        text= "Generations:").grid                (row=0, column=0)

        self.gen_value.set(1)
        self.menu_gen['values'] = tuple(range(1, 13))
        self.slid_linesize.set(1.0)
        self.bgColor.set( Color.default() )
        self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set)
        self.scrl_output.config(command=self.text_output.yview)

        self.fram_input.grid      (row=0, column=0)
        self.fram_seed.grid       (row=1, column=0, sticky= 'ew')
        self.fram_prod.grid       (row=2, column=0, sticky= 'ew')
        self.fram_draw.grid       (row=3, column=0, sticky= 'ew')
        self.fram_drawParams.grid (row=4, column=0, sticky= 'ew')
        self.fram_gen.grid        (row=5, column=0, sticky= 'ew')
        self.fram_output.grid     (row=6, column=0, sticky= 'ew')
        self.entr_seed.grid       (row=0, column=1, sticky= 'ew')
        self.list_prod.grid       (row=0, column=1, sticky= 'ew')
        self.butt_prodAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_prodEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew')
        self.list_draw.grid       (row=0, column=1)
        self.butt_drawAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_drawEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew')
        self.chek_incColor.grid   (row=0, column=2)
        self.slid_linesize.grid   (row=0, column=1, sticky= 'ew')
        self.slid_timer.grid      (row=1, column=1, sticky= 'ew')
        self.slid_angle.grid      (row=2, column=1, sticky= 'ew')
        self.entr_bgcolor.grid    (row=3, column=1, sticky= 'ew')
        self.menu_gen.grid        (row=0, column=1, sticky= 'ew')
        self.text_output.grid     (row=1, column=0)
        self.scrl_output.grid     (row=1, column=1, sticky= 'ns')

    def makeCanvasFrame(self):
        self.fram_canvas = Frame(self, bd=10, relief=self.style)
        self.canvas      = Canvas(self.fram_canvas, width= canvas_width, height= canvas_height)
        self.fram_canvas.grid(row=0, column=1, sticky='nesw')
        self.canvas.grid(sticky='nesw')
        self.canvas.bind("<Button-1>", self.click)
        self.curr_canvas = self.canvas

    def makeIgnitionFrame(self):
        self.fullScreen    = Int()
        self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height)
        self.butt_generate = Button(self.fram_ignition,   text= " -- GENERATE -- ", width=111, command= self.generate)
        self.butt_draw     = Button(self.fram_ignition,   text= " -- DRAW -- ",     width=100, command= self.drawAll, state= 'disabled')
        self.butt_print    = Button(self.fram_ignition,   text= "Save Image", command= self.saveImage, state= 'disabled')
        self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled')
        self.fram_ignition.grid(row=1, column=0, columnspan=2)
        self.butt_generate.grid(row=0, column=0, columnspan=2)
        self.butt_draw.grid(    row=1, column=0)
        self.butt_print.grid(   row=0, column=2, rowspan= 2, sticky='ns')
        self.chek_fullscrn.grid(row=1, column=1)

    def createWidgets(self):
        self.incThickYN    = False
        self.reverseThick  = False
        self.style         = RIDGE
        self.startingPoint = (20, 20)
        self.generated     = False
        self.fileOptions()
        self.makeMenuBar()
        self.makeInputFrame()
        self.makeCanvasFrame()
        self.makeIgnitionFrame()
Example #25
0
class Gui(Frame):
    def __init__(self, control, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.config(padx=2)
        self.queue = Queue()
        self.control = control
        self.disabledWhileRunning = []

        self.formulae = list(map(lambda t: StringVar(self, t), ["x/22.5+4", "50-x*50/180"]))
        self.executionTime = DoubleVar(self, "360")
        self.programSpeed = IntVar(self, "292")
        self.maxTravel = IntVar(self, "-200000")
        self.loadSettings()

        self.createWidgets()
        self.thread = None

    def compileFormulae(self):
        rv = []
        for f in self.formulae:
            body = "def formula5480750923(x):\n  return " + f.get()
            l = {}
            try:
                exec(body, {}, l)
            except:
                rv.append(None)
                continue
            compiled = l["formula5480750923"]
            compiled(0)
            rv.append(compiled)
        return rv

    def plotFormulae(self):
        try:
            compiled = self.compileFormulae()
        except:
            return
        for g in self.graphs:
            g.points = []
        self.canvas.x.end = self.executionTime.get()
        self.canvas.clear()
        for x in range(self.canvas.x.start, int(self.canvas.x.end)):
            point = []
            for c in range(len(compiled)):
                v = None
                if compiled[c]:
                    v = compiled[c](x)
                assert isinstance(v, float)
                point.append(v)
            self.__addPoint__(x, point)
        self.canvas.update()

    def __start__(self):
        self.canvas.x.end = self.executionTime.get()
        pumps = self.compileFormulae()
        self.setValues()
        self.control.mover.setSpeed(abs(int(self.programSpeed.get())))
        start_time = float(self.current_time.get())

        def calcPumpValues(time):
            values = list(map(lambda x: x(time), pumps))
            self.__addPoint__(time, values)
            self.current_time.set(time)
            return values

        def thFunc():
            try:
                for g in self.graphs:
                    g.points = []
                self.control.executeProgram(start_time, calcPumpValues)
            finally:
                self.invoke(self.__enableControls__)

        self.__disableControls__()
        self.canvas.clear()
        self.thread = Thread(target=thFunc, name="Control")
        self.thread.start()

    def __enableControls__(self):
        for e in self.disabledWhileRunning:
            e.config(state=NORMAL)

    def __disableControls__(self):
        for e in self.disabledWhileRunning:
            e.config(state="disabled")

    def __addPoint__(self, x, values):
        for v in values:
            assert isinstance(v, float)

        def c():
            for i in range(len(self.canvas.graphs)):
                self.canvas.graphs[i].addPoint(x, values[i])

        self.invoke(c)

    def invoke(self, callable):
        self.after_idle(callable)

    def __stop__(self):
        self.control.stop()

    def __quit__(self):
        def quitting():
            self.__stop__()
            if self.thread and self.thread.is_alive():
                print("Thread is active")
                return False
            self.quit()
            return True

        run_repeating(self, quitting)

    def __move__(self, steps):
        speed = int(self.speed.get())
        if speed < 0:
            speed *= -1
            self.speed.set(speed)
        self.control.mover.setSpeed(speed)
        self.control.mover.go(steps)

    def __up__(self):
        steps = int(self.steps.get())
        self.__move__(steps)

    def __down__(self):
        steps = int(self.steps.get())
        self.__move__(-steps)

    def showValues(self):
        self.maxTravel.set(self.control.mover.maxTravel)
        self.executionTime.set(self.control.fullTime)
        self.programSpeed.set(self.control.mover.getSpeed())

    def setValues(self):
        self.control.mover.maxTravel = int(self.maxTravel.get())
        self.control.fullTime = float(self.executionTime.get())
        self.control.mover.setSpeed(abs(int(self.programSpeed.get())))

    def loadSettings(self):
        config = Config()
        try:
            config.read()
        except KeyError:
            pass
        config.configureControl(self.control)
        for i in range(len(self.formulae)):
            self.formulae[i].set(config.formulae[i])
        self.showValues()

    def saveSettings(self):
        self.setValues()
        config = Config()
        config.getFromControl(self.control)
        for i in range(len(self.formulae)):
            config.formulae[i] = self.formulae[i].get()
        config.write()

    def createWidgets(self):
        panel = Frame(self, name="mainMenu")
        panel.grid(sticky=W)
        Button(panel, name="quit", text="Выход", command=self.__quit__).grid(row=0, column=0)
        Button(panel, name="reconnect", text="Пересоединение", command=self.control.reconnect).grid(row=0, column=1)
        b = Button(panel, text="Загрузить", command=self.loadSettings)
        b.grid(row=0, column=2)
        self.disabledWhileRunning.append(b)
        b = Button(panel, text="Сохранить", command=self.saveSettings)
        b.grid(row=0, column=3)
        self.disabledWhileRunning.append(b)
        panel = LabelFrame(self, text="Прямое управление стаканом", name="motor")
        panel.grid(sticky=W)
        b = Button(panel, text="Вверх", command=self.__up__, name="up")
        b.grid(row=0, column=0)
        self.disabledWhileRunning.append(b)
        b = Button(panel, text="Вниз", command=self.__down__, name="down")
        b.grid(row=1, column=0)
        self.disabledWhileRunning.append(b)
        Label(panel, text="Шаг:").grid(sticky=E, row=0, column=1)
        self.steps = IntVar(self, "10000")
        Entry(panel, textvariable=self.steps, width=6).grid(sticky=W, row=0, column=2)
        Label(panel, text="Скорость:").grid(sticky=E, row=1, column=1)
        self.speed = IntVar(self, "2000")
        Entry(panel, textvariable=self.speed, width=6).grid(sticky=W, row=1, column=2)
        self.position = IntVar(self, "1000")

        def readPosition():
            try:
                self.position.set(self.control.mover.getPosition())
            except (ConnectionResetError, Timeout):
                pass

        run_repeating(self, readPosition, 10000)
        b = Button(panel, text="Прочитать положение", command=readPosition)
        b.grid(row=0, column=3, columnspan=2)
        self.disabledWhileRunning.append(b)
        Label(panel, text="Положение:").grid(sticky=E, row=1, column=3)
        Entry(panel, textvariable=self.position, width=8, state="disabled").grid(sticky=W, row=1, column=4)

        panel = LabelFrame(self, text="Программа", name="program")
        program = panel
        panel.grid(sticky=W + E)
        panel.columnconfigure(1, weight=1)
        row = 0
        for f in self.formulae:
            columns, rows = self.grid_size()
            Label(panel, text="Насос %d:" % (row + 1)).grid(row=row, column=0, sticky=E)
            e = Entry(panel, textvariable=f)
            e.grid(sticky=E + W, row=row, column=1)
            self.disabledWhileRunning.append(e)
            f.trace("w", lambda *x: self.after_idle(self.plotFormulae))
            row += 1
        panel = Frame(program, name="mover")
        panel.grid(columnspan=2, sticky=W)
        Label(panel, text="Максимальное смещение:").grid(sticky=E)
        Entry(panel, textvariable=self.maxTravel).grid(sticky=W, row=0, column=1)
        Label(panel, text="Скорость:").grid(sticky=E)
        Entry(panel, textvariable=self.programSpeed).grid(sticky=W, row=1, column=1)
        Label(panel, text="Время выполнения (в секундах):").grid(sticky=E)
        e = Entry(panel, textvariable=self.executionTime)
        e.grid(sticky=W, row=2, column=1)
        self.current_time = DoubleVar(self, "0")
        Label(panel, text="Текущее время:").grid(sticky=E)
        e = Entry(panel, textvariable=self.current_time)
        e.grid(sticky=W, row=3, column=1)
        self.disabledWhileRunning.append(e)
        self.executionTime.trace("w", lambda *x: self.plotFormulae())

        panel = Frame(program, name="bottom")
        panel.grid(columnspan=2, sticky=W)
        row = 0
        startButton = Button(panel, name="start", text="Старт", command=self.__start__)
        startButton.grid(row=row, column=0)
        self.disabledWhileRunning.append(startButton)
        Button(panel, text="Стоп", command=self.__stop__).grid(row=row, column=1)

        self.canvas = GraphCanvas(self)
        self.graphs = (Graph(self.canvas), Graph(self.canvas))

        self.canvas.x.end = 100
        self.canvas.y.end = 24
        self.plotFormulae()
        self.canvas.grid(sticky=E + W + S + N)
        columns, rows = self.grid_size()
        self.columnconfigure(columns - 1, weight=1)
        self.rowconfigure(rows - 1, weight=1)
Example #26
0
class OptimizeGroup(Group):
    def __init__(self, *args, **kwargs):
        self._app = kwargs.pop('wavesyn_root')   
        self.__topwin = kwargs.pop('topwin')

        super().__init__(*args, **kwargs)
                
        parameter_frame    = Frame(self)
        parameter_frame.pack(side='left', expand='yes', fill='y')
        self.__num = LabeledEntry(parameter_frame)
        set_attributes(self.__num,
            label_text   = 'num',
            entry_text   = '1',
            label_width  = 5,
            entry_width  = 8,
            checker_function   = self._app.gui.value_checker.check_int
        )
        self.__num.entry.bind('<Return>', lambda event: self._on_solve_click())
        self.__num.pack(side='top')

        self.__pci  = LabeledEntry(parameter_frame)
        set_attributes(self.__pci,
            label_text   = 'PCI',
            entry_text   = '100',
            label_width  = 5,
            entry_width  = 8,
            checker_function = self._app.gui.value_checker.check_int
        )
        self.__pci.pack(side='top')
        
        self.__parallel_checker_variable    = IntVar()
        self.__parallel_checker  = Checkbutton(parameter_frame, text="Parallel", variable=self.__parallel_checker_variable, command=self._on_parallel_checker_click)
        self.__parallel_checker.pack()
        
        progfrm = Frame(self)
        progfrm.pack(side='left', expand='yes', fill='y')

        self.__genbtn = Button(progfrm, text='Generate', command=self._on_solve_click)
        self.__genbtn.pack(side='top')  
        Button(progfrm, text='Stop', command=self._on_stop_button_click).pack(side='top')         
        
        self.__progressbar_variable = IntVar()
        self.__finishedwav = IntVar()        
        self.__progressbar = Progressbar(progfrm, orient='horizontal', variable=self.__progressbar_variable, maximum=100)
        self.__progressbar.pack(side='left')
        self.__progressbar.config(length=55)   
        self.__finishedwavbar = Progressbar(progfrm, orient='horizontal', variable=self.__finishedwav)
        self.__finishedwavbar.pack(side='left')
        self.__finishedwavbar.config(length=30)  

        self.name = 'Generate'

        self.getparams = None
        self.__stopflag = False

        
    def _on_solve_click(self):
        params = self.__topwin.parameter_group.get_parameters()
        repeat_times = self.__num.get_int()   
        
        if self.__parallel_checker_variable.get():
            run = self.__topwin.current_algorithm.process_run
        else:
            run = self.__topwin.current_algorithm.thread_run
        with code_printer():
            run(on_finished=['store', 'plot'], progress_indicator='progress_dialog', repeat_times=repeat_times, **params)


    def _on_stop_button_click(self):
        self.__stopflag = True
        
        
    def _on_parallel_checker_click(self):
        topwin = self.__topwin
        if topwin.current_algorithm.need_cuda:
            self.__parallel_checker_variable.set(0)
            topwin.root_node.gui.dialogs.report(f'''{topwin.node_path}:
Current algorithm "{topwin.current_algorithm.meta.name}" need CUDA worker, which does not support multi-cpu parallel.
            ''')
            
            
    def _cancel_parallel(self):
        self.__parallel_checker_variable.set(0)
class IpdSubOptionsForm(VerticalScrolledFrame):
        
    # Initialize the GUI
    def __init__(self, root):
        
        
        VerticalScrolledFrame.__init__(self, root)
        #Frame.__init__(self, root)
        #super(500, 500)
        root.title("Choose IPD-IMGT/HLA Submission Options")
        self.parent = root

        #button_opt = {'fill': Tkconstants.BOTH, 'padx': 35, 'pady': 5}
                        
        # This window should not be resizeable. I guess.
        self.parent.resizable(width=False, height=False)
        #self.parent.resizable(width=True, height=True)
        
        # To define the exit behavior.  Save and exit.
        self.parent.protocol('WM_DELETE_WINDOW', self.saveOptions)
        
        # Define the return behavior.  Same as "close window" etc
        root.bind('<Return>', self.returnFunction)
        
        self.instructionsFrame = Frame(self.interior)  
        self.instructionText = StringVar()       
        self.instructionText.set('\nThese options are required for an IPD allele submission.\n'
            + 'Login Credentials will not be stored, but they will be sent to IPD via\n'
            + 'secure https connection.\n')        
        Label(self.instructionsFrame, width=85, height=6, textvariable=self.instructionText).pack()
        self.instructionsFrame.pack()
        
        #Standard Inputs widths for the form elements
        formInputWidth = 35
        labelInputWidth = 35
                
        # Make a frame to contain the input variables
        # self.interior is defined in the ScrolledWindow class
        self.submissionDetailsInputFrame = Frame(self.interior)

        self.usernameInstrText = StringVar()
        self.usernameInstrText.set('IPD Username:'******'IPD Password:'******'Cell/Sample ID:')
        self.sampleIDinstrLabel = Label(self.submissionDetailsInputFrame, width=labelInputWidth, height=1, textvariable=self.sampleIDInstrText).grid(row=2, column=0)
        self.inputSampleID = StringVar()
        self.inputSampleIDEntry = Entry(self.submissionDetailsInputFrame, width=formInputWidth, textvariable=self.inputSampleID).grid(row=2, column=1)

        self.geneInstrStringVar = StringVar()
        self.geneInstrStringVar.set('Gene:')
        self.geneInstrLabel = Label(self.submissionDetailsInputFrame, width=labelInputWidth, height=1, textvariable=self.geneInstrStringVar).grid(row=3, column=0)
        self.inputGene = StringVar()        
        self.inputGeneEntry = Entry(self.submissionDetailsInputFrame, width=formInputWidth, textvariable=self.inputGene).grid(row=3, column=1)

        self.chooseClassIntVar = IntVar()
        self.chooseClassIntVar.set(1)
        Radiobutton(self.submissionDetailsInputFrame, text="HLA Class I ", variable=self.chooseClassIntVar, value=1).grid(row=4, column=0)
        Radiobutton(self.submissionDetailsInputFrame, text="HLA Class II", variable=self.chooseClassIntVar, value=2).grid(row=4, column=1)

        self.alleleInstrText = StringVar()
        self.alleleInstrText.set('Allele Local Name:')
        self.alleleInstrLabel = Label(self.submissionDetailsInputFrame, width=labelInputWidth, height=1, textvariable=self.alleleInstrText).grid(row=5, column=0)
        self.inputAllele = StringVar() 
        self.inputAlleleEntry = Entry(self.submissionDetailsInputFrame, width=formInputWidth, textvariable=self.inputAllele).grid(row=5, column=1)
        
        
        
        
        # New form stuff
        # Gotta add this to the load/save config nonsense below.
        
        
        # TODO: Can I just load an ENA accession? I think that is possible.  Easier than filling it in here
        
        
        # TODO: When ENA Sequence Accession # Is provided, I can probably lookup an annotated sequence.
        # Should I put a button next to this field 
        # Button: "Lookup This ENA Sequence Accession #"
        # If it is found, then i already know the sequence with exon boundaries.
        
        
        # TODO: Do I need to specify if it is ENA / Genbank / The other one?  Probably not.
        # I can require an ENA code and disregard Genbank.
        # Radio Buttons?  
        # ENA / Genbank Accession #
        # No, this tool is for ENA submission. But this is a question for James Robinson.
        # Should i choose between which intermediate databse they use?
        self.enaAccInstrText = StringVar()
        self.enaAccInstrText.set('ENA Sequence Accession #:')
        self.enaAccInstrLabel = Label(self.submissionDetailsInputFrame, width=labelInputWidth, height=1, textvariable=self.enaAccInstrText).grid(row=6, column=0)
        self.inputEnaAcc = StringVar()
        self.inputEnaAccEntry = Entry(self.submissionDetailsInputFrame, width=formInputWidth, textvariable=self.inputEnaAcc).grid(row=6, column=1)

        
        # Release Date
        self.releaseDateInstrText = StringVar()
        self.releaseDateInstrText.set('IPD Release Date:')
        self.releaseDateInstrLabel = Label(self.submissionDetailsInputFrame, width=labelInputWidth, height=1, textvariable=self.releaseDateInstrText).grid(row=7, column=0)
        self.inputReleaseDate = StringVar() 
        self.inputReleaseDateEntry = Entry(self.submissionDetailsInputFrame, width=formInputWidth, textvariable=self.inputReleaseDate).grid(row=7, column=1)
        
        # Reference Details
        # Is this allele in a published paper or not?
        # 0=unpublished, 1=published
        self.publishedReferenceIntVar = IntVar()
        self.publishedReferenceIntVar.set(0)
        
        self.submissionDetailsInputFrame.pack()
 
        
        self.unpublishedReferenceFrame = Frame(self.interior)   
        
        self.referenceInstrText = StringVar()
        self.referenceInstrText.set('\nPlease provide some information about a\npublished paper relevant to this sequence.\n')
        self.referenceInstrLabel = Label(self.unpublishedReferenceFrame, width=70, height=4, textvariable=self.referenceInstrText).pack()#.grid(row=2, column=0)
             
        Radiobutton(self.unpublishedReferenceFrame, text="No Published Reference.", variable=self.publishedReferenceIntVar, value=0).pack()
        self.unpublishedReferenceFrame.pack()

        self.publishedReferenceFrame = Frame(self.interior)
        
        # Radio Button: Published
        Radiobutton(self.unpublishedReferenceFrame, text="Use This Reference:", variable=self.publishedReferenceIntVar, value=1).pack()
        
        # Reference Title
        self.referenceTitleInstrText = StringVar()
        self.referenceTitleInstrText.set('Reference Title:')
        self.referenceTitleInstrLabel = Label(self.publishedReferenceFrame, width=labelInputWidth, height=1, textvariable=self.referenceTitleInstrText).grid(row=1, column=0)
        self.inputReferenceTitle = StringVar() 
        self.inputReferenceTitleEntry = Entry(self.publishedReferenceFrame, width=formInputWidth, textvariable=self.inputReferenceTitle).grid(row=1, column=1)
        
        # Authors
        self.referenceAuthorsInstrText = StringVar()
        self.referenceAuthorsInstrText.set('Reference Authors:')
        self.referenceAuthorsInstrLabel = Label(self.publishedReferenceFrame, width=labelInputWidth, height=1, textvariable=self.referenceAuthorsInstrText).grid(row=2, column=0)
        self.inputReferenceAuthors = StringVar() 
        self.inputReferenceAuthorsEntry = Entry(self.publishedReferenceFrame, width=formInputWidth, textvariable=self.inputReferenceAuthors).grid(row=2, column=1)
        
        # Journal
        self.referenceJournalInstrText = StringVar()
        self.referenceJournalInstrText.set('Reference Journal:')
        self.referenceJournalInstrLabel = Label(self.publishedReferenceFrame, width=labelInputWidth, height=1, textvariable=self.referenceJournalInstrText).grid(row=3, column=0)
        self.inputReferenceJournal = StringVar() 
        self.inputReferenceJournalEntry = Entry(self.publishedReferenceFrame, width=formInputWidth, textvariable=self.inputReferenceJournal).grid(row=3, column=1)

        self.publishedReferenceFrame.pack()
               
        # Make a frame to contain the input variables.
        # I had to make 2 of them to organize my gui, maybe I can name this better.
        self.submissionDetailsInputFrame2 = Frame(self.interior)
            
        # /alignment -> defined by IPD sequence alignment service
        # In this case, it is the closest known allele.
        self.closestAlleleInstrText = StringVar()
        self.closestAlleleInstrText.set('Closest Known HLA Allele:')
        self.closestAlleleInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.closestAlleleInstrText).grid(row=1, column=0)
        self.inputClosestAllele = StringVar() 
        self.inputClosestAlleleEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputClosestAllele).grid(row=1, column=1)

        # Written Description
        # Looks like this is a description of how the sequence differes from closest knnown allele
        self.closestAlleleWrittenDescriptionInstrText = StringVar()
        self.closestAlleleWrittenDescriptionInstrText.set('Differences from Closest Allele:')
        self.closestAlleleWrittenDescriptionInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.closestAlleleWrittenDescriptionInstrText).grid(row=2, column=0)
        self.inputClosestAlleleWrittenDescription = StringVar() 
        self.inputClosestAlleleWrittenDescriptionEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputClosestAlleleWrittenDescription).grid(row=2, column=1)

        
        # DONOR INFORMATION
        
        # Cell ID (cellnum)
        # Wait, is this the same as the sample ID? Should I move the sample ID field down here?
        # No. I am disregarding this sample ID.
        
        # Ethnic Origin - Text
        self.ethnicOriginInstrText = StringVar()
        self.ethnicOriginInstrText.set('Ethnic Origin:')
        self.ethnicOriginInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.ethnicOriginInstrText).grid(row=3, column=0)
        self.inputEthnicOrigin = StringVar() 
        self.inputEthnicOriginEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputEthnicOrigin).grid(row=3, column=1)

        # Sex - Text
        self.sexInstrText = StringVar()
        self.sexInstrText.set('Sex:')
        self.sexInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.sexInstrText).grid(row=4, column=0)
        self.inputSex = StringVar() 
        self.inputSexEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputSex).grid(row=4, column=1)

        # TODO Make a boolean
        # Consanguineous (T/F)
        self.consanguineousInstrText = StringVar()
        self.consanguineousInstrText.set('Sample is Consanguineous:')
        self.consanguineousInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.consanguineousInstrText).grid(row=5, column=0)
        self.inputConsanguineous = StringVar() 
        self.inputConsanguineousEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputConsanguineous).grid(row=5, column=1)
        
        # TODO Make a boolean
        # Homozygous (T/F)
        # TODO: Accepted values are 'Yes', 'No', 'Unknown'
        # Make dropdown for this, or radio buttons.
        self.homozygousInstrText = StringVar()
        self.homozygousInstrText.set('Sample is Homozygous:')
        self.homozygousInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.homozygousInstrText).grid(row=6, column=0)
        self.inputHomozygous = StringVar() 
        self.inputHomozygousEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputHomozygous).grid(row=6, column=1)

        # Lab of Origin (text)
        self.labOriginInstrText = StringVar()
        self.labOriginInstrText.set('Lab of Origin:')
        self.labOriginInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.labOriginInstrText).grid(row=7, column=0)
        self.inputLabOrigin = StringVar() 
        self.inputLabOriginEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputLabOrigin).grid(row=7, column=1)
        
        # Lab Contact
        self.labContactInstrText = StringVar()
        self.labContactInstrText.set('Lab Contact:')
        self.labContactInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.labContactInstrText).grid(row=8, column=0)
        self.inputLabContact = StringVar() 
        self.inputLabContactEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputLabContact).grid(row=8, column=1)
              
        # Cell Availability
        # Material Available (T/F)
        self.materialAvailableInstrText = StringVar()
        self.materialAvailableInstrText.set('Material Availability:')
        self.materialAvailableInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.materialAvailableInstrText).grid(row=9, column=0)
        self.inputMaterialAvailable = StringVar() 
        self.inputMaterialAvailableEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputMaterialAvailable).grid(row=9, column=1)
        
        # Cell Bank (Text)
        self.cellBankInstrText = StringVar()
        self.cellBankInstrText.set('Cell Bank:')
        self.cellBankInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.cellBankInstrText).grid(row=10, column=0)
        self.inputCellBank = StringVar() 
        self.inputCellBankEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputCellBank).grid(row=10, column=1)
        
        # Cell Workshop Details
        # I think Cell Workshop Details is just a header. there isn't new information here, just a header. 
        # TODO: Compare this with the IPD Submission website, im not missing something?
        
        self.submissionDetailsInputFrame2.pack()
        
        # numbering these input frames are not informative. Oh well. This frame has HLA Allele calls on it.
        self.submissionDetailsInputFrame3 = Frame(self.interior)

         
        # Alternative HLA DNA Typing
        # Dropdown Box with another Entry Field?
        # I need:
        # Label
        self.sourceHLAInstrText = StringVar()
        self.sourceHLAInstrText.set('Source HLA Types (Sequenced):')
        self.sourceHLAInstrLabel = Label(self.submissionDetailsInputFrame3, width=labelInputWidth, height=1, textvariable=self.sourceHLAInstrText).grid(row=1, column=0)
        # Combo Box, with source_hla dictionary keys. Sorted.
        # Text input, with the gene specified.
        # "Clear" button. clear out all allele calls.
        # Configuration should be assigned whenever text changes.
        # I Think i need a new panel for this. Yeah.
        
        
        # Source Serology Typing
        # Maybe the same as DNA typing?
        # Ignore for now.
        
        # Sequencing Methods
            
        # Primers
        # This is probably a Dropdown with Entry field also.
        
        # TODO: Comments.  Where does this stuff go?  This is details about the lab of origin. I haven't tried specifying this one yet, ask James how to do it.
        # Comments
        
        
        
        
        self.submissionDetailsInputFrame3.pack()


        

        # Make a frame for the save options button.
        self.saveOptionsFrame = Frame(self.interior)
        Button(self.saveOptionsFrame, text='Save Options', command=self.saveOptions).grid(row=0, column=0)
        self.saveOptionsFrame.pack()
        
        self.loadOptions()
        
    # I needed a function for the return keypress to latch onto.
    # It is just a wrapper for the saveOptions method.
    def returnFunction(self, event):
        self.saveOptions()

    # submissionOptions is a dictionary, passed by the parent.
    def loadOptions(self):
        if getConfigurationValue('ipd_username') is not None:
            self.inputUsername.set(getConfigurationValue('ipd_username'))
            
        if getConfigurationValue('ipd_password') is not None:
            self.inputPassword.set(getConfigurationValue('ipd_password'))
            
        if getConfigurationValue('sample_id') is not None:
            self.inputSampleID.set(getConfigurationValue('sample_id'))
            
        if getConfigurationValue('gene') is not None:
            self.inputGene.set(getConfigurationValue('gene'))
            
        if getConfigurationValue('class') is not None:
            if (str(getConfigurationValue('class')) == '1'):
                self.chooseClassIntVar.set(1)
            elif (str(getConfigurationValue('class')) == '2'):
                self.chooseClassIntVar.set(2)
            else:
                raise Exception('Error loading IPD submission options. Invalid class:' + str(getConfigurationValue('class')))
    
        if getConfigurationValue('allele_name') is not None:
            self.inputAllele.set(getConfigurationValue('allele_name'))
            
        if getConfigurationValue('ena_sequence_accession') is not None:
            self.inputEnaAcc.set(getConfigurationValue('ena_sequence_accession'))
        
        if getConfigurationValue('ena_release_date') is not None:
            self.inputReleaseDate.set(getConfigurationValue('ena_release_date'))
   
        # 0=unpublished, 1=published
        #print('1Setting is_published value to:' + getConfigurationValue('is_published'))
        if (getConfigurationValue('is_published') is None or getConfigurationValue('is_published') == 'None'):
            self.publishedReferenceIntVar.set(0)
            #print('2Setting is_published value to:' + getConfigurationValue('is_published'))

        else:
            self.publishedReferenceIntVar.set(getConfigurationValue('is_published'))


        if getConfigurationValue('reference_title') is not None:
            self.inputReferenceTitle.set(getConfigurationValue('reference_title'))            
        if getConfigurationValue('reference_authors') is not None:
            self.inputReferenceAuthors.set(getConfigurationValue('reference_authors'))            
        if getConfigurationValue('reference_journal') is not None:
            self.inputReferenceJournal.set(getConfigurationValue('reference_journal'))
     
        if getConfigurationValue('reference_journal') is not None:
            self.inputReferenceJournal.set(getConfigurationValue('reference_journal'))

        if getConfigurationValue('closest_known_allele') is not None:
            self.inputClosestAllele.set(getConfigurationValue('closest_known_allele'))
        if getConfigurationValue('closest_allele_written_description') is not None:
            self.inputClosestAlleleWrittenDescription.set(getConfigurationValue('closest_allele_written_description'))
          
        if getConfigurationValue('ethnic_origin') is not None:
            self.inputEthnicOrigin.set(getConfigurationValue('ethnic_origin'))          
        if getConfigurationValue('sex') is not None:
            self.inputSex.set(getConfigurationValue('sex'))              
        if getConfigurationValue('consanguineous') is not None:
            self.inputConsanguineous.set(getConfigurationValue('consanguineous'))          
        if getConfigurationValue('homozygous') is not None:
            self.inputHomozygous.set(getConfigurationValue('homozygous'))  

        if getConfigurationValue('lab_of_origin') is not None:
            self.inputLabOrigin.set(getConfigurationValue('lab_of_origin'))          
        if getConfigurationValue('lab_contact') is not None:
            self.inputLabContact.set(getConfigurationValue('lab_contact')) 
            
        if getConfigurationValue('material_availability') is not None:
            self.inputMaterialAvailable.set(getConfigurationValue('material_availability'))          
        if getConfigurationValue('cell_bank') is not None:
            self.inputCellBank.set(getConfigurationValue('cell_bank')) 
            
        # TODO: 
        # Load options for HLA allele calls.
        # Clear the combo-box, and fill it with the keys of my hla allele call dictionary.  
            
    def saveOptions(self):
        # Close the window
        # TODO: If i force the user to fill in all the options, this form is really obnoxious.
        # Instead they should be allowed to close it and I will still warn them.
        # I can re-think this plan if people are trying to submit bad data.
        
        #if (self.checkOptions()):
        
        #Don't force user to fill in all the options:
        self.checkOptions()
        if(True):
            
            
            logging.info ('Saving Options....')
            
            assignConfigurationValue('ipd_username', self.inputUsername.get())
            # I store this password so I can use it in the submission
            # I don't ever want to save the password. Make sure it isn't being saved in the config, in AlleleSubCommon.py
            assignConfigurationValue('ipd_password', self.inputPassword.get())
            assignConfigurationValue('sample_id', self.inputSampleID.get())
            assignConfigurationValue('gene', self.inputGene.get())
            assignConfigurationValue('class', str(self.chooseClassIntVar.get()))             
            assignConfigurationValue('allele_name', self.inputAllele.get())

            assignConfigurationValue('ena_sequence_accession', self.inputEnaAcc.get())
            assignConfigurationValue('ena_release_date', self.inputReleaseDate.get())
            
            assignConfigurationValue('is_published', str(self.publishedReferenceIntVar.get()))
            #print('Saving is_published configuration as :' + str(self.publishedReferenceIntVar.get()))
            
            assignConfigurationValue('reference_title',self.inputReferenceTitle.get())    
            assignConfigurationValue('reference_authors',self.inputReferenceAuthors.get())    
            assignConfigurationValue('reference_journal',self.inputReferenceJournal.get())            
           
            assignConfigurationValue('closest_known_allele', self.inputClosestAllele.get())
            assignConfigurationValue('closest_allele_written_description', self.inputClosestAlleleWrittenDescription.get())
      
            assignConfigurationValue('ethnic_origin', self.inputEthnicOrigin.get())
            assignConfigurationValue('sex', self.inputSex.get())
            
            # TODO: Accepted values are 'Yes', 'No', 'Unknown'
            # Make dropdown for these
            assignConfigurationValue('consanguineous', self.inputConsanguineous.get())
            assignConfigurationValue('homozygous', self.inputHomozygous.get())
            
            assignConfigurationValue('lab_of_origin', self.inputLabOrigin.get())
            assignConfigurationValue('lab_contact', self.inputLabContact.get())
            
            assignConfigurationValue('material_availability', self.inputMaterialAvailable.get())
            assignConfigurationValue('cell_bank', self.inputCellBank.get())
   
            # I have saved hla calls in a dictionary. They should have been saved individually.
   
            self.parent.destroy() 
            
            
        else:
            #logging.info('Not ready to save, you are missing options.')
            pass
        
    def checkOptions(self):
        # TODO this method
        logging.info ('Checking options.')

        # Don't check the IPD Username
        # Don't check the IPD Password
        
        if (not self.inputSampleID.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing a Sample ID. Please try again.')
            return False        
        if (not self.inputGene.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing a Gene. Please try again.')
            return False
        if (not self.inputAllele.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an Allele Name. Please try again.')
            return False
        
        if (not self.inputEnaAcc.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an ENA Accession Number. Please try again.')
            return False
        if (not self.inputReleaseDate.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an IPD Submission Release Date. Please try again.')
            return False

        # This is NOne if nothing is selected.
        if (self.publishedReferenceIntVar.get() == 0):
        # unpublished, nothing to check
            pass
        else:
            if ((not self.inputReferenceTitle.get())
                or (not self.inputReferenceAuthors.get())
                or (not self.inputReferenceJournal.get())
                ):
                messagebox.showwarning('Missing Form Value',
                    'You are must supply information about the published Reference. Please try again.')
                return False

        if (not self.inputClosestAllele.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing the closest known reference allele to this sequence. Please provide this information.')
            return False
        if (not self.inputEthnicOrigin.get()):
            messagebox.showwarning('Missing Form Value',
                'Please provide a description of an ethnic origin for this sample.')
            return False
        if (not self.inputSex.get()):
            messagebox.showwarning('Missing Form Value',
                'Please identify the sex for this sample.')
            return False
        
        # TODO: Accepted values are 'Yes', 'No', 'Unknown' I think
        if (not self.inputConsanguineous.get()):
            messagebox.showwarning('Missing Form Value',
                'Please indicate if the sample is consanguineous or not.')
            return False
        if (not self.inputHomozygous.get()):
            messagebox.showwarning('Missing Form Value',
                'Please indicate if the sample is homozygous or not.')
            return False
        
        
        if (not self.inputLabOrigin.get()):
            messagebox.showwarning('Missing Form Value',
                'Please provide the name of the submitting laboratory.')
            return False
        if (not self.inputLabContact.get()):
            messagebox.showwarning('Missing Form Value',
                'Please provide the name of the laboratory contact.')
            return False

        if (not self.inputMaterialAvailable.get()):
            messagebox.showwarning('Missing Form Value',
                'Please indicate if the cell material is available.')
            return False
        if (not self.inputCellBank.get()):
            messagebox.showwarning('Missing Form Value',
                'Please provide the name of the cell bank where the sample can be found.')
            return False

        # TODO Validate the HLA ALlele calls. I won't do IMGT/HLA validation, I will leave that validation up to IMGT/HLA
        # Validate A, B, DRB1. The rest, I don't care.

        # All options look good, right?
        return True
    
    
    def closeWindow(self):
        #writeConfigurationFile()

        self.parent.destroy()        
Example #28
0
class SaleTerminal:

    def __init__(self, master):
        self.master = master
        master.title("Point of Sale")
# Initializing the counter so that the user can see their sum for their items purchased
        self.total = 0
        self.entered_number = 0
# Creating the box and total area for an active sum update
        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")
# Testing the method of inputting how much your item should cost, but will take this out if not working by PRoject Demo
        vcmd = master.register(self.validate)
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
# Here I create the vast majority of the buttons, I set them to look for their respective functions "Bx" and
# execute when the left click on the mouse is performed on the specific button
        self.B1 = Button(master, text="Coca-Cola", command=lambda: self.update("B1"))
        self.B2 = Button(master, text="Lays", command=lambda: self.update("B2"))
        self.B3 = Button(master, text="MJ Thriller", command=lambda: self.update("B3"))
        self.B4 = Button(master, text="Time Mag", command=lambda: self.update("B4"))
        self.B5 = Button(master, text="USB", command=lambda: self.update("B5"))
        self.B6 = Button(master, text="Star Wars", command=lambda: self.update("B6"))
        self.B7 = Button(master, text="Total", command=lambda: self.update("B7"))
        self.B8 = Button(master, text="Print", command=lambda: self.update("B8"))
        self.subtract_button = Button(master, text="Save $10", command=lambda: self.update("subtract10"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))


        # Here I set the layout for the buttons, I can specify where on the main window I would like everything.

        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)

        self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E)

        self.B1.grid(row=2, column=0)
        self.B2.grid(row=2, column=1)
        self.B3.grid(row=3, column=0)
        self.B4.grid(row=3, column=1)
        self.B5.grid(row=3, column=2)
        self.B6.grid(row=2, column=2)
        self.B7.grid(row=1, column=3)
        self.B8.grid(row=3, column=4)

        self.subtract_button.grid(row=3, column=3)
        self.reset_button.grid(row=2, column=3, sticky=W+E)


# For the input of value for specific items in the box provided
    def validate(self, new_text):

        if not new_text: # the field is being cleared
            self.entered_number = 0
            return True


# These functions help define what a button does when pressed
    def update(self, method):
# Create or Append a text file wit hthe given name
        f = open("Receipt.txt", "a")
# If B1 is pressed, then add the price of B1 to the total and print this string to the text file
#This process is duplicated for each button given their unique message and price
        if method == "B1":
            #self.total += self.entered_number
            self.total += 2.76


            print("Coca-Cola (12 Pack)             $2.76", file=f)
        elif method == "B2":
            self.total += 2.99

            print("Lays Classic                    $2.99", file=f)
        elif method == "B3":
            self.total += 7.00

            print("Michael J.- Thriller            $7.00 ", file=f)
        elif method == "B4":
            self.total += 3.50

            print("Time Magazine                   $3.50", file=f)
        elif method == "B5":
            self.total += 19.99

            print("USB 3.0 Cruzer                  $19.99", file=f)
        elif method == "B6":
            self.total += 9.98

            print("Star Wars: V                    $9.98", file=f)
        elif method == "subtract10":
            self.total -= 10
            SubTot = self.total

            print("Discount                       -$10.00",file=f)
        elif method == "B7":
            roundedTotal = round(self.total, 2)


            print("\n------------------------------------ \n    Your total today is: $", roundedTotal, file=f)
            print("\n\n    Payment: Android Pay \n    Technology: Bluetooth and NFC \n    APPROVED", file=f)
            print("\n \n \n        Thank you very much.\n" "        Please come back again.", file=f)
            call(["./rpi", "args", "to", "rpi"])
            # Here we call a program called "Hello World" to execute. This program is the GCC make of the C file
            # essentialy, the IDE will create this build when you compile
        elif method == "B8":
            call(["sudo", "./helloworld", "args", "to", "helloworld"])
        elif method == "reset":
            # Here I reset the counter
            self.total = 0

            print("             KWIK-E Mart \n         ******************** \n         * 123 Evergreen Tr. * \n              * S4S 0A2 *\n         * (306) 591-0909 *\n         ********************  \n         Welcome to KWIK-E Mart\n \n \n \n------------------------------------ \n ", file=open("Receipt.txt", "w"))
        else: # reset
            self.total = 0

        roundedTot = round(self.total,2)
        self.total_label_text.set(roundedTot)
        self.entry.delete(0, END)
def createwindow():
    global componentlist
    global intrinsiclist
    global intrinsicvaluelist
    global extrinsiclist
    global extrinsicvaluelist
    global affordanceformulalist

    clearall_button = Button(framer.Objframe, text="clear", command = lambda: clearlists(componentlist, intrinsiclist, intrinsicvaluelist,
                                                                              extrinsiclist, extrinsicvaluelist, affordanceformulalist))
    clearall_button.config(image = framer.cancelbtnpic, borderwidth = 0, bg = "#fa7878", activebackground= "#fa7878", compound = CENTER, foreground = "white", activeforeground = "#fa7878", font=(None, 13))
    clearall_button.place ( x = 560, y = 590 )
    tooltip.CreateToolTip(clearall_button, text = 'Tooltip:\n\n'
                 'Klick this button to discard your modifications\n'
                 'and clear all checkboxes, option menus and text fields')

    exec_button = Button(framer.Objframe, text="save", command = lambda: getvals(pred_entry, optionVar, optionVarHead, headgroup_entry,
                                                                      optionVarConc, concavitygroup_entry, rotvalx, rotvaly,
                                                                      rotvalz, reflvalxy, reflvalxz, reflvalyz, optionVarScale,
                                                                      optionVarMovable))
    exec_button.config(image = framer.smallbtnpic, borderwidth = 0, bg = "#a3ff8f", activebackground= "#a3ff8f", compound = CENTER, foreground = "white", activeforeground = "#a3ff8f", font=(None, 13))
    exec_button.place ( x = 560, y = 636 )
    tooltip.CreateToolTip(exec_button, text = 'Tooltip:\n\n'
                 'Klick this button to save your modifications\n'
                 'to a VoxML conform XML document')

    debug_textfield = tk.Text(framer.Objframe, height=4, width=48)
    debug_textfield.configure(relief = RIDGE, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    debug_textfield.place ( x = 100, y = 590 )

    group_label = Label(framer.Objframe, text = "Group:", foreground = "white", background = "#404040", font=(None, 14))
    group_label.place (x = 360, y = 50)
    tooltip.CreateToolTip(group_label, text = 'Tooltip:\n\n'
                 'Use Integers to refer to groups of parts,\n'
                 'habitats or affordance formulas')

    args_label = Label(framer.Objframe, text = "Arguments:", foreground = "white", background = "#404040", font=(None, 14))
    args_label.place (x = 440, y = 50)
    tooltip.CreateToolTip(args_label, text = 'Tooltip:\n\n'
                 'Insert functions arguments in entry fields\n'
                 'below')

    lex_label = Label(framer.Objframe, text = "<Lex>", foreground = "white", background = "#404040", font=(None, 14))
    lex_label.place (x = 50, y = 50)

    pred_label = Label(framer.Objframe, text = "Predicate:", foreground = "white", background = "#404040", font=(None, 12))
    pred_label.place (x = 100, y = 80)

    pred_entry = Entry(framer.Objframe)
    pred_entry.configure(relief = RIDGE, width = 17, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    pred_entry.place (x = 190, y = 80)
    
    typesub_label = Label(framer.Objframe, text = "Type:", foreground = "white", background = "#404040", font=(None, 12))
    typesub_label.place (x = 100, y = 110)

    optionVar = StringVar()
    optionVar.set("physobj")

    option = OptionMenu(framer.Objframe, optionVar, "physobj", "physobj", "physobj*artifact")
    option.place(x = 190, y = 110)
    option.config( width = 145, height = 14, image = framer.menutickpic, anchor = "w", bd = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    type_label = Label(framer.Objframe, text = "<Type>", foreground = "white", background = "#404040", font=(None, 14))
    type_label.place (x = 50, y = 140)

    head_label = Label(framer.Objframe, text = "Head:", foreground = "white", background = "#404040", font=(None, 12))
    head_label.place (x = 100, y = 170)

    headgroup_entry = Entry(framer.Objframe, width = 4)
    headgroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    headgroup_entry.place (x = 370, y = 170)
    tooltip.CreateToolTip(headgroup_entry, text = 'Tooltip:\n\n'
                 '*OPTIONAL*')

    optionVarHead = StringVar()
    optionVarHead.set("ellipsoid")

    optionmenuhead = OptionMenu(framer.Objframe, optionVarHead, "ellipsoid", "ellipsoid", "bipyramid", "cylindroid", "cupola", "frustum",
                                "hemiellipsoid", "parallelepiped", "prismatoid", "pyramid", "rectangular_prism", "sheet",
                                "toroid", "wedge")
    optionmenuhead.place(x = 190, y = 170)
    optionmenuhead.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 11))

    component_label = Label(framer.Objframe, text = "Component:", foreground = "white", background = "#404040", font=(None, 12))
    component_label.place (x = 100, y = 200)

    component_entry = Entry(framer.Objframe)
    component_entry.configure(relief = RIDGE, width = 17, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    component_entry.place (x = 190, y = 200)

    componentgroup_entry = Entry(framer.Objframe, width = 4)
    componentgroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    componentgroup_entry.place (x = 370, y = 200)
    tooltip.CreateToolTip(componentgroup_entry, text = 'Tooltip:\n\n'
                 '*OPTIONAL*')

    duplicatevar = IntVar()
    duplicatevar.set(0)
    
    dupecheckbutton = Checkbutton(framer.Objframe, text="", variable=duplicatevar)
    dupecheckbutton.var = duplicatevar
    dupecheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", font=(None, 12))
    dupecheckbutton.place ( x = 470, y = 200 )
    tooltip.CreateToolTip(dupecheckbutton, text = 'Tooltip:\n\n'
                 'Check this box if the Object has multiple instances\n'
                 'or copies of that same part\n\n *OPTIONAL*')

    add_component_button = Button(framer.Objframe, text="add", command = lambda: addcomponent(component_entry, componentgroup_entry, duplicatevar,
                                                                                   debug_textfield, componentlist_textfield,optionVarComponentlist, OptionMenuComponentlist))
    add_component_button.config(image = framer.smallbtnpic, borderwidth = 0, bg = "#a3ff8f", activebackground= "#a3ff8f", compound = CENTER, foreground = "white", activeforeground = "#a3ff8f", font=(None, 13))
    add_component_button.place ( x = 560, y = 198 )
    tooltip.CreateToolTip(add_component_button, text = 'Tooltip:\n\n'
                 'Klick this button to add a component\n'
                 'to the componentlist of the current object')

    concavity_label = Label(framer.Objframe, text = "Concavity:", foreground = "white", background = "#404040", font=(None, 12))
    concavity_label.place (x = 100, y = 230)

    optionVarConc = StringVar()
    optionVarConc.set("Flat")

    optionmenuconc = OptionMenu(framer.Objframe, optionVarConc, "Flat", "Flat", "Concave", "Convex")
    optionmenuconc.place(x = 190, y = 230)
    optionmenuconc.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    concavitygroup_entry = Entry(framer.Objframe, width = 4)
    concavitygroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    concavitygroup_entry.place (x = 370, y = 230)
    tooltip.CreateToolTip(concavitygroup_entry, text = 'Tooltip:\n\n'
                 '*OPTIONAL*')

    rotatsym_label = Label(framer.Objframe, text = "Rotatsym:", foreground = "white", background = "#404040", font=(None, 12))
    rotatsym_label.place (x = 100, y = 260)

    rotvalx = IntVar()
    rotvalx.set(0)
    rotvaly = IntVar()
    rotvaly.set(0)
    rotvalz = IntVar()
    rotvalz.set(0)

    rotxcheckbutton = Checkbutton(framer.Objframe, text="X", variable=rotvalx)
    rotxcheckbutton.var = rotvalx
    rotxcheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    rotxcheckbutton.place ( x = 190, y = 260 )

    rotxcheckbuttonlabel = Label(framer.Objframe, text="X")
    rotxcheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    rotxcheckbuttonlabel.place ( x = 210, y = 262 )

    rotycheckbutton = Checkbutton(framer.Objframe, text="Y", variable=rotvaly)
    rotycheckbutton.var = rotvaly
    rotycheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    rotycheckbutton.place ( x = 230, y = 260 )

    rotycheckbuttonlabel = Label(framer.Objframe, text="Y")
    rotycheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    rotycheckbuttonlabel.place ( x = 250, y = 262 )

    rotzcheckbutton = Checkbutton(framer.Objframe, text="Z", variable=rotvalz)
    rotzcheckbutton.var = rotvalz
    rotzcheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    rotzcheckbutton.place ( x = 270, y = 260 )

    rotzcheckbuttonlabel = Label(framer.Objframe, text="Z")
    rotzcheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    rotzcheckbuttonlabel.place ( x = 290, y = 262 )

    reflsym_label = Label(framer.Objframe, text = "Reflsym:", foreground = "white", background = "#404040", font=(None, 12))
    reflsym_label.place (x = 100, y = 290)

    reflvalxy = IntVar()
    reflvalxy.set(0)
    reflvalxz = IntVar()
    reflvalxz.set(0)
    reflvalyz = IntVar()
    reflvalyz.set(0)

    reflxycheckbutton = Checkbutton(framer.Objframe, text="XY", variable=reflvalxy)
    reflxycheckbutton.var = reflvalxy
    reflxycheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    reflxycheckbutton.place ( x = 190, y = 290 )

    reflxycheckbuttonlabel = Label(framer.Objframe, text="XY")
    reflxycheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    reflxycheckbuttonlabel.place ( x = 210, y = 292 )

    reflxzcheckbutton = Checkbutton(framer.Objframe, text="XZ", variable=reflvalxz)
    reflxzcheckbutton.var = reflvalxz
    reflxzcheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    reflxzcheckbutton.place ( x = 240, y = 290 )

    reflxzcheckbuttonlabel = Label(framer.Objframe, text="XZ")
    reflxzcheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    reflxzcheckbuttonlabel.place ( x = 260, y = 292 )

    reflyzcheckbutton = Checkbutton(framer.Objframe, text="YZ", variable=reflvalyz)
    reflyzcheckbutton.var = reflvalyz
    reflyzcheckbutton.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "#404040", activeforeground = "#404040", font=(None, 12))
    reflyzcheckbutton.place ( x = 290, y = 290 )

    reflyzcheckbuttonlabel = Label(framer.Objframe, text="YZ")
    reflyzcheckbuttonlabel.config(borderwidth = 0, background = "#404040", activebackground= "#404040", foreground = "white", font=(None, 12))
    reflyzcheckbuttonlabel.place ( x = 310, y = 292 )

    habitat_label = Label(framer.Objframe, text = "<Habitat>", foreground = "white", background = "#404040", font=(None, 14))
    habitat_label.place (x = 50, y = 320)

    intrinsic_label = Label(framer.Objframe, text = "Intrinsic:", foreground = "white", background = "#404040", font=(None, 12))
    intrinsic_label.place (x = 100, y = 350)

    optionVarIntr = StringVar()
    optionVarIntr.set("UP")

    optionmenuint = OptionMenu(framer.Objframe, optionVarIntr, "UP", "UP", "TOP", "NEAR", "FRONT")
    optionmenuint.place(x = 190, y = 350)
    optionmenuint.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    intrinsicgroup_entry = Entry(framer.Objframe, width = 4)
    intrinsicgroup_entry.place (x = 370, y = 350)
    intrinsicgroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    tooltip.CreateToolTip(intrinsicgroup_entry, text = 'Tooltip:\n\n'
                 '*OPTIONAL*')

    intrinsicarg1_entry = Entry(framer.Objframe, width = 4)
    intrinsicarg1_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    intrinsicarg1_entry.place (x = 440, y = 350)

    intrinsicarg2_entry = Entry(framer.Objframe, width = 4)
    intrinsicarg2_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    intrinsicarg2_entry.place (x = 485, y = 350)
    
    add_intrinsic_button = Button(framer.Objframe, text="add", command = lambda: addhabitat(optionVarIntr, intrinsicgroup_entry, intrinsicarg1_entry,
                                                                                 intrinsicarg2_entry, intrinsiclist, intrinsicvaluelist,
                                                                                 "intr", debug_textfield, optionVarIntrinsiclist, OptionMenuIntrinsiclist, componentlist_textfield))
    add_intrinsic_button.config(image = framer.smallbtnpic, borderwidth = 0, bg = "#a3ff8f", activebackground= "#a3ff8f", compound = CENTER, foreground = "white", activeforeground = "#a3ff8f", font=(None, 13))
    add_intrinsic_button.place ( x = 560, y = 348 )

    tooltip.CreateToolTip(add_intrinsic_button, text = 'Tooltip:\n\n'
                 'Klick this button to add an intrinsic habitat\n'
                 'to the list of intrinsic habitats of the current object')

    extrinsic_label = Label(framer.Objframe, text = "Extrinsic:", foreground = "white", background = "#404040", font=(None, 12))
    extrinsic_label.place (x = 100, y = 380)

    optionVarExtr = StringVar()
    optionVarExtr.set("UP")

    optionmenuext = OptionMenu(framer.Objframe, optionVarExtr, "UP", "UP", "TOP", "NEAR", "FRONT")
    optionmenuext.place(x = 190, y = 380)
    optionmenuext.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    extrinsicgroup_entry = Entry(framer.Objframe, width = 4)
    extrinsicgroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    extrinsicgroup_entry.place (x = 370, y = 380)
    tooltip.CreateToolTip(extrinsicgroup_entry, text = 'Tooltip:\n\n'
                 '*OPTIONAL*')

    extrinsicarg1_entry = Entry(framer.Objframe, width = 4)
    extrinsicarg1_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    extrinsicarg1_entry.place (x = 440, y = 380)

    extrinsicarg2_entry = Entry(framer.Objframe, width = 4)
    extrinsicarg2_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    extrinsicarg2_entry.place (x = 485, y = 380)

    add_extrinsic_button = Button(framer.Objframe, text="add", command = lambda: addhabitat(optionVarExtr, extrinsicgroup_entry, extrinsicarg1_entry,
                                                                                 extrinsicarg2_entry, extrinsiclist, extrinsicvaluelist,
                                                                                 "extr", debug_textfield, optionVarExtrinsiclist, OptionMenuExtrinsiclist, componentlist_textfield))
    add_extrinsic_button.config(image = framer.smallbtnpic, borderwidth = 0, bg = "#a3ff8f", activebackground= "#a3ff8f", compound = CENTER, foreground = "white", activeforeground = "#a3ff8f", font=(None, 13))
    add_extrinsic_button.place ( x = 560, y = 378 )

    tooltip.CreateToolTip(add_extrinsic_button, text = 'Tooltip:\n\n'
                 'Klick this button to add an extrinsic habitat\n'
                 'to the list of extrinsic habitats of the current object')

    affordance_label = Label(framer.Objframe, text = "<Affordances>", foreground = "white", background = "#404040", font=(None, 14))
    affordance_label.place (x = 50, y = 410)

    affordanceformula_label = Label(framer.Objframe, text = "Formula:", foreground = "white", background = "#404040", font=(None, 12))
    affordanceformula_label.place (x = 100, y = 440)

    optionVarAfford = StringVar()
    optionVarAfford.set("grasp")

    optionmenuafford = OptionMenu(framer.Objframe, optionVarAfford, "grasp", "grasp", "lift", "roll", "slide", "put_on", "put_in")
    optionmenuafford.place(x = 190, y = 440)
    optionmenuafford.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    affordanceformulagroup_entry = Entry(framer.Objframe, width = 4)
    affordanceformulagroup_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    affordanceformulagroup_entry.place (x = 370, y = 440)

    affordarg1_entry = Entry(framer.Objframe, width = 4)
    affordarg1_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    affordarg1_entry.place (x = 440, y = 440)

    affordarg2_entry = Entry(framer.Objframe, width = 4)
    affordarg2_entry.configure(relief = RIDGE, width = 3, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    affordarg2_entry.place (x = 485, y = 440)

    add_affordanceformula_button = Button(framer.Objframe, text="add", command = lambda: addformula(optionVarAfford, affordanceformulagroup_entry,
                                                                                         affordarg1_entry, affordarg2_entry, debug_textfield,
                                                                                         optionVarAffordancelist, OptionMenuAffordancelist, componentlist_textfield))
    add_affordanceformula_button.config(image = framer.smallbtnpic, borderwidth = 0, bg = "#a3ff8f", activebackground= "#a3ff8f", compound = CENTER, foreground = "white", activeforeground = "#a3ff8f", font=(None, 13))
    add_affordanceformula_button.place ( x = 560, y = 438 )

    tooltip.CreateToolTip(add_affordanceformula_button, text = 'Tooltip:\n\n'
                 'Klick this button to add an affordance formula\n'
                 'to the list of affordance formulas of the current object')

    embodiement_label = Label(framer.Objframe, text="<Embodiement>", foreground = "white", background = "#404040", font=(None, 14))
    embodiement_label.place (x = 50, y = 470)

    scale_label = Label(framer.Objframe, text = "Scale:", foreground = "white", background = "#404040", font=(None, 12))
    scale_label.place (x = 100, y = 500)

    optionVarScale = StringVar()
    optionVarScale.set("agent")

    OptionMenuScale = OptionMenu(framer.Objframe, optionVarScale, "< agent", "< agent", "agent", "> agent")
    OptionMenuScale.place(x = 190, y = 500)
    OptionMenuScale.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))

    movable_label = Label(framer.Objframe, text = "Movable:", foreground = "white", background = "#404040", font=(None, 12))
    movable_label.place (x = 100, y = 530)

    optionVarMovable = StringVar()
    optionVarMovable.set("True")

    OptionMenuMovable = OptionMenu(framer.Objframe, optionVarMovable, "True", "True", "False")
    OptionMenuMovable.place(x = 190, y = 530)
    OptionMenuMovable.config(width=145, height = 14, image = framer.menutickpic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#a3ff8f", font=(None, 12))
    

    componentlist_label = Label(framer.Objframe, text = "File Preview:", foreground = "white", background = "#404040", font=(None, 14))
    componentlist_label.place (x = 670, y = 50)

    componentlist_textfield = tk.Text(framer.Objframe, height=10, width=40)
    componentlist_textfield.configure(relief = RIDGE, bd = 2, foreground = "white", insertbackground = "white", background = "#505050", font=(None, 12))
    componentlist_textfield.place ( x = 670, y = 80 )

    optionVarComponentlist = StringVar()
    optionVarComponentlist.set("Select Component")

    OptionMenuComponentlist = OptionMenu(framer.Objframe, optionVarComponentlist, "Select Component")
    OptionMenuComponentlist.place(x = 670, y = 300)
    OptionMenuComponentlist.config(width=250, height = 16, image = framer.cancelmenupic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#fa7878", font=(None, 12))
    OptionMenuComponentlist['menu'].entryconfig(1, background = "#404040" ,activebackground = "#404040", foreground = "white", activeforeground = "#fa7878")

    removecompo_button = Button(framer.Objframe, text="remove", command = lambda: removefromlist(componentlist, componentlist_textfield, OptionMenuComponentlist, optionVarComponentlist, debug_textfield))
    removecompo_button.config(image = framer.cancelbtnpic, borderwidth = 0, bg = "#fa7878", activebackground= "#fa7878", compound = CENTER, foreground = "white", activeforeground = "#fa7878", font=(None, 13))
    removecompo_button.place ( x = 960, y = 300 )


    optionVarIntrinsiclist = StringVar()
    optionVarIntrinsiclist.set("Select Intrinsic Habitat")
    
    OptionMenuIntrinsiclist = OptionMenu(framer.Objframe, optionVarIntrinsiclist, "Select Intrinsic Habitat")
    OptionMenuIntrinsiclist.place(x = 670, y = 348)
    OptionMenuIntrinsiclist.config(width=250, height = 16, image = framer.cancelmenupic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#fa7878", font=(None, 12))

    removeintr_button = Button(framer.Objframe, text="remove", command = lambda: removefromlist(intrinsiclist, componentlist_textfield, OptionMenuIntrinsiclist, optionVarIntrinsiclist, debug_textfield))
    removeintr_button.config(image = framer.cancelbtnpic, borderwidth = 0, bg = "#fa7878", activebackground= "#fa7878", compound = CENTER, foreground = "white", activeforeground = "#fa7878", font=(None, 13))
    removeintr_button.place ( x = 960, y = 348 )

    optionVarExtrinsiclist = StringVar()
    optionVarExtrinsiclist.set("Select Extrinsic Habitat")
    
    OptionMenuExtrinsiclist = OptionMenu(framer.Objframe, optionVarExtrinsiclist, "Select Extrinsic Habitat")
    OptionMenuExtrinsiclist.place(x = 670, y = 380)
    OptionMenuExtrinsiclist.config(width=250, height = 16, image = framer.cancelmenupic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#fa7878", font=(None, 12))

    removeextr_button = Button(framer.Objframe, text="remove", command = lambda: removefromlist(extrinsiclist, componentlist_textfield, OptionMenuExtrinsiclist, optionVarExtrinsiclist, debug_textfield))
    removeextr_button.config(image = framer.cancelbtnpic, borderwidth = 0, bg = "#fa7878", activebackground= "#fa7878", compound = CENTER, foreground = "white", activeforeground = "#fa7878", font=(None, 13))
    removeextr_button.place ( x = 960, y = 380 )


    optionVarAffordancelist = StringVar()
    optionVarAffordancelist.set("Select Affordance Formula")
    
    OptionMenuAffordancelist = OptionMenu(framer.Objframe, optionVarAffordancelist, "Select Affordance Formula")
    OptionMenuAffordancelist.place(x = 670, y = 440)
    OptionMenuAffordancelist.config(width=250, height = 16, image = framer.cancelmenupic, anchor = "w", borderwidth = 0,  indicatoron=0, compound = LEFT, bg = "#404040", activebackground= "#404040", foreground = "white", activeforeground = "#fa7878", font=(None, 12))

    removeAffordance_button = Button(framer.Objframe, text="remove", command = lambda: removefromlist(affordanceformulalist, componentlist_textfield, OptionMenuAffordancelist, optionVarAffordancelist, debug_textfield))
    removeAffordance_button.config(image = framer.cancelbtnpic, borderwidth = 0, bg = "#fa7878", activebackground= "#fa7878", compound = CENTER, foreground = "white", activeforeground = "#fa7878", font=(None, 13))
    removeAffordance_button.place ( x = 960, y = 440 )

    drdwnlistgrn = [option, optionmenuhead, optionmenuconc, optionmenuint, optionmenuext, optionmenuafford, OptionMenuScale, OptionMenuMovable]
    drdwnlistred = [OptionMenuComponentlist, OptionMenuIntrinsiclist, OptionMenuExtrinsiclist, OptionMenuAffordancelist]
    for drdwn in drdwnlistgrn:
        i = 0
        while i < drdwn['menu'].index('end') + 1:
            drdwn['menu'].entryconfig(i, background = "#404040" ,activebackground = "#505050", foreground = "white", activeforeground = "#a3ff8f")
            i += 1

    
    for drdwn in drdwnlistred:
        i = 0
        while i < drdwn['menu'].index('end') + 1:
            drdwn['menu'].entryconfig(i, background = "#404040" ,activebackground = "#505050", foreground = "white", activeforeground = "#fa7878")
            i += 1
        drdwn['menu'].add_command(label = "                                                                       ", command=tk._setit(optionVarComponentlist, "Select Component"))
        drdwn['menu'].entryconfig(1, background = "#404040" ,activebackground = "#404040", foreground = "white", activeforeground = "#fa7878")
Example #30
0
class Start_Frame(Frame):
    """
    Fenêtre initiale. Demande à l'utilisateur d'entrer les dimensions de la
    grille à créer. Permet également d'ouvrir une grille préexistante.
    """

    TITLE = "Dosun Fuwari Solver"
    HELPTEXT = "Enter the dimensions of the grid you want to create: (maximum 20x20)"

    def __init__(self, master=None):
        """
        Initialisation automatique à la création de la fenêtre d'initialisation
        """
        super().__init__(master, padding=(20, 20, 20, 20))
        # assigner les variables d'instance
        self.master = master
        # variables Tk qui contiendront les valeurs entrées dans les deux champs de
        # texte
        self.x = IntVar()
        self.y = IntVar()
        # Les initialiser à des valeurs cohérentes
        self.x.set(2)
        self.y.set(2)

        # Dessiner la fenêtre
        self.create_widgets()

    def create_widgets(self):
        """
        Affiche le formulaire de démarrage.
        """
        # Titre
        Label(
            self,
            text=self.TITLE,
            font=("Helvetica", 16),
            anchor=N,
            padding=(0, 0, 0, 10),
        ).grid(row=0, column=0, columnspan=4, sticky=W + E + N)
        # Texte d'indication
        Label(
            self,
            text=self.HELPTEXT,
            wraplength=300,
            font=("Helvetica", 12),
            anchor=N,
            justify=LEFT,
            padding=(0, 0, 0, 10),
        ).grid(row=1, column=0, columnspan=3, sticky=W + E)

        # Commande de validation des entrées
        # Source: https://stackoverflow.com/a/31048136
        # Empêche la création de grilles de dimensions ridicules
        vcmd = (self.register(self.validate), "%d", "%P", "%S")

        # Formulaire d'entrée de la largeur de la grille
        Label(self, text="Width:").grid(row=2, column=0)
        x_entry = Entry(self,
                        textvariable=self.x,
                        validate="key",
                        validatecommand=vcmd)
        x_entry.grid(row=2, column=1, sticky=W + E)
        # Formulaire d'entrée de la hauteur de la grille
        Label(self, text="Height:").grid(row=3, column=0)
        y_entry = Entry(self,
                        textvariable=self.y,
                        validate="key",
                        validatecommand=vcmd)
        y_entry.grid(row=3, column=1, sticky=W + E)

        # Bouton Start
        sub_btn = Button(
            self,
            text="Start!",
            command=lambda: self.start_editor(int(x_entry.get()),
                                              int(y_entry.get())),
        )
        # Associer la même action à la touche entrée qu'au bouton start
        self.master.bind(
            "<Return>",
            lambda e: self.start_editor(int(x_entry.get()), int(y_entry.get()),
                                        e),
        )
        # Pareil avec le bouton entrée du pavé numérique
        self.master.bind(
            "<KP_Enter>",
            lambda e: self.start_editor(int(x_entry.get()), int(y_entry.get()),
                                        e),
        )
        sub_btn.grid(row=2, column=3, rowspan=2)

    def validate(self, action, value_if_allowed, text):
        """
        Renvoie True ssi la valeur fournie dans text est convertissable en
        entier et a une valeur autorisée ( > 0 et <= 20)
        Source: https://stackoverflow.com/a/31048136
        """
        # Ne vérifier l'entrée que si on insère un caractère
        if action == "1":
            # N'autoriser que des chiffres
            if text in "0123456789":
                try:
                    # Vérifier que la valeur saisie est un entier et est entre
                    # les bornes choisies
                    return 0 < int(value_if_allowed) <= 20
                except ValueError:
                    # La valeur n'était pas un entier: enpêcher la saisie
                    return False
            else:
                # La valeur n'était pas un chiffre
                return False
        else:
            # Sinon on s'en fout (on n'empêche pas de supprimer, sélectionner
            # comme on veut)
            return True

    def start_editor(self, x, y, event=None):
        """
        Détruit la fenêtre initiale et ouvre une fenêtre d'édition avec une
        grille de la taille choisie par l'utilisateur
        """
        self.destroy()
        self.master.change(Editor_Frame, [x, y, {"blacks": [], "zones": []}])

    def open_grid(self):
        """
        Ouvre une grille préexistante dans une fenêtre d'édition
        """
        filename = askopenfilename(
            initialdir=".",
            filetypes=(("JSON File", "*.json"), ("All Files", "*.*")),
            title="Choose a file.",
        )
        if filename:
            grid = fio.read_grid(filename)
            self.destroy()
            self.master.change(Editor_Frame,
                               [grid["width"], grid["height"], grid])

    def create_menu(self, root):
        """
        Dessine le "menu" - la barre d'options en haut de la fenêtre.
        """
        menubar = Menu(root)
        fileMenu = Menu(menubar, tearoff=0)
        fileMenu.add_command(label="Open grid", command=self.open_grid)
        fileMenu.add_command(label="Quit", command=quit)
        menubar.add_cascade(label="File", menu=fileMenu)
        return menubar
Example #31
0
class GameLogic:  # pylint: disable=too-many-instance-attributes
    # all instance-attributes are needed to run the show
    """ Luokka toteuttaa pelin toiminnallisuuden ja logiikan, käyttäen apunaan eri olioita.

    Attributes:
        first_wheel = yksittäinen pelilinja, Wheel-olio
        second_wheel = yksittäinen pelilinja, Wheel-olio
        third_wheel = yksittäinen pelilinja, Wheel-olio
        credits = pelivarat, Credit-olio
        bet = pelipanos
        bet_list = lista eri pelipanoksista
        payoff = voittojen laskemiseen käytettävä Payoff-olio
        last_win_amount = viimeisin voiton suuruus
        list_of_wheels = kaikki voittolinjat sisältävä lista
        can_be_locked = käytetään pelilinjoen lukituksen ohitukseen
    """
    def __init__(self):
        """"Konstruktori joka luo pelilogiikan olion.
        """

        self.first_wheel = Wheel()
        self.second_wheel = Wheel()
        self.third_wheel = Wheel()
        self.credits = Credit()
        self.bet = IntVar()
        self.bet_list = [1, 2, 5, 10]
        self.payoff = Payoff()
        self.last_win_amount = IntVar()
        self.last_win_amount.set(0)
        self.list_of_wheels = (self.first_wheel, self.second_wheel,
                               self.third_wheel)
        self.can_be_locked = True

    def start(self):
        """Alustaa pelipanoksen oikeaksi
        """
        self.raise_bet()

    def play(self):
        """Tarkistaa riittävätkö pelivarat pelaamiseen, olivatko aiemmalla kieroksella
        pelilinjat lukittu ja arpoo pelilinjoille uudet arvot"""

        if self.check_credits():
            if not self.can_be_locked:
                self.unlock_all_and_spin()
            else:
                if self.check_locked_wheels():
                    self.use_credit_and_spin()
            return True
        return False

    def check_credits(self):
        """Tarkistaa riittävät pelivarat pelin pelaamiseen"""
        if self.credits.value.get() == 0:
            return False

        if self.credits.value.get() < self.bet.get():
            return False
        return True

    def check_locked_wheels(self):
        """Tarkistaa olivatko osa pelilinjoista lukittu edellisellä kieroksella. """

        locked_wheels = 0
        for wheel in self.list_of_wheels:
            if wheel.is_locked:
                locked_wheels += 1
                self.can_be_locked = False
        if locked_wheels > len(self.list_of_wheels) - 1:
            self.can_be_locked = True
            return False
        return True

    def unlock_all_and_spin(self):
        """Käytetään pelilinjojen lukituksen vapauttamiseen, jos esim. edellisellä kierroksella
        osa linjoista on ollut lukittuna. Jokaisen pelikierroksen jälkeen joka sisältää lukitun
        pelilinja, tulee olla vähintaa yksi kierros jossa kaikki pelilinjat arvotaan uudestaan """

        self.first_wheel.set_unlocked()
        self.second_wheel.set_unlocked()
        self.third_wheel.set_unlocked()
        self.use_credit_and_spin()
        self.can_be_locked = True

    def use_credit_and_spin(self):
        """Toiminnallisuus joka kuluttaa pelivaroja panoksen verran,
        arpoo uudet arvot pelilinjoilla ja tarkistaa tuliko voittoa"""

        self.credits.use_credit(self.bet.get())
        self.spin_all_wheels()
        self.check_for_payoff()

    def check_for_payoff(self):
        """Tarkistaa tuliko kierroksella voittoa"""

        if self.payoff.check_for_win(self.first_wheel.value,
                                     self.second_wheel.value,
                                     self.third_wheel.value):

            payoff_amount = self.payoff.payoff_amount(self.first_wheel.value,
                                                      self.bet.get())
            self.credits.add_payoff(payoff_amount)
            self.last_win_amount.set(payoff_amount)
            self.can_be_locked = False

    def raise_bet(self):
        """Korottaa pelipanoksen"""

        next_bet = self.bet_list.pop(0)
        self.bet.set(next_bet)
        self.bet_list.append(next_bet)

    def spin_all_wheels(self):
        """Arpoo uudet arvot pelilinjoille jotka eivät ole lukittu"""

        self.first_wheel.spin()
        self.second_wheel.spin()
        self.third_wheel.spin()
Example #32
0
class MyFirstGUI:
    def __init__(self, master):
        self.master = master

        master.title("GUI do Sensor")

        # Variaveis do Sensor
        #threadSensor = Thread(target = novoSensor(),)
        #threadSensor.start()
        # REMOVER SENSOR E ADICIONAR CONTROLLER P/ MVC PENDENTE FALTA FAZER
        self.sensor = novoSensor(cpf_sensor, ip_servidor, tcp_porta)

        # Label principal
        self.label = Label(master, text="Configurações do Sensor:")
        self.label.grid(row=0, column=1, columnspan=1)

        # Label BPM:
        self.bpm_label = Label(master, text="BPM:")
        self.bpm_label.grid(row=1, column=0, sticky=W)

        # Valor BPM e Label_Valor_BPM
        self.valor_bpm_label_num = IntVar()
        self.valor_bpm_label_num.set(self.sensor.bpm)
        self.valor_bpm_label = Label(master,
                                     textvariable=self.valor_bpm_label_num)
        self.valor_bpm_label.grid(row=1, column=1)

        # Botão Incrementar BPM
        self.incrementar_bpm_button = Button(master,
                                             text="/\\",
                                             command=self.incrementarBPM)
        self.incrementar_bpm_button.grid(row=1, column=2)

        self.decrementar_bpm_button = Button(master,
                                             text="\\/",
                                             command=self.decrementarBPM)
        self.decrementar_bpm_button.grid(row=1, column=3)

        # # # # MOVIMENTO # # # #

        # Label movimento
        self.movimento_label = Label(master, text="Movimentando:")
        self.movimento_label.grid(row=2, column=0, sticky=W)

        # Valor Movimento e Label_Valor_Movimento
        if (True == self.sensor.movimento):
            self.valor_movimento_label = Label(master, text="SIM!")
        else:
            self.valor_movimento_label = Label(master, text="NÃO!")
        self.valor_movimento_label.grid(row=2, column=1)

        # Botão Movimentar
        self.movimentar_button = Button(master,
                                        text="ANDA!",
                                        command=self.movimentar)
        self.movimentar_button.grid(row=2, column=2)

        self.parar_button = Button(master, text="PARA!", command=self.parar)
        self.parar_button.grid(row=2, column=3)

        # # # # PRESSAO # # # #

        # Label Pressao
        self.pressao_label = Label(master, text="Pressão:")
        self.pressao_label.grid(row=3, column=0, sticky=W)

        # Valor Pressao e Label_Valor_Pressao
        self.valor_pressao_label = Label(master, text=str(self.sensor.pressao))
        self.valor_pressao_label.grid(row=3, column=1)

        # Botão Incrementar Pressao
        self.pressao_baixa_button = Button(master,
                                           text="BAIXA",
                                           command=self.pressao_baixa)
        self.pressao_baixa_button.grid(row=3, column=2)

        # Botão Decrementar Pressao
        self.pressao_normal_button = Button(master,
                                            text="NORMAL",
                                            command=self.pressao_normal)
        self.pressao_normal_button.grid(row=3, column=3)

        # Botão Pressao Alta
        self.pressao_alta_button = Button(master,
                                          text="ALTA",
                                          command=self.pressao_alta)
        self.pressao_alta_button.grid(row=3, column=4)

        # # # # COORDENADAS # # # #

        # Label POSX
        self.posicaox_label = Label(master, text="X:")
        self.posicaox_label.grid(row=4, column=0, sticky=W)

        # Valor posicaoX
        self.valor_posicaox_label_num = IntVar()
        self.valor_posicaox_label_num.set(self.sensor.x)
        self.valor_posicaox_label = Label(
            master, textvariable=self.valor_posicaox_label_num)
        self.valor_posicaox_label.grid(row=4, column=1)

        # Botão Incrementar X
        self.incrementar_posicaox_button = Button(
            master, text="/\\", command=self.incrementar_posicaox)
        self.incrementar_posicaox_button.grid(row=4, column=2)

        # Botão Decrementar X
        self.decrementar_posicaox_button = Button(
            master, text="\\/", command=self.decrementar_posicaox)
        self.decrementar_posicaox_button.grid(row=4, column=3)

        # Label POSY
        self.posicaoy_label = Label(master, text="Y:")
        self.posicaoy_label.grid(row=5, column=0, sticky=W)

        # Valor posicaoY
        self.valor_posicaoy_label_num = IntVar()
        self.valor_posicaoy_label_num.set(self.sensor.y)
        self.valor_posicaoy_label = Label(
            master, textvariable=self.valor_posicaoy_label_num)
        self.valor_posicaoy_label.grid(row=5, column=1)

        # Botão Incrementar X
        self.incrementar_posicaoy_button = Button(
            master, text="/\\", command=self.incrementar_posicaoy)
        self.incrementar_posicaoy_button.grid(row=5, column=2)

        # Botão Decrementar X
        self.decrementar_posicaoy_button = Button(
            master, text="\\/", command=self.decrementar_posicaoy)
        self.decrementar_posicaoy_button.grid(row=5, column=3)

        # # # # FECHAR # # # #

        # Botão fechar
        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.grid(row=6, column=1, columnspan=1)

        # Atualiza dados da interface
        # FALTA FAZER

    # # # Funções da classe # # #

#    def atualizarValores(self):
# FALTA FAZER

    def incrementarBPM(self):
        self.sensor.bpm += 1
        self.valor_bpm_label_num.set(self.sensor.bpm)
        self.valor_bpm_label = Label(self.master,
                                     textvariable=self.valor_bpm_label_num)

    def decrementarBPM(self):
        self.sensor.bpm -= 1
        self.valor_bpm_label_num.set(self.sensor.bpm)
        self.valor_bpm_label = Label(self.master,
                                     textvariable=self.valor_bpm_label_num)

    def pressao_baixa(self):
        self.sensor.pressao = 1
        self.valor_pressao_label = Label(self.master,
                                         text=str(self.sensor.pressao))
        self.valor_pressao_label.grid(row=3, column=1)

    def pressao_normal(self):
        self.sensor.pressao = 0
        self.valor_pressao_label = Label(self.master,
                                         text=str(self.sensor.pressao))
        self.valor_pressao_label.grid(row=3, column=1)

    def pressao_alta(self):
        self.sensor.pressao = 2
        self.valor_pressao_label = Label(self.master,
                                         text=str(self.sensor.pressao))
        self.valor_pressao_label.grid(row=3, column=1)

    def movimentar(self):
        self.sensor.movimento = True
        self.valor_movimento_label = Label(self.master, text="SIM!")
        self.valor_movimento_label.grid(row=2, column=1)

    def parar(self):
        self.sensor.movimento = False
        self.valor_movimento_label = Label(self.master, text="NÃO!")
        self.valor_movimento_label.grid(row=2, column=1)

    def incrementar_posicaox(self):
        self.sensor.x += 1
        self.valor_posicaox_label_num.set(self.sensor.x)
        self.valor_posicaox_label = Label(
            self.master, textvariable=self.valor_posicaox_label_num)

    def decrementar_posicaox(self):
        self.sensor.x -= 1
        self.valor_posicaox_label_num.set(self.sensor.x)
        self.valor_posicaox_label = Label(
            self.master, textvariable=self.valor_posicaox_label_num)

    def incrementar_posicaoy(self):
        self.sensor.y += 1
        self.valor_posicaoy_label_num.set(self.sensor.y)
        self.valor_posicaoy_label = Label(
            self.master, textvariable=self.valor_posicaoy_label_num)

    def decrementar_posicaoy(self):
        self.sensor.y -= 1
        self.valor_posicaoy_label_num.set(self.sensor.y)
        self.valor_posicaoy_label = Label(
            self.master, textvariable=self.valor_posicaoy_label_num)
Example #33
0
class RandomExcursionTestItem:
    def __init__(self, master, title, x_coor, y_coor, data, variant=False):
        self.__chb_var = IntVar()
        self.__state = StringVar()
        self.__count = StringVar()
        self.__xObs = StringVar()
        self.__p_value = StringVar()
        self.__result = StringVar()
        self.__results = []
        self.__variant = variant

        checkbox = Checkbutton(master, text=title, variable=self.__chb_var)
        checkbox.place(x=x_coor, y=y_coor)

        state_label = LabelTag(master,
                               'State', (x_coor + 60), (y_coor + 30),
                               width=100,
                               font_size=12,
                               border=2,
                               relief='groove')
        if variant:
            self.__state.set('-1.0')
        else:
            self.__state.set('+1')
        state_option = OptionMenu(master, self.__state, *data)
        state_option.place(x=(x_coor + 60),
                           y=(y_coor + 60),
                           height=25,
                           width=100)
        if not variant:
            xObs_label = LabelTag(master,
                                  'CHI-SQUARED', (x_coor + 165), (y_coor + 30),
                                  width=350,
                                  font_size=12,
                                  border=2,
                                  relief='groove')
            xObs_Entry = Entry(master, textvariable=self.__xObs)
            xObs_Entry.place(x=(x_coor + 165),
                             y=(y_coor + 60),
                             width=350,
                             height=25)
        else:
            count_label = LabelTag(master,
                                   'Count', (x_coor + 165), (y_coor + 30),
                                   width=350,
                                   font_size=12,
                                   border=2,
                                   relief='groove')
            count_Entry = Entry(master, textvariable=self.__count)
            count_Entry.place(x=(x_coor + 165),
                              y=(y_coor + 60),
                              width=350,
                              height=25)
            pass
        p_value_label = LabelTag(master,
                                 'P-Value', (x_coor + 520), (y_coor + 30),
                                 width=350,
                                 font_size=12,
                                 border=2,
                                 relief='groove')
        p_value_Entry = Entry(master, textvariable=self.__p_value)
        p_value_Entry.place(x=(x_coor + 520),
                            y=(y_coor + 60),
                            width=350,
                            height=25)
        conclusion_label = LabelTag(master,
                                    'Conclusion', (x_coor + 875),
                                    (y_coor + 30),
                                    width=150,
                                    font_size=12,
                                    border=2,
                                    relief='groove')
        conclusion_Entry = Entry(master, textvariable=self.__result)
        conclusion_Entry.place(x=(x_coor + 875),
                               y=(y_coor + 60),
                               width=150,
                               height=25)

        update_button = Button(master, text='Update', command=self.update)
        update_button.config(font=("Calibri", 10))
        update_button.place(x=(x_coor + 1030),
                            y=(y_coor + 60),
                            width=180,
                            height=25)

    def get_check_box_value(self):
        return self.__chb_var.get()

    def set_check_box_value(self, value):
        self.__chb_var.set(value)

    def set_results(self, results):
        self.__results = results
        self.update()

    def update(self):
        match = False
        for result in self.__results:
            if result[0] == self.__state.get():
                if self.__variant:
                    self.__count.set(result[2])
                else:
                    self.__xObs.set(result[2])

                self.__p_value.set(result[3])
                self.__result.set(self.get_result_string(result[4]))
                match = True

        if not match:
            if self.__variant:
                self.__count.set('')
            else:
                self.__xObs.set('')

            self.__p_value.set('')
            self.__result.set('')

    def get_result_string(self, result):
        if result == True:
            return 'Random'
        else:
            return 'Non-Random'

    def reset(self):
        self.__chb_var.set('0')
        if self.__variant:
            self.__state.set('-1.0')
            self.__count.set('')
        else:
            self.__state.set('+1')
            self.__xObs.set('')

        self.__p_value.set('')
        self.__result.set('')
class EnaSubOptionsForm(VerticalScrolledFrame):
        
    # Initialize the GUI
    def __init__(self, root):
        
        #Frame.__init__(self, root)
        VerticalScrolledFrame.__init__(self, root)
        
        root.title("Choose EMBL-ENA Submission Options")
        self.parent = root
        
        # Assign the icon of this sub-window.
        assignIcon(self.parent)

        #button_opt = {'fill': Tkconstants.BOTH, 'padx': 35, 'pady': 5}
        
        # To define the exit behavior.  Save and exit.
        self.parent.protocol('WM_DELETE_WINDOW', self.saveOptions)
        
        # Define the return behavior.  Same as "close window" etc
        root.bind('<Return>', self.returnFunction)
  
        # This window should not be resizeable. I guess.
        self.parent.resizable(width=False, height=False)
        
        #Standard Inputs widths for the form elements
        formInputWidth = 30
        labelInputWidth = 30
        
        self.instructionsFrame = Frame(self.interior)  
        self.instructionText = StringVar()       
        self.instructionText.set('\nProvide this required sequence metadata, please.\n' 
                + 'The Allele Local Name is provided by the submitting laboratory.\n'
                + 'You may name it similar to the closest known allele,\n'
                + 'if you wish.')        
        Label(self.instructionsFrame, width=85, height=6, textvariable=self.instructionText).pack()
        self.instructionsFrame.pack()
        
        self.submissionDetailsInputFrame2 = Frame(self.interior)
  
        self.sampleIDInstrText = StringVar()
        self.sampleIDInstrText.set('Sample ID:')
        self.sampleIDinstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.sampleIDInstrText).grid(row=0, column=0)
        self.inputSampleID = StringVar()
        self.inputSampleIDEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputSampleID).grid(row=0, column=1)

        self.geneInstrStringVar = StringVar()
        self.geneInstrStringVar.set('Gene:')
        self.geneInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.geneInstrStringVar).grid(row=1, column=0)
        self.inputGene = StringVar()        
        self.inputGeneEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputGene).grid(row=1, column=1)

        self.chooseClassIntVar = IntVar()
        self.chooseClassIntVar.set(1)
        Radiobutton(self.submissionDetailsInputFrame2, text="HLA Class I ", variable=self.chooseClassIntVar, value=1).grid(row=2, column=0)
        Radiobutton(self.submissionDetailsInputFrame2, text="HLA Class II", variable=self.chooseClassIntVar, value=2).grid(row=2, column=1)

        self.alleleInstrText = StringVar()
        self.alleleInstrText.set('Allele Local Name:')
        self.alleleInstrLabel = Label(self.submissionDetailsInputFrame2, width=labelInputWidth, height=1, textvariable=self.alleleInstrText).grid(row=3, column=0)
        self.inputAllele = StringVar() 
        self.inputAlleleEntry = Entry(self.submissionDetailsInputFrame2, width=formInputWidth, textvariable=self.inputAllele).grid(row=3, column=1)

        self.submissionDetailsInputFrame2.pack()
                
                
        # Make a frame to contain the Test/Production radio buttons.
        self.testProductionFrame = Frame(self.interior)
        
        self.testProductionInstrText = StringVar()
        self.testProductionInstrText.set('\nBy default, you submit to the EMBL-ENA test servers,\n'
            + 'where submissions are regularly deleted.\n'
            + 'change this option if you want to submit to the live environment.\n'
            + 'Login Credentials will not be stored, but they will be sent\n'
            + 'to EMBL-ENA via REST during allele submission.\n'
            )
        self.alleleInstrLabel = Label(self.testProductionFrame, width=70, height=7, textvariable=self.testProductionInstrText).pack()#.grid(row=2, column=0)
 
        # 1 = Test.  0 = Production/live server
        self.chooseTestServersIntVar = IntVar()
        # a short check in case the config value has not been implemented yet.
        if(getConfigurationValue('test_submission') is not None):        
            self.chooseTestServersIntVar.set(int(getConfigurationValue('test_submission')))
        else:
            self.chooseTestServersIntVar.set(1)
 
        Radiobutton(self.testProductionFrame, text="Submit to EMBL-ENA TEST / DEMO environment.", variable=self.chooseTestServersIntVar, value=1).pack()
        Radiobutton(self.testProductionFrame, text="Submit to EMBL-ENA LIVE / PROD environment.", variable=self.chooseTestServersIntVar, value=0).pack()
        
        self.testProductionFrame.pack()
     
        # Make a frame to contain the input variables
        self.submissionDetailsInputFrame = Frame(self.interior)

        self.usernameInstrText = StringVar()
        self.usernameInstrText.set('EMBL-ENA Username:'******'EMBL-ENA Password:'******'\nEMBL-ENA will store the sequence in an "Analysis" object.\n'
                + 'You must specify an analysis Alias, Title, and\n'
                + 'Description for every submitted sequence.\n'
                + 'The Alias must be unique.\n'
            )
        self.analysisMetadataLabel = Label(self.analysisOptionsInputFrame, width=70, height=5, textvariable=self.analysisMetadataInstrText).pack()#.grid(row=2, column=0)
        self.analysisOptionsInputFrame.pack()
       
        
        
        # Frame to specify Analysis Information
        self.newAnalysisFrame = Frame(self.interior)    
        
        self.analysisAliasInstrText = StringVar()
        self.analysisAliasInstrText.set('Analysis Alias:')
        self.analysisAliasInstrLabel = Label(self.newAnalysisFrame, width=labelInputWidth, height=1, textvariable=self.analysisAliasInstrText).grid(row=0, column=0)
        self.inputAnalysisAlias = StringVar()
        self.inputStudyIdEntry = Entry(self.newAnalysisFrame, width=formInputWidth, textvariable=self.inputAnalysisAlias).grid(row=0, column=1)

        self.analysisTitleInstrText = StringVar()
        self.analysisTitleInstrText.set('Analysis Title:')
        self.analysisTitleInstrLabel = Label(self.newAnalysisFrame, width=labelInputWidth, height=1, textvariable=self.analysisTitleInstrText).grid(row=1, column=0)
        self.inputAnalysisTitle = StringVar()
        self.inputAnalysisTitleEntry = Entry(self.newAnalysisFrame, width=formInputWidth, textvariable=self.inputAnalysisTitle).grid(row=1, column=1)

        self.analysisDescriptionInstrText = StringVar()
        self.analysisDescriptionInstrText.set('Analysis Description:')
        self.analysisDescriptionInstrLabel = Label(self.newAnalysisFrame, width=labelInputWidth, height=1, textvariable=self.analysisDescriptionInstrText).grid(row=2, column=0)
        self.inputAnalysisDescription = StringVar()
        self.inputAnalysisDescriptionEntry = Entry(self.newAnalysisFrame, width=formInputWidth, textvariable=self.inputAnalysisDescription).grid(row=2, column=1)
        
        self.newAnalysisFrame.pack()
       
        # A Frame for specifing the details of the Study / Project
        self.projectDetailsFrame = Frame(self.interior)
        
        self.alleleInstrText = StringVar()
        self.alleleInstrText.set('\nEMBL-ENA requires that submissions are assigned to a Study/Project.\n'
            + 'You must either:\n\n'
            + '1.) Provide an existing EMBL-ENA study/project accession #.\n'
            + 'This was provided in a previous submission, or you can see a list of\n'
            + 'your projects by logging into EMBL-ENA Webin. (ex. \'PRJEB01234\')\n'
            + '\n'
            + '2.) Specify metadata for a new study at EMBL-ENA.\n'
            + 'Provide an Identifier, Title, and short Abstract for the new Study,\n'
            + 'and I will create it automatically.\n'
            + 'Study Identifier must be Unique.'
            )
        self.alleleInstrLabel = Label(self.projectDetailsFrame, width=70, height=12, textvariable=self.alleleInstrText).pack()#.grid(row=2, column=0)
 
        self.chooseProjectIntVar = IntVar()
        self.chooseProjectIntVar.set(2)
 
        # A frame for the "new study" radio button
        self.existingProjectFrame = Frame(self.projectDetailsFrame)
        Radiobutton(self.existingProjectFrame, text="Use this study accession:", variable=self.chooseProjectIntVar, value=1).grid(row=0,column=0)
        self.inputStudyAccession = StringVar()
        self.inputStudyIdEntry = Entry(self.existingProjectFrame, width=formInputWidth, textvariable=self.inputStudyAccession).grid(row=0, column=1)
        self.existingProjectFrame.pack()
        
        
        # Filler Label
        Label(self.projectDetailsFrame, width=labelInputWidth, height=1, text=' ').pack()
        
        # This radio button is on the project details frame, but not 
        # on one of it's sub-frames (existingProjectFrame or newProjectFrame)  
        # That's so i can pack it, and not use a grid
        Radiobutton(self.projectDetailsFrame, text="Create a new study with this information:", variable=self.chooseProjectIntVar, value=2).pack()

        self.newProjectFrame = Frame(self.projectDetailsFrame)            

        self.studyIdInstrText = StringVar()
        self.studyIdInstrText.set('Short Study Identifier:')
        self.studyIdInstrLabel = Label(self.newProjectFrame, width=labelInputWidth, height=1, textvariable=self.studyIdInstrText).grid(row=0, column=0)
        self.inputStudyId = StringVar()
        self.inputStudyIdEntry = Entry(self.newProjectFrame, width=formInputWidth, textvariable=self.inputStudyId).grid(row=0, column=1)

        self.studyShortTitleInstrText = StringVar()
        self.studyShortTitleInstrText.set('Descriptive Study Title:')
        self.studyShortTitleInstrLabel = Label(self.newProjectFrame, width=labelInputWidth, height=1, textvariable=self.studyShortTitleInstrText).grid(row=1, column=0)
        self.inputStudyShortTitle = StringVar()
        self.inputStudyShortTitleEntry = Entry(self.newProjectFrame, width=formInputWidth, textvariable=self.inputStudyShortTitle).grid(row=1, column=1)

        self.studyAbstractInstrText = StringVar()
        self.studyAbstractInstrText.set('Study Description / Abstract:')
        self.studyAbstractInstrLabel = Label(self.newProjectFrame, width=labelInputWidth, height=1, textvariable=self.studyAbstractInstrText).grid(row=2, column=0)
        self.inputStudyAbstract = StringVar()
        self.inputStudyAbstractEntry = Entry(self.newProjectFrame, width=formInputWidth, textvariable=self.inputStudyAbstract).grid(row=2, column=1)
        
        self.newProjectFrame.pack()
        
        self.projectDetailsFrame.pack()

        # Make a frame for the save options button.
        self.saveOptionsFrame = Frame(self.interior)
        Button(self.saveOptionsFrame, text='Save Options', command=self.saveOptions).grid(row=0, column=0)
        self.saveOptionsFrame.pack()
        
        # TODO: Should there be a cancel button, to close this window without saving?
        
        self.loadOptions()

    # I needed a function for the return keypress to latch onto.
    # It is just a wrapper for the saveOptions method.
    def returnFunction(self, event):
        self.saveOptions()
       

    # submissionOptions is a dictionary, passed by the parent.
    def loadOptions(self):
        if getConfigurationValue('ena_username') is not None:
            self.inputUsername.set(getConfigurationValue('ena_username'))
            
        if getConfigurationValue('ena_password') is not None:
            self.inputPassword.set(getConfigurationValue('ena_password'))
            
        if getConfigurationValue('sample_id') is not None:
            self.inputSampleID.set(getConfigurationValue('sample_id'))
            
        if getConfigurationValue('gene') is not None:
            self.inputGene.set(getConfigurationValue('gene'))
            
        if getConfigurationValue('class') is not None:
            if (str(getConfigurationValue('class')) == '1'):
                self.chooseClassIntVar.set(1)
            elif (str(getConfigurationValue('class')) == '2'):
                self.chooseClassIntVar.set(2)
            else:
                raise Exception('Error loading EMBL-ENA submission options. Invalid class:' + str(getConfigurationValue('class')))
    
        if getConfigurationValue('allele_name') is not None:
            self.inputAllele.set(getConfigurationValue('allele_name'))
            
        if getConfigurationValue('choose_project') is not None:
            if (str(getConfigurationValue('choose_project')) == '1'):
                self.chooseProjectIntVar.set(1)
            elif (str(getConfigurationValue('choose_project')) == '2'):
                self.chooseProjectIntVar.set(2)
            else:
                raise Exception('Error loading EMBL-ENA submission options. Invalid Project choice:' + str(getConfigurationValue('choose_project')))
            
        if getConfigurationValue('study_accession') is not None:
            self.inputStudyAccession.set(getConfigurationValue('study_accession'))
            
        if getConfigurationValue('study_identifier') is not None:
            self.inputStudyId.set(getConfigurationValue('study_identifier'))
            
        if getConfigurationValue('study_short_title') is not None:
            self.inputStudyShortTitle.set(getConfigurationValue('study_short_title'))
            
        if getConfigurationValue('study_abstract') is not None:
            self.inputStudyAbstract.set(getConfigurationValue('study_abstract'))
            
        if getConfigurationValue('test_submission') is not None:
            # 1 = Test.  0 = Production/live server
            self.chooseTestServersIntVar.set(int(getConfigurationValue('test_submission')))
            
        if getConfigurationValue('analysis_alias') is not None:
            self.inputAnalysisAlias.set(getConfigurationValue('analysis_alias'))
        if getConfigurationValue('analysis_title') is not None:
            self.inputAnalysisTitle.set(getConfigurationValue('analysis_title'))
        if getConfigurationValue('analysis_description') is not None:
            self.inputAnalysisDescription.set(getConfigurationValue('analysis_description'))


    def saveOptions(self):
        # Close the window
        if (self.checkOptions()):
            logging.info ('Saving Options....')
            
            assignConfigurationValue('ena_username', self.inputUsername.get())
            # I store this password so I can use it in the submission
            # I don't ever want to save the password. Make sure it isn't being saved in the config, in AlleleSubCommon.py
            assignConfigurationValue('ena_password', self.inputPassword.get())
            assignConfigurationValue('sample_id', self.inputSampleID.get())
            assignConfigurationValue('gene', self.inputGene.get())
            assignConfigurationValue('class', str(self.chooseClassIntVar.get()))             
            assignConfigurationValue('allele_name', self.inputAllele.get())
            assignConfigurationValue('choose_project', str(self.chooseProjectIntVar.get()))    
            assignConfigurationValue('study_accession', self.inputStudyAccession.get())                    
            assignConfigurationValue('study_identifier', self.inputStudyId.get())            
            assignConfigurationValue('study_short_title', self.inputStudyShortTitle.get())
            assignConfigurationValue('study_abstract', self.inputStudyAbstract.get())
            assignConfigurationValue('test_submission', str(self.chooseTestServersIntVar.get()))
            assignConfigurationValue('analysis_alias', str(self.inputAnalysisAlias.get()))
            assignConfigurationValue('analysis_title', str(self.inputAnalysisTitle.get()))
            assignConfigurationValue('analysis_description', str(self.inputAnalysisDescription.get()))
            
            self.parent.destroy() 
            
        else:
            #logging.info('Not ready to save, you are missing options.')
            pass
        
    def checkOptions(self):
        
        # TODO: THis is really annoying. I should allow them to close this screen without providing all the information
        # Im sure a user will complain about this.
        
        #logging.info ('Checking options.')
       
        # Don't check the ena Username
        # Don't check the ena Password
        
        # TODO: I should be more strict with this enforcement.  I got rid of the False returns because it was too darn annoying.
        
        if (not self.inputSampleID.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing a Sample ID. Please try again.')
            #return False
            return True
        
        if (not self.inputGene.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing a Gene. Please try again.')
            #return False
            return True
        
        # Don't check the class boolean
        
        if (not self.inputAllele.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an Allele Name. Please try again.')
            #return False
            return True
        
        if (str(self.chooseProjectIntVar.get()) == '1'):
            # Use Existing Project
            if (not self.inputStudyAccession.get()):
                messagebox.showwarning('Missing Form Value',
                    'You are missing a Study Accession number. Please try again.')
                #return False
                return True
            
        elif(str(self.chooseProjectIntVar.get()) == '2'):
            # Use New Project
            if (not self.inputStudyId.get()):
                messagebox.showwarning('Missing Form Value',
                    'You are missing a Study Name. Please try again.')
                #return False
                return True
            
            if (not self.inputStudyShortTitle.get()):
                messagebox.showwarning('Missing Form Value',
                    'You are missing a Study Description. Please try again.')
                #return False
                return True
            
            
            if (not self.inputStudyAbstract.get()):
                messagebox.showwarning('Missing Form Value',
                    'You are missing a Study Accession number. Please try again.')
                #return False
                return True
            
        else:
            raise Exception ('Unknown value of self.chooseProjectIntVar. I expect 1 or 2. Observed:' + str(self.chooseProjectIntVar))
        
        
        if (not self.inputAnalysisAlias.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an Analysis Alias. Please try again.')
            #return False
            return True        
        
        if (not self.inputAnalysisTitle.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an Analysis Title. Please try again.')
            #return False
            return True        
        
        if (not self.inputAnalysisDescription.get()):
            messagebox.showwarning('Missing Form Value',
                'You are missing an Analysis Description. Please try again.')
            #return False
            return True
        
    

        # All options look good, right?
        
        
        return True
    
    
    def closeWindow(self):
        self.parent.destroy()        
Example #35
0
class App(Frame):
    """The main application."""
    def __init__(self, master=None, path="", flags=DEFAULT_FLAGS):
        """Initialize the frame."""
        # get the "path" keyword argument, unique to MyPanel2
        tc0_text = DEFAULT_FILE_TEXT

        if path:
            # expand to full pathname for current directory
            if not os.path.dirname(path):
                path = os.path.abspath(os.path.join(os.getcwd(), path))
            tc0_text = path

        # if no flags were passed, use the defaults
        if flags == (False, ) * 8:
            flags = DEFAULT_FLAGS

        Frame.__init__(self, master, relief=RAISED)
        self.pack(fill=BOTH)
        self._create_widgets()
        self._create_menubar()
        self._initialize(tc0_text, flags)

    def about_me(self):
        """Handle About..."""
        print("about_me")

    def log(self, _s):
        """Log this string _s to the frame and the console."""
        print("%s" % _s)
        self._e2.insert(END, "\n- " + _s)
        self._e2.see(END)

    ########################################################################

    def do_et(self, pathname, et_flag, html_flag):
        """Run the ET function."""
        # self.log("do_et: %s %s %s" % (pathname, et_flag, html_flag))
        self.log("Processing ET and/or HTML")

        et_options = Options()
        et_options.html = html_flag

        body = et.do_body2(pathname, index=MIN_INDEX, options=et_options)

        if et_flag:
            output_filename = "%s.csv" % pathname
            outfile = open(output_filename, "w")
            print(body, file=outfile)
            outfile.close()
            print("et output is in %s" % output_filename)

    ########################################################################

    def do_gpx2kml(self, pathname):
        """Create a KML file from the path data."""
        self.log("Processing gpx2hkml")

        input_filename = pathname
        output_filename = None
        gpx2kml.create_kml_file(input_filename, output_filename)

    ########################################################################

    def do_mr(self, pathname):
        """Process the pathname file using mr.py."""
        self.log(f"Processing mr: {pathname}")

        mr_options = Options()
        mr.process_arg(pathname, mr_options)

    ########################################################################

    def do_rooter(self, pathname):
        """Create a Rooter HTML File."""
        self.log("Creating Rooter file")

        rooter.do_rooter(pathname)  # , options=ro_options)

    ########################################################################

    def do_rtept(self, pathname):
        """Create a Streets & Trips Route GPX File.

        Arguments:
            pathname {[type]} -- [description]
        """
        try:
            self.log("do_rtept")
            output_filename = make_rtept.do_make_rtept(pathname)
            self.log("%s created" % output_filename)
        except Exception as _e:
            print(_e)
            self.log(traceback.format_exc())

    ########################################################################

    def do_gs(self, pathname):
        """Create a Cachly gpx File.

        Arguments:
            pathname {str} -- pathname
        """
        self.log("Creating Cachly file")
        try:
            make_gs.process_arg(pathname)
        except Exception as _e:
            print(_e)
            self.log(traceback.format_exc())

    ########################################################################

    def do_html_maps(self, pathname):
        """Create a HTML Maps File.

        Arguments:
            pathname {str} -- pathname
        """
        self.log("Creating HTML Maps file")
        try:
            make_html_maps.process_arg(pathname)
        except Exception as _e:
            print(_e)
            self.log(traceback.format_exc())

    ########################################################################

    def _create_widgets(self):
        self._s1 = StringVar()
        self._s2 = StringVar()
        self._v1 = IntVar()
        self._v2 = IntVar()
        self._v3 = IntVar()
        self._v4 = IntVar()
        self._v5 = IntVar()
        self._v6 = IntVar()
        self._v7 = IntVar()
        self._v8 = IntVar()

        self.lf1 = LabelFrame(self, text="Filename:")
        self.lf1.pack(fill=BOTH)

        self.lf2 = LabelFrame(self,
                              text="Processing choices: pick at least one")
        #       self.lf2.config(label="Processing choices: pick at least one")
        self.lf2.pack(fill=BOTH)

        self.lf3 = LabelFrame(self, text="Logging")
        #       self.lf3.config(label="Logging")
        self.lf3.pack(fill=BOTH)

        self._b1 = Button(self,
                          text="Run",
                          command=self.b1_callback,
                          default=ACTIVE)
        self._b1.pack(side="bottom")

        self._e1 = Entry(self.lf1, textvariable=self._s1)
        self._e1.pack(fill=BOTH)
        self._e1.bind("<Button-1>", self.e1_callback)

        self._e2 = Text(self.lf3, height=10, width=72, wrap=NONE)
        self._e2.pack(fill=BOTH)

        self._c1 = Checkbutton(self.lf2,
                               text="ET - generate Excel .csv output",
                               variable=self._v1)
        self._c1.pack(anchor=W)

        self._c2 = Checkbutton(self.lf2,
                               text="HTML - include HTML output from et.py",
                               variable=self._v2)
        self._c2.pack(anchor=W)

        self._c3 = Checkbutton(self.lf2,
                               text="KML - output for Google Earth",
                               variable=self._v3)
        self._c3.pack(anchor=W)

        self._c4 = Checkbutton(self.lf2,
                               text="MR - generate a .gpx route file",
                               variable=self._v4)
        self._c4.pack(anchor=W)

        self._c5 = Checkbutton(self.lf2,
                               text="ROOTER - generate a Rooter file",
                               variable=self._v5)
        self._c5.pack(anchor=W)

        self._c6 = Checkbutton(
            self.lf2,
            text="RTEPT - generate a Streets and Trips GPX _rtept file",
            variable=self._v6)
        self._c6.pack(anchor=W)

        self._c7 = Checkbutton(self.lf2,
                               text="Cachly - generate a Cachly file",
                               variable=self._v7)
        self._c7.pack(anchor=W)

        self._c8 = Checkbutton(self.lf2,
                               text="HTML Maps - generate a HTML Maps file",
                               variable=self._v8)
        self._c8.pack(anchor=W)

    def _create_menubar(self):
        self.menubar = Menu(self)

        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Quit", command=self.quit)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About Me", command=self.about_me)

        self.menubar.add_cascade(label="File", menu=self.filemenu)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

#       self.master.config(menu=self.menubar)

    def _initialize(self, tc0_text, flags):
        self._s1.set(tc0_text)
        self._s2.set("Logging")
        self._v1.set(flags[0])
        self._v2.set(flags[1])
        self._v3.set(flags[2])
        self._v4.set(flags[3])
        self._v5.set(flags[4])
        self._v6.set(flags[5])
        self._v7.set(flags[6])
        self._v8.set(flags[7])

    def b1_callback(self):
        """Handle the callback operation of the  _b1 button."""
        print(
            '"%s"' % self._e1.get(),
            self._v1.get(),
            self._v2.get(),
            self._v3.get(),
            self._v4.get(),
            self._v5.get(),
            self._v6.get(),
            self._v7.get(),
            self._v8.get(),
        )

        if self._s1.get() == DEFAULT_FILE_TEXT:
            self.e1_callback(None)
            return
        else:
            print("Process %s" % self._s1.get())
            _d = {
                "pathname": self._s1.get(),
                "et_flag": self._v1.get(),
                "html_flag": self._v2.get(),
                "kml_flag": self._v3.get(),
                "mr_flag": self._v4.get(),
                "ro_flag": self._v5.get(),
                "rtept_flag": self._v6.get(),
                "gs_flag": self._v7.get(),
                "hm_flag": self._v8.get(),
            }
            self.process_parameters(**_d)
            self.after_idle(self._shutdown)

    def _shutdown(self):
        """Shutdown after three seconds."""
        self.after(3000, self.quit())

    def e1_callback(self, _event):
        """Handle the callback function for _e1."""
        # print("e1_callback", "%s" % event)
        filename = tkFileDialog.askopenfilename(filetypes=(("gpx files",
                                                            "*.gpx"),
                                                           ("all files",
                                                            "*.*")))
        if filename:
            self._s1.set(filename)

    def process_parameters(self,
                           pathname="",
                           et_flag=True,
                           html_flag=False,
                           kml_flag=True,
                           mr_flag=True,
                           ro_flag=True,
                           rtept_flag=True,
                           gs_flag=True,
                           hm_flag=False):
        """Perform the processing specified by pathname and flags."""
        # print(
        #     "et_flag:", et_flag, "\n",
        #     "html_flag:", html_flag, "\n",
        #     "kml_flag:", kml_flag, "\n",
        #     "mr_flag:", mr_flag, "\n",
        #     "ro_flag:", ro_flag, "\n",
        #     "rtept_flag:", rtept_flag, "\n",
        #     "gs_flag:", gs_flag, "\n",
        #     "hm_flag:", hm_flag, "\n",
        # )

        self.log("Reading from %s" % pathname)

        if not (et_flag or html_flag or kml_flag or mr_flag or ro_flag
                or rtept_flag or gs_flag or hm_flag):
            self.log("ERROR: Nothing to do: no flags set")
            return

        # perform the processing
        if et_flag or html_flag:
            self.do_et(pathname, et_flag=et_flag, html_flag=html_flag)

        if kml_flag:
            self.do_gpx2kml(pathname)

        if mr_flag:
            self.do_mr(pathname)

        if ro_flag:
            self.do_rooter(pathname)

        if rtept_flag:
            self.log("rtept_flag: %s" % pathname)
            self.do_rtept(pathname)

        if gs_flag:
            self.do_gs(pathname)

        if hm_flag:
            self.do_html_maps(pathname)

        self.log("Done!")
Example #36
0
    myDirDesc.set('Directory:')

    lblDirDesc = tk.Label(frame, textvariable=myDirDesc)
    lblDirDesc.grid(column=0, row=3, pady=myPady)

    lblDir = tk.Label(frame, textvariable=myDir)
    lblDir.grid(column=0, row=4, pady=myPady)

    global btnDir
    btnDir = tk.Button(frame, text="Select Dir", command=selectDir)

    btnDir.grid(column=0, row=5, pady=myPady)

    # radioButtons
    var = IntVar()
    var.set(1)  # Set option 1 as default

    global rb2Stems
    rb2Stems = tk.Radiobutton(root,
                              text="Vocals/accompaniment (2 stems)",
                              variable=var,
                              value=1)
    rb2Stems.place(relwidth=0.5, relheight=0.1, relx=0.25, rely=0.55)

    global rb4Stems
    rb4Stems = tk.Radiobutton(root,
                              text="Vocals/drums/bass/other (4 stems)",
                              variable=var,
                              value=2)
    rb4Stems.place(relwidth=0.5, relheight=0.1, relx=0.25, rely=0.65)
Example #37
0
city_info.pack(pady=(3, 0))
whether_lab.pack(pady=(0, 2))
temp_label.pack(pady=(0, 2))
feelslike_lab.pack(pady=(0, 2))
tempmin_lab.pack(pady=(0, 2))
tempmax_lab.pack(pady=(0, 1))
humidity_lab.pack()
iconlab.pack(pady=8)

# input frame
city_entry = tkinter.Entry(input_frame, width=20, font=large_font)
submit_button = tkinter.Button(
    input_frame, text='Submit', font=large_font, bg=input_color, command=search)

search_method = IntVar()
search_method.set(1)
search_city = tkinter.Radiobutton(input_frame, text='Search By City Name',
                                  variable=search_method, value=1, font=small_font, bg=input_color)
search_zip = tkinter.Radiobutton(input_frame, text='Search By Zip Code',
                                 variable=search_method, value=2, font=small_font, bg=input_color)

city_entry.grid(row=0, column=0, padx=10, pady=(10, 0))
submit_button.grid(row=0, column=1, padx=10,
                   pady=(10, 0), sticky='e', ipadx=15)
search_city.grid(row=1, column=0, pady=2, sticky='w')
search_zip.grid(row=1, column=0, pady=2, padx=5, sticky='e', columnspan=2)


# run the windows main loop
root.mainloop()
class TilesetCreator(Frame):
    """
    Converts smaller individual tiles into one tileset image
    Will not keep aspect ratio so ensure that images are the correct aspect ratio before running
    """
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.open_dir = StringVar()
        self.tile_width = IntVar()
        self.tile_height = IntVar()
        self.output_dir = StringVar()

        self.init_ui()

    def init_ui(self):
        """
        Initializes all the widgets and UI elements
        :return: None
        """
        # Configure the frame
        self.parent.title("Tileset Creator")
        self.parent.config(padx=4, pady=4)
        self.parent.resizable(0, 0)

        # Create the main widgets
        # Tile Width
        Label(self.parent, text="Tile Width: ").grid(row=0,
                                                     column=0,
                                                     columnspan=2)
        Entry(self.parent, width=3,
              textvariable=self.tile_width).grid(row=1, column=0, columnspan=2)
        self.tile_width.set(32)

        # Tile Height
        Label(self.parent, text="Tile Height: ").grid(row=2,
                                                      column=0,
                                                      columnspan=2)
        Entry(self.parent, width=3,
              textvariable=self.tile_height).grid(row=3,
                                                  column=0,
                                                  columnspan=2)
        self.tile_height.set(32)

        # Image Directory
        Label(self.parent, text="Image Directory: ").grid(row=4,
                                                          column=0,
                                                          columnspan=2)
        Entry(self.parent, width=32, textvariable=self.open_dir).grid(row=5,
                                                                      column=0)
        Button(self.parent, text="...",
               command=self.choose_in_dir).grid(row=5, column=1)

        # Output Directory
        Label(self.parent, text="Output Directory: ").grid(row=6,
                                                           column=0,
                                                           columnspan=2)
        Entry(self.parent, width=32,
              textvariable=self.output_dir).grid(row=7, column=0)
        Button(self.parent, text="...",
               command=self.choose_out_dir).grid(row=7, column=1)

        # Action button
        Button(self.parent, text="Create Tileset",
               command=self.create_tileset).grid(row=8, column=0, columnspan=2)

    def choose_in_dir(self):
        """
        Opens the Tkinter choose dir dialog and then sets the dir entry to the directory chosen
        :return: None
        """
        directory = filedialog.askdirectory()
        self.open_dir.set(directory)

    def choose_out_dir(self):
        """
        Opens the Tkinter choose dir dialog and then sets the output dir entry to the directory chosen
        :return: None
        """
        directory = filedialog.askdirectory()
        self.output_dir.set(directory)

    def create_tileset(self):
        """
        Create the tileset image by opening each of the tile images, resizing them to the appropriate size and then
        placing them in a larger image
        :return: None
        """
        # Ensure the directory isn't empty
        if self.open_dir.get() is None or self.open_dir.get() == "":
            showerror("Error", "Invalid directory selected")
            return

        file_count = 0
        for file in os.listdir(self.open_dir.get()):
            if file.endswith(".png") or file.endswith(".jpg"):
                file_count += 1

        # Ensure there are actual files
        if file_count <= 0:
            showerror("Error", "Could not find any .png or .jpg files")
            return

        # Amount of tiles across and down (total tiles = tiles * tiles)
        tiles = int(ceil(sqrt(file_count)))

        # Create the parent image for the tileset (where the tiles will be pasted)
        image_width = tiles * self.tile_width.get()
        image_height = tiles * self.tile_height.get()
        tileset = Image.new("RGBA", (image_width, image_height), "white")

        # Loop through all the images and paste them into the appropriate positions in the tileset
        row = 0
        column = 0
        for file in os.listdir(self.open_dir.get()):

            # Only worried about images ending with common formats (jpg and png)
            if file.endswith(".png") or file.endswith(".jpg"):

                # Open the image and scale down using LANCZOS (best scaling, poor performance)
                tile = Image.open(self.open_dir.get() + "/" + file)
                tile = tile.resize(
                    (self.tile_width.get(), self.tile_height.get()),
                    Image.LANCZOS)

                # Paste the tile into the tileset
                y_pos = int(column * self.tile_width.get())
                x_pos = int(row * self.tile_height.get())
                tileset.paste(tile, (y_pos, x_pos))

                # Handle coordinate changes
                column += 1
                if column > tiles:
                    column = 0
                    row += 1

        # Save the output to the same directory this script was run
        outfile = self.output_dir.get() + "/tileset.png"
        tileset.save(outfile, "png")
        messagebox.showinfo("Complete", "Tileset saved to " + outfile)
def main(task_field,task_tree,progress):
    print('here')
    Head_data_file=open(repositroy_url+'/Head_data_file.txt','r')
    state=''
    state_name=''
    task_field.config(state='normal')
    task_field.replace(1.0,END,'Clearing neo4j nodes...')
    task_field.config(state='disabled')
    task_tree.config(state='normal')
    task_tree.replace(1.0,END,'Working...')
    task_tree.config(state='disabled')
    graph.cypher.execute("MATCH(n) OPTIONAL MATCH(n)-[r]->() DELETE n,r")
    global file_exit_flag
    task_field.config(state='normal')
    task_field.replace(1.0,END,'Graph database creation in progress...')
    task_field.config(state='disabled')
    progress_count=IntVar()
    progress.config(mode='determinate',maximum=file_download_count,value=0,variable=progress_count)
    graph.cypher.execute('MERGE(c:Country{country_name:"India",label_name:"Country"})')
    country_name=graph.find_one("Country",'country_name',"India")
    while file_exit_flag and not kill_flag:
        Head_data_read=Head_data_file.readline()
        if(Head_data_read!=''):
            #print(Head_data_read)
            #print(Head_data_read)
            if(Head_data_read=='STATE\n') and not kill_flag:
                Head_data_read=Head_data_file.readline()
                state_name=Head_data_read.replace('\n','')
                task_tree.config(state='normal')
                task_tree.replace(1.0,END,'Updating database for state-'+state_name+'\n')
                task_tree.config(state='disabled')
                print('State-'+state_name)
                #state=Node("State",state_name=state_name,label_name="State")
                #graph.create(state,Relationship(country_name,"CONTAIN",0))
                graph.cypher.execute('MERGE(s:State{state_name:"'+state_name+'",label_name:"State"})')
                state=graph.find_one("State","state_name",state_name)
                graph.create(Relationship(country_name,"CONTAIN",state))
            else:
                if(Head_data_read=='FILE NAME START HERE\n') and not kill_flag:
                    while(Head_data_read!='FILE NAME END HERE\n'):
                        Head_data_read=Head_data_file.readline()
                        if(Head_data_read!='FILE NAME END HERE\n'):
                            region=Head_data_read.replace('\n','')
                            task_tree.config(state='normal')
                            task_tree.insert(END,'Updating region-'+region+'\n')
                            print('Region-'+region)
                            region_file_name=Head_data_file.readline()
                            #print(region)#region_file_name.split('.csv')[0])
                            data_parser(region,region_file_name.split('.csv')[0],state,state_name,progress_count)
                            global count
                            count+=1
                            progress_count.set(count)

                #print('done')
                #Head_data_read=Head_data_file.readline()
        else:
            file_exit_flag=False
        #data_parser(repositroy_url)
    task_field.config(state='normal')
    task_tree.config(state='normal')
    task_field.replace(1.0,END,'Database creation is complete!')
    task_tree.replace(1.0,END,'Database updated!')
    task_field.config(state='disabled')
    task_field.config(state='disabled')
#if __name__=='__main__':main()
Example #40
0
File: tree.py Project: DrDub/nltk
class TreeView(object):
    def __init__(self, *trees):
        from math import sqrt, ceil

        self._trees = trees

        self._top = Tk()
        self._top.title('NLTK')
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Control-q>', self.destroy)

        cf = self._cframe = CanvasFrame(self._top)
        self._top.bind('<Control-p>', self._cframe.print_to_file)

        # Size is variable.
        self._size = IntVar(self._top)
        self._size.set(12)
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())

        # Lay the trees out in a square.
        self._width = int(ceil(sqrt(len(trees))))
        self._widgets = []
        for i in range(len(trees)):
            widget = TreeWidget(cf.canvas(), trees[i], node_font=bold,
                                leaf_color='#008040', node_color='#004080',
                                roof_color='#004040', roof_fill='white',
                                line_color='#004040', draggable=1,
                                leaf_font=helv)
            widget.bind_click_trees(widget.toggle_collapsed)
            self._widgets.append(widget)
            cf.add_widget(widget, 0, 0)

        self._layout()
        self._cframe.pack(expand=1, fill='both')
        self._init_menubar()

    def _layout(self):
        i = x = y = ymax = 0
        width = self._width
        for i in range(len(self._widgets)):
            widget = self._widgets[i]
            (oldx, oldy) = widget.bbox()[:2]
            if i % width == 0:
                y = ymax
                x = 0
            widget.move(x-oldx, y-oldy)
            x = widget.bbox()[2] + 10
            ymax = max(ymax, widget.bbox()[3] + 10)

    def _init_menubar(self):
        menubar = Menu(self._top)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self._cframe.print_to_file,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        zoommenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        zoommenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        zoommenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=28, command=self.resize)
        zoommenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=50, command=self.resize)
        menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu)

        self._top.config(menu=menubar)

    def resize(self, *e):
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())
        xspace = self._size.get()
        yspace = self._size.get()
        for widget in self._widgets:
            widget['node_font'] = bold
            widget['leaf_font'] = helv
            widget['xspace'] = xspace
            widget['yspace'] = yspace
            if self._size.get() < 20: widget['line_width'] = 1
            elif self._size.get() < 30: widget['line_width'] = 2
            else: widget['line_width'] = 3
        self._layout()

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)
Example #41
0
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkinter.font.Font(family='helvetica',
                                    size=self._size.get())
        if self._size.get() < 0: big = self._size.get()-2
        else: big = self._size.get()+2
        self._bigfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(buttonframe, text='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Autostep',
               background='#90c0d0', foreground='black',
               command=self.autostep,).pack(side='left')
        Button(buttonframe, text='Expand', underline=0,
               background='#90f090', foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe, text='Match', underline=0,
               background='#90f090', foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe, text='Backtrack', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
        self._redraw()

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   #width=525, height=250,
                                   closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match', underline=0,
                             command=self.match, accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand', underline=0,
                             command=self.expand, accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack', underline=0,
                             command=self.backtrack, accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=10, accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=5, accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=2, accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc: widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.label()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {'tree_color': '#000000', 'tree_width': 2,
                   'node_font': bold, 'leaf_font': helv,}
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [TextWidget(canvas, word, font=self._font)
                             for word in self._sent]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom-twidget.bbox()[3]-5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()


    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index, ' %s (TRIED)' %
                                          productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().label().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees(): leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e): self._autostep = 0; self._step()
    def match(self, *e): self._autostep = 0; self._match()
    def expand(self, *e): self._autostep = 0; self._expand()
    def backtrack(self, *e): self._autostep = 0; self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return 0

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return 0

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return 1
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return 0

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size+2)))
        self._redraw()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas, tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2, tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.label()['color'] = '#20a050'

        (oldx, oldy) = oldtree.label().bbox()[:2]
        (newx, newy) = widget.label().bbox()[:2]
        widget.move(oldx-newx, oldy-newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30-widget.label().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.label().width()/2 -
                  widget.subtrees()[0].bbox()[0]/2 -
                  widget.subtrees()[0].bbox()[2]/2)
            for subtree in widget.subtrees(): subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = ['gray%d' % (10*int(10*x/self._animation_frames.get()))
                  for x in range(self._animation_frames.get(),0,-1)]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets: twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index+1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings: sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index-1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame,
                            widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.label()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get())))
                   for x in range(1, self._animation_frames.get()+1)]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.label())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets: widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame,
                            widgets, colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().label()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame,
                            frame-1, widget, dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame,
                            frame-1, widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split() #[XX] use tagged?
        self.reset()
Example #42
0
class App:
    def __init__(self, master):
        self.initDone = False
        self.initGuiData()
        self.master = master
        self.master.title("Hot wire cutter (version 0.1.f)")
        self.nb = ttk.Notebook(self.master)
        self.nb.enable_traversal()
        self.queueTkSendMsg = queue.Queue()
        self._thread_cmd = threading.Thread(target=self.execCmd,
                                            args=(self.queueTkSendMsg, "rien"))
        self._thread_cmd.setDaemon(
            True
        )  #added by mstrens in order to kill automatically the thread when program close
        self._thread_cmd.start()

        self.queueTkGetMsg = queue.Queue()
        self.tGrbl = Grbl(
            self.nb, self, self.queueTkGetMsg
        )  #create an instance of Gerbil in order to communicate with GRBL
        # queue is used to get message back from interface

        self.tProfil = Profil(self.nb,
                              self)  #add a tab for selecting the profile
        self.tTransform = Transform(self.nb,
                                    self)  #add a tab to modify the profile
        self.tBloc = Bloc(self.nb,
                          self)  #add a tab to design the wing and the bloc
        self.tMargin = Margin(self.nb,
                              self)  #add a tab to design the vertical margin
        self.tMaterial = Material(self.nb,
                                  self)  #add a tab to specify the material
        self.tGuillotine = Guillotine(
            self.nb, self, self.queueTkSendMsg)  #add a tab to make guillotine
        self.tCut = Cut(self.nb, self)  #add a tab to cut
        self.tTable = Table(self.nb,
                            self)  #add a tab to define the Table (size)
        self.nb.pack()
        atexit.register(self.tGrbl.disconnectToGrbl)
        self.initDone = True
        self.running = True

        self.periodicCall()
        self.validateAllOn = True
        self.validateAll(0)  #validate all

        #self.tBloc.toTableRight.set(self.tTable.dY.get() - self.tTable.lG.get() - self.tTable.lD.get() - self.tBloc.toTableLeft.get() - self.tBloc.lX.get() )
        #print (self.tBloc.toTableRight.get())

    def execCmd(self, queue, rien):
        """
        thread in order to execute task outside the main tkhtread (when they can take to much time e.g.)
        get Cmd via a queue queueTkSendMsg
        used e.g. when a button is clicked in Thinker
        not sure it is really requested for this application
        """
        while True:
            msg = queue.get()
            if msg == "Connect":
                self.tGrbl.connectToGrbl()
                self.tGuillotine.updateBtnState()
            elif msg == "Disconnect":
                self.tGrbl.disconnectToGrbl()
                self.tGuillotine.updateBtnState()

    def processIncoming(self):
        """Handle all messages currently in the queue, if any."""
        while self.queueTkGetMsg.qsize():
            try:
                msg = self.queueTkGetMsg.get(0) + "\n"
                # Check contents of message and do whatever is needed. As a
                # simple test, print it (in real life, you would
                # suitably update the GUI's display in a richer fashion).
                #print("getting a message in queue",msg)
                self.tGuillotine.msgBox.insert(END, msg)
            except queue.Empty:
                # just on general principles, although we don't
                # expect this branch to be taken in this case
                pass

    def periodicCall(self):
        """
        Check every 200 ms if there is something new in the queue.
        execute it when tkinter is sleeping
        """
        self.processIncoming()
        if not self.running:
            # This is the brutal stop of the system. You may want to do
            # some cleanup before actually shutting it down.
            #import sys
            #sys.exit(1)
            pass
        self.master.after(200, self.periodicCall)

    #def calback(self, a , b, c):
    #    print("do something")

    def initGuiData(self):
        #not saved with config
        self.validateAllOn = False
        self.warningMsg = StringVar(value="")
        self.cutMsg = StringVar(value="")
        self.limMinX = DoubleVar(
            value='0.0')  # min value to plot on X axis (not saved in .ini)
        self.limMinY = DoubleVar(
            value='0.0')  # min value to plot on Y axis (not saved in .ini)
        self.zoom = StringVar(value="1X")
        #self.zoom.trace('w', self.calback)
        self.configUploadFileName = None
        self.tableUploadFileName = None
        self.tableSaveFileName = None
        self.materialUploadFileName = None
        self.materialSaveFileName = None
        self.connected = StringVar(value="OFF")
        self.grblStatus = StringVar(value="Not connected")
        self.grblXG = DoubleVar(value="0")  #grbl horizontal left pos
        self.grblYG = DoubleVar(value="0")  #grbl vertical left pos
        self.grblXD = DoubleVar(value="0")  #grbl horizontal right pos
        self.grblYD = DoubleVar(value="0")  #grbl vertical right pos
        self.grblF = DoubleVar(value="0")  #grbl feed rate
        self.grblS = DoubleVar(value="0")  #grbl heating
        self.gMoveAxis = StringVar(
            value="Both")  # grbl axis to move (left,right)
        self.gMoveDist = DoubleVar(value="10")  #grbl mistance to move
        # Transformed profil based on original (filled by validateTransform) ; is an numpy array and not a usual List
        #take care of Chord, but not of position of block and margins...
        self.tRootX = np.array([])
        self.tRootY = np.array([])
        self.tRootS = []
        self.tTipX = np.array([])
        self.tTipY = np.array([])
        self.tTipS = []
        # Position profil (in a numpy array) based on "t" profile and position of block and margins...
        self.pRootX = np.array([])
        self.pRootY = np.array([])
        self.pRootS = []
        self.pTipX = np.array([])
        self.pTipY = np.array([])
        self.pTipS = []
        #guillotine
        self.gVSpeedNoCut = DoubleVar(value='5')
        self.gHSpeedNoCut = DoubleVar(value='5')
        self.gCuttingSpeed = DoubleVar(value='5')
        self.gApplyCalculatedHeating = IntVar(value='1')
        self.gHeating = DoubleVar(value='50')
        self.gType = StringVar(value="Vertical")
        self.gCuttingWhile = StringVar(value="Both")
        #self.gHeatWhileArming = IntVar(value='1')
        self.gVDist = DoubleVar(value='10')
        self.gHDist = DoubleVar(value='10')

        #saved in config
        #profil
        self.oRootX = [
        ]  # original profil : usual python List ; saved in the files
        self.oRootY = []
        self.oRootS = []  # synchro points
        self.oTipX = []
        self.oTipY = []
        self.oTipS = []
        self.nameRoot = StringVar(value="")
        self.nameTip = StringVar(value="")
        #transform
        self.cRoot = DoubleVar(value='200.0')  #chord
        self.cTip = DoubleVar(value='150.0')  #chord
        self.incidenceRoot = DoubleVar(value='0.0')
        self.thicknessRoot = DoubleVar(value='100.0')
        self.vInvertRoot = IntVar(value='0')
        self.incidenceTip = DoubleVar(value='0.0')
        self.thicknessTip = DoubleVar(value='100.0')
        self.vInvertTip = IntVar(value='0')
        self.covering = DoubleVar(value='0.0')
        self.keepChord = IntVar(value='0')
        self.smooth = IntVar(value='0')
        self.nbrPoints = IntVar(value='50')
        self.repartition = DoubleVar(value='2.0')
        self.reducePoints = IntVar(value='0')

        #bloc
        self.blocLX = DoubleVar(value='600.0')  #Length = envergure
        self.blocHZ = DoubleVar(value='50.0')  #height of the bloc
        self.fLeading = DoubleVar(value='10.0')  #fleche
        self.fTrailing = DoubleVar(
            value='-30'
        )  #self.cRoot.get() - self.cTip.get() - self.fLeading.get()) #calculated
        self.mLeading = DoubleVar(value='5.0')
        self.mTrailingRoot = DoubleVar(value='10.0')
        self.mTrailingTip = DoubleVar(value='10.0')
        self.leftRightWing = StringVar(value='Left')
        self.blocPosition = StringVar(value='Left')  #Left or Right position
        self.blocToTableLeft = DoubleVar(
            value='100.0')  #calculated but depend on bloc position
        self.blocToTableRight = DoubleVar(
            value='10.0')  #calculated but depend on bloc position
        self.blocToTableTrailingRoot = IntVar(value='50')
        self.blocToTableTrailingTip = IntVar(value='50')  #calculated
        self.blocToTableLeadingRoot = IntVar(value='50')  #calculated
        self.blocToTableLeadingTip = IntVar(value='50')  #calculated
        #margin
        self.hTrailingRoot = DoubleVar(value='10.0')
        self.hTrailingTip = DoubleVar(value='10.0')  #calculated
        self.hLeadingRoot = DoubleVar(value='10.0')  #calculated
        self.hLeadingTip = DoubleVar(value='10.0')  #calculated
        self.hMaxRoot = DoubleVar(value='10.0')  #calculated
        self.hMaxTip = DoubleVar(value='10.0')  #calculated
        self.hMinRoot = DoubleVar(value='10.0')  #calculated
        self.hMinTip = DoubleVar(value='10.0')  #calculated
        self.hOffset = DoubleVar(value='10.0')  #heigh of the base of the bloc
        self.alignProfil = StringVar(value="Trailing")
        self.hProfil = DoubleVar(
            value='20.0')  #heigh of the profile in the bloc
        self.angleInRoot = DoubleVar(value='0.0')
        self.angleInTip = DoubleVar(value='0.0')
        self.angleOutRoot = DoubleVar(value='0.0')
        self.angleOutTip = DoubleVar(value='0.0')
        """
        self.hMaxRootNorm = 0
        self.hMinRootNorm = 0
        self.hLeadingRootNorm = 0
        self.hMaxTipNorm = 0
        self.hMinTipNorm = 0
        self.hLeadingTipNorm = 0
        """
        #Material
        self.mSpeedHigh = DoubleVar(value='10.0')  #speed max
        self.mSpeedHalf = DoubleVar(value='5.0')  #speed min
        self.mSpeedLow = DoubleVar(value='1.0')  #speed min
        self.mRadSpHigh = DoubleVar(value='0.9')  #Radiance at high max
        self.mRadSpHalf = DoubleVar(value='1.5')  #Radiance at half speed
        self.mHeatSpHigh = IntVar(value='90')  #Heat at High speed
        self.mHeatSpLow = IntVar(value='40')  #Heat at low speed
        self.mName = StringVar(value="No material name")
        #table
        self.tableYY = DoubleVar(value='1000.0')  # distance between 2 axis
        self.tableYG = DoubleVar(
            value='20.0')  #distance between left Y axis and left table edge
        self.tableYD = DoubleVar(value='20.0')  # same on the rigth side
        self.cMaxY = DoubleVar(value='500.0')  # max course in Y
        self.cMaxZ = DoubleVar(value='200.0')  # max course in Z (height)
        self.vMaxY = DoubleVar(value='10.0')  # max speed in Y
        self.vMaxZ = DoubleVar(value='5.0')  # max speed in Z (height)
        self.tHeatingMax = DoubleVar(value='100.0')  # max heating
        self.tName = StringVar(value="No table name")
        #self.tComPort = StringVar(value="Select a Com port")
        self.tComPort = StringVar(value="COM6")
        self.tBaudrate = StringVar(value="115200")
        self.tPreHeat = DoubleVar(value='5.0')  # delay between Heat and move
        self.tPostHeat = DoubleVar(value='5.0')  # delay between Move and Heat

        #cut
        self.vCut = DoubleVar(
            value='2.0'
        )  # max speed for cutting (on root or tip depending the longest)
        self.gCodeStart1 = StringVar(value="")
        self.gCodeStart2 = StringVar(value="")
        self.gCodeStart3 = StringVar(value="")
        self.gCodeStart4 = StringVar(value="")
        self.gCodeEnd1 = StringVar(value="")
        self.gCodeEnd2 = StringVar(value="")
        self.gCodeEnd3 = StringVar(value="")
        self.gCodeEnd4 = StringVar(value="")
        self.gCodeLetters = StringVar(value="XYZA")

        #self.validatePart()

    def uploadConfig(self):
        #global configUploadFileName
        #configUploadFileName = filedialog.askopenfilename(initialdir="C:/Data/",
        self.configUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Ini files", "*.ini"),("All files","*.*")),
                            title = "Choose a file."
                            )
        if len(self.configUploadFileName) > 0:
            self.validateAllOn = False
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Profil")
            config.add_section("Transform")
            config.add_section("Bloc")
            config.add_section("Material")
            config.add_section("Table")
            config.add_section("Cut")
            config.add_section("Guillotine")

            config.read(self.configUploadFileName)
            self.oRootX = stringToListOfFloat(config.get("Profil", "RootX"))
            self.oRootY = stringToListOfFloat(config.get("Profil", "RootY"))
            self.oRootS = stringToListOfFloat(config.get("Profil", "RootS"))
            self.oTipX = stringToListOfFloat(config.get("Profil", "TipX"))
            self.oTipY = stringToListOfFloat(config.get("Profil", "TipY"))
            self.oTipS = stringToListOfFloat(config.get("Profil", "TipS"))
            self.nameRoot.set(value=config.get("Profil", "nameRoot"))
            self.nameTip.set(value=config.get("Profil", "nameTip"))

            self.cRoot.set(value=config.getfloat("Transform", "cRoot"))
            self.cTip.set(value=config.getfloat("Transform", "cTip"))
            self.incidenceRoot.set(
                value=config.getfloat("Transform", "incidenceRoot"))
            self.thicknessRoot.set(
                value=config.getfloat("Transform", "thicknessRoot"))
            self.vInvertRoot.set(
                value=config.getint("Transform", "vInvertRoot"))
            self.incidenceTip.set(
                value=config.getfloat("Transform", "incidenceTip"))
            self.thicknessTip.set(
                value=config.getfloat("Transform", "thicknessTip"))
            self.vInvertTip.set(value=config.getint("Transform", "vInvertTip"))
            self.covering.set(value=config.getfloat("Transform", "covering"))
            self.keepChord.set(value=config.getint("Transform", "keepChord"))
            self.smooth.set(value=config.getint("Transform", "smooth"))
            self.nbrPoints.set(value=config.getint("Transform", "nbrPoints"))
            self.repartition.set(
                value=config.getfloat("Transform", "repartition"))
            self.reducePoints.set(
                value=config.getint("Transform", "reducePoints"))

            self.blocLX.set(value=config.getfloat("Bloc", "blocLX"))
            self.blocHZ.set(value=config.getfloat("Bloc", "blocHZ"))
            self.fLeading.set(value=config.getfloat("Bloc", "fLeading"))
            self.mLeading.set(value=config.getfloat("Bloc", "mLeading"))
            self.mTrailingRoot.set(
                value=config.getfloat("Bloc", "mTrailingRoot"))
            self.mTrailingTip.set(
                value=config.getfloat("Bloc", "mTrailingTip"))
            self.leftRightWing.set(value=config.get("Bloc", "leftRightWing"))
            self.blocPosition.set(value=config.get("Bloc", "blocPosition"))
            self.blocToTableLeft.set(
                value=config.getfloat("Bloc", "blocToTableLeft"))
            self.blocToTableRight.set(
                value=config.getfloat("Bloc", "blocToTableRight"))
            self.blocToTableTrailingRoot.set(
                value=config.getint("Bloc", "blocToTableTrailingRoot"))
            self.blocToTableTrailingTip.set(
                value=config.getint("Bloc", "blocToTableTrailingTip"))
            self.blocToTableLeadingRoot.set(
                value=config.getint("Bloc", "blocToTableLeadingRoot"))
            self.blocToTableLeadingTip.set(
                value=config.getint("Bloc", "blocToTableLeadingTip"))

            self.hTrailingRoot.set(
                value=config.getfloat("Bloc", "hTrailingRoot"))
            self.hTrailingTip.set(
                value=config.getfloat("Bloc", "hTrailingTip"))
            self.hLeadingRoot.set(
                value=config.getfloat("Bloc", "hLeadingRoot"))
            self.hLeadingTip.set(value=config.getfloat("Bloc", "hLeadingTip"))
            self.hMaxRoot.set(value=config.getfloat("Bloc", "hMaxRoot"))
            self.hMaxTip.set(value=config.getfloat("Bloc", "hMaxTip"))
            self.hMinRoot.set(value=config.getfloat("Bloc", "hMinRoot"))
            self.hMinTip.set(value=config.getfloat("Bloc", "hMinTip"))
            self.hOffset.set(value=config.getfloat("Bloc", "hOffset"))
            self.alignProfil.set(value=config.get("Bloc", "alignProfil"))
            self.hProfil.set(value=config.get("Bloc", "hProfil"))
            try:
                self.angleInRoot.set(
                    value=config.getfloat("Bloc", "angleInRoot"))
                self.angleInTip.set(
                    value=config.getfloat("Bloc", "angleInTip"))
                self.angleOutRoot.set(
                    value=config.getfloat("Bloc", "angleOutRoot"))
                self.angleOutTip.set(
                    value=config.getfloat("Bloc", "angleOutTip"))
            except:
                pass
            """
            self.hMaxRootNorm = config.get("Bloc", "hMaxRootNorm")
            self.hMinRootNorm = config.get("Bloc", "hMinRootNorm")
            self.hLeadingRootNorm = config.get("Bloc", "hLeadingRootNorm")
            self.hMaxTipNorm = config.get("Bloc", "hMaxTipNorm")
            self.hMinTipNorm = config.get("Bloc", "hMinTipNorm")
            self.hLeadingTipNorm = config.get("Bloc", "hLeadingTipNorm")
            """

            self.mSpeedHigh.set(
                value=config.getfloat("Material", "mSpeedHigh"))
            self.mSpeedHalf.set(
                value=config.getfloat("Material", "mSpeedHalf"))
            self.mSpeedLow.set(value=config.getfloat("Material", "mSpeedLow"))
            self.mRadSpHigh.set(
                value=config.getfloat("Material", "mRadSpHigh"))
            self.mRadSpHalf.set(
                value=config.getfloat("Material", "mRadSpHalf"))
            self.mHeatSpHigh.set(
                value=config.getfloat("Material", "mHeatSpHigh"))
            self.mHeatSpLow.set(
                value=config.getfloat("Material", "mHeatSpLow"))
            self.mName.set(value=config.get("Material", "mName"))

            self.tableYY.set(value=config.getfloat("Table", "tableYY"))
            self.tableYG.set(value=config.getfloat("Table", "tableYG"))
            self.tableYD.set(value=config.getfloat("Table", "tableYD"))
            self.cMaxY.set(value=config.getfloat("Table", "cMaxY"))
            self.cMaxZ.set(value=config.getfloat("Table", "cMaxZ"))
            self.vMaxY.set(value=config.getfloat("Table", "vMaxY"))
            self.vMaxZ.set(value=config.getfloat("Table", "vMaxZ"))
            self.tHeatingMax.set(value=config.getfloat("Table", "tHeatingMax"))
            self.tName.set(value=config.get("Table", "tName"))
            self.tComPort.set(value=config.get("Table", "tComPort"))
            self.tBaudrate.set(value=config.get("Table", "tBaudrate"))
            self.tPreHeat.set(value=config.getfloat("Table", "tPreHeat"))
            self.tPostHeat.set(value=config.getfloat("Table", "tPostHeat"))

            self.vCut.set(value=config.getfloat("Cut", "vCut"))
            self.gCodeStart1.set(value=config.get("Cut", "gCodeStart1"))
            self.gCodeStart2.set(value=config.get("Cut", "gCodeStart2"))
            self.gCodeStart3.set(value=config.get("Cut", "gCodeStart3"))
            self.gCodeStart4.set(value=config.get("Cut", "gCodeStart4"))
            self.gCodeEnd1.set(value=config.get("Cut", "gCodeEnd1"))
            self.gCodeEnd2.set(value=config.get("Cut", "gCodeEnd2"))
            self.gCodeEnd3.set(value=config.get("Cut", "gCodeEnd3"))
            self.gCodeEnd4.set(value=config.get("Cut", "gCodeEnd4"))
            self.gCodeLetters.set(value=config.get("Cut", "gCodeLetters"))

            self.gVSpeedNoCut.set(
                value=config.getfloat("Guillotine", "gVSpeedNoCut"))
            self.gHSpeedNoCut.set(
                value=config.getfloat("Guillotine", "gHSpeedNoCut"))
            self.gCuttingSpeed.set(
                value=config.getfloat("Guillotine", "gCuttingSpeed"))
            self.gApplyCalculatedHeating.set(
                value=config.getint("Guillotine", "gApplyCalculatedHeating"))
            self.gHeating.set(value=config.getfloat("Guillotine", "gHeating"))
            self.gType.set(value=config.get("Guillotine", "gType"))
            self.gCuttingWhile.set(
                value=config.get("Guillotine", "gCuttingWhile"))
            self.gVDist.set(value=config.getfloat("Guillotine", "gVDist"))
            self.gHDist.set(value=config.getfloat("Guillotine", "gHDist"))
            """
            x ,y , self.hMaxRootNorm, self.hMinRootNorm , self.hLeadingRootNorm = self.normaliseProfil(
                self.oRootX, self.oRootY, self.cRoot.get(), 0, 0)
            x ,y , self.hMaxTipNorm, self.hMinTipNorm , self.hLeadingTipNorm = self.normaliseProfil(
                self.oTipX, self.oTipY, self.cTip.get(), 0, 0)
            """
            self.validateAllOn = True
            self.validateAll(0)
            self.tProfil.updatePlotRoot()
            self.tProfil.updatePlotTip()

    def uploadTable(self):
        self.tableUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Table files", "*.tab"),("All files","*.*")),
                            title = "Choose a file to upload a table."
                            )
        if len(self.tableUploadFileName) > 0:
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Table")
            config.add_section("Cut")

            config.read(self.tableUploadFileName)
            self.tableYY.set(value=config.getfloat("Table", "tableYY"))
            self.tableYG.set(value=config.getfloat("Table", "tableYG"))
            self.tableYD.set(value=config.getfloat("Table", "tableYD"))
            self.cMaxY.set(value=config.getfloat("Table", "cMaxY"))
            self.cMaxZ.set(value=config.getfloat("Table", "cMaxZ"))
            self.vMaxY.set(value=config.getfloat("Table", "vMaxY"))
            self.vMaxZ.set(value=config.getfloat("Table", "vMaxZ"))
            self.tHeatingMax.set(value=config.getfloat("Table", "tHeatingMax"))
            self.tName.set(value=config.get("Table", "tName"))
            self.tComPort.set(value=config.get("Table", "tComPort"))
            self.tBaudrate.set(value=config.get("Table", "tBaudrate"))
            self.tPreHeat.set(value=config.getfloat("Table", "tPreHeat"))
            self.tPostHeat.set(value=config.getfloat("Table", "tPostHeat"))

            self.vCut.set(value=config.getfloat("Cut", "vCut"))
            self.gCodeStart1.set(value=config.get("Cut", "gCodeStart1"))
            self.gCodeStart2.set(value=config.get("Cut", "gCodeStart2"))
            self.gCodeStart3.set(value=config.get("Cut", "gCodeStart3"))
            self.gCodeStart4.set(value=config.get("Cut", "gCodeStart4"))
            self.gCodeEnd1.set(value=config.get("Cut", "gCodeEnd1"))
            self.gCodeEnd2.set(value=config.get("Cut", "gCodeEnd2"))
            self.gCodeEnd3.set(value=config.get("Cut", "gCodeEnd3"))
            self.gCodeEnd4.set(value=config.get("Cut", "gCodeEnd4"))
            self.gCodeLetters.set(value=config.get("Cut", "gCodeLetters"))

            self.validateAll(
                20)  # recalculate and redraw bloc, margin and after

    def uploadMaterial(self):
        self.materialUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Material", "*.mat"),("All files","*.*")),
                            title = "Choose a file to upload a material"
                            )
        if len(self.materialUploadFileName) > 0:
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Material")

            config.read(self.materialUploadFileName)
            self.mSpeedHigh.set(
                value=config.getfloat("Material", "mSpeedHigh"))
            self.mSpeedHalf.set(
                value=config.getfloat("Material", "mSpeedHalf"))
            self.mSpeedLow.set(value=config.getfloat("Material", "mSpeedLow"))
            self.mRadSpHigh.set(
                value=config.getfloat("Material", "mRadSpHigh"))
            self.mRadSpHalf.set(
                value=config.getfloat("Material", "mRadSpHalf"))
            self.mHeatSpHigh.set(
                value=config.getfloat("Material", "mHeatSpHigh"))
            self.mHeatSpLow.set(
                value=config.getfloat("Material", "mHeatSpLow"))
            self.mName.set(value=config.get("Material", "mName"))

            self.validateAll(30)  # recalculate and redraw cutting

    def saveConfig(self):
        config = configparser.ConfigParser()
        config.add_section("Profil")
        config.add_section("Transform")
        config.add_section("Bloc")
        config.add_section("Material")
        config.add_section("Table")
        config.add_section("Cut")
        config.add_section("Guillotine")

        #save all paramaters
        config.set(
            "Profil", "RootX",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootX]))))
        config.set(
            "Profil", "RootY",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootY]))))
        config.set(
            "Profil", "RootS",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootS]))))
        config.set(
            "Profil", "TipX",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipX]))))
        config.set(
            "Profil", "TipY",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipY]))))
        config.set(
            "Profil", "TipS",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipS]))))
        config.set("Profil", "nameRoot", self.nameRoot.get())
        config.set("Profil", "nameTip", self.nameTip.get())

        config.set("Transform", "cRoot", str(self.cRoot.get()))
        config.set("Transform", "cTip", str(self.cTip.get()))
        config.set("Transform", "incidenceRoot", str(self.incidenceRoot.get()))
        config.set("Transform", "thicknessRoot", str(self.thicknessRoot.get()))
        config.set("Transform", "vInvertRoot", str(self.vInvertRoot.get()))
        config.set("Transform", "incidenceTip", str(self.incidenceTip.get()))
        config.set("Transform", "thicknessTip", str(self.thicknessTip.get()))
        config.set("Transform", "vInvertTip", str(self.vInvertTip.get()))
        config.set("Transform", "covering", str(self.covering.get()))
        config.set("Transform", "keepChord", str(self.keepChord.get()))
        config.set("Transform", "smooth", str(self.smooth.get()))
        config.set("Transform", "nbrPoints", str(self.nbrPoints.get()))
        config.set("Transform", "repartition", str(self.repartition.get()))
        config.set("Transform", "reducePoints", str(self.reducePoints.get()))

        config.set("Bloc", "blocLX", str(self.blocLX.get()))
        config.set("Bloc", "blocHZ", str(self.blocHZ.get()))
        config.set("Bloc", "fLeading", str(self.fLeading.get()))
        config.set("Bloc", "fTrailing", str(self.fTrailing.get()))
        config.set("Bloc", "mLeading", str(self.mLeading.get()))
        config.set("Bloc", "mTrailingRoot", str(self.mTrailingRoot.get()))
        config.set("Bloc", "mTrailingTip", str(self.mTrailingTip.get()))
        config.set("Bloc", "leftRightWing", self.leftRightWing.get())
        config.set("Bloc", "blocPosition", self.blocPosition.get())
        config.set("Bloc", "blocToTableLeft", str(self.blocToTableLeft.get()))
        config.set("Bloc", "blocToTableRight",
                   str(self.blocToTableRight.get()))
        config.set("Bloc", "blocToTableTrailingRoot",
                   str(self.blocToTableTrailingRoot.get()))
        config.set("Bloc", "blocToTableTrailingTip",
                   str(self.blocToTableTrailingTip.get()))
        config.set("Bloc", "blocToTableLeadingRoot",
                   str(self.blocToTableLeadingRoot.get()))
        config.set("Bloc", "blocToTableLeadingTip",
                   str(self.blocToTableLeadingTip.get()))

        config.set("Bloc", "hTrailingRoot", str(self.hTrailingRoot.get()))
        config.set("Bloc", "hTrailingTip", str(self.hTrailingTip.get()))
        config.set("Bloc", "hLeadingRoot", str(self.hLeadingRoot.get()))
        config.set("Bloc", "hLeadingTip", str(self.hLeadingTip.get()))
        config.set("Bloc", "hMaxRoot", str(self.hMaxRoot.get()))
        config.set("Bloc", "hMaxTip", str(self.hMaxTip.get()))
        config.set("Bloc", "hMinRoot", str(self.hMinRoot.get()))
        config.set("Bloc", "hMinTip", str(self.hMinTip.get()))
        config.set("Bloc", "hOffset", str(self.hOffset.get()))
        config.set("Bloc", "alignProfil", self.alignProfil.get())
        config.set("Bloc", "hProfil", str(self.hProfil.get()))
        config.set("Bloc", "angleInRoot", str(self.angleInRoot.get()))
        config.set("Bloc", "angleInTip", str(self.angleInTip.get()))
        config.set("Bloc", "angleOutRoot", str(self.angleOutRoot.get()))
        config.set("Bloc", "angleOutTip", str(self.angleOutTip.get()))

        config.set("Material", "mSpeedHigh", str(self.mSpeedHigh.get()))
        config.set("Material", "mSpeedHalf", str(self.mSpeedHalf.get()))
        config.set("Material", "mSpeedLow", str(self.mSpeedLow.get()))
        config.set("Material", "mRadSpHigh", str(self.mRadSpHigh.get()))
        config.set("Material", "mRadSpHalf", str(self.mRadSpHalf.get()))
        config.set("Material", "mHeatSpHigh", str(self.mHeatSpHigh.get()))
        config.set("Material", "mHeatSpLow", str(self.mHeatSpLow.get()))
        config.set("Material", "mName", self.mName.get())

        config.set("Table", "tableYY", str(self.tableYY.get()))
        config.set("Table", "tableYG", str(self.tableYG.get()))
        config.set("Table", "tableYD", str(self.tableYD.get()))
        config.set("Table", "cMaxY", str(self.cMaxY.get()))
        config.set("Table", "cMaxZ", str(self.cMaxZ.get()))
        config.set("Table", "vMaxY", str(self.vMaxY.get()))
        config.set("Table", "vMaxZ", str(self.vMaxZ.get()))
        config.set("Table", "tHeatingMax", str(self.tHeatingMax.get()))
        config.set("Table", "tName", self.tName.get())
        config.set("Table", "tComPort", self.tComPort.get())
        config.set("Table", "tBaudrate", self.tBaudrate.get())
        config.set("Table", "tPreHeat", str(self.tPreHeat.get()))
        config.set("Table", "tPostHeat", str(self.tPostHeat.get()))

        config.set("Cut", "vCut", str(self.vCut.get()))
        config.set("Cut", "gCodeStart1", self.gCodeStart1.get())
        config.set("Cut", "gCodeStart2", self.gCodeStart2.get())
        config.set("Cut", "gCodeStart3", self.gCodeStart3.get())
        config.set("Cut", "gCodeStart4", self.gCodeStart4.get())
        config.set("Cut", "gCodeEnd1", self.gCodeEnd1.get())
        config.set("Cut", "gCodeEnd2", self.gCodeEnd2.get())
        config.set("Cut", "gCodeEnd3", self.gCodeEnd3.get())
        config.set("Cut", "gCodeEnd4", self.gCodeEnd4.get())
        config.set("Cut", "gCodeLetters", self.gCodeLetters.get())

        config.set("Guillotine", "gVSpeedNoCut", str(self.gVSpeedNoCut.get()))
        config.set("Guillotine", "gHSpeedNoCut", str(self.gHSpeedNoCut.get()))
        config.set("Guillotine", "gCuttingSpeed",
                   str(self.gCuttingSpeed.get()))
        config.set("Guillotine", "gApplyCalculatedHeating",
                   str(self.gApplyCalculatedHeating.get()))
        config.set("Guillotine", "gHeating", str(self.gHeating.get()))
        config.set("Guillotine", "gType", self.gType.get())
        config.set("Guillotine", "gCuttingWhile", self.gCuttingWhile.get())
        config.set("Guillotine", "gVDist", str(self.gVDist.get()))
        config.set("Guillotine", "gHDist", str(self.gHDist.get()))


        configSaveFileName = filedialog.asksaveasfilename(title="Save as...", defaultextension="*.ini",\
            filetypes=[("Ini files","*.ini"),("All files", "*")], initialfile=self.configUploadFileName)
        if len(configSaveFileName) > 0:
            config.write(open(configSaveFileName, 'w'))

    def saveTable(self):
        config = configparser.ConfigParser()
        config.add_section("Table")
        config.add_section("Cut")
        config.set("Table", "tableYY", str(self.tableYY.get()))
        config.set("Table", "tableYG", str(self.tableYG.get()))
        config.set("Table", "tableYD", str(self.tableYD.get()))
        config.set("Table", "cMaxY", str(self.cMaxY.get()))
        config.set("Table", "cMaxZ", str(self.cMaxZ.get()))
        config.set("Table", "vMaxY", str(self.vMaxY.get()))
        config.set("Table", "vMaxZ", str(self.vMaxZ.get()))
        config.set("Table", "tHeatingMax", str(self.tHeatingMax.get()))
        config.set("Table", "tName", self.tName.get())
        config.set("Table", "tComPort", self.tComPort.get())
        config.set("Table", "tBaudrate", self.tBaudrate.get())
        config.set("Table", "tPreHeat", str(self.tPreHeat.get()))
        config.set("Table", "tPostHeat", str(self.tPostHeat.get()))

        config.set("Cut", "vCut", str(self.vCut.get()))
        config.set("Cut", "gCodeStart1", self.gCodeStart1.get())
        config.set("Cut", "gCodeStart2", self.gCodeStart2.get())
        config.set("Cut", "gCodeStart3", self.gCodeStart3.get())
        config.set("Cut", "gCodeStart4", self.gCodeStart4.get())
        config.set("Cut", "gCodeEnd1", self.gCodeEnd1.get())
        config.set("Cut", "gCodeEnd2", self.gCodeEnd2.get())
        config.set("Cut", "gCodeEnd3", self.gCodeEnd3.get())
        config.set("Cut", "gCodeEnd4", self.gCodeEnd4.get())
        config.set("Cut", "gCodeLetters", self.gCodeLetters.get())

        if self.tableSaveFileName == None:
            self.tableSaveFileName = self.tableUploadFileName
        self.tableSaveFileName = filedialog.asksaveasfilename(title="Save table as...", defaultextension="*.tab",\
            filetypes=[("Table files","*.tab"),("All files", "*")], initialfile=self.tableSaveFileName)
        if len(self.tableSaveFileName) > 0:
            config.write(open(self.tableSaveFileName, 'w'))

    def saveMaterial(self):
        config = configparser.ConfigParser()
        config.add_section("Material")
        config.set("Material", "mSpeedHigh", str(self.mSpeedHigh.get()))
        config.set("Material", "mSpeedHalf", str(self.mSpeedHalf.get()))
        config.set("Material", "mSpeedLow", str(self.mSpeedLow.get()))
        config.set("Material", "mRadSpHigh", str(self.mRadSpHigh.get()))
        config.set("Material", "mRadSpHalf", str(self.mRadSpHalf.get()))
        config.set("Material", "mHeatSpHigh", str(self.mHeatSpHigh.get()))
        config.set("Material", "mHeatSpLow", str(self.mHeatSpLow.get()))
        config.set("Material", "mName", self.mName.get())

        if self.materialSaveFileName == None:
            self.materialSaveFileName = self.materialUploadFileName
        self.materialSaveFileName = filedialog.asksaveasfilename(title="Save material as...", defaultextension="*.material",\
            filetypes=[("Material files","*.material"),("All files", "*")], initialfile=self.materialSaveFileName)
        if len(self.materialSaveFileName) > 0:
            config.write(open(self.materialSaveFileName, 'w'))

    def validatePart(self):
        self.fTrailing.set(-(self.cRoot.get() - self.cTip.get() -
                             self.fLeading.get()))
        if self.blocPosition.get() == "Left":
            self.tBloc.blocToTableRightBox[
                'validate'] = 'none'  # disable validate, otherwise we call validate inside validate
            self.blocToTableRight.set(self.tableYY.get() - self.tableYG.get() -
                                      self.tableYD.get() -
                                      self.blocToTableLeft.get() -
                                      self.blocLX.get())
            self.tBloc.blocToTableRightBox[
                'validate'] = 'focusout'  #enable after the update
        else:
            self.tBloc.blocToTableRightBox[
                'validate'] = 'none'  # disable validate, otherwise we call validate inside validate
            self.blocToTableLeft.set(self.tableYY.get() - self.tableYG.get() -
                                     self.tableYD.get() -
                                     self.blocToTableRight.get() -
                                     self.blocLX.get())
            self.tBloc.blocToTableRightBox['validate'] = 'focusout'
        self.blocToTableTrailingTip.set(self.blocToTableTrailingRoot.get() -
                                        self.fTrailing.get())
        self.blocToTableLeadingRoot.set(self.blocToTableTrailingRoot.get() +
                                        self.cRoot.get() +
                                        self.mTrailingRoot.get() +
                                        self.mLeading.get())

        self.blocToTableLeadingTip.set(self.blocToTableTrailingTip.get() +
                                       self.cTip.get() +
                                       self.mTrailingTip.get() +
                                       self.mLeading.get())
        #self.mSpeedHalf.set(self.mSpeedHigh.get() / 2) #half speed = high speed /2

    def validateAll(self, level):
        # level is used to avoid to recalculate some data when not needed
        # 0 = calculate all (original profil change)
        # 10 = calculate Transform and after (Transform profil: chord, incidence...)
        # 20 = calculate Bloc/margin and after (change table or bloc position)
        # 30 = calculate cutting (change speed, material)
        if self.initDone and self.validateAllOn:  #avoid validate during the set up of tkinter widgets and when validateAll is disabled
            #try:
            if level == 0:
                self.tProfil.updatePlotRoot()
                self.tProfil.updatePlotTip()

            if level <= 10:
                #create tRoot and tTipX based on oRoot and oTip and chords but not based on bloc and margin
                # draw the view in Transform (= tRoot and tTip)

                if (len(self.oRootX) > 0) and (len(self.oTipX) > 0):
                    #create tRoot and tTipX based on oRoot and oTip and chords but not based on bloc and margin
                    self.tTransform.validateTransform()
                    self.tTransform.updatePlotRoot()
                    self.tTransform.updatePlotTip()

            if level <= 20:
                pass
                #create pRoot and pTipX based on tRoot and tTip and based on Table, bloc and margin
                self.validatePart()
                #print("validatePart is done")
                self.calculatePositions()
                #print("calculatepositions is done")
                # draw the bloc ()
                self.tBloc.updatePlotBloc()
                #print("updatePlotBloc is done")
                #draw the margins
                self.tMargin.updatePlotMargin()
                #print("updatePlotMargin is done")

                #update heating for guillotine
                self.tGuillotine.updateGuillotineHeating()
                #print("updateGuillotineHeating is done")

            if level <= 30:  # calculate Cut based on Material
                self.mSpeedHalf.set(self.mSpeedHigh.get() /
                                    2)  #half speed = high speed /2
                if (len(self.pRootX) > 0) and (len(self.pTipX) > 0):
                    pass
                    #print("begin calculateRedraw")
                    self.tCut.calculateRedraw()
                    #print("end calculateRedraw")
            warningMsg = ""
            if (len(self.oRootX) <= 1) and (len(self.oTipX) <= 1):
                warningMsg = "Root and Tip profiles missing"
            elif len(self.oRootX) <= 1:
                warningMsg = "Root profile missing"
            elif len(self.oTipX) <= 1:
                warningMsg = "Tip profile missing"
            elif (self.tRootS.count(4) + self.tRootS.count(10)) != (
                    self.tTipS.count(4) + self.tTipS.count(10)):
                warningMsg = "Transformed root and tip profiles must have the same number of synchro points"
            self.warningMsg.set(warningMsg)
            #next 2 lines are normally as comment
            #except:

        return True

    def calculatePositions(self):
        #create bRoot and bTipX based on tRoot and tTip and based on bloc and margin
        #calculate Root and Tip offset to apply
        if (len(self.tRootX) > 0) and (len(
                self.tTipX) > 0):  # and (len(self.tRootX) == len(self.tTipX)):
            #calculate relative height of max, min leading
            hMaxRootNorm, hMinRootNorm, hLeadingRootNorm = self.calculateRelativeHeigths(
                self.tRootX, self.tRootY)
            hMaxTipNorm, hMinTipNorm, hLeadingTipNorm = self.calculateRelativeHeigths(
                self.tTipX, self.tTipY)

            #Apply vertical aligment
            if self.alignProfil.get() == "Trailing":
                self.hTrailingRoot.set(self.hProfil.get())
                self.hTrailingTip.set(self.hProfil.get())
            elif self.alignProfil.get() == "Leading":
                self.hTrailingRoot.set(self.hProfil.get() - hLeadingRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hLeadingTipNorm)
            elif self.alignProfil.get() == "Extrados":
                self.hTrailingRoot.set(self.hProfil.get() - hMaxRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hMaxTipNorm)
            elif self.alignProfil.get() == "Intrados":
                self.hTrailingRoot.set(self.hProfil.get() - hMinRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hMinTipNorm)
            self.hLeadingRoot.set(self.hTrailingRoot.get() + hLeadingRootNorm)
            self.hLeadingTip.set(self.hTrailingTip.get() + hLeadingTipNorm)
            self.hMaxRoot.set(self.blocHZ.get() - self.hTrailingRoot.get() -
                              hMaxRootNorm)
            self.hMaxTip.set(self.blocHZ.get() - self.hTrailingTip.get() -
                             hMaxTipNorm)
            self.hMinRoot.set(self.hTrailingRoot.get() + hMinRootNorm)
            self.hMinTip.set(self.hTrailingTip.get() + hMinTipNorm)

            #apply offsets
            self.pRootX = self.tRootX + self.blocToTableTrailingRoot.get(
            ) + self.mTrailingRoot.get()
            self.pTipX = self.tTipX + self.blocToTableTrailingTip.get(
            ) + self.mTrailingTip.get()
            self.pRootY = self.tRootY + self.hOffset.get(
            ) + self.hTrailingRoot.get()
            self.pTipY = self.tTipY + self.hOffset.get(
            ) + self.hTrailingRoot.get()
            self.pRootS = list(self.tRootS)  #create list of synchro
            self.pTipS = list(self.tTipS)  #create list of synchro

    """
    def validateFloat(self, reason, val , name , old,  min , max):
        if reason == "focusout":
            try :  
                v = float(val)
                if v >= float(min) and v <= float(max):
                    
                    return True
                return True    
            except : 
                return False
        elif reason == "focusout":
            if float(val) > float(max):
                print("focus out max exceeded")
                return False
            return self.validateAll()        
        return True
    """

    def normaliseArrayProfil(self, aX, aY, chord):
        #normalise the profil with chord
        if len(aX) > 0:
            minX = np.min(aX)
            maxX = np.max(aX)
            ratio = chord / (maxX - minX)
            aXn = aX * ratio
            aXn = aXn - aXn[0]
            aXn = -1.0 * aXn  # multiply by -1 to reverse the order
            aYn = aY * ratio
            aYn = aYn - aYn[0]
            return aXn, aYn

    """
    def normaliseProfil (self , pX , pY , coord , oY, oZ):
        #normalise the profil with coord and offset of origin
        if len(pX) > 0:
            aX = np.array(pX)
            aY = np.array(pY)
            minX = np.min(aX)
            idxMin = np.where(aX == minX) #return an array with indexes
            maxX = np.max(aX)
            minY = np.min(aY)
            maxY = np.max(aY)
            ratio= coord / ( maxX - minX )  
            aX = aX * ratio
            aX = aX - aX[0]
            aX = -1 * aX # multiply by -1 to reverse the order
            aX = aX + oY
            aY = aY * ratio
            aY = aY - aY[0]
            aY = aY + oZ
            maxh = (maxY / ( maxX - minX ) ) - pY[0]
            minh = (minY / ( maxX - minX ) ) - pY[0] 
            if len(idxMin) > 0 and len(idxMin[0]) > 0:
                r = idxMin[0][0]
                leadingh = (pY[r] / ( maxX - minX ) ) - pY[0]
            else:
                leadingh = 0
                        #print("normalised aX=", aX , "aY=", aY)
            return aX.tolist() , aY.tolist() ,maxh ,minh, leadingh
    """

    def calculateRelativeHeigths(self, pX, pY):
        maxX = np.max(pX)
        idxMax = np.where(pX == maxX)  #return an array with indexes
        minY = np.min(pY)
        maxY = np.max(pY)
        maxh = maxY - pY[0]
        minh = minY - pY[0]
        if len(idxMax) > 0 and len(idxMax[0]) > 0:
            r = idxMax[0][0]
            leadingh = pY[r] - pY[0]
        else:
            leadingh = 0
        return maxh, minh, leadingh
Example #43
0
class CharacterSheetTab(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.player = StringVar()
        self.character = StringVar()
        self.dm = StringVar()
        self.str = StringVar()
        self.int = StringVar()
        self.wis = StringVar()
        self.dex = StringVar()
        self.con = StringVar()
        self.cha = StringVar()
        self.JPpoison = StringVar()
        self.JPwands = StringVar()
        self.JPparalysis = StringVar()
        self.JPbreath = StringVar()
        self.JPspell = StringVar()
        self.class_ = StringVar()
        self.race = StringVar()
        self.align = StringVar()
        self.AC = StringVar()
        self.HP = StringVar()
        self.maxHP = StringVar()
        self.XP_to_add = StringVar()
        self.XPbonus = StringVar()
        self.XPtotal = IntVar()
        self.level = StringVar()

        self.init_once()

        (
            self.baseXP,
            self.mainCarRace,
            self.mainCarClass) = self.classDifferenciation()
        self.remainingXP = StringVar()
        self.remainingXP.set(self.getRemainingXP())
        self.bonusXP = StringVar()
        self.bonusXP.set(self.getBonusXP())

        self.freeze = IntVar()
        self.freeze.set(1)

        Label(self, text="Player Name:").grid(row=0, column=0, columnspan=2)
        Label(self, text="Character Name :").grid(
            row=0, column=4, columnspan=2)
        Label(self, text="DM Name:").grid(row=0, column=8, columnspan=2)
        Label(self, text="STR:").grid(row=1, column=0)
        Label(self, text="INT:").grid(row=2, column=0)
        Label(self, text="WIS:").grid(row=3, column=0)
        Label(self, text="DEX:").grid(row=4, column=0)
        Label(self, text="CON:").grid(row=5, column=0)
        Label(self, text="CHA:").grid(row=6, column=0)
        Label(self, text="Poison/Deathray:").grid(row=1, column=2)
        Label(self, text="Wands:").grid(row=2, column=2)
        Label(self, text="Paralysis:").grid(row=3, column=2)
        Label(self, text="Dragon Breath:").grid(row=4, column=2)
        Label(self, text="Spells:").grid(row=5, column=2)
        Label(self, text="Armor Class").grid(row=1, column=4, columnspan=1)
        Label(self, text="Health Points").grid(row=1, column=5, columnspan=3)
        Label(self, text="  /  ").grid(row=2, column=6)
        Label(self, text="Class :").grid(row=3, column=4)
        Label(self, text="Race :").grid(row=4, column=4)
        Label(self, text="XP to add :").grid(row=7, column=0)
        Label(self, text="Remaining :").grid(row=8, column=0)
        Label(self, text="Bonus :").grid(row=7, column=2)
        Label(self, text="Alignment :").grid(row=3, column=6)
        Label(self, text="Level :").grid(row=9, column=0, columnspan=2)
        self.remainingLabel = Label(
            self,
            textvariable=self.remainingXP,
            relief=SUNKEN,
            width=5)
        self.remainingLabel.grid(row=8, column=1)
        self.bonusLabel = Label(
            self,
            textvariable=self.bonusXP,
            relief=SUNKEN,
            width=5)
        self.bonusLabel.grid(row=7, column=3)
        self.levelLabel = Label(
            self,
            textvariable=self.level,
            relief=SUNKEN,
            width=5)
        self.levelLabel.grid(row=9, column=2, columnspan=2)

        Eplayer = Entry(self, textvariable=self.player)
        Eplayer.grid(row=0, column=2, columnspan=2)
        Eplayer.bind(sequence='<KeyRelease>', func=self.refresh)

        Echaracter = Entry(self, textvariable=self.character)
        Echaracter.grid(row=0, column=6, columnspan=2)
        Echaracter.bind(sequence='<KeyRelease>', func=self.refresh)

        EDM = Entry(self, textvariable=self.dm)
        EDM.grid(row=0, column=10, columnspan=2)
        EDM.bind(sequence='<KeyRelease>', func=self.refresh)

        Estr = Entry(self, textvariable=self.str)
        Estr.grid(row=1, column=1)
        Estr.bind(sequence='<KeyRelease>', func=self.refresh)

        Eint = Entry(self, textvariable=self.int)
        Eint.grid(row=2, column=1)
        Eint.bind(sequence='<KeyRelease>', func=self.refresh)

        Ewis = Entry(self, textvariable=self.wis)
        Ewis.grid(row=3, column=1)
        Ewis.bind(sequence='<KeyRelease>', func=self.refresh)

        Edex = Entry(self, textvariable=self.dex)
        Edex.grid(row=4, column=1)
        Edex.bind(sequence='<KeyRelease>', func=self.refresh)

        Econ = Entry(self, textvariable=self.con)
        Econ.grid(row=5, column=1)
        Econ.bind(sequence='<KeyRelease>', func=self.refresh)

        Echa = Entry(self, textvariable=self.cha)
        Echa.grid(row=6, column=1)
        Echa.bind(sequence='<KeyRelease>', func=self.refresh)

        Entry(self, textvariable=self.JPpoison).grid(row=1, column=3)
        Entry(self, textvariable=self.JPwands).grid(row=2, column=3)
        Entry(self, textvariable=self.JPparalysis).grid(row=3, column=3)
        Entry(self, textvariable=self.JPbreath).grid(row=4, column=3)
        Entry(self, textvariable=self.JPspell).grid(row=5, column=3)
        Entry(self, textvariable=self.AC).grid(row=2, column=4)
        Entry(self, textvariable=self.HP).grid(row=2, column=5)
        Entry(self, textvariable=self.maxHP).grid(row=2, column=7)

        EXP = Entry(self, textvariable=self.XP_to_add)
        EXP.grid(row=7, column=1)
        EXP.bind(sequence='<KeyPress-Return>', func=self.addXP)

        OptionMenu(
            self, self.class_,
            "Class",
            "Warrior",
            "Wizard",
            "Thief",
            "Cleric").grid(row=3, column=5)
        OptionMenu(
            self, self.align,
            "Alignment",
            "Lawful Good",
            "Lawful Neutral",
            "Lawful Evil",
            "Neutral Good",
            "Neutral Neutral",
            "Neutral Evil",
            "Chaotic Good",
            "Chaotic Neutral",
            "Chaotic Evil").grid(row=3, column=7)
        OptionMenu(
            self, self.race,
            "Race",
            "Human",
            "Elf",
            "Dwarf",
            "Halfelin").grid(row=4, column=5)

        Button(
            self,
            text="Add XP",
            command=self.refresh,
            width=6).grid(row=10, column=3)

    def refresh(self, event):
        (
            self.baseXP,
            self.mainCarRace,
            self.mainCarClass) = self.classDifferenciation()
        self.remainingXP.set(self.getRemainingXP())
        self.bonusXP.set(self.getBonusXP())
        self.update_idletasks()

    def addXP(self, event):
        (
            self.baseXP,
            self.mainCarRace,
            self.mainCarClass) = self.classDifferenciation()
        self.remainingXP.set(self.getRemainingXP())
        self.bonusXP.set(self.getBonusXP())
        self.addXPToTotal()
        self.update_idletasks()

    def save(self):
        file_ = filedialog.asksaveasfile(
            parent=self,
            mode="w",
            title="Save your Character Sheet",
            defaultextension=".dndcs",
            filetypes=[
                ("Character Sheets", ".dndcs"),
                ("All Files", ".*")])
        string = ""
        list_vars = [
            self.player, self.character, self.dm, self.str, self.int,
            self.wis, self.dex, self.con, self.cha, self.JPpoison,
            self.JPwands, self.JPparalysis, self.JPbreath, self.JPspell,
            self.class_, self.race, self.align, self.AC, self.HP,
            self.maxHP, self.XPtotal, self.level]
        for i in range(len(list_vars)):
            string += str(list_vars[i].get())+"\n"

        string = string[:-2]
        file_.write(string)
        file_.close()

    def load(self):
        self.reset()
        file_ = filedialog.askopenfile(
            parent=self, mode="r", title="Open a Character Sheet",
            defaultextension=".dndcs",
            filetypes=[
                ("Character Sheets", ".dndcs"),
                ("All Files", ".*")]
        )
        list_vars = [
            self.player, self.character, self.dm, self.str, self.int,
            self.wis, self.dex, self.con, self.cha, self.JPpoison,
            self.JPwands, self.JPparalysis, self.JPbreath, self.JPspell,
            self.class_, self.race, self.align, self.AC, self.HP,
            self.maxHP, self.XPtotal, self.level]
        i = 0
        for line in file_:
            line.strip()
            list_vars[i].set(line)
            i += 1
        file_.close()
        self.refresh(1)

    def reset(self):
        self.player.set("")
        self.character.set("")
        self.dm.set("")
        self.str.set("")
        self.int.set("")
        self.wis.set("")
        self.dex.set("")
        self.con.set("")
        self.cha.set("")
        self.JPpoison.set("")
        self.JPwands.set("")
        self.JPparalysis.set("")
        self.JPbreath.set("")
        self.JPspell.set("")
        self.class_.set("Class")
        self.race.set("Race")
        self.align.set("Alignment")
        self.AC.set("")
        self.HP.set("")
        self.maxHP.set("")
        self.XP_to_add.set("")
        self.XPbonus.set("")
        self.XPtotal.set(0)
        self.level.set("1")

    def classDifferenciation(self):
        XPToReturn = 0
        mainCarClass = 0
        mainCarRace = 0
        if self.class_.get() == "Warrior":
            XPToReturn += 2000
            mainCarClass = int(self.str.get())
        elif self.class_.get() == "Wizard":
            XPToReturn += 2500
            mainCarClass = int(self.int.get())
        elif self.class_.get() == "Cleric":
            XPToReturn += 1500
            mainCarClass = int(self.wis.get())
        elif self.class_.get() == "Thief":
            XPToReturn += 1200
            mainCarClass = int(self.dex.get())
        else:
            XPToReturn += 0
        if self.race.get() == "Human":
            XPToReturn += 0
            mainCarRace = int(self.cha.get())
        elif self.race.get() == "Elf":
            XPToReturn += 1500
            mainCarRace = int(self.str.get())
        elif self.race.get() == "Dwarf":
            XPToReturn += 500
            mainCarRace = int(self.con.get())
        elif self.race.get() == "Halfelin":
            XPToReturn += 800
            mainCarRace = int(self.dex.str.get())
        return XPToReturn, mainCarClass, mainCarRace

    def getRemainingXP(self):
        remainingXP = int(self.baseXP) * int(self.level.get()) - \
            int(self.XPtotal.get())
        return str(remainingXP)

    def getBonusXP(self):
        bonusPercentage = 0
        if 16 <= self.mainCarClass <= 18:
            bonusPercentage += 5
        elif 13 <= self.mainCarClass <= 15:
            bonusPercentage += 0
        elif 9 <= self.mainCarClass <= 12:
            bonusPercentage -= 5
        elif 3 <= self.mainCarClass <= 8:
            bonusPercentage -= 10
        else:
            bonusPercentage = 0

        if 16 <= self.mainCarRace <= 18:
            bonusPercentage += 5
        elif 13 <= self.mainCarRace <= 15:
            bonusPercentage += 0
        elif 9 <= self.mainCarRace <= 12:
            bonusPercentage -= 5
        elif 3 <= self.mainCarRace <= 8:
            bonusPercentage -= 10
        else:
            bonusPercentage = 0
        self.bonus = bonusPercentage
        return str(bonusPercentage) + "%"

    def addXPToTotal(self):
        (
            self.baseXP,
            self.mainCarRace,
            self.mainCarClass) = self.classDifferenciation()
        self.remainingXP.set(self.getRemainingXP())
        self.bonusXP.set(self.getBonusXP())
        remaining = int(self.getRemainingXP())
        bonus = int(self.getBonusXP().strip("%"))
        if self.XP_to_add.get() != '':
            XP_to_add = int(self.XP_to_add.get())
        else:
            XP_to_add = 0
        self.XP_to_add.set("")
        total = self.XPtotal.get()
        total += XP_to_add*(1+bonus/100)
        self.XPtotal.set(total)
        if total >= remaining:
            self.level.set(str(int(self.level.get())+1))

    def rollCharacteristics(self):
        if self.freeze.get() == 0:
            chars = [
                self.str, self.int, self.wis,
                self.dex, self.con, self.cha]
            for char in chars:
                char.set(str(
                    rd.randint(1, 6) + rd.randint(1, 6) + rd.randint(1, 6)))
        pass

    @method_once
    def init_once(self):
        self.level.set("1")
        self.baseXP = 0
        self.mainCarRace = 0
        self.mainCarClass = 0
        self.bonus = 0
        self.XP_to_add.set("0")
Example #44
0
)
edit_menu.add_separator()
edit_menu.add_command(label="Find",
                      underline=0,
                      accelerator="Ctrl+F",
                      command=find_text)
edit_menu.add_separator()
edit_menu.add_command(label="Select All",
                      underline=7,
                      accelerator="Ctrl+A",
                      command=select_all)
menu_bar.add_cascade(label="Edit", menu=edit_menu)

view_menu = Menu(menu_bar, tearoff=0)
show_line_number = IntVar()
show_line_number.set(1)
view_menu.add_checkbutton(label="Show Line Number",
                          variable=show_line_number,
                          command=update_line_numbers)
show_cursor_info = IntVar()
show_cursor_info.set(1)
view_menu.add_checkbutton(
    label="Show Cursor Location at Bottom",
    variable=show_cursor_info,
    command=show_cursor_info_bar,
)
to_highlight_line = BooleanVar()
view_menu.add_checkbutton(
    label="Highlight Current Line",
    onvalue=1,
    offvalue=0,
class PasswordGenerator():
    def __init__(self):
        root = Tk()
        root.title('密码生成器')
        root.update()

        self.root = root
        self.ps_length = IntVar(value=8)
        self.ps_level = IntVar(value=3)
        self.password = StringVar()

        self.load_view()
        root.mainloop()

    def load_view(self):

        f1 = Frame(self.root)
        f1.pack(padx=10, pady=5)

        Label(f1, text="密码长度:").grid(row=0, column=0)

        f1r = Frame(f1)
        f1r.grid(row=0, column=1)

        Entry(f1r,
              textvariable=self.ps_length,
              width=5,
              validate="key",
              validatecommand=(self.test, '%P')).grid(row=0, column=1)

        Button(f1r, text="+", command=self.calcPlus).grid(row=0, column=2)
        Button(f1r, text="-", command=self.calcSubt).grid(row=0, column=3)

        Label(f1, text="密码强度:").grid(row=1, column=0)

        f1rb = Frame(f1)
        f1rb.grid(row=1, column=1)

        Radiobutton(f1rb, text="简单", variable=self.ps_level,
                    value=1).grid(row=1, column=1)
        Radiobutton(f1rb, text="一般", variable=self.ps_level,
                    value=3).grid(row=1, column=2)
        Radiobutton(f1rb, text="复杂", variable=self.ps_level,
                    value=4).grid(row=1, column=3)

        Entry(self.root, textvariable=self.password, state="readonly").pack()

        submit = Button(self.root, text="生成密码并复制到剪切板", command=self.getPw)
        submit.pack()

    def cutLength(self):
        res = []
        for i in range(self.ps_level.get(), 1, -1):
            res.append(
                random.randint(1,
                               self.ps_length.get() - sum(res) - i + 1))
        res.append(self.ps_length.get() - sum(res))
        random.shuffle(res)
        return res

    def makePassword(self, dists, arr):
        res = []
        for i in range(len(arr)):
            for j in range(arr[i]):
                res += random.choice(dists[i])
        random.shuffle(res)
        return ''.join(res)

    def getPassword(self):
        arr = self.cutLength()
        str1 = '01'
        str2 = '23456789'
        str3 = 'abcdefghijkmnpqrstuvwxyz'
        str4 = 'ABCDEFGHJKMNPQRSTUVWXYZ'
        str5 = '_@!,.:;-=+/?'

        dists = {
            1: [str1 + str2],
            3: [str2, str3, str4],
            4: [str2, str3, str4, str5]
        }
        return self.makePassword(dists[self.ps_level.get()], arr)

    def test(self, res):
        if res.isdigit():
            return int(res) > 4
        else:
            return False

    def calcPlus(self):
        self.ps_length.set(self.ps_length.get() + 1)

    def calcSubt(self):
        lengVal = self.ps_length.get()
        if lengVal > 4:
            self.ps_length.set(lengVal - 1)

    def getPw(self):
        res = self.getPassword()
        clipboard.copy(res)
        self.password.set(res)
Example #46
0
class ErlangCT:
    def __init__(self, f_path):
        self.root = Tk()
        self.root.title("P2: Erlang-C Calculator")

        # excel file path
        self.f_path = f_path

        # member variables
        self.num_servers = 0  # result: number of servers
        self.ew = 0.0  # result: expected waiting time
        self.en = 0.0  # result: expected number packets in system
        self.ens = 0.0  # result: expected number of busy servers
        self.alpha = 0.0  # input: max waiting time
        self.l = 0.0  # input: lambda
        self.u = 0.0  # input: mu

        # text fields and validation for each variable
        self.alpha_entry = Entry(self.root)
        self.l_entry = Entry(self.root)
        self.u_entry = Entry(self.root)

        # text field labels
        self.alpha_label = Label(self.root,
                                 text="Waiting Time Should Not Exceed: ")
        self.l_label = Label(self.root, text="Desired Arrival Rate (lambda): ")
        self.u_label = Label(self.root, text="Desired Service Rate (mu): ")

        # calcualte button
        self.calculate_button = Button(
            self.root,
            text="Calculate",
            command=lambda: self.update("calculate"))
        self.main_menu_button = Button(
            self.root,
            text="Main Menu",
            command=lambda: self.update("main-menu"))

        # initialize result text field
        self.num_servers_result = IntVar()
        self.num_servers_result.set(self.num_servers)
        self.ew_result = DoubleVar()
        self.ew_result.set(self.ew)
        self.en_result = DoubleVar()
        self.en_result.set(self.en)
        self.ens_result = DoubleVar()
        self.ens_result.set(self.en)

        # result text field labels
        self.num_servers_text_label = Label(self.root,
                                            text="Number of Servers Required:")
        self.num_servers_result_label = Label(
            self.root, textvariable=self.num_servers_result)
        self.es_text_label = Label(self.root, text="Expected Waiting Time:")
        self.ew_result_label = Label(self.root, textvariable=self.ew_result)
        self.en_text_label = Label(self.root,
                                   text="Expected Number Packets in System:")
        self.en_result_label = Label(self.root, textvariable=self.en_result)
        self.ens_text_label = Label(self.root,
                                    text="Expected Number of Busy Servers:")
        self.ens_result_label = Label(self.root, textvariable=self.ens_result)

        # Calculator Layout
        self.alpha_label.grid(row=1, column=0, columnspan=3, sticky=W)
        self.alpha_entry.grid(row=1, column=4, columnspan=1, sticky=E)
        self.l_label.grid(row=2, column=0, columnspan=3, sticky=W)
        self.l_entry.grid(row=2, column=4, columnspan=1, sticky=E)
        self.u_label.grid(row=3, column=0, columnspan=3, sticky=W)
        self.u_entry.grid(row=3, column=4, columnspan=1, sticky=E)
        self.calculate_button.grid(row=4, column=0)
        self.num_servers_text_label.grid(row=5, column=0, sticky=W)
        self.num_servers_result_label.grid(row=5,
                                           column=3,
                                           columnspan=2,
                                           sticky=E)
        self.es_text_label.grid(row=6, column=0, sticky=W)
        self.ew_result_label.grid(row=6, column=3, columnspan=2, sticky=E)
        self.en_text_label.grid(row=7, column=0, sticky=W)
        self.en_result_label.grid(row=7, column=3, columnspan=2, sticky=E)
        self.ens_text_label.grid(row=8, column=0, sticky=W)
        self.ens_result_label.grid(row=8, column=3, columnspan=2, sticky=E)
        self.main_menu_button.grid(row=9, column=0)

    def update(self, method):
        if method == "calculate":
            self.alpha = float(self.alpha_entry.get())
            self.l = float(self.l_entry.get())
            self.u = float(self.u_entry.get())

            result = erlang_c_time(self.l, self.u, self.alpha)
            self.num_servers = result['c']
            self.ew = result['ew']
            self.en = result['en']
            self.ens = result['ens']
            self.num_servers_result.set(self.num_servers)
            self.ew_result.set(self.ew)
            self.en_result.set(self.en)
            self.ens_result.set(self.ens)

            self.write_to_excel()

        elif method == "main-menu":
            self.root.destroy()
            from main_menu import MainMenu
            m_menu = MainMenu(self.f_path)
            m_menu.root.mainloop()

        else:  # reset
            self.num_servers = 0

    def write_to_excel(self):
        wb = load_workbook(self.f_path)
        ws = wb["Part 2"]
        data = [["Inputs", "Values", "Results", "Values"],
                [
                    "Max P(wait)", "", "Number of Servers",
                    str(self.num_servers)
                ], ["Max E(w)",
                    str(self.alpha), "E(S)",
                    str(self.ew)],
                ["Arrival Rate",
                 str(self.l), "E(N)",
                 str(self.en)], ["Service Rate",
                                 str(self.u), "", ""]]
        i = 1
        for v in data:
            j = 1
            for e in v:
                c = ws.cell(row=i, column=j)
                c.value = e
                j += 1
            i += 1

        wb.save(self.f_path)
Example #47
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Shift Reduce Parser Application')

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10) # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1['text'] = ''

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkinter.font.Font(family='helvetica',
                                    size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Reductions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:#len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind('<Motion>', self._highlight_hover)
        self._prodlist.bind('<Leave>', self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Alt-q>', self.destroy)
        self._top.bind('<Alt-x>', self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind('<space>', self.step)
        self._top.bind('<s>', self.shift)
        self._top.bind('<Alt-s>', self.shift)
        self._top.bind('<Control-s>', self.shift)
        self._top.bind('<r>', self.reduce)
        self._top.bind('<Alt-r>', self.reduce)
        self._top.bind('<Control-r>', self.reduce)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<u>', self.undo)
        self._top.bind('<Alt-u>', self.undo)
        self._top.bind('<Control-u>', self.undo)
        self._top.bind('<Control-z>', self.undo)
        self._top.bind('<BackSpace>', self.undo)

        # Misc
        self._top.bind('<Control-p>', self.postscript)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

        # Animation speed control
        self._top.bind('-', lambda e,a=self._animate:a.set(20))
        self._top.bind('=', lambda e,a=self._animate:a.set(10))
        self._top.bind('+', lambda e,a=self._animate:a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom')
        Button(buttonframe, text='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Shift', underline=0,
               background='#90f090', foreground='black',
               command=self.shift).pack(side='left')
        Button(buttonframe, text='Reduce', underline=0,
               background='#90f090', foreground='black',
               command=self.reduce).pack(side='left')
        Button(buttonframe, text='Undo', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.undo).pack(side='left')

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Shift', underline=0,
                             command=self.shift, accelerator='Ctrl-s')
        rulemenu.add_command(label='Reduce', underline=0,
                             command=self.reduce, accelerator='Ctrl-r')
        rulemenu.add_separator()
        rulemenu.add_command(label='Undo', underline=0,
                             command=self.undo, accelerator='Ctrl-u')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animate, value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animate, value=20,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animate, value=10,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animate, value=4,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   width=525, closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0,0,0,0, fill='#c0f0f0',
                                                 outline='black')
        self._exprline = canvas.create_line(0,0,0,0, dash='.')
        self._stacktop = canvas.create_line(0,0,0,0, fill='#408080')
        size = self._size.get()+4
        self._stacklabel = TextWidget(canvas, 'Stack', color='#004040',
                                      font=self._boldfont)
        self._rtextlabel = TextWidget(canvas, 'Remaining Text',
                                      color='#004040', font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas['scrollregion'].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2-y1+10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y-4)
        self._canvas.coords(self._exprline, 0, y*2-10, 5000, y*2-10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5-x1, 3-y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2-x2-5, 3-y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {'tree_color': '#4080a0', 'tree_width': 2,
                           'node_font': self._boldfont,
                           'node_color': '#006060',
                           'leaf_color': '#006060', 'leaf_font':self._font}
                widget = tree_to_treesegment(self._canvas, tok,
                                             **attribs)
                widget.label()['color'] = '#000000'
            else:
                widget = TextWidget(self._canvas, tok,
                                    color='#000000', font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas, tok,
                                color='#000000', font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width()+25)
        rlabelwidth = self._rtextlabel.width()+10
        if stackx >= cx2-max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4+cx2-rtextwidth, 0)
        self._rtextlabel.move(cx2-self._rtextlabel.bbox()[2]-5, 0)

        midx = (stackx + cx2-max(rtextwidth, rlabelwidth))/2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:
            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx: self.shift()
                else: self._redraw()
            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2]+50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, 'end')
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset App'
        self._lastoper2['text'] = ''
        self._redraw()

    def step(self, *e):
        if self.reduce(): return True
        elif self.shift(): return True
        else:
            if list(self._parser.parses()):
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Success'
            else:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Failure'

    def shift(self, *e):
        if self._animating_lock: return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1['text'] = 'Shift:'
            self._lastoper2['text'] = '%r' % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return True
        return False

    def reduce(self, *e):
        if self._animating_lock: return
        production = self._parser.reduce()
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock: return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    #########################################
    ##  Menubar callbacks
    #########################################

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))

        #self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        #self._lastoper_label['font'] = ('helvetica', -size)
        #self._lastoper1['font'] = ('helvetica', -size)
        #self._lastoper2['font'] = ('helvetica', -size)
        #self._prodlist['font'] = ('helvetica', -size)
        #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Shift-Reduce Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Shift-Reduce Parser Application',
                     (__doc__ or '').strip(), width=75)

    def about(self, *e):
        ABOUT = ("NLTK Shift-Reduce Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Shift-Reduce Parser Application'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split() #[XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0: return

        self._reduce_menu.delete(0, 'end')
        for production in productions:
            self._reduce_menu.add_command(label=str(production),
                                          command=self.reduce)
        self._reduce_menu.post(self._canvas.winfo_pointerx(),
                               self._canvas.winfo_pointery())

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0: left = 5
        else: left = self._stackwidgets[-1].bbox()[2]+10

        # Start animating.
        dt = self._animate.get()
        dx = (left-right)*1.0/dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame,
                            frame-1, widget, dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1]) # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].label().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist*2.0/dt
        self._animate_reduce_frame(dt/2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets: widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame,
                            frame-1, widgets, dy)
        else:
            del self._stackwidgets[-len(widgets):]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree): raise ValueError()
            label = TextWidget(self._canvas, str(tok.label()), color='#006060',
                               font=self._boldfont)
            widget = TreeSegmentWidget(self._canvas, label, widgets,
                                       width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2-y1+10
            if not self._stackwidgets: x = 5
            else: x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

#             # Delete the old widgets..
#             del self._stackwidgets[-len(widgets):]
#             for widget in widgets:
#                 self._cframe.destroy_widget(widget)
#
#             # Make a new one.
#             tok = self._parser.stack()[-1]
#             if isinstance(tok, Tree):
#                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
#                            'node_font': bold, 'node_color': '#006060',
#                            'leaf_color': '#006060', 'leaf_font':self._font}
#                 widget = tree_to_treesegment(self._canvas, tok.type(),
#                                              **attribs)
#                 widget.node()['color'] = '#000000'
#             else:
#                 widget = TextWidget(self._canvas, tok.type(),
#                                     color='#000000', font=self._font)
#             widget.bind_click(self._popup_reduce)
#             (x1, y1, x2, y2) = self._stacklabel.bbox()
#             y = y2-y1+10
#             if not self._stackwidgets: x = 5
#             else: x = self._stackwidgets[-1].bbox()[2] + 10
#             self._cframe.add_widget(widget, x, y)
#             self._stackwidgets.append(widget)

            #self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index: return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.label()['color'] = '#00a000'
                else:
                    stackwidget['color'] = '#00a000'

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1: return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.label()['color'] = 'black'
            else:
                stackwidget['color'] = 'black'
Example #48
0
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master,
                           validate="key",
                           validatecommand=(vcmd, '%P'))

        self.add_button = Button(master,
                                 text="+",
                                 command=lambda: self.update("add"))
        self.subtract_button = Button(master,
                                      text="-",
                                      command=lambda: self.update("subtract"))
        self.reset_button = Button(master,
                                   text="Reset",
                                   command=lambda: self.update("reset"))

        # LAYOUT

        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)

        self.entry.grid(row=1, column=0, columnspan=3, sticky=W + E)

        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.reset_button.grid(row=2, column=2, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
            return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        else:  # reset
            self.total = 0

        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
Example #49
0
class CadastroVeiculo:
    def __init__(self, master):
        self.app_main = tkinter.Toplevel(master)
        # self.app_main = tkinter.Tk()
        self.app_main.title("Cadastro de Veículo")
        self.centralizar_tela()
        self.atualizando_cadastro = False
        self.veiculo_atual = None
        self.combobox_tipo_veiculo = None
        self.combobox_peso_balanca = None

        self.tipo_veiculo = StringVar()
        self.tolerancia_balanca = StringVar()
        self.quantidade_lacres = IntVar()
        self.lote = StringVar()
        self.placa_1 = StringVar()
        self.placa_2 = StringVar()
        self.placa_3 = StringVar()
        self.placa_4 = StringVar()

        Label(self.app_main, text="Tipo Veículo: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=0, row=0, padx=5)
        self.combobox_tipo_veiculo = Combobox(self.app_main,
                                              textvariable=self.tipo_veiculo,
                                              width=40,
                                              state="readonly")
        self.combobox_tipo_veiculo.grid(sticky="we",
                                        column=0,
                                        row=1,
                                        padx=5,
                                        columnspan=2)
        self.combobox_tipo_veiculo['values'] = [
            t for t in TipoVeiculoService.listar_tipos_veiculos()
        ]

        Label(self.app_main, text="Peso Balança: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=0, row=2, padx=5)
        self.combobox_peso_balanca = Combobox(
            self.app_main,
            textvariable=self.tolerancia_balanca,
            width=40,
            state="readonly")
        self.combobox_peso_balanca.grid(sticky="we",
                                        column=0,
                                        row=3,
                                        padx=5,
                                        columnspan=2)
        self.combobox_peso_balanca['values'] = [
            t for t in PesoBalancaService.listar_pesos_balanca()
        ]

        Label(self.app_main, text="Qtd. Lacres:",
              font=(None, 8, 'normal')).grid(sticky=W, column=0, row=4, padx=5)
        entry_numero_lacres = tkinter.Entry(
            self.app_main, textvariable=self.quantidade_lacres)
        entry_numero_lacres.grid(sticky="we",
                                 column=0,
                                 row=5,
                                 padx=(5, 10),
                                 columnspan=2)
        entry_numero_lacres.config(validate="key",
                                   validatecommand=(self.app_main.register(
                                       NumberUtils.eh_inteiro), '%P'))

        Label(self.app_main, text="Cavalo: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=0, row=6, padx=5)
        entry_placa_1 = Entry(self.app_main, textvariable=self.placa_1)
        entry_placa_1.grid(sticky="we", column=0, row=7, padx=5)
        entry_placa_1.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.placa_1))

        Label(self.app_main,
              text="Município Cavalo: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=1, row=6, padx=5)
        self.entry_municipio_placa_1 = AutocompleteEntry(self.app_main,
                                                         width=20)
        self.entry_municipio_placa_1.grid(sticky="we",
                                          column=1,
                                          row=7,
                                          padx=(5, 10))
        self.entry_municipio_placa_1.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.entry_municipio_placa_1.var))

        Label(self.app_main, text="Placa 2: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=0, row=8, padx=5)
        entry_placa_2 = Entry(self.app_main, textvariable=self.placa_2)
        entry_placa_2.grid(sticky="we", column=0, row=9, padx=5)
        entry_placa_2.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.placa_2))

        Label(self.app_main,
              text="Município Placa 2: ",
              font=(None, 8, 'normal')).grid(sticky=W, column=1, row=8, padx=5)
        self.entry_municipio_placa_2 = AutocompleteEntry(self.app_main,
                                                         width=20)
        self.entry_municipio_placa_2.grid(sticky="we",
                                          column=1,
                                          row=9,
                                          padx=(5, 10))
        self.entry_municipio_placa_2.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.entry_municipio_placa_2.var))

        Label(self.app_main, text="Placa 3: ",
              font=(None, 8, 'normal')).grid(sticky=W,
                                             column=0,
                                             row=10,
                                             padx=5)
        entry_placa_3 = Entry(self.app_main, textvariable=self.placa_3)
        entry_placa_3.grid(sticky="we", column=0, row=11, padx=5)
        entry_placa_3.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.placa_3))

        Label(self.app_main,
              text="Município Placa 3: ",
              font=(None, 8, 'normal')).grid(sticky=W,
                                             column=1,
                                             row=10,
                                             padx=5)
        self.entry_municipio_placa_3 = AutocompleteEntry(self.app_main,
                                                         width=20)
        self.entry_municipio_placa_3.grid(sticky="we",
                                          column=1,
                                          row=11,
                                          padx=(5, 10))
        self.entry_municipio_placa_3.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.entry_municipio_placa_3.var))

        Label(self.app_main, text="Placa 4: ",
              font=(None, 8, 'normal')).grid(sticky=W,
                                             column=0,
                                             row=12,
                                             padx=5)
        entry_placa_4 = Entry(self.app_main, textvariable=self.placa_4)
        entry_placa_4.grid(sticky="we", column=0, row=13, padx=5)
        entry_placa_4.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.placa_4))

        Label(self.app_main,
              text="Município Placa 4: ",
              font=(None, 8, 'normal')).grid(sticky=W,
                                             column=1,
                                             row=12,
                                             padx=5)
        self.entry_municipio_placa_4 = AutocompleteEntry(self.app_main,
                                                         width=20)
        self.entry_municipio_placa_4.grid(sticky="we",
                                          column=1,
                                          row=13,
                                          padx=(5, 10))
        self.entry_municipio_placa_4.bind(
            "<KeyRelease>",
            lambda ev: CadastroVeiculo.converter_para_maiusculo(
                ev, self.entry_municipio_placa_4.var))

        Button(self.app_main, text='Salvar', command=self.salvar_ou_atualizar) \
            .grid(sticky='we', column=0, row=14, padx=5, pady=5)

        self.botao_deletar = Button(self.app_main,
                                    text='Excluir',
                                    command=self.deletar,
                                    state=DISABLED)
        self.botao_deletar.grid(sticky='we',
                                column=1,
                                row=14,
                                padx=10,
                                pady=10)

    def centralizar_tela(self):
        window_width = self.app_main.winfo_reqwidth()
        window_height = self.app_main.winfo_reqheight()

        position_right = int(self.app_main.winfo_screenwidth() / 2.3 -
                             window_width / 2)
        position_down = int(self.app_main.winfo_screenheight() / 3 -
                            window_height / 2)

        self.app_main.geometry("+{}+{}".format(position_right, position_down))

    @staticmethod
    def converter_para_maiusculo(event, var):
        var.set(var.get().upper())

    def salvar_ou_atualizar(self):
        try:
            self.verificar_campos_obrigatorios()
            if self.veiculo_atual is None or self.veiculo_atual.id is None:
                self.salvar()
            else:
                self.atualizar()

        except RuntimeError as e:
            messagebox.showerror("Erro", e)

    def salvar(self):
        try:
            self.veiculo_atual = Veiculo()
            self.atualizar_dados_veiculo(self.veiculo_atual)
            VeiculoService.salvar_ou_atualizar(self.veiculo_atual)
            messagebox.showinfo("Sucesso", "Veículo salvo com sucesso!")
            self.app_main.destroy()

        except peewee.IntegrityError:
            traceback.print_exc(file=sys.stdout)
            messagebox.showerror(
                "Cadastro duplicado!",
                "Já existe um veículo cadastrado com esses dados!")
        except Exception as e:
            messagebox.showerror("Erro", e)

    def atualizar(self):
        try:
            self.atualizar_dados_veiculo(self.veiculo_atual)
            VeiculoService.salvar_ou_atualizar(self.veiculo_atual)
            messagebox.showinfo("Sucesso", "Veículo atualizado com sucesso!")
            self.app_main.destroy()
        except Exception as e:
            messagebox.showerror("Erro", e)

    def deletar(self):
        deletar = messagebox.askokcancel("Confirmar",
                                         "Excluir registro pernamentemente ?")
        if deletar:
            try:
                VeiculoService.deletar_veiculo(self.veiculo_atual)
                messagebox.showinfo("Sucesso", "Veículo deletado com sucesso!")

            except Exception as e:
                messagebox.showerror("Erro",
                                     "Erro deletar veículo!\n{}".format(e))

    def atualizar_dados_veiculo(self, veiculo):
        self.botao_deletar['state'] = 'normal'

        descricao_tipo_veiculo = self.tipo_veiculo.get().split(' - ')[1]
        tipo_veiculo = TipoVeiculoService.pesquisar_tipo_veiculo_pela_descricao(
            descricao_tipo_veiculo)

        descricao_peso_balanca = self.tolerancia_balanca.get().split(' - ')[1]
        peso_balanca = PesoBalancaService.pesquisar_pesos_balanca_pela_descricao(
            descricao_peso_balanca)

        quantidade_lacres = self.quantidade_lacres.get()
        placa1 = self.placa_1.get().strip()
        placa2 = self.placa_2.get().strip()
        placa3 = self.placa_3.get().strip()
        placa4 = self.placa_4.get().strip()
        c1 = CadastroVeiculo.extrair_codigo_municipio(
            self.entry_municipio_placa_1.get())
        c2 = CadastroVeiculo.extrair_codigo_municipio(
            self.entry_municipio_placa_2.get())
        c3 = CadastroVeiculo.extrair_codigo_municipio(
            self.entry_municipio_placa_3.get())
        c4 = CadastroVeiculo.extrair_codigo_municipio(
            self.entry_municipio_placa_4.get())
        municipio_placa1 = MunicipioService.pesquisar_municipio_pelo_codigo(c1)
        municipio_placa2 = MunicipioService.pesquisar_municipio_pelo_codigo(c2)
        municipio_placa3 = MunicipioService.pesquisar_municipio_pelo_codigo(c3)
        municipio_placa4 = MunicipioService.pesquisar_municipio_pelo_codigo(c4)

        veiculo.tipo_veiculo = tipo_veiculo
        veiculo.peso_balanca = peso_balanca
        veiculo.quantidade_lacres = quantidade_lacres
        veiculo.placa1 = placa1
        veiculo.placa2 = placa2
        veiculo.placa3 = placa3
        veiculo.placa4 = placa4
        veiculo.municipio_placa1 = municipio_placa1
        veiculo.municipio_placa2 = municipio_placa2
        veiculo.municipio_placa3 = municipio_placa3
        veiculo.municipio_placa4 = municipio_placa4

    @staticmethod
    def extrair_codigo_municipio(municipio):
        return "".join(re.findall("\\d*", municipio))

    def verificar_campos_obrigatorios(self):
        if not self.tipo_veiculo.get():
            raise RuntimeError("Campo obrigatório",
                               "O campo 'Tipo Veículo' é obrigatório!")

        if not self.tolerancia_balanca.get():
            RuntimeError("Campo obrigatório",
                         "O campo 'Tolerância Balança' é obrigatório!")

        if not self.placa_1.get():
            RuntimeError("Campo obrigatório",
                         "A placa do cavalo é obrigatório!")

        CadastroVeiculo.validar_formato_placa(self.placa_1.get().strip())
        CadastroVeiculo.validar_formato_municipio(
            self.entry_municipio_placa_1.get().strip())

        if self.placa_2.get().strip():
            CadastroVeiculo.validar_formato_placa(self.placa_2.get().strip())
            CadastroVeiculo.validar_formato_municipio(
                self.entry_municipio_placa_2.get().strip())

        if self.placa_3.get().strip():
            CadastroVeiculo.validar_formato_placa(self.placa_3.get().strip())
            CadastroVeiculo.validar_formato_municipio(
                self.entry_municipio_placa_3.get().strip())

        if self.placa_4.get().strip():
            CadastroVeiculo.validar_formato_placa(self.placa_4.get().strip())
            CadastroVeiculo.validar_formato_municipio(
                self.entry_municipio_placa_4.get().strip())

    @staticmethod
    def validar_formato_placa(placa):
        formato_correto = bool(
            re.match("^[A-Z]{3}[0-9][0-9A-Z][0-9]{2}$", placa))
        print('formato: {} - {}'.format(formato_correto, placa))
        if not formato_correto:
            raise RuntimeError(
                "Placa '{}' está em um formato inválido!".format(placa))

    @staticmethod
    def validar_formato_municipio(municipio):
        formato_correto = bool(re.match("^[A-Z]{2}\\s[0-9]{7}$", municipio))
        print('formato: {} - {}'.format(formato_correto, municipio))
        if not formato_correto:
            raise RuntimeError(
                "Município '{}' está em um formato inválido!".format(
                    municipio))

    def setar_campos_para_edicao(self, veiculo):
        self.botao_deletar['state'] = 'normal'
        self.veiculo_atual = veiculo

        CadastroVeiculo.selecionar_item_combobox(self.combobox_tipo_veiculo,
                                                 veiculo.tipo_veiculo)
        CadastroVeiculo.selecionar_item_combobox(self.combobox_peso_balanca,
                                                 veiculo.peso_balanca)
        self.quantidade_lacres.set(veiculo.quantidade_lacres)
        self.placa_1.set(veiculo.placa1)
        self.placa_2.set(veiculo.placa2 if veiculo.placa2 else '')
        self.placa_3.set(veiculo.placa3 if veiculo.placa3 else '')
        self.placa_4.set(veiculo.placa4 if veiculo.placa4 else '')

        self.entry_municipio_placa_1.var.set('{} {}'.format(
            veiculo.municipio_placa1.uf, veiculo.municipio_placa1.codigo))

        if veiculo.placa2:
            self.entry_municipio_placa_2.var.set('{} {}'.format(
                veiculo.municipio_placa2.uf, veiculo.municipio_placa2.codigo))

        if veiculo.placa3:
            self.entry_municipio_placa_3.var.set('{} {}'.format(
                veiculo.municipio_placa3.uf, veiculo.municipio_placa3.codigo))

        if veiculo.placa4:
            self.entry_municipio_placa_4.var.set('{} {}'.format(
                veiculo.municipio_placa4.uf, veiculo.municipio_placa4.codigo))

    @staticmethod
    def selecionar_item_combobox(combobox, selecao):
        cont = 0
        for v in combobox['values']:
            if v == str(selecao):
                combobox.current(cont)
            cont += 1
Example #50
0
class TestItem:
    def __init__(self, master, title, x_coor, y_coor, serial=False):
        self.__chb_var = IntVar()
        self.__p_value = StringVar()
        self.__result = StringVar()
        self.__p_value_02 = StringVar()
        self.__result_02 = StringVar()
        checkbox = Checkbutton(master, text=title, variable=self.__chb_var)
        checkbox.place(x=x_coor, y=y_coor)

        p_value_entry = Entry(master, textvariable=self.__p_value)
        p_value_entry.config(state=DISABLED)
        p_value_entry.place(x=365, y=y_coor, width=500, height=25)

        result_entry = Entry(master, textvariable=self.__result)
        result_entry.config(state=DISABLED)
        result_entry.place(x=870, y=y_coor, width=350, height=25)

        if serial:
            p_value_entry_02 = Entry(master, textvariable=self.__p_value_02)
            p_value_entry_02.config(state=DISABLED)
            p_value_entry_02.place(x=365, y=y_coor + 30, width=500, height=25)

            result_entry_02 = Entry(master, textvariable=self.__result_02)
            result_entry_02.config(state=DISABLED)
            result_entry_02.place(x=870, y=y_coor + 30, width=350, height=25)

    def get_check_box_value(self):
        return self.__chb_var.get()

    def set_check_box_value(self, value):
        self.__chb_var.set(value)

    def set_p_value(self, value):
        self.__p_value.set(value)

    def set_result_value(self, value):
        self.__result.set(value)

    def set_p_value_02(self, value):
        self.__p_value_02.set(value)

    def set_result_value_02(self, value):
        self.__result_02.set(value)

    def set_values(self, values):
        self.__p_value.set(values[0])
        self.__result.set(self.__get_result_string(values[1]))

    def set_p_2_values(self, values):
        self.__p_value_02(values[0])
        self.__result_02(self.__get_result_string(values[1]))

    def reset(self):
        self.set_check_box_value(0)
        self.set_p_value('')
        self.set_result_value('')
        self.set_p_value_02('')
        self.set_result_value_02('')

    def __get_result_string(self, result):
        if result == True:
            return 'Random'
        else:
            return 'Non-Random'
Example #51
0
class CFGDemo:
    def __init__(self, grammar, text):
        self._grammar = grammar
        self._text = text

        # Set up the main window.
        self._top = Tk()
        self._top.title("Context Free Grammar Demo")

        # Base font size
        self._size = IntVar(self._top)
        self._size.set(12)  # = medium

        # Set up the key bindings
        self._init_bindings(self._top)

        # Create the basic frames
        frame1 = Frame(self._top)
        frame1.pack(side="left", fill="y", expand=0)
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_grammar(frame1)
        self._init_treelet(frame1)
        self._init_workspace(self._top)

    # //////////////////////////////////////////////////
    # Initialization
    # //////////////////////////////////////////////////

    def _init_bindings(self, top):
        top.bind("<Control-q>", self.destroy)

    def _init_menubar(self, parent):
        pass

    def _init_buttons(self, parent):
        pass

    def _init_grammar(self, parent):
        self._prodlist = ProductionList(parent, self._grammar, width=20)
        self._prodlist.pack(side="top", fill="both", expand=1)
        self._prodlist.focus()
        self._prodlist.add_callback("select", self._selectprod_cb)
        self._prodlist.add_callback("move", self._selectprod_cb)

    def _init_treelet(self, parent):
        self._treelet_canvas = Canvas(parent, background="white")
        self._treelet_canvas.pack(side="bottom", fill="x")
        self._treelet = None

    def _init_workspace(self, parent):
        self._workspace = CanvasFrame(parent, background="white")
        self._workspace.pack(side="right", fill="both", expand=1)
        self._tree = None
        self.reset_workspace()

    # //////////////////////////////////////////////////
    # Workspace
    # //////////////////////////////////////////////////

    def reset_workspace(self):
        c = self._workspace.canvas()
        fontsize = int(self._size.get())
        node_font = ("helvetica", -(fontsize + 4), "bold")
        leaf_font = ("helvetica", -(fontsize + 2))

        # Remove the old tree
        if self._tree is not None:
            self._workspace.remove_widget(self._tree)

        # The root of the tree.
        start = self._grammar.start().symbol()
        rootnode = TextWidget(c, start, font=node_font, draggable=1)

        # The leaves of the tree.
        leaves = []
        for word in self._text:
            leaves.append(TextWidget(c, word, font=leaf_font, draggable=1))

        # Put it all together into one tree
        self._tree = TreeSegmentWidget(c, rootnode, leaves, color="white")

        # Add it to the workspace.
        self._workspace.add_widget(self._tree)

        # Move the leaves to the bottom of the workspace.
        for leaf in leaves:
            leaf.move(0, 100)

        # self._nodes = {start:1}
        # self._leaves = dict([(l,1) for l in leaves])

    def workspace_markprod(self, production):
        pass

    def _markproduction(self, prod, tree=None):
        if tree is None:
            tree = self._tree
        for i in range(len(tree.subtrees()) - len(prod.rhs())):
            if tree["color", i] == "white":
                self._markproduction  # FIXME: Is this necessary at all?

            for j, node in enumerate(prod.rhs()):
                widget = tree.subtrees()[i + j]
                if (isinstance(node, Nonterminal)
                        and isinstance(widget, TreeSegmentWidget)
                        and node.symbol == widget.label().text()):
                    pass  # matching nonterminal
                elif (isinstance(node, str) and isinstance(widget, TextWidget)
                      and node == widget.text()):
                    pass  # matching nonterminal
                else:
                    break
            else:
                # Everything matched!
                print("MATCH AT", i)

    # //////////////////////////////////////////////////
    # Grammar
    # //////////////////////////////////////////////////

    def _selectprod_cb(self, production):
        canvas = self._treelet_canvas

        self._prodlist.highlight(production)
        if self._treelet is not None:
            self._treelet.destroy()

        # Convert the production to a tree.
        rhs = production.rhs()
        for (i, elt) in enumerate(rhs):
            if isinstance(elt, Nonterminal):
                elt = Tree(elt)
        tree = Tree(production.lhs().symbol(), *rhs)

        # Draw the tree in the treelet area.
        fontsize = int(self._size.get())
        node_font = ("helvetica", -(fontsize + 4), "bold")
        leaf_font = ("helvetica", -(fontsize + 2))
        self._treelet = tree_to_treesegment(canvas,
                                            tree,
                                            node_font=node_font,
                                            leaf_font=leaf_font)
        self._treelet["draggable"] = 1

        # Center the treelet.
        (x1, y1, x2, y2) = self._treelet.bbox()
        w, h = int(canvas["width"]), int(canvas["height"])
        self._treelet.move((w - x1 - x2) / 2, (h - y1 - y2) / 2)

        # Mark the places where we can add it to the workspace.
        self._markproduction(production)

    def destroy(self, *args):
        self._top.destroy()

    def mainloop(self, *args, **kwargs):
        self._top.mainloop(*args, **kwargs)
Example #52
0
class UBX_MSGRATE_Frame(Frame):
    """
    UBX Message Rate configuration command panel.
    """

    def __init__(self, app, container, *args, **kwargs):
        """
        Constructor.

        :param object app: reference to main tkinter application
        :param frame container: container frame
        """

        self.__app = app  # Reference to main application class
        self.__master = self.__app.get_master()  # Reference to root class (Tk)
        self.__container = container

        Frame.__init__(self, self.__container.container, *args, **kwargs)

        self._img_send = ImageTk.PhotoImage(Image.open(ICON_SEND))
        self._img_pending = ImageTk.PhotoImage(Image.open(ICON_PENDING))
        self._img_confirmed = ImageTk.PhotoImage(Image.open(ICON_CONFIRMED))
        self._img_warn = ImageTk.PhotoImage(Image.open(ICON_WARNING))
        self._ddc_rate = IntVar()
        self._uart1_rate = IntVar()
        self._usb_rate = IntVar()
        self._spi_rate = IntVar()
        self._cfg_msg_command = None

        self._body()
        self._do_layout()
        self._attach_events()
        self._reset()

    def _body(self):
        """
        Set up frame and widgets.
        """

        MAX_RATE = 0xFF
        self._lbl_cfg_msg = Label(self, text=LBLCFGMSG, anchor="w")
        self._lbx_cfg_msg = Listbox(
            self,
            border=2,
            relief="sunken",
            bg=ENTCOL,
            height=7,
            justify=LEFT,
            exportselection=False,
        )
        self._scr_cfg_msg = Scrollbar(self, orient=VERTICAL)
        self._lbx_cfg_msg.config(yscrollcommand=self._scr_cfg_msg.set)
        self._scr_cfg_msg.config(command=self._lbx_cfg_msg.yview)
        self._lbl_ddc = Label(self, text="I2C")
        self._spn_ddc = Spinbox(
            self,
            width=3,
            from_=0,
            to=MAX_RATE,
            textvariable=self._ddc_rate,
            state=READONLY,
            readonlybackground=ENTCOL,
        )
        self._lbl_uart1 = Label(self, text="UART1")
        self._spn_uart1 = Spinbox(
            self,
            width=3,
            from_=0,
            to=MAX_RATE,
            textvariable=self._uart1_rate,
            state=READONLY,
            readonlybackground=ENTCOL,
        )
        self._lbl_usb = Label(self, text="USB")
        self._spn_usb = Spinbox(
            self,
            width=3,
            from_=0,
            to=MAX_RATE,
            textvariable=self._usb_rate,
            state=READONLY,
            readonlybackground=ENTCOL,
        )
        self._lbl_spi = Label(self, text="SPI")
        self._spn_spi = Spinbox(
            self,
            width=3,
            from_=0,
            to=MAX_RATE,
            textvariable=self._spi_rate,
            state=READONLY,
            readonlybackground=ENTCOL,
        )
        self._lbl_send_command = Label(self)
        self._btn_send_command = Button(
            self,
            image=self._img_send,
            width=50,
            fg="green",
            command=self._on_send_cfg_msg,
            font=self.__app.font_md,
        )

    def _do_layout(self):
        """
        Layout widgets.
        """

        self._lbl_cfg_msg.grid(column=0, row=0, columnspan=6, padx=3, sticky=(W, E))
        self._lbx_cfg_msg.grid(
            column=0, row=1, columnspan=2, rowspan=8, padx=3, pady=3, sticky=(W, E)
        )
        self._scr_cfg_msg.grid(column=1, row=1, rowspan=8, sticky=(N, S, E))
        self._lbl_ddc.grid(column=2, row=1, rowspan=2, padx=0, pady=1, sticky=(E))
        self._spn_ddc.grid(column=3, row=1, rowspan=2, padx=0, pady=0, sticky=(W))
        self._lbl_uart1.grid(column=2, row=3, rowspan=2, padx=0, pady=1, sticky=(E))
        self._spn_uart1.grid(column=3, row=3, rowspan=2, padx=0, pady=0, sticky=(W))
        self._lbl_usb.grid(column=2, row=5, rowspan=2, padx=0, pady=1, sticky=(E))
        self._spn_usb.grid(column=3, row=5, rowspan=2, padx=0, pady=0, sticky=(W))
        self._lbl_spi.grid(column=2, row=7, rowspan=2, padx=0, pady=1, sticky=(E))
        self._spn_spi.grid(column=3, row=7, rowspan=2, padx=0, pady=0, sticky=(W))
        self._btn_send_command.grid(
            column=4, row=1, rowspan=8, ipadx=3, ipady=3, sticky=(E)
        )
        self._lbl_send_command.grid(
            column=5, row=1, rowspan=8, ipadx=3, ipady=3, sticky=(E)
        )

        (cols, rows) = self.grid_size()
        for i in range(cols):
            self.grid_columnconfigure(i, weight=1)
        for i in range(rows):
            self.grid_rowconfigure(i, weight=1)
        self.option_add("*Font", self.__app.font_sm)

    def _attach_events(self):
        """
        Bind listbox selection events.
        """

        self._lbx_cfg_msg.bind("<<ListboxSelect>>", self._on_select_cfg_msg)

    def _reset(self):
        """
        Reset settings to defaults.
        """

        idx = 0
        for _, val in UBX_CONFIG_MESSAGES.items():
            self._lbx_cfg_msg.insert(idx, val)
            idx += 1

    def update_status(self, cfgtype, **kwargs):
        """
        Update pending confirmation status.
        """

        if cfgtype == "CFG-MSG":
            self.__container.set_status("CFG-MSG GET message received", "green")
            self._ddc_rate.set(kwargs.get("ddcrate", 0))
            self._uart1_rate.set(kwargs.get("uart1rate", 0))
            self._usb_rate.set(kwargs.get("usbrate", 0))
            self._spi_rate.set(kwargs.get("spirate", 0))
            self._lbl_send_command.config(image=self._img_confirmed)
        elif cfgtype == "ACK-NAK":
            self.__container.set_status("CFG-MSG POLL message rejected", "red")
            self._lbl_send_command.config(image=self._img_warn)

    def _on_select_cfg_msg(self, *args, **kwargs):  # pylint: disable=unused-argument
        """
        CFG-MSG command has been selected.
        """

        idx = self._lbx_cfg_msg.curselection()
        self._cfg_msg_command = self._lbx_cfg_msg.get(idx)

        # poll selected message configuration to get current message rates
        msg = key_from_val(UBX_CONFIG_MESSAGES, self._cfg_msg_command)
        self._do_poll_msg(msg)

    def _on_send_cfg_msg(self, *args, **kwargs):  # pylint: disable=unused-argument
        """
        CFG-MSG command send button has been clicked.
        """

        msg = key_from_val(UBX_CONFIG_MESSAGES, self._cfg_msg_command)
        msgClass = int.from_bytes(msg[0:1], "little", signed=False)
        msgID = int.from_bytes(msg[1:2], "little", signed=False)
        rateDDC = int(self._ddc_rate.get())
        rateUART1 = int(self._uart1_rate.get())
        rateUSB = int(self._usb_rate.get())
        rateSPI = int(self._spi_rate.get())
        data = UBXMessage(
            "CFG",
            "CFG-MSG",
            SET,
            msgClass=msgClass,
            msgID=msgID,
            rateDDC=rateDDC,
            rateUART1=rateUART1,
            rateUSB=rateUSB,
            rateSPI=rateSPI,
        )
        self.__app.serial_handler.serial_write(data.serialize())
        self._lbl_send_command.config(image=self._img_pending)
        self.__container.set_status("CFG-MSG SET message sent", "green")
        self.__container.set_pending(UBX_CFGMSG, ("ACK-ACK", "ACK-NAK"))

        self._do_poll_msg(msg)

    def _do_poll_msg(self, msg):
        """
        Poll message rate.
        """

        data = UBXMessage("CFG", "CFG-MSG", POLL, payload=msg)  # poll for a response
        self.__app.serial_handler.serial_write(data.serialize())
        self._lbl_send_command.config(image=self._img_pending)
        self.__container.set_status("CFG-MSG POLL message sent", "blue")
        self.__container.set_pending(UBX_CFGMSG, ("CFG-MSG", "ACK-NAK"))
Example #53
0
class window(Tk):
    """Creates a window to display current progress in the game and return values given to the game object in order to progress
    the game.
    Creates a keyboard with extra buttons to show game stats, close the window, and start a new game
    Finds the current stage of the game and displays the appropriate PNG file in the window"""

    # Step 4.1: Create init function, bringing data from Game object

    def __init__(self, game_obj: 'expects game class object'):
        assert (type(game_obj)) == game
        Tk.__init__(self)
        self.title('Hangman')

        self.geometry("1000x600+250+100")
        self.head = Label(text='Hello World!')
        self.game = game_obj
        self.word_label = Label(self,
                                text="  " + self.game.partial_word + '  ',
                                font=('Concolas 24 bold'))

        self.try_label = Label(self, text="Guesses left:")
        self.wins_label = Label(self, text="Wins:")
        self.losses_label = Label(self, text="Losses:")

        self.labeltext = IntVar()
        self.labeltext.set(self.game.Misses())
        self.missNum = Label(self, textvariable=self.labeltext)

        self.wintext = IntVar()
        self.wintext.set(self.game.totalwin)
        self.winNum = Label(self, textvariable=self.wintext)

        self.losstext = IntVar()
        self.losstext.set(self.game.totalloss)
        self.lossNum = Label(self, textvariable=self.losstext)

        self.keyboard_function()
        self.hangman_stage(0)
        self.package_update(0)

    # Step 4.2: Create Hint keyboard function

    def hint_function(self):
        """Function for the a button that returns the next letter while counting the hint as a missed guess"""
        self.game.miss += 1
        self.labeltext.set(self.game.miss)
        for c in self.game.word.upper():
            if c in self.game.partial_word:
                pass
            else:
                x = c
                self.keyboard_return(x)
                break

        self.package_update(1)
        print(self.game.miss)

    # Step 4.3: Create new game keyboard function

    def new_game_button(self):
        """Function for the new game button to reset the game values and spawn a new word"""
        self.game.new_game()
        self.package_update(
            0
        )  #Run both to set up initial conditions and reset all the previously triggered conditions
        self.package_update(1)

    # Step 4.4: Create keyboard function

    def keyboard_function(self):
        """Function spawns all of the buttons for the GUI keyboard"""
        self.close_button = Button(self,
                                   text="Close",
                                   command=self.quit,
                                   activebackground='red',
                                   activeforeground='light blue',
                                   font=("Helvetica 18"),
                                   width=4)
        self.close_button.grid(row=4, column=12)
        self.new_button = Button(self,
                                 text="New Game",
                                 command=lambda n=0: self.new_game_button(),
                                 activebackground='red',
                                 activeforeground='light blue',
                                 font=("Helvetica 18"))
        self.new_button.grid(row=4, column=3, columnspan=2)
        self.miss_button = Button(self,
                                  text="Hint",
                                  command=self.hint_function,
                                  font=("Helvetica 18"),
                                  width=4)
        self.miss_button.grid(column=3, row=3)
        keyboard = [
            'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D',
            'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'
        ]
        n = 0
        for i in keyboard:
            Button(self,
                   text=i,
                   command=lambda d=i: self.keyboard_return(d),
                   font=("Helvetica 18"),
                   width=4).grid(row=2 + n // 10, column=3 + n % 10)
            n += 1
            if n == 10:
                n += 1
            elif n == 20:
                n += 2

    # Step 4.3: Create keyboard return function which gets called every time a button is activated

    def keyboard_return(self, x: str):
        """Function takes button presses and progresses the game"""
        assert (type(x)) == str
        if self.game.miss < 6:
            self.game.partial_word, self.game.miss = self.game.word_checker(
                self.game.word, self.game.partial_word, x, self.game.miss)
        self.package_update(
            1
        )  # 2 Times because it doesnt work otherwise, probably due to timing
        self.package_update(1)
        print(self.game)

    # Step 4.4: Create image function to render hangman picture and update it

    def hangman_stage(self,
                      stage: int) -> 'Mutates imgLabel with Photoimage object':
        """function takes an integer between 0 and 6 and displays the corresponding stage in the GUI"""
        assert (type(stage)) == int
        photos = [
            PhotoImage(file='hangman-0.png'),
            PhotoImage(file='hangman-1.png'),
            PhotoImage(file='hangman-2.png'),
            PhotoImage(file='hangman-3.png'),
            PhotoImage(file='hangman-4.png'),
            PhotoImage(file='hangman-5.png'),
            PhotoImage(file='hangman-6.png')
        ]
        self.imgLabel = Label(image=photos[stage])
        self.imgLabel.image = photos[
            stage]  # Python's garbage collector won't keep the images unless I create an object specific variable to hold it
        self.imgLabel.images = photos
        self.imgLabel.grid(row=0, column=0, columnspan=3, padx=10, pady=40)

    # Step 4.5: Create a packing function to place all objects on the grid and update grid

    def package_update(self, update: int):
        """function places all objects on a grid to display
        the param update takes two arguments
        0 - initial placement
        1 - update placement

        function places certain items on the grid every time it is ran
        items that only need to be placed once are only executed if update = 0
        otherwise items that only need to be placed during certain stages
        or items that change throughout the game are placed if update = 1"""

        self.word_label = Label(self,
                                text="  " + self.game.partial_word + "  ",
                                font=('Concolas 24 bold'))
        self.word_label.grid(row=0, column=3, columnspan=6, padx=10)
        self.labeltext.set(self.game.Misses())
        self.wintext.set(self.game.totalwin)
        self.losstext.set(self.game.totalloss)
        self.missNum.grid(column=1, row=2)
        self.winNum.grid(column=1, row=3)
        self.lossNum.grid(column=1, row=4)

        if update == 0:
            self.loss_label = Label(self,
                                    text='                         ',
                                    font=('Concolas 24 bold'))
            self.loss_label.grid(row=1, column=3, columnspan=6, padx=10)
            self.head.grid(column=0, row=1)
            self.try_label.grid(column=0, row=2)
            self.losses_label.grid(column=0, row=4)
            self.wins_label.grid(column=0, row=3)
        else:
            if self.game.miss < 6:
                self.hangman_stage(self.game.miss)
                self.loss_label = Label(self,
                                        text='                      ',
                                        font=('Concolas 24 bold'))
                self.loss_label.grid(row=1, column=3, columnspan=6, padx=10)
            else:
                self.hangman_stage(6)
                self.loss_label = Label(self,
                                        text='Y O U  L O S T',
                                        font=('Concolas 24 bold'))
                self.loss_label.grid(row=1, column=3, columnspan=6, padx=10)
        return
Example #54
0
class TreeView(object):
    def __init__(self, *trees):
        from math import sqrt, ceil

        self._trees = trees

        self._top = Tk()
        self._top.title('NLTK')
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Control-q>', self.destroy)

        cf = self._cframe = CanvasFrame(self._top)
        self._top.bind('<Control-p>', self._cframe.print_to_file)

        # Size is variable.
        self._size = IntVar(self._top)
        self._size.set(12)
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())

        # Lay the trees out in a square.
        self._width = int(ceil(sqrt(len(trees))))
        self._widgets = []
        for i in range(len(trees)):
            widget = TreeWidget(cf.canvas(),
                                trees[i],
                                node_font=bold,
                                leaf_color='#008040',
                                node_color='#004080',
                                roof_color='#004040',
                                roof_fill='white',
                                line_color='#004040',
                                draggable=1,
                                leaf_font=helv)
            widget.bind_click_trees(widget.toggle_collapsed)
            self._widgets.append(widget)
            cf.add_widget(widget, 0, 0)

        self._layout()
        self._cframe.pack(expand=1, fill='both')
        self._init_menubar()

    def _layout(self):
        i = x = y = ymax = 0
        width = self._width
        for i in range(len(self._widgets)):
            widget = self._widgets[i]
            (oldx, oldy) = widget.bbox()[:2]
            if i % width == 0:
                y = ymax
                x = 0
            widget.move(x - oldx, y - oldy)
            x = widget.bbox()[2] + 10
            ymax = max(ymax, widget.bbox()[3] + 10)

    def _init_menubar(self):
        menubar = Menu(self._top)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Print to Postscript',
                             underline=0,
                             command=self._cframe.print_to_file,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(label='Tiny',
                                 variable=self._size,
                                 underline=0,
                                 value=10,
                                 command=self.resize)
        zoommenu.add_radiobutton(label='Small',
                                 variable=self._size,
                                 underline=0,
                                 value=12,
                                 command=self.resize)
        zoommenu.add_radiobutton(label='Medium',
                                 variable=self._size,
                                 underline=0,
                                 value=14,
                                 command=self.resize)
        zoommenu.add_radiobutton(label='Large',
                                 variable=self._size,
                                 underline=0,
                                 value=28,
                                 command=self.resize)
        zoommenu.add_radiobutton(label='Huge',
                                 variable=self._size,
                                 underline=0,
                                 value=50,
                                 command=self.resize)
        menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu)

        self._top.config(menu=menubar)

    def resize(self, *e):
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())
        xspace = self._size.get()
        yspace = self._size.get()
        for widget in self._widgets:
            widget['node_font'] = bold
            widget['leaf_font'] = helv
            widget['xspace'] = xspace
            widget['yspace'] = yspace
            if self._size.get() < 20: widget['line_width'] = 1
            elif self._size.get() < 30: widget['line_width'] = 2
            else: widget['line_width'] = 3
        self._layout()

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)
Example #55
0
class Root(Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title('Biolocalizacion')
        self.minsize(500, 200)
        ico = os.path.join(PROJECT_DIR, 'resources/favicon.ico')
        # self.wm_iconbitmap(ico)
        self.labelFrameWaiting = ttk.LabelFrame(self, text='')
        self.labelFrameWaiting.grid(column=0, row=1, padx=30, pady=10)
        self.createLabel()

    def createLabel(self):
        self.labelFrameOptionMenu = ttk.LabelFrame(self,
                                                   text='Tipo de secuencia')
        self.labelFrameOptionMenu.grid(column=0, row=0, padx=20, pady=20)
        self.optionMenu()
        self.labelFrameOpenFile = ttk.LabelFrame(
            self, text='Abrir archivo a geolocalizar')
        self.labelFrameOpenFile.grid(column=1, row=0, padx=20, pady=20)
        self.label = ttk.Label(self.labelFrameOpenFile, text='')
        self.label.grid(column=1, row=2)
        self.button()
        self.labelFrameBootstrap = ttk.LabelFrame(self, text='Bootstrap')
        self.labelFrameBootstrap.grid(column=2, row=0, padx=20, pady=20)
        self.input()

    def optionMenu(self):
        self.typeSequence = StringVar(self.labelFrameOptionMenu)
        self.typeSequence.set(next(iter(SEQUENCE_TYPE.keys())))
        w = OptionMenu(self.labelFrameOptionMenu, self.typeSequence,
                       *SEQUENCE_TYPE.keys())
        w.pack()

    def button(self):
        self.button = ttk.Button(self.labelFrameOpenFile,
                                 text='Ingrese archivo',
                                 command=self.fileDialog)
        self.button.grid(column=1, row=1, padx=30, pady=10)

    def fileDialog(self):
        if platform.system() == 'Windows':  # Windows
            self.fileName = filedialog.askopenfilename(
                initialdir='/',
                title='Seleccionar archivo',
                filetype=(('fasta', '*.fasta'), ('All Files', '*.*')))
        else:  # linux variants
            self.fileName = filedialog.askopenfilename(
                initialdir='/',
                title='Seleccionar archivo',
                filetypes=(('fasta', '*.fasta'), ('All Files', '*.*')))
        try:
            self.check_fasta()
            self.button.configure(text=os.path.basename(self.fileName))
            self.waitingLabel()
            geolocation.run(self.fileName,
                            alphabet=SEQUENCE_TYPE.get(
                                self.typeSequence.get()),
                            bootstrap=self.bootstrap.get(),
                            aligned=self.aligned,
                            quantitySequences=self.quantitySequences)
            self.waitingLabel.config(text='Procesado con exito')
            self.update()
            filepath = 'egfr-family.phy.log'
            # Windows
            # threading.Thread(target=lambda: os.system('egfr-family.phy.log')).start()
            # Linux
            # threading.Thread(target=lambda: subprocess.run(["xdg-open", 'egfr-family.phy.log'], check=True)).start()
            if platform.system() == 'Darwin':  # macOS
                threading.Thread(
                    target=lambda: subprocess.run(['open', filepath])).start()
            elif platform.system() == 'Windows':  # Windows
                threading.Thread(target=lambda: os.startfile(filepath)).start()
            else:  # linux variants
                threading.Thread(target=lambda: subprocess.run(
                    ["xdg-open", filepath], check=True)).start()
            threading.Thread(target=lambda: plt.show()).run()
            self._update()
        except FileNotFoundError:
            pass
        except TypeSequenceException:
            pass
        except Exception:
            pass

    def check_fasta(self):
        self.aligned = False
        self.is_fasta()
        self.is_content_valid_fasta()

    def is_fasta(self):
        with open(self.fileName, "r") as handle:
            fasta = SeqIO.parse(handle, "fasta")
            if not any(
                    fasta
            ):  # False when `fasta` is empty, i.e. wasn't a FASTA file
                msg = 'El formato del archivo debe ser fasta'
                self.label.configure(text=msg)
                raise Exception(msg)

    def is_content_valid_fasta(self):
        with open(self.fileName, "r") as handle:
            lines = iter(handle.read().splitlines(True))
            nextLine = next(lines, None)
            seqs = []
            seq = []
            if nextLine.startswith('>'):
                nextLine = next(lines, None)
                while nextLine is not None:
                    if not nextLine.startswith('>'):
                        seq.append(nextLine)
                        nextLine = next(lines, None)
                    else:
                        seq = "".join(seq)
                        seq = seq.replace("\n", "")
                        seq = seq.replace("\r", "")
                        seqs.append(seq)
                        seq = []
                        nextLine = next(lines, None)
                seq = "".join(seq)
                seq = seq.replace("\n", "")
                seq = seq.replace("\r", "")
                seqs.append(seq)
                self.quantitySequences = len(seqs)
                if self.quantitySequences < SEQUENCES_MIN:
                    msg = 'Un mínimo de 5 secuencias es requerido'
                    self.label.configure(text=msg)
                    raise Exception(msg)
                msg = ''
                if self.is_aligned(seqs):
                    self.aligned = True
                    msg = msg + ' Secuencias alineadas, se salteara ese paso'
                self.label.configure(text=msg)
                if len(
                        set(
                            list(
                                map(lambda sequence: len(list(set(sequence))),
                                    seqs)))) == 1:
                    for sequence in seqs:
                        seqDistinct = list(set(sequence))
                        seqDistinct.sort()
                        if seqDistinct == [
                                'A', 'C', 'G', 'T'
                        ] or seqDistinct == ['A', 'C', 'G', 'U']:
                            if self.typeSequence.get().lower() != "nucleotido":
                                msg = 'Ha especificado tipo de secuencia: ' + self.typeSequence.get(
                                ) + ' y son posibles secuencias de nucleotidos'
                                if not messagebox.askyesno(
                                        message=msg + ", ¿Desea continuar?",
                                        title="Advertencia"):
                                    raise TypeSequenceException(msg)
                                else:
                                    break
                        else:
                            if self.typeSequence.get().lower() != 'proteina':
                                msg = 'Ha especificado tipo de secuencia: ' + self.typeSequence.get(
                                ) + ' y son posibles secuencias de proteinas'
                                if not messagebox.askyesno(
                                        message=msg + ", ¿Desea continuar?",
                                        title="Advertencia"):
                                    raise TypeSequenceException(msg)
                                else:
                                    break
            else:
                msg = 'El formato del contenido debe comenzar con > para cada header por secuencia'
                self.label.configure(text=msg)
                raise Exception(msg)

    def is_aligned(self, seqs):
        return len(set(list(map(
            lambda sequence: len(sequence), seqs)))) == 1 and next(
                filter(lambda sequence: '-' in sequence, seqs),
                None) is not None

    def waitingLabel(self):
        self.waitingLabel = ttk.Label(self.labelFrameWaiting, text='')
        self.infoWaitingLabel = ttk.Label(self.labelFrameWaiting, text='')
        self.button.state(["disabled"])
        msg = ''
        if self.aligned:
            msg = 'Secuencias alineadas, se salteara ese paso.'
        self.infoWaitingLabel.grid(column=0, row=0)
        self.infoWaitingLabel.config(text=msg)
        self.waitingLabel.grid(column=1, row=0)
        self.waitingLabel.config(text="Procesando...")
        self.update()

    def input(self):
        # vcmd = (self.register(self.onValidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        # self.bootstrap = IntVar(self, value="1000")
        # self.entry = Entry(self.labelFrameBootstrap, validate="key", validatecommand=vcmd, textvariable=self.bootstrap)
        # self.bootstrap = max(self.bootstrap.get(), 1000)
        # self.entry.grid(column=1, row=1, padx=30, pady=10)
        # self.entry.pack()
        self.bootstrap = IntVar(self.labelFrameBootstrap)
        self.bootstrap.set(next(iter(BOOTSTRAP_QUANTITY)))
        w = OptionMenu(self.labelFrameBootstrap, self.bootstrap,
                       *BOOTSTRAP_QUANTITY)
        w.pack()

    def onValidate(self, action, index, value_if_allowed, prior_value, text,
                   validation_type, trigger_type, widget_name):
        if value_if_allowed:
            try:
                int(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False

    def _update(self):
        python_script.main_refresh(self, python_script)
class App(Tk):
    def showMessage(self, messagetype, messageString):
        if messagetype==MSG_ERROR:
            messagebox.showerror("Error", messageString)
        elif messagetype==MSG_WARN:
            messagebox.showwarning("Warning",messageString)
        elif messagetype==MSG_INFO:
            messagebox.showinfo("Information",messageString)
    
    def sendMessage(self, messageType,messageText):
        self.api.sendMessage(messageType,messageText)
    
    def getGrid(self):
        if self.gpsl==None:
            print('GPS Listener not running. Update settings and try again.')
           # js8callAPIsupport.js8CallUDPAPICalls.showMessage(MSG_ERROR, getStatus()))
            self.showMessage('ERROR', 'GPS Listener not running. Update settings and try again.')
            return
        if self.showoutput==1:
            print('Getting Grid from GPS')
        gpsText = self.gpsl.getMaidenhead()
        if self.showoutput==1:
            print(gpsText)
        if gpsText==None:
            gpsText = "No Fix"
        
        ngr = self.gpsl.get_ngr()
        
        if gpsText!=None:
            if gpsText=='None':
                gpsText="No Fix"
                    #print("Got Grid "+gpsText)
            if ngr!=None:
                None
                #print("Got NGR "+ngr)
            
            latlon=''
        
            if self.gpsl.getStatus().startswith('Error'):
                self.gpsText=self.gpsl.getStatus()
                lat=None
                lon=None
                latlon=self.gpsl.getStatus()
            else:
                lat=self.gpsl.getCurrentLat()
                lon=self.gpsl.getCurrentLon()
        
            if lat!=None:
                latf = f"{lat:.5f}"
                lonf = f"{lon:.5f}"
                latlon=str(latf)+', '+str(lonf)
        
            self.var1.set(gpsText)
            self.latlonvar.set(latlon)        
            
            return gpsText

#            if gpsText!= "No Fix" and gpsText!='JJ00aa00':
#                self.setJS8CallGridButton.configure(state='normal')
#                self.sendJS8CallALLCALLButton.configure(state='normal')
#                self.latlonButton.configure(state='normal')
                #self.ngrStr.set(ngr)
#            else:
#                self.setJS8CallGridButton.configure(state='disabled')
#                self.sendJS8CallALLCALLButton.configure(state='disabled')
#                self.latlonButton.configure(state='normal')
#                self.ngrStr.set('No Fix')
#                self.var1.set('No Fix')
#                self.latlonvar.set('No Fix')
            
            #if gpsText=='JJ00aa00':
                #self.ngrStr.set('No Fix')
    
   
    def show_frame(self, context):
        frame = self.frames[context]
        frame.tkraise()
    def nav_buttons(self, frame, controller):
        
#        gps_page=Button(frame, text="GPS", command=lambda:controller.show_frame(GPSPage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
#        gps_page.grid(row=2, column=0)
#        aprs_page=Button(frame, text="APRS Message", command=lambda:controller.show_frame(MessagePage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
#        aprs_page.grid(row=2, column=1)
#        settings_page=Button(frame, text="Settings", command=lambda:controller.show_frame(SettingsPage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
#        settings_page.grid(row=2, column=2)

        rh=0.1
        rw=0.28
        rx=0.01
       # ry=0.02
        
        gps_page=Button(frame, text="GPS", command=lambda:controller.show_frame(GPSPage), bg="white")
        gps_page.grid(row=2, column=0, sticky=W+E+N+S, padx=5, pady=5)

        aprs_page=Button(frame, text="APRS Message", command=lambda:controller.show_frame(MessagePage), bg="white")
        aprs_page.grid(row=2, column=1, sticky=W+E+N+S, padx=5, pady=5)
        settings_page=Button(frame, text="Settings", command=lambda:controller.show_frame(SettingsPage), bg="white")
        settings_page.grid(row=2, column=2, sticky=W+E+N+S, padx=5, pady=5)
    
    def sendGridToALLCALL(self,gridText):
        self.api.sendGridToALLCALL(gridText, self.gpsl.getStatus())
    def sendGridToJS8Call(self, gridText):
        self.api.sendGridToJS8Call(gridText, self.gpsl.getStatus())
      
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Main Window is closing, call any function you'd like here!")

    def __enter__(self):
            # make a database connection and return it
        print('Starting')
    def ask_quit(self):
        if self.gpsl!=None:
            print('Shutting down GPS Listener')
            self.gpsl.setReadGPS(False)
            self.gpsl.join()
            
        print('Exiting. Thanks for using JS8CallUtils By M0IAX')
        self.destroy()  
    def update_timer(self):
        if self.autoGridToJS8Call.get()==0:
            self.initTimer()
            self.timerStr.set("Timer Not Active")
            
        if self.autoGridToJS8Call.get()==1:
            
            if self.timer<=0:
                self.initTimer()
            self.timer=self.timer-1
            t="Timer: " + str(self.timer)
            self.timerStr.set(t)
            
            if self.timer<=0:
                print('Got to Zero')
                gridstr = self.getGrid()
                print('grd ', gridstr)
                combotext=self.autocombo.get()
                print("combo text ", combotext)
                if gridstr!=None and gridstr!='' and gridstr!="No Fix":
                    if combotext=="Auto update JS8Call Grid":
                        self.sendGridToJS8Call(gridstr)
                    if combotext=="Auto TX Grid to APRSIS":    
                        self.sendGridToALLCALL(gridstr)
                    if combotext=="Auto TX Grid to APRSIS and Update JS8Call Grid":    
                        self.sendGridToJS8Call(gridstr)
                        self.sendGridToALLCALL(gridstr)

                else:
                    print('No grid. enabld gps and wait for fix')        
                self.initTimer()
        self.after(1000, self.update_timer)
    #def update_status_timer(self):
    #    self.mainWindow.after(10000, self.update_status_timer)

    def initTimer(self):
            self.timer=self.MAX_TIMER
    def autocomboChange(self, event):
        return ''
    def comboChange(self, event):
        mode = self.combo.get()
        if mode=="APRS":
            self.callLbl.config(text='Enter Callsign (including SSID)')
        elif mode=="Email":
            self.callLbl.config(text='Enter Email Address to send to')
        elif mode=="SMS":
            self.callLbl.config(text='Enter cell phone number')
    def cb(self):
        None
        #if self.autoGridToJS8Call.get()==0:
        #    self.autoGridToJS8Call.set(1)
        #else:
        #    self.autoGridToJS8Call.set(0)
        #    self.timerStr.set("Timer Not Active")

    def refreshSettings(self):
        self.settingValues = settings.Settings()

        self.showoutput = int(self.settingValues.getDebugSettingValue('showoutput'))
        
        self.timeinmins = int(self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(self.settingValues.getAppSettingValue('autoselectedoption'))

        self.autocombo.current(self.autooption) #set the selected item
        
        self.MAX_TIMER=self.timeinmins*60    
    
        self.serverPortVar = StringVar()
        self.serverVar = IntVar()
        
        self.serverPortVar.set(int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(self.settingValues.getNetworkSettingValue('serverip'))
        
        self.gpsOption = self.settingValues.getGPSHardwareSettingValue('option')
    
        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()
        
        self.gpsComPortVar.set(self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(self.settingValues.getAppSettingValue('autoonatstart'))
        
        self.autoGridCheck.configure(text="Enable Auto update every "+str(self.timeinmins)+" mins.")
        
        if self.gpsOption=='None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')
            
            
        if self.gpsl!=None:
            self.gpsl.setPrecision(int(self.settingValues.getAppSettingValue('precision')))
            self.gpsl.setShowDebug(self.showoutput)
            
        if self.gpsOptionBeforeRefresh!=self.gpsOption:
            if self.gpsl!=None:
                print('Shutting down GPS Listener')
                #self.gpsl.destroy()
                self.gpsl.setReadGPS(False)
                self.gpsl.join()
                self.gpsl=None
            if self.gpsOption!='None':
                print('Starting GPS Listener')
                if self.gpsOption=='GPSD':
                    self.gpsl = gpsdGPSListener.GpsListener( self.settingValues.getAppSettingValue('precision'),
                                                            self.showoutput
                                                            )
                else:
                    print('Running serial gps again')
                    self.gpsl = serialGPSlistener.GPSListener(self.settingValues.getGPSHardwareSettingValue('gpscomport'),
                                                            self.settingValues.getGPSHardwareSettingValue('gpsportspeed'),
                                                            self.settingValues.getAppSettingValue('precision'),
                                                            self.showoutput
                                                            )
                self.gpsl.start()
            else:
                print('Setting thread to None')
                self.gpsl=None    
        self.gpsOptionBeforeRefresh=self.gpsOption
            

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        
        self.seq=1
        
        self.settingValues = settings.Settings()
        
        self.showoutput = int(self.settingValues.getDebugSettingValue('showoutput'))
        
        self.timeinmins = int(self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(self.settingValues.getAppSettingValue('autoselectedoption'))

        #self.autocombo.set(self.autooption)
        
        self.MAX_TIMER=self.timeinmins*60    
    
        self.serverPortVar = StringVar()
        self.serverVar = IntVar()
        
        self.serverPortVar.set(int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(self.settingValues.getNetworkSettingValue('serverip'))
        
        self.api = js8callAPIsupport.js8CallUDPAPICalls(self.settingValues.getNetworkSettingValue('serverip'),
                                                        int(self.settingValues.getNetworkSettingValue('serverport')))
        
        self.gpsOption = self.settingValues.getGPSHardwareSettingValue('option')
    
        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()
        
        self.gpsComPortSpeedVar = self.settingValues.getGPSHardwareSettingValue('gpsportspeed')
        self.gpsComPortVar = self.settingValues.getGPSHardwareSettingValue('gpscomport') 
        
        self.gpsOptionBeforeRefresh = self.gpsOption
        
        self.gpsl=None
        
        if self.gpsOption!="None":
            if self.gpsOption=='GPSD':
                self.gpsl = gpsdGPSListener.GpsListener( self.settingValues.getAppSettingValue('precision'),
                                                        self.showoutput
                                                        )
            else:
                self.gpsl = serialGPSlistener.GPSListener(self.settingValues.getGPSHardwareSettingValue('gpscomport'),
                                                        self.settingValues.getGPSHardwareSettingValue('gpsportspeed'),
                                                        self.settingValues.getAppSettingValue('precision'),
                                                        self.showoutput
                                                        )
        
            self.gpsl.start()

        self.geometry(str(WIDTH)+"x"+str(HEIGHT))
        self.title("JS8Call Utilities by M0IAX")
        
        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()
        self.maidPreceision = StringVar()
        self.autoTimeVar = StringVar()
        self.autoGridToJS8Call = IntVar()
        
        self.var1 = StringVar()
        self.var2 = StringVar()
        self.latlonvar = StringVar()
        
        #set default values
        self.gpsComPortVar.set(self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(self.settingValues.getAppSettingValue('autoonatstart'))
        
        #Main window frame
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        
        self.frames = {}

        for F in (GPSPage, MessagePage, SettingsPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')
            
        self.show_frame(GPSPage)

        bottomFrame=Frame(self)
        bottomFrame.pack()
                
        self.autocombo = Combobox(bottomFrame, state='readonly',width=45)
        self.autocombo.state='disabled'
        self.autocombo.bind('<<ComboboxSelected>>', self.autocomboChange)    
        self.autocombo['values']= ("Auto update JS8Call Grid", "Auto TX Grid to APRSIS", "Auto TX Grid to APRSIS and Update JS8Call Grid")
 
        self.autocombo.current(self.autooption) #set the selected item
        #self.autocombo.place(relx=0.05,rely=0.63, relwidth=0.9,relheight=0.1)
        self.autocombo.grid(row=0, column=0,sticky=W+E+N+S)
    
        self.autoGridToJS8Call = IntVar(value=self.autoatstart)
        self.autoGridCheck = Checkbutton(bottomFrame, text="Enable Auto update every "+str(self.timeinmins)+" mins.", variable=self.autoGridToJS8Call, command=self.cb)
        #self.autoGridCheck.place(relx=0.05,rely=0.71, relwidth=0.9,relheight=0.1)
        self.autoGridCheck.grid(row=1, column=0, sticky=W+E+N+S, padx=5, pady=5)

        if self.gpsOption=='None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')
        
        self.timer=60 #Set timer to 60 for the first tx GPS should have a lock in that time
        self.timerStr = StringVar()
        
        self.timerStr.set("Timer Not Active")
        self.timerlabel = Label(bottomFrame, textvariable=self.timerStr )
        #self.timerlabel.place(relx=0.05,rely=0.81, relwidth=0.9,relheight=0.1)
        self.timerlabel.grid(row=2, column=0,sticky=W+E+N+S)
    
        buttonFrame=Frame(self)
        buttonFrame.pack()
        
        self.nav_buttons(buttonFrame, self)
        
        self.update_timer()
Example #57
0
class Config:

    """Read/write and store all data from config files."""

    def __init__(self, cmdLineParams, master=None):
        self.cmdLineParams = cmdLineParams
        self.master = master

        self.ai_path = ''  # Path to FG_ROOT/AI directory.
        self.apt_path = ''  # Path to FG_ROOT/Airports/apt.dat.gz file.
        self.metar_path = ''  # Path to FG_ROOT/Airports/metar.dat.gz file.

        self.aircraft_dirs = [] # List of aircraft directories.
        # Dictionary whose keys are aircraft names. For each aircraft name 'n',
        # self.aircraftDict[n] is the list, in self.aircraft_dirs priority
        # order, of all Aircraft instances with that name.
        self.aircraftDict = {}
        self.aircraftList = []  # Sorted list of Aircraft instances.

        self.scenario_list = []  # List of selected scenarios.
        # List of all aircraft carriers found in AI scenario folder.
        # Each entry format is:
        # ["ship name", "parking position"... , "scenario name"]
        self.carrier_list = []

        self.settings = []  # List of basic settings read from config file.
        self.text = ''  # String to be shown in command line options window.

        # 'self.aircraftId' is the central variable telling which particular
        # aircraft is selected in FFGo's interface. It is a tuple of the form
        # (aircraftName, aircraftDir).
        self.aircraftId = misc.Observable()
        self.aircraft = StringVar()
        self.aircraftDir = StringVar()
        # Whenever 'self.aircraftId' is set, 'self.aircraft' and
        # 'self.aircraftDir' are automatically updated to reflect the new value
        # (and their observers called, even if the values didn't change).
        self.aircraftId.trace("w", self.updateAircraftNameAndDirFromAircraftId)
        # Note: the FFGo config file stores the values of 'self.aircraft' and
        #       'self.aircraftDir' separately (this makes the compatibility
        #       path easy with versions that don't know about aircraftDir).

        self.airport = StringVar() # ICAO code of the selected airport
        self.alreadyProposedChanges = StringVar()
        self.apt_data_source = IntVar()
        self.auto_update_apt = IntVar()
        self.carrier = StringVar() # when non-empty, we are in “carrier mode”
        self.FG_aircraft = StringVar()
        self.FG_bin = StringVar()
        self.FG_root = StringVar()
        self.FG_scenery = StringVar()
        self.FG_working_dir = StringVar()

        self.MagneticField_bin = StringVar()
        self.MagneticField_bin.trace('w', self.updateMagFieldProvider)

        self.filteredAptList = IntVar()
        self.language = StringVar()
        self.park = StringVar()
        self.rwy = StringVar()
        self.scenario = StringVar()
        self.mainWindowGeometry = StringVar()
        self.saveWindowPosition = IntVar()
        self.baseFontSize = StringVar()
        self.TkDefaultFontSize = IntVar()

        # tkinter.BooleanVar feels kind of messy. Sometimes, it prints out as
        # 'True', other times as '1'... IntVar seems more predictable.
        self.showFGCommand = IntVar()
        self.showFGCommandInSeparateWindow = IntVar()
        self.FGCommandGeometry = StringVar()
        self.showFGOutput = IntVar()
        self.showFGOutputInSeparateWindow = IntVar()
        self.FGOutputGeometry = StringVar()
        self.autoscrollFGOutput = IntVar()
        # Option to translate --parkpos into --lat, --lon and --heading (useful
        # when --parkpos is broken in FlightGear)
        self.fakeParkposOption = IntVar()

        self.airportStatsManager = None # will be initialized later
        self.aircraftStatsManager = None # ditto
        self.airportStatsShowPeriod = IntVar()
        self.airportStatsExpiryPeriod = IntVar()
        self.aircraftStatsShowPeriod = IntVar()
        self.aircraftStatsExpiryPeriod = IntVar()

        self.keywords = {'--aircraft=': self.aircraft,
                         '--airport=': self.airport,
                         '--fg-root=': self.FG_root,
                         '--fg-scenery=': self.FG_scenery,
                         '--carrier=': self.carrier,
                         '--parkpos=': self.park,
                         '--runway=': self.rwy,
                         'AIRCRAFT_DIR=': self.aircraftDir,
                         'AI_SCENARIOS=': self.scenario,
                         'ALREADY_PROPOSED_CHANGES=':
                                             self.alreadyProposedChanges,
                         'APT_DATA_SOURCE=': self.apt_data_source,
                         'AUTO_UPDATE_APT=': self.auto_update_apt,
                         'FG_BIN=': self.FG_bin,
                         'FG_AIRCRAFT=': self.FG_aircraft,
                         'FG_WORKING_DIR=': self.FG_working_dir,
                         'MAGNETICFIELD_BIN=': self.MagneticField_bin,
                         'FILTER_APT_LIST=': self.filteredAptList,
                         'LANG=': self.language,
                         'WINDOW_GEOMETRY=': self.mainWindowGeometry,
                         'SAVE_WINDOW_POSITION=': self.saveWindowPosition,
                         'BASE_FONT_SIZE=': self.baseFontSize,
                         'SHOW_FG_COMMAND=': self.showFGCommand,
                         'SHOW_FG_COMMAND_IN_SEPARATE_WINDOW=':
                         self.showFGCommandInSeparateWindow,
                         'FG_COMMAND_GEOMETRY=': self.FGCommandGeometry,
                         'SHOW_FG_OUTPUT=': self.showFGOutput,
                         'SHOW_FG_OUTPUT_IN_SEPARATE_WINDOW=':
                         self.showFGOutputInSeparateWindow,
                         'FG_OUTPUT_GEOMETRY=': self.FGOutputGeometry,
                         'AUTOSCROLL_FG_OUTPUT=': self.autoscrollFGOutput,
                         'FAKE_PARKPOS_OPTION=': self.fakeParkposOption,
                         'AIRPORT_STATS_SHOW_PERIOD=':
                         self.airportStatsShowPeriod,
                         'AIRPORT_STATS_EXPIRY_PERIOD=':
                         self.airportStatsExpiryPeriod,
                         'AIRCRAFT_STATS_SHOW_PERIOD=':
                         self.aircraftStatsShowPeriod,
                         'AIRCRAFT_STATS_EXPIRY_PERIOD=':
                         self.aircraftStatsExpiryPeriod}

        # In order to avoid using a lot of memory, detailed airport data is
        # only loaded on demand. Since this is quite slow, keep a cache of the
        # last retrieved data.
        self.aptDatCache = collections.deque(maxlen=50)

        self._earlyTranslationsSetup()
        self._createUserDirectories()
        self._maybeMigrateFromFGoConfig()
        # Not having the FlightGear version at this point is not important
        # enough to justify pestering the user about it. :-)
        # Defer logging of the detected FG version to fit nicely with
        # the other startup messages.
        self.update(ignoreFGVersionError=True, logFGVersion=False)

        self.setTkDefaultFontSize()
        self.setupFonts(init=True)

    def setTkDefaultFontSize(self):
        """Save unaltered TkDefaultFont size."""
        size = tkinter.font.nametofont("TkDefaultFont").actual()["size"]
        self.TkDefaultFontSize.set(size)

    def setupFonts(self, init=False):
        """Setup the default fonts.

        When called with init=True, custom fonts are created and
        stored as attributes of self. Otherwise, they are simply
        configured.

        """
        # According to <http://www.tcl.tk/man/tcl8.4/TkCmd/font.htm>, font
        # sizes are interpreted this way:
        #   - for positive values, the unit is points;
        #   - for negative values, the unit is pixels;
        #   - 0 is a special value for "a platform-dependent default size".
        #
        # Apparently, Tkinter doesn't accept floats for the 'size' parameter of
        # <font>.configure(), even when positive (tested with Python 2.7.3).
        baseSize = int(float(self.baseFontSize.get()))
        # Get the actual size when baseSize == 0, otherwise scaling won't work
        # since 0*factor == 0, regardless of the (finite) factor.
        if baseSize == 0:
            baseSize = self.TkDefaultFontSize.get()

        def scale(factor):
            return int(round(baseSize * factor))

        def configFontSize(style, factor):
            font = tkinter.font.nametofont("Tk%sFont" % style)
            font.configure(size=scale(factor))

        # Configure built-in fonts
        for style in ("Default", "Text", "Fixed", "Caption", "Tooltip"):
            # The 'if init:' here is a workaround for a weird problem: when
            # saving the settings from the Preferences dialog, even if the very
            # same font size is set here as the one that was used at program
            # initialization, the main window layout gets broken, with the
            # airport chooser Treeview taking more and more horizontal space
            # every time the settings are saved. Avoiding to reconfigure the
            # fonts in such "reinit" conditions works around the problem...
            if init:
                configFontSize(style, 1)

        for style, factor in (("Menu", 20 / 18.), ("Heading", 20 / 18.),
                              ("SmallCaption", 16 / 18.), ("Icon", 14 / 18.)):
            if init:            # Second part of the workaround mentioned above
                configFontSize(style, factor)

        # Create or configure custom fonts, depending on 'init'
        aboutTitleFontSize = scale(42 / 18.)
        if init:
            self.aboutTitleFont = tkinter.font.Font(
                family="Helvetica", weight="bold", size=aboutTitleFontSize)
        else:
            self.aboutTitleFont.configure(size=aboutTitleFontSize)

        # Final part of the workaround mentioned above. Normally, the code
        # should always be executed, regardless of the value of 'init'.
        if init:
            # For the ttk.Treeview widget
            treeviewHeadingFontSize = scale(1.)
            # Redundant test, right. Hopefully, one day, we'll be able to get
            # rid of the workaround and this test won't be redundant anymore.
            if init:
                self.treeviewHeadingFont = tkinter.font.Font(
                    weight="normal", size=treeviewHeadingFontSize)
            else:
                self.treeviewHeadingFont.configure(size=treeviewHeadingFontSize)

            style = ttk.Style()
            style.configure("Treeview.Heading", font=self.treeviewHeadingFont)

    def makeInstalledAptList(self):
        logger.notice(_("Building the list of installed airports "
                        "(this may take some time)..."))
        # writelines() used below doesn't automatically add line terminators
        airports = [ icao + '\n' for icao in self._findInstalledApt() ]
        logger.info("Opening '{}' for writing".format(INSTALLED_APT))
        with open(INSTALLED_APT, "w", encoding="utf-8") as fout:
            fout.writelines(airports)

    def readMetarDat(self):
        """Fetch METAR station list from metar.dat.gz file"""
        logger.info("Opening '{}' for reading".format(self.metar_path))
        res = []

        with gzip.open(self.metar_path, mode='rt', encoding='utf-8') as fin:
            for line in fin:
                if not line.startswith('#'):
                    res.append(line.strip())

        return res

    def rebuildApt(self):
        """Rebuild apt file."""
        self._makeAptDigest()

    def _computeAircraftDirList(self):
        FG_AIRCRAFT_env = os.getenv("FG_AIRCRAFT", "")
        if FG_AIRCRAFT_env:
            FG_AIRCRAFT_envList = FG_AIRCRAFT_env.split(os.pathsep)
        else:
            FG_AIRCRAFT_envList = []

        # FG_ROOT/Aircraft
        defaultAircraftDir = os.path.join(self.FG_root.get(),
                                          DEFAULT_AIRCRAFT_DIR)

        aircraft_dirs = (self.FG_aircraft.get().split(os.pathsep)
                         + FG_AIRCRAFT_envList + [defaultAircraftDir])
        return aircraft_dirs

    def logDetectedFlightGearVersion(self, logLevel=LogLevel.notice,
                                     prefix=True):
        if self.FG_version is not None:
            FG_version = str(self.FG_version)
        else:
            FG_version = pgettext("FlightGear version", "none")

        # Uses the same string as in App.about()
        message = _("Detected FlightGear version: {ver}").format(
            ver=FG_version)
        logger.log(logLevel, prefix, message)

    def getFlightGearVersion(self, ignoreFGVersionError=False, log=False):
        # This import requires the translation system [_() function] to be in
        # place.
        from .fgdata import fgversion

        self.FG_version = None  # in case an exception is raised below
        FG_bin = self.FG_bin.get()
        FG_root = self.FG_root.get()
        exc = None

        if FG_bin and FG_root:
            try:
                self.FG_version = fgversion.getFlightGearVersion(
                    FG_bin, FG_root, self.FG_working_dir.get())
            except fgversion.error as e:
                exc = e         # may need to be raised later

        if log:
            self.logDetectedFlightGearVersion()

        if exc is not None and not ignoreFGVersionError:
            raise exc

    # This is a callback for FFGo's misc.Observable class.
    def updateAircraftNameAndDirFromAircraftId(self, aircraftId):
        aircraftName, aircraftDir = aircraftId
        self.aircraft.set(aircraftName)
        self.aircraftDir.set(aircraftDir)

    def aircraftWithNameAndDir(self, name, dir_):
        """Get the Aircraft instance for a given name and directory."""
        try:
            aircrafts = self.aircraftDict[name]
        except KeyError:
            raise NoSuchAircraft(name, dir_)

        for aircraft in aircrafts:
            # The idea is that the directory 'dir_' passed here should have
            # been discovered earlier by a filesystem exploration, therefore
            # there must be one Aircraft instance that has an exact match for
            # both 'name' and 'dir_' (no need to use 'os.path.samefile()',
            # which would be slower, could raise errors...).
            if aircraft.dir == dir_:
                return aircraft
        else:
            raise NoSuchAircraft(name, dir_)

    def aircraftWithId(self, aircraftId):
        """Get the Aircraft instance for a given aircraft ID."""
        return self.aircraftWithNameAndDir(*self.aircraftId.get())

    def getCurrentAircraft(self):
        """Get the Aircraft instance for the currently-selected aircraft."""
        return self.aircraftWithId(self.aircraftId.get())

    def _findAircraft(self, acName, acDir):
        """Return an aircraft ID for 'acName' and 'acDir' if possible.

        If no aircraft is found with the given name and directory, fall
        back to:
          - an identically-named aircraft in a different directory
            (taking the first in FG_AIRCRAFT precedence order);
          - if this isn't possible either, fall back to the default
            aircraft. The returned aircraft ID will have an empty
            directory component if even the default aircraft isn't
            available in this case.

        Log an appropriate warning or notice when a fallback strategy is
        used.

        """
        if acName in self.aircraftDict:
            for ac in self.aircraftDict[acName]:
                if ac.dir == acDir:
                    aircraft = ac
                    break
            else:
                aircraft = self.aircraftDict[acName][0]
                logger.notice(
                    _("Could not find aircraft '{aircraft}' under '{dir}', "
                      "taking it from '{fallback}' instead").format(
                          aircraft=acName, dir=acDir, fallback=aircraft.dir))
        else:
            try:
                defaultAircrafts = self.aircraftDict[DEFAULT_AIRCRAFT]
            except KeyError:
                aircraft = None
                logger.warning(
                    _("Could not find the default aircraft: {aircraft}")
                    .format(aircraft=DEFAULT_AIRCRAFT))
            else:
                aircraft = defaultAircrafts[0]
                logger.notice(
                    _("Could not find aircraft '{aircraft}', using "
                      "'{fallback}' from '{dir}' instead").format(
                          aircraft=acName, fallback=aircraft.name,
                          dir=aircraft.dir))

        if aircraft is None:
            return (DEFAULT_AIRCRAFT, '')
        else:
            return (aircraft.name, aircraft.dir)

    def sanityChecks(self):
        status, *rest = self.decodeParkingSetting(self.park.get())
        if status == "invalid":
            logger.warning(
                _("Invalid syntax for the parking setting ({setting!r}), "
                  "resetting it.").format(setting=self.park.get()))
            self.park.set('')

        if self.rwy.get() and self.park.get():
            # Impossible to at the same time set a non-default runway and a
            # parking position. The latter wins. :-)
            self.rwy.set('')

    def update(self, path=None, ignoreFGVersionError=False, logFGVersion=True):
        """Read config file and update variables.

        path is a path to different than default config file

        """
        if self.aircraftStatsManager is None: # application init
            # Requires the translation system to be in place
            from . import stats_manager
            self.aircraftStatsManager = \
                                      stats_manager.AircraftStatsManager(self)
        else:
            # Save the in-memory statistics (from Aircraft instances) to
            # persistent storage. This expires old stats, according to
            # self.aircraftStatsExpiryPeriod.
            self.aircraftStatsManager.save()

        del self.settings
        del self.text
        del self.aircraft_dirs
        del self.apt_path
        del self.ai_path
        del self.metar_path
        del self.aircraftDict
        del self.aircraftList
        del self.scenario_list
        del self.carrier_list

        # The variable will be set again right after reading the config
        # file, therefore there is no need to run the callbacks now
        # (such as updating the aircraft image).
        self.aircraftId.set((DEFAULT_AIRCRAFT, ''), runCallbacks=False)
        self.airport.set(DEFAULT_AIRPORT)
        self.alreadyProposedChanges.set('')
        self.apt_data_source.set(1)
        self.auto_update_apt.set(1)
        self.carrier.set('')
        self.FG_aircraft.set('')
        self.FG_bin.set('')
        self.FG_root.set('')
        self.FG_scenery.set('')
        self.FG_working_dir.set('')
        self.MagneticField_bin.set('')
        self.language.set('')
        self.baseFontSize.set(DEFAULT_BASE_FONT_SIZE)
        self.mainWindowGeometry.set('')
        self.saveWindowPosition.set('1')
        self.showFGCommand.set('1')
        self.showFGCommandInSeparateWindow.set('0')
        self.FGCommandGeometry.set('')
        self.showFGOutput.set('1')
        self.showFGOutputInSeparateWindow.set('0')
        self.FGOutputGeometry.set('')
        self.autoscrollFGOutput.set('1')
        self.park.set('')
        self.fakeParkposOption.set('0')
        self.rwy.set('')
        self.scenario.set('')
        self.filteredAptList.set(0)
        self.airportStatsShowPeriod.set('365')    # approx. one year
        self.airportStatsExpiryPeriod.set('3652') # approx. ten years
        self.aircraftStatsShowPeriod.set('365')
        self.aircraftStatsExpiryPeriod.set('3652')

        self.settings, self.text = self._read(path)

        for line in self.settings:
            cut = line.find('=') + 1

            if cut:
                name = line[:cut]
                value = line[cut:]

                if value:
                    if name in self.keywords:
                        var = self.keywords[name]
                        var.set(value)

        # Useful to know when the airport has been changed
        self.previousAirport = self.airport.get()

        self._setLanguage(self.language.get())
        setupTranslationHelper(self)

        self.aircraft_dirs = self._computeAircraftDirList()
        self.apt_path = os.path.join(self.FG_root.get(), APT_DAT)
        self.ai_path = os.path.join(self.FG_root.get(), AI_DIR)
        self.metar_path = os.path.join(self.FG_root.get(), METAR_DAT)

        self.aircraftDict, self.aircraftList = self._readAircraft()
        # Load the saved statistics into the new in-memory Aircraft instances
        # (the set of aircrafts may have just changed, hence the need to save
        # the stats before the in-memory aircraft list is updated, and reload
        # them afterwards).
        self.aircraftStatsManager.load()
        # Choose a suitable aircraft, even if the one defined by
        # 'self.aircraft' and 'self.aircraftDir' isn't available.
        self.aircraftId.set(self._findAircraft(self.aircraft.get(),
                                               self.aircraftDir.get()))

        self.scenario_list, self.carrier_list = self._readScenarios()
        self.sanityChecks()
        self.getFlightGearVersion(ignoreFGVersionError=ignoreFGVersionError,
                                  log=logFGVersion)

    def write(self, text=None, path=None):
        """Write the configuration to a file.

        text -- content of text window processed by CondConfigParser
                (pass None to use the value of Config.text)
        path -- path to the file the config will be written to
                (the default config file is used if this argument is
                empty or None)

        """
        if not path:
            path = CONFIG
        if text is None:
            text = self.text

        options = []
        keys = list(self.keywords.keys())
        keys.sort()

        for k in keys:
            v = self.keywords[k]
            if k in ('--carrier=', '--airport=', '--parkpos=', '--runway='):
                if v.get():
                    options.append(k + v.get())
            else:
                options.append(k + str(v.get()))

        s = '\n'.join(options)
        logger.info("Opening config file for writing: '{}'".format(path))

        with open(path, mode='w', encoding='utf-8') as config_out:
            config_out.write(s + '\n' + CUT_LINE + '\n')
            # Make sure the config file has exactly one newline at the end
            while text.endswith('\n\n'):
                text = text[:-1]
            if not text.endswith('\n'):
                text += '\n'
            config_out.write(text)

    def _findInstalledApt(self):
        """Walk thru all scenery and find installed airports.

        Take geographic coordinates from directories names and compare them
        with airports coordinates in apt file.

        The result is a sorted list of ICAO codes for matching airports.

        """
        coord_dict = {}
        sceneries = self.FG_scenery.get().split(os.pathsep)

        for scenery in sceneries:
            path = os.path.join(scenery, 'Terrain')
            if os.path.exists(path):
                for dir in os.listdir(path):
                    p = os.path.join(path, dir)
                    for coords in os.listdir(p):
                        d = os.path.join(p, coords)
                        if not os.path.isdir(d):
                            continue

                        logger.debug("Exploring Terrain directory '{}' -> '{}'"
                                     .format(p, coords))
                        converted = self._stringToCoordinates(coords)
                        if converted is not None:
                            coord_dict[converted] = None
                        else:
                            logger.notice(
                                _("Ignoring directory '{}' (unexpected name)")
                                .format(d))

        coords = coord_dict.keys()
        res = []
        for icao in self.sortedIcao():
            airport = self.airports[icao]
            for c in coords:
                if (c[0][0] < airport.lat < c[0][1] and
                    c[1][0] < airport.lon < c[1][1]):
                    res.append(icao)

        return res

    def _calculateRange(self, coordinates):
        c = coordinates
        if c.startswith('s') or c.startswith('w'):
            c = int(c[1:]) * (-1)
            return c, c + 1
        else:
            c = int(c[1:])
            return c, c + 1

    def _createUserDirectories(self):
        """Create config, log and stats directories if they don't exist."""
        for d in USER_DATA_DIR, LOG_DIR, STATS_DIR:
            os.makedirs(d, exist_ok=True)

    def _maybeMigrateFromFGoConfig_dialogs(self, parent):
        message = _("Initialize {prg}'s configuration from your existing " \
                    "FGo! configuration?").format(prg=PROGNAME)
        detail = (_("""\
You have no {cfgfile} file but you do have a {fgo_cfgfile} file,
which normally belongs to FGo!. Except in rare circumstances
(such as using braces or backslashes, or opening brackets at the
beginning of a config line), a configuration file from
FGo! 1.5.5 or earlier should be usable as is by {prg}.""")
                  .replace('\n', ' ') + "\n\n" + _("""\
If {fgo_cfgfile} was written by FGo! 1.5.5 or earlier, you
should probably say “Yes” here in order to initialize {prg}'s
configuration based on your FGo! config file (precisely:
copy {fgo_cfgfile} to {cfgfile}).""")
                  .replace('\n', ' ') + "\n\n" + _("""\
If {fgo_cfgfile} was written by a version of FGo! that is greater
than 1.5.5, it is advised to say “No” here.""")
                  .replace('\n', ' ')
                 ).format(prg=PROGNAME, cfgfile=CONFIG, fgo_cfgfile=FGO_CONFIG)

        if askyesno(PROGNAME, message, detail=detail, parent=parent):
            choice = "migrate from FGo!"
        else:
            message = _("Create a default {prg} configuration?").format(
                prg=PROGNAME)
            detail = _("""\
Choose “Yes” to create a basic {prg} configuration now. If you
choose “No”, {prg} will exit and you'll have to create {cfgfile}
yourself, or restart {prg} to see the same questions again.""") \
                     .replace('\n', ' ').format(prg=PROGNAME, cfgfile=CONFIG)

            if askyesno(PROGNAME, message, detail=detail, parent=parent):
                choice = "create default cfg"
                message = _("Creating a default {prg} configuration.").format(
                    prg=PROGNAME)
                detail = (_("""\
It is suggested that you go to the Settings menu and choose
Preferences to review your newly-created configuration.""")
                          .replace('\n', ' ') + "\n\n" + _("""\
You can also reuse most, if not all FlightGear options you
had in FGo!'s main text box (the “options window”). Just copy
them to the corresponding {prg} text box.""")
                          .replace('\n', ' ') + "\n\n" + _("""\
Note: you may run both FGo! and {prg} simultaneously, as their
configurations are kept separate.""")
                          .replace('\n', ' ')
                         ).format(prg=PROGNAME)
                showinfo(PROGNAME, message, detail=detail, parent=parent)
            else:
                choice = "abort"

        return choice

    def _maybeMigrateFromFGoConfig(self):
        if os.path.isfile(FGO_CONFIG) and not os.path.isfile(CONFIG):
            baseSize = tkinter.font.nametofont("TkDefaultFont").actual()["size"]
            def configFontSize(val, absolute=False):
                for style in ("Default", "Text", "Fixed", "Caption", "Tooltip"):
                    font = tkinter.font.nametofont("Tk{}Font".format(style))
                    if absolute:
                        font.configure(size=val)
                    else:
                        font.configure(size=int(round(baseSize * val)))

            # Make sure most people can read the following dialogs (the
            # standard Tk size may be rather small): 140% increase
            configFontSize(1.4, absolute=False)

            choice = None       # user choice in the to-be-displayed dialogs
            # It seems we need an otherwise useless Toplevel window in order to
            # center the Tk standard dialogs...
            t = tkinter.Toplevel()
            try:
                # Transparent if the OS supports it
                t.attributes('-alpha', '0.0')
                # Center the Toplevel. To be effective, this would probably
                # need a visit to the Tk event loop, however it is enough to
                # have the child dialogs centered, which is what matters here.
                self.master.eval('tk::PlaceWindow {} center'.format(
                    t.winfo_pathname(t.winfo_id())))
                choice = self._maybeMigrateFromFGoConfig_dialogs(t)
            finally:
                t.destroy()

            # Restore font size for later self.setupFonts() call
            configFontSize(baseSize, absolute=True)

            if choice in (None, "abort"):
                raise AbortConfig
            elif choice == "migrate from FGo!":
                # shutil.copy() and shutil.copy2() attempt to preserve the file's
                # permission mode, which is undesirable here → manual copy.
                with open(FGO_CONFIG, "r", encoding='utf-8') as fgoConfig, \
                     open(CONFIG, "w", encoding='utf-8') as config:
                    config.write(fgoConfig.read())
            else:
                assert choice == "create default cfg", repr(choice)

    def _makeAptDigest(self, head=None):
        """Build apt database from apt.dat.gz"""
        if self.FG_root.get():
            _ProcessApt(self.master, self, self.apt_path, head)

    def _read(self, path=None):
        """Read the specified or a default configuration file.

        - If 'path' is None and CONFIG exists, load CONFIG;
        - if 'path' is None and CONFIG does not exist, load the
          configuration from the presets and default, localized
          config_ll resource;
        - otherwise, load configuration from the specified file.

        """
        try:
            # ExitStack not strictly necessary here, but allows clean and
            # convenient handling of the various files or resources the
            # configuration may be loaded from.
            with contextlib.ExitStack() as stack:
                res = self._read0(stack, path)
        except OSError as e:
            message = _('Error loading configuration')
            showerror(_('{prg}').format(prg=PROGNAME), message, detail=str(e))
            res = ([''], '')

        return res

    _presetsBlankLineOrCommentCre = re.compile(r"^[ \t]*(#|$)")

    def _read0(self, stack, path):
        # Data before the CUT_LINE in the config file, destined to
        # self.settings
        settings = []
        # Data after the CUT_LINE in the config file, destined to
        # self.text and to be parsed by CondConfigParser
        condConfLines = []

        if path is not None or (path is None and os.path.exists(CONFIG)):
            if path is None:
                path = CONFIG
            logger.info("Opening config file '{}' for reading".format(path))
            configStream = stack.enter_context(open(path, "r",
                                                    encoding="utf-8"))
            beforeCutLine = True
        else:                 # Use default config if no regular config exists.
            # Load presets if exists.
            if resourceExists(PRESETS):
                with textResourceStream(PRESETS) as presets:
                    for line in presets:
                        line = line.strip()
                        if not self._presetsBlankLineOrCommentCre.match(line):
                            settings.append(line)

            # Find the currently used language according to the environment.
            try:
                lang_code = gettext.translation(
                    MESSAGES, LOCALE_DIR).info()['language']
            except OSError:
                lang_code = 'en'

            if not resourceExists(DEFAULT_CONFIG_STEM + lang_code):
                lang_code = 'en'
            resPath = DEFAULT_CONFIG_STEM + lang_code

            configStream = stack.enter_context(textResourceStream(resPath))
            # There is no "cut line" in the template config files.
            beforeCutLine = False

        for line in configStream:
            if beforeCutLine:
                line = line.strip()

            if line != CUT_LINE:
                if beforeCutLine:
                    # Comments wouldn't be preserved on saving, therefore don't
                    # try to handle them before the "cut line".
                    if line:
                        settings.append(line)
                else:
                    condConfLines.append(line)
            else:
                beforeCutLine = False

        return (settings, ''.join(condConfLines))

    def _readAircraft(self):
        """
        Walk through Aircraft directories and return the available aircrafts.

        Return a tuple (aircraftDict, aircraftList) listing all
        aircrafts found via self.aircraft_dirs.

        aircraftDict is a dictionary whose keys are the names (derived
        from the -set.xml files) of all aircrafts. For each aircraft
        name 'n', aircraftDict[n] is the list, in self.aircraft_dirs
        priority order, of all Aircraft instances with that name.

        aircraftList is the sorted list of all Aircraft instances,
        suitable for quick building of the aircraft list in the GUI.

        """
        aircraftDict = {}
        for dir_ in self.aircraft_dirs:
            if os.path.isdir(dir_):
                for d in os.listdir(dir_):
                    self._readAircraftData(dir_, d, aircraftDict)

        aircraftList = []
        # First sort by lowercased aircraft name
        sortFunc = lambda s: (s.lower(), s)
        for acName in sorted(aircraftDict.keys(), key=sortFunc):
            # Then sort by position in self.aircraft_dirs
            aircraftList.extend(aircraftDict[acName])

        return (aircraftDict, aircraftList)

    def _readAircraftData(self, dir_, d, aircraftDict):
        path = os.path.join(dir_, d)
        if os.path.isdir(path):
            for f in os.listdir(path):
                self._appendAircraft(f, aircraftDict, path)

    def _appendAircraft(self, f, aircraftDict, path):
        if f.endswith('-set.xml'):
            # Dirty and ugly hack to prevent carrier-set.xml in
            # seahawk directory to be attached to the aircraft
            # list.
            if (not path.startswith('seahawk') and
                    f != 'carrier-set.xml'):
                name = f[:-8]
                if name not in aircraftDict:
                    aircraftDict[name] = []

                aircraft = Aircraft(name, path)
                aircraftDict[name].append(aircraft)

    def sortedIcao(self):
        return sorted(self.airports.keys())

    def _readApt(self):
        """Read the apt digest file (create a new one if none exists).

        Return a list of AirportStub instances.

        """
        from .fgdata import apt_dat

        if not os.path.exists(APT):
            # Create a new file if self.FG_root is non-empty
            self._makeAptDigest()

        if not os.path.isfile(APT): # may happen if self.FG_root was empty
            self.aptDatSize, self.airports = 0, {}
            return []

        for attempt in itertools.count(start=1):
            try:
                self.aptDatSize, self.airports = apt_dat.AptDatDigest.read(APT)
            except apt_dat.UnableToParseAptDigest:
                if attempt < 2:
                    self._makeAptDigest()
                else:
                    raise
            else:
                break

        if self.filteredAptList.get():
            installedApt = self._readInstalledAptSet()
            res = [ self.airports[icao] for icao in self.sortedIcao()
                    if icao in installedApt ]
        else:
            res = [ self.airports[icao] for icao in self.sortedIcao() ]

        return res

    def _readInstalledAptSet(self):
        """Read the set of locally installed airports from INSTALLED_APT.

        Create a new INSTALLED_APT file if none exists yet.
        Return a frozenset(), which offers very fast membership test
        compared to a list.

        """
        if not os.path.exists(INSTALLED_APT):
            self.makeInstalledAptList()

        logger.info("Opening installed apt file '{}' for reading".format(
            INSTALLED_APT))

        with open(INSTALLED_APT, "r", encoding="utf-8") as f:
            # Strip the newline char ending every line
            res = frozenset([ line[:-1] for line in f ])

        return res

    def _readScenarios(self):
        """Walk through AI scenarios and read carrier data.

        Return two lists:
            scenarios: [scenario name, ...]
            carrier data: [[name, parkking pos, ..., scenario name], ...]
        Return two empty lists if no scenario is found.
        """
        carriers = []
        scenarios = []
        if os.path.isdir(self.ai_path):
            for f in os.listdir(self.ai_path):
                path = os.path.join(self.ai_path, f)

                if os.path.isfile(path) and f.lower().endswith('.xml'):
                    scenario_name = f[:-4]
                    scenarios.append(scenario_name)
                    # Appends to 'carriers'
                    self._append_carrier_data(carriers, path, scenario_name)

        return sorted(scenarios), sorted(carriers)

    def _append_carrier_data(self, carriers, xmlFilePath, scenario_name):
        logger.info("Reading scenario data from '{}'".format(xmlFilePath))
        root = self._get_root(xmlFilePath)
        scenario = root.find('scenario')

        if scenario is not None:
            for e in scenario.iterfind('entry'):
                typeElt = e.find('type')
                if typeElt is not None and typeElt.text == 'carrier':
                    data = self._get_carrier_data(e, scenario_name)
                    carriers.append(data)

    def _get_root(self, xmlFilePath):
        tree = ElementTree.parse(xmlFilePath)
        return tree.getroot()

    def _get_carrier_data(self, e, scenario_name):
        nameElt = e.find('name')
        if nameElt is not None:
            data = [nameElt.text]
        else:
            data = ['unnamed']

        for child in e.iterfind('parking-pos'):
            parkingNameElt = child.find('name')
            if parkingNameElt is not None:
                data.append(parkingNameElt.text)

        data.append(scenario_name)
        return data

    # The '1' is the version number of this custom format for the contents of
    # Config.park, in case we need to change it.
    aptDatParkConfStart_cre = re.compile(r"::apt\.dat::1::(?P<nameLen>\d+),")
    aptDatParkConfEnd_cre = re.compile(
        r"""lat=(?P<lat>{floatRegexp}),
            lon=(?P<lon>{floatRegexp}),
            heading=(?P<heading>{floatRegexp})$""".format(
            floatRegexp=r"-?\d+(\.\d*)?"),
        re.VERBOSE)

    def decodeParkingSetting(self, parkConf):
        status = "invalid"      # will be overridden if correct in the end
        parkName = None
        options = []

        if not parkConf:
            status = "none"     # no parking position
        else:
            mo = self.aptDatParkConfStart_cre.match(parkConf)
            if mo:
                # Length of the following parking name (after the comma)
                nameLen = int(mo.group("nameLen"))
                i = mo.end("nameLen") + 1 + nameLen

                if len(parkConf) > i and parkConf[i] == ";":
                    mo2 = self.aptDatParkConfEnd_cre.match(parkConf[i+1:])
                    if mo2:
                        parkName = parkConf[mo.end("nameLen")+1:i]
                        options = ["--lat=" + mo2.group("lat"),
                                   "--lon=" + mo2.group("lon"),
                                   "--heading=" + mo2.group("heading")]
                        status = "apt.dat"
            else:                   # plain parking name
                parkName = parkConf
                options = ["--parkpos=" + parkName]
                status = "groundnet"

        return (status, parkName, options)

    def _earlyTranslationsSetup(self):
        """Setup translations before the config file has been read.

        The language is determined from the environment (LANGUAGE,
        LC_ALL, LC_MESSAGES, and LANG—cf. gettext.translation() and
        gettext.find()).

        """
        try:
            langCode = gettext.translation(
                MESSAGES, LOCALE_DIR).info()['language']
        except OSError:
            langCode = 'en'

        self._setLanguage(langCode)

    def _setLanguage(self, lang):
        # Initialize provided language...
        try:
            L = gettext.translation(MESSAGES, LOCALE_DIR, languages=[lang])
            L.install()
        # ...or fallback to system default.
        except Exception:
            gettext.install(MESSAGES, LOCALE_DIR)

    # Regexp for directory names such as w040n20
    _geoDirCre = re.compile(r"[we]\d{3}[ns]\d{2}$")

    def _stringToCoordinates(self, coordinates):
        """Convert geo coordinates to decimal format."""
        if not self._geoDirCre.match(coordinates):
            return None

        lat = coordinates[4:]
        lon = coordinates[:4]

        lat_range = self._calculateRange(lat)
        lon_range = self._calculateRange(lon)
        return lat_range, lon_range

    def _autoUpdateApt(self):
        if not self.auto_update_apt.get() or not os.path.exists(self.apt_path):
            return
        old_timestamp = self._readAptTimestamp()
        self._updateApt(old_timestamp)

    def _readAptTimestamp(self):
        if not os.path.exists(APT_TIMESTAMP):
            self._writeAptTimestamp('')

        logger.info("Opening apt timestamp file '{}' for reading".format(
            APT_TIMESTAMP))
        with open(APT_TIMESTAMP, "r", encoding="utf-8") as timestamp:
            old_modtime = timestamp.read()
        return old_modtime

    def _writeAptTimestamp(self, s=None):
        if s is None:
            s = self._getAptModTime()

        logger.info("Opening apt timestamp file '{}' for writing".format(
            APT_TIMESTAMP))
        with open(APT_TIMESTAMP, "w", encoding="utf-8") as timestamp:
            timestamp.write(s)

    def _getAptModTime(self):
        return str(os.path.getmtime(self.apt_path))

    def _updateApt(self, old_timestamp):
        if old_timestamp != self._getAptModTime():
            self._makeAptDigest(head=_('Modification of apt.dat.gz detected.'))
            # The new apt.dat may invalidate the current parking
            status, *rest = self.decodeParkingSetting(self.park.get())
            if status == "apt.dat":
                # This was a parking position obtained from apt.dat; it may be
                # invalid with the new file, reset.
                self.park.set('')

            # This is also outdated with respect to the new apt.dat.
            self.aptDatCache.clear()

    # Accept any arguments to allow safe use as a Tkinter variable observer
    def updateMagFieldProvider(self, *args):
        from .geo.magfield import EarthMagneticField, MagVarUnavailable
        try:
            self.earthMagneticField = EarthMagneticField(self)
        except MagVarUnavailable as e:
            self.earthMagneticField = None
            self.earthMagneticFieldLastProblem = e.message

        from .fgdata import airport as airport_mod
        from .fgdata import parking as parking_mod
        from .gui import airport_finder as airport_finder_mod
        from .gui import gps_tool as gps_tool_mod

        for module in (airport_mod, parking_mod, airport_finder_mod,
                       gps_tool_mod):
            module.setupEarthMagneticFieldProvider(self.earthMagneticField)
Example #58
0
class CFGDemo(object):
    def __init__(self, grammar, text):
        self._grammar = grammar
        self._text = text

        # Set up the main window.
        self._top = Tk()
        self._top.title('Context Free Grammar Demo')

        # Base font size
        self._size = IntVar(self._top)
        self._size.set(12) # = medium

        # Set up the key bindings
        self._init_bindings(self._top)

        # Create the basic frames
        frame1 = Frame(self._top)
        frame1.pack(side='left', fill='y', expand=0)
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_grammar(frame1)
        self._init_treelet(frame1)
        self._init_workspace(self._top)

    #//////////////////////////////////////////////////
    # Initialization
    #//////////////////////////////////////////////////

    def _init_bindings(self, top):
        top.bind('<Control-q>', self.destroy)

    def _init_menubar(self, parent): pass

    def _init_buttons(self, parent): pass

    def _init_grammar(self, parent):
        self._prodlist = ProductionList(parent, self._grammar, width=20)
        self._prodlist.pack(side='top', fill='both', expand=1)
        self._prodlist.focus()
        self._prodlist.add_callback('select', self._selectprod_cb)
        self._prodlist.add_callback('move', self._selectprod_cb)

    def _init_treelet(self, parent):
        self._treelet_canvas = Canvas(parent, background='white')
        self._treelet_canvas.pack(side='bottom', fill='x')
        self._treelet = None

    def _init_workspace(self, parent):
        self._workspace = CanvasFrame(parent, background='white')
        self._workspace.pack(side='right', fill='both', expand=1)
        self._tree = None
        self.reset_workspace()

    #//////////////////////////////////////////////////
    # Workspace
    #//////////////////////////////////////////////////

    def reset_workspace(self):
        c = self._workspace.canvas()
        fontsize = int(self._size.get())
        node_font = ('helvetica', -(fontsize+4), 'bold')
        leaf_font = ('helvetica', -(fontsize+2))

        # Remove the old tree
        if self._tree is not None:
            self._workspace.remove_widget(self._tree)

        # The root of the tree.
        start = self._grammar.start().symbol()
        rootnode = TextWidget(c, start, font=node_font, draggable=1)

        # The leaves of the tree.
        leaves = []
        for word in self._text:
            leaves.append(TextWidget(c, word, font=leaf_font, draggable=1))

        # Put it all together into one tree
        self._tree = TreeSegmentWidget(c, rootnode, leaves,
                                       color='white')

        # Add it to the workspace.
        self._workspace.add_widget(self._tree)

        # Move the leaves to the bottom of the workspace.
        for leaf in leaves: leaf.move(0,100)

        #self._nodes = {start:1}
        #self._leaves = dict([(l,1) for l in leaves])

    def workspace_markprod(self, production):
        pass

    def _markproduction(self, prod, tree=None):
        if tree is None: tree = self._tree
        for i in range(len(tree.subtrees())-len(prod.rhs())):
            if tree['color', i] == 'white':
                self._markproduction

            for j, node in enumerate(prod.rhs()):
                widget = tree.subtrees()[i+j]
                if (isinstance(node, Nonterminal) and
                    isinstance(widget, TreeSegmentWidget) and
                    node.symbol == widget.label().text()):
                    pass # matching nonterminal
                elif (isinstance(node, compat.string_types) and
                      isinstance(widget, TextWidget) and
                      node == widget.text()):
                    pass # matching nonterminal
                else: break
            else:
                # Everything matched!
                print('MATCH AT', i)

    #//////////////////////////////////////////////////
    # Grammar
    #//////////////////////////////////////////////////

    def _selectprod_cb(self, production):
        canvas = self._treelet_canvas

        self._prodlist.highlight(production)
        if self._treelet is not None: self._treelet.destroy()

        # Convert the production to a tree.
        rhs = production.rhs()
        for (i, elt) in enumerate(rhs):
            if isinstance(elt, Nonterminal): elt = Tree(elt)
        tree = Tree(production.lhs().symbol(), *rhs)

        # Draw the tree in the treelet area.
        fontsize = int(self._size.get())
        node_font = ('helvetica', -(fontsize+4), 'bold')
        leaf_font = ('helvetica', -(fontsize+2))
        self._treelet = tree_to_treesegment(canvas, tree,
                                            node_font=node_font,
                                            leaf_font=leaf_font)
        self._treelet['draggable'] = 1

        # Center the treelet.
        (x1, y1, x2, y2) = self._treelet.bbox()
        w, h = int(canvas['width']), int(canvas['height'])
        self._treelet.move((w-x1-x2)/2, (h-y1-y2)/2)

        # Mark the places where we can add it to the workspace.
        self._markproduction(production)

    def destroy(self, *args):
        self._top.destroy()

    def mainloop(self, *args, **kwargs):
        self._top.mainloop(*args, **kwargs)
Example #59
0
class PypeTkPad(object):

    def __init__(self, master, queue, pypeOutput):
      
        self.queue = queue
        self.pypeOutput = pypeOutput

        self.master = master
        self.master.title('PypePad')
        self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0))
        self.master.minsize(300, 100)
        self.output_file_name = None
        
        self.BuildMainFrame()
        self.UpdateOutput()

    def NewCommand(self):
        self.ClearAllCommand()

    def OpenCommand(self):
        import tkinter.filedialog
        from tkinter import END
        openfile = tkinter.filedialog.askopenfile()
        if not openfile:
            return
        for line in openfile.readlines():
            self.text_input.insert(END,line)
 
    def SaveCommand(self):
        import tkinter.filedialog
        from tkinter import END
        saveasfile = tkinter.filedialog.asksaveasfile()
        if not saveasfile:
            return
        alltext = self.text_input.get("1.0",END)
        saveasfile.write(alltext)
 
    def QuitCommand(self):
        self.master.quit()

    def ClearInputCommand(self):
        from tkinter import END
        self.text_input.delete("1.0",END)
        
    def ClearOutputCommand(self):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.delete("1.0",END)
        self.text_output["state"] = DISABLED
        self.text_output.see(END)
        self.text_output.update()
        
    def ClearAllCommand(self):
        self.ClearInputCommand()
        self.ClearOutputCommand()

    def OutputFileCommand(self):
        import tkinter.filedialog
        outputfilename = tkinter.filedialog.asksaveasfilename()
        if sys.platform == 'win32' and len(outputfilename.split()) > 1:
            outputfilename = '"%s"' % outputfilename
        self.output_file_name = outputfilename

    def AboutCommand(self):
        self.OutputText('\n')
        self.OutputText('* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n')
        self.OutputText('\n')

    def UpdateOutput(self):
        if self.pypeOutput:
            text = self.pypeOutput.pop(0)
            self.output_stream.write(text)
        self.master.after(10,self.UpdateOutput)

    def RunPype(self,arguments):
        if not arguments:
            return
        if self.output_to_file.get() is not 'n' and self.output_file_name:
            self.output_stream.output_to_file = True
            self.output_stream.output_file = open(self.output_file_name,self.output_to_file.get())
        else:
            self.output_stream.output_to_file = False

        self.queue.append(arguments)
 
    def GetWordUnderCursor(self):
        from tkinter import CURRENT
        splitindex = self.text_input.index(CURRENT).split('.')
        line = self.text_input.get(splitindex[0]+".0",splitindex[0]+".end")
        wordstart = line.rfind(' ',0,int(splitindex[1])-1)+1
        wordend = line.find(' ',int(splitindex[1]))
        if wordend == -1:
            wordend = len(line)
        word = line[wordstart:wordend]
        return word

    def GetWordIndex(self):
        startindex = self.text_input.index("insert-1c wordstart")
        endindex = self.text_input.index("insert-1c wordend")
        if self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == '-':
           startindex = self.text_input.index("insert-1c wordstart -2c") 
        elif self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == ' ':
           startindex = self.text_input.index("insert-1c wordstart -1c")
        self.wordIndex[0] = startindex
        self.wordIndex[1] = endindex
        word = self.text_input.get(self.wordIndex[0],self.wordIndex[1])
        return word

    def GetLogicalLine(self,physicallineid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallineid]]
 
    def GetLogicalLineRange(self,physicallinefirstid,physicallinelastid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallinefirstid]:indexes[physicallinelastid]+1]
   
    def GetAllLogicalLines(self):
        return self.GetLogicalLines()[1]
   
    def GetLogicalLines(self):
        from tkinter import END
        # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior
        physicallines = [str(line) for line in self.text_input.get("1.0",END).split('\n')]
        lines = []
        indexes = [0] * len(physicallines)
        lineid = 0
        previousline = ""
        join = 0
        for line in physicallines:
            if line.startswith('#'):
                if join:
                    indexes[lineid] = indexes[lineid-1]
            elif join:
                if line.endswith('\\'):
                    lines[-1] = lines[-1] + " " + line[:-1]
                    join = 1
                else:
                    lines[-1] = lines[-1] + " " + line
                    join = 0
                indexes[lineid] = indexes[lineid-1]
            else:
                if line.endswith('\\'):
                    join = 1
                    lines.append(line[:-1])
                else:
                    lines.append(line)
                    join = 0
                if lineid > 0:
                    indexes[lineid] = indexes[lineid-1]+1
            lineid += 1
        return indexes, lines

    def GetLineUnderCursor(self):
        from tkinter import INSERT
        currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1
        return self.GetLogicalLine(currentlineid)

    def RunAllCommand(self):
        lines = self.GetAllLogicalLines()
        for line in lines:
            if line and line.strip():
                self.RunPype(line)

    def RunLineCommand(self):
        line = self.GetLineUnderCursor()
        if line and line.strip():
            self.RunPype(line)
      
    def RunSelectionCommand(self):
        from tkinter import TclError, SEL_FIRST, SEL_LAST
        try:
            firstlineid = int(self.text_input.index(SEL_FIRST).split('.')[0]) - 1
            lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1
            lines = self.GetLogicalLineRange(firstlineid,lastlineid)
            for line in lines:
                self.RunPype(line)
        except TclError:
            pass

    def GetSuggestionsList(self,word):
        list = []
        try:
            from vmtk import vmtkscripts
            from vmtk import pypes
        except ImportError:
            return None
        if word.startswith('--'):
            list = ['--pipe','--help']
        elif word.startswith('-'):
            optionlist = []
            scriptindex = self.text_input.search('vmtk',self.wordIndex[0],backwards=1)
            moduleName  = self.text_input.get( scriptindex,scriptindex+' wordend' )
            try:
                module = importlib.import_module('vmtk.'+moduleName)
                # Find the principle class to instantiate the requested action defined inside the requested writerModule script.
                # Returns a single member list (containing the principle class name) which satisfies the following criteria:
                #   1) is a class defined within the script
                #   2) the class is a subclass of pypes.pypescript
                scriptObjectClasses = [x for x in dir(module) if isclass(getattr(module, x)) and issubclass(getattr(module, x), pypes.pypeScript)]
                scriptObjectClassName = scriptObjectClasses[0]
                scriptObject = getattr(module, scriptObjectClassName)
                scriptObject = scriptObject()
                members = scriptObject.InputMembers + scriptObject.OutputMembers
                for member in members:
                    optionlist.append('-'+member.OptionName)
                list = [option for option in optionlist if option.count(word)]
            except:
                return list
        else:
            list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word)]
            for index, item in enumerate(list):
                # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
                if 'vmtk.' == item[0:5]:
                    splitList = item.split('.')
                    list[index] = splitList[1]
                else:
                    continue
        return list

    def FillSuggestionsList(self,word):
        from tkinter import END
        self.suggestionslist.delete(0,END)
        suggestions = self.GetSuggestionsList(word)
        for suggestion in suggestions:
            self.suggestionslist.insert(END,suggestion)

    def ReplaceTextCommand(self,word):
        self.text_input.delete(self.wordIndex[0],self.wordIndex[1])
        self.text_input.insert(self.wordIndex[0],word)
        self.text_input.focus_set()

    def ShowHelpCommand(self):
        word = self.GetWordUnderCursor()
        self.OutputText(word)
        if word:
            self.RunPype(word+' --help')
        else: 
            self.OutputText('Enter your vmtk Pype above and Run.\n')

    def AutoCompleteCommand(self):
        word = self.GetWordIndex()
        self.suggestionswindow.withdraw()
        if word:
            self.FillSuggestionsList(word)
            self.suggestionswindow.geometry("%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),self.text_output.winfo_rooty()))
            self.suggestionswindow.deiconify()
            self.suggestionswindow.lift()
            
    def InsertScriptName(self,scriptname):
        from tkinter import INSERT
        self.text_input.insert(INSERT,scriptname+' ')
        
    def InsertFileName(self):
        from tkinter import INSERT
        import tkinter.filedialog
        openfilename = tkinter.filedialog.askopenfilename()
        if not openfilename:
            return
        if len(openfilename.split()) > 1:
            openfilename = '"%s"' % openfilename
        self.text_input.insert(INSERT,openfilename+' ')

    def KeyPressHandler(self,event):
        if event.keysym == "Tab" :
            self.AutoCompleteCommand()
            self.suggestionslist.focus_set()
            self.suggestionslist.selection_set(0)
            return "break"
        else:
            self.text_input.focus_set()

    def TopKeyPressHandler(self,event):
        from tkinter import ACTIVE, INSERT
        if event.keysym in ['Down','Up'] :
            self.suggestionslist.focus_set()
        elif event.keysym == "Return":
            word = self.suggestionslist.get(ACTIVE)
            self.ReplaceTextCommand(word)
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
        elif len(event.keysym) == 1 :
            self.suggestionswindow.withdraw()
            self.text_input.insert(INSERT,event.keysym)
            self.text_input.focus_set()
        else :
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
    
    def NewHandler(self,event):
        self.NewCommand() 

    def OpenHandler(self,event):
        self.OpenCommand()

    def SaveHandler(self,event):
        self.SaveCommand()

    def InsertFileNameHandler(self,event):
        self.InsertFileName()
        return "break"
 
    def QuitHandler(self,event):
        self.QuitCommand()

    def ShowHelpHandler(self,event):
        self.ShowHelpCommand()

    def RunKeyboardHandler(self,event):
        from tkinter import SEL_FIRST, TclError
        try: 
            self.text_input.index(SEL_FIRST)
            self.RunSelectionCommand()
        except TclError:
            self.RunLineCommand()
        return "break"
         
    def RunAllHandler(self,event):
        self.RunAllCommand()
      
    def PopupHandler(self,event):
        try:
            self.popupmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popupmenu.grab_release()

    def OutputText(self,text):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.insert(END,text)
        self.text_output["state"] = DISABLED

    def BuildScriptMenu(self,parentmenu,modulename):
        from tkinter import Menu
        menu = Menu(parentmenu,bd=1,activeborderwidth=0)
        try:
            module = importlib.import_module('vmtk.'+modulename)
        except ImportError:
            return None
        scriptnames = [scriptname for scriptname in getattr(module, '__all__')]
        for index, scriptname in enumerate(scriptnames):
            # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
            if 'vmtk.' == scriptname[0:5]:
                splitList = scriptname.split('.')
                scriptnames[index] = splitList[1]
            else:
                continue
        menulength = 20
        for i in range(len(scriptnames)//menulength+1):
            subscriptnames = scriptnames[i*menulength:(i+1)*menulength]
            if not subscriptnames:
                break 
            submenu = Menu(menu,bd=1,activeborderwidth=0)
            menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu)
            for scriptname in subscriptnames:
                callback = CallbackShim(self.InsertScriptName,scriptname)
                submenu.add_command(label=scriptname,command=callback)
        return menu 

    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)