Ejemplo n.º 1
2
class per():
    def __init__(self,data,y,v='план'):
        
        w=Toplevel()
        w.wm_title('Доп')
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        years=sorted(data.keys())
        cols=data['2013']['degurs']  # ЗАГЛУШКА : список дежурных

        self.t=Treeview(w,columns=cols)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=65,anchor='center')
        self.t.tag_configure('табель',background='green')
        self.t.tag_configure('ош',background='red')
        #self.t.tag_configure('табель',background='green')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)

        for y in years:
            x=self.t.insert('','end',text=y)
            eeY=[]
            for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
                d0=data[y]
                if m not in d0: continue
                d=d0[m]
                rez=dict()
                tag=''
                if v=='авто':
                    if 'табель' in d['degur']:
                        vv='табель'
                        tag=vv
                    else:
                        vv='план'
                elif v=='табель':
                    if 'табель' not in d['degur']:
                        vv='план'
                        tag='ош'
                    else:
                        vv=v
                        tag=vv
                else:
                    vv=v
                for j,s in d['degur'][vv].items():
                    rez[j]=analyse2(s,d)
                NUL=(0,0,0,0,0,0,0)
                ee=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3]+rez.get(j,NUL)[4] for j in cols]
                eeY.append(ee)
                self.t.insert(x,'end',text=m,values=[x or '-' for x in ee],tag=tag)
            eeY=[sum(x) for x in zip(*eeY)]
            self.t.insert(x,'end',text='итого',values=eeY,tag='Y')
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		back_btn=Button(self,text="Back",command=lambda:controller.show_frame(Main), width=30)
		subject_tree=Treeview( self, columns=('#1','#2','#3'))

		subject_tree.heading('#1',text='Sl No.')
		subject_tree.heading('#2',text='Subject Name')
		subject_tree.heading('#3',text='Subject Code')

		subject_tree.column('#1',stretch=YES,width=80)
		subject_tree.column('#2',stretch=YES,width=250)
		subject_tree.column('#3',stretch=YES,width=190)


		subject_tree['show']='headings'

		subject_list = see_subjects()
		for subject in subject_list:
			subject_tree.insert("",'end',values=subject)
		
		heading_label = Label(self, text="All Subjects List", font=MED_FONT)
		heading_label.grid(row=0, column=0, padx=10,pady=5,sticky="W")

		subject_tree.grid(row=1, column=0, padx=50, pady=10, columnspan=2, sticky='nsew')
		back_btn.grid(row=2, column=0, padx=180, pady=10, sticky="W")
Ejemplo n.º 3
0
 def CreateUI(self):
     tv = Treeview(self)
     tv['columns'] = ('Job Number', 'Registration number',
                      'Picked Date', 'Customer Name', 'Contact',
                      'Issues', 'Expected Day', 'Expected Bill')
     tv.heading('#0', text='Job Number', anchor='center')
     tv.column('#0', anchor='center')
     tv.heading('#1', text='Registration number', anchor='center')
     tv.column('#1', anchor='center')
     tv.heading('#2', text='Picked Date', anchor='center')
     tv.column('#2', anchor='center')
     tv.heading('#3', text='Customer Name', anchor='center')
     tv.column('#3', anchor='center')
     tv.heading('#4', text='Contact', anchor='center')
     tv.column('#4', anchor='center')
     tv.heading('#5', text='Issues', anchor='center')
     tv.column('#5', anchor='center')
     tv.heading('#6', text='Expected Day', anchor='center')
     tv.column('#6', anchor='center')
     tv.heading('#7', text='Expected Bill', anchor='center')
     tv.column('#7', anchor='center')
     tv.grid(sticky=(N, S, W, E))
     self.treeview = tv
     self.grid_rowconfigure(0, weight=1)
     self.grid_columnconfigure(0, weight=1)
Ejemplo n.º 4
0
    def tbl_butt(*args):
        global roots_tbl
        global fn

        fn = FEntry.get()

        roots_tbl = None
        roots_tbl = Frame(root)

        tbl = Treeview(roots_tbl, columns =\
            ("number", "method", "a", "b", "root",\
            "func", "iter", "time", "err"),
            show = "headings"
            )

        tbl.heading("number", text="№")
        tbl.column("number", width=50, stretch=False)
        tbl.heading("method", text="Метод")
        tbl.column("method", width=60, stretch=False)
        tbl.heading("a", text="A")
        tbl.column("a", width=70, stretch=False)
        tbl.heading("b", text="B")
        tbl.column("b", width=70, stretch=False)
        tbl.heading("root", text="x")
        tbl.column("root", width=80, stretch=False)
        tbl.heading("func", text="f(x)")
        tbl.column("func", width=80, stretch=False)
        tbl.heading("iter", text="Итерации")
        tbl.column("iter", width=100, stretch=False)
        tbl.heading("time", text="Время")
        tbl.column("time", width=80, stretch=False)
        tbl.heading("err", text="Ошибка")
        tbl.column("err", width=70, stretch=False)

        tbl.grid(row=0, column=0)

        sb = Scrollbar(roots_tbl, orient=VERTICAL)
        sb.grid(row=0, column=1, sticky=NS, padx=8)
        tbl.configure(xscrollcommand=sb.set)
        sb.configure(command=tbl.xview)

        roots = getSolutions(test_func, \
        float(ASpinbox.get()), float(BSpinbox.get()), \
        float(HSpinbox.get()), float(ESpinbox.get()), \
        int(MaxIterSpinbox.get()), sys.float_info.epsilon)

        for i in range(2, 2 * len(roots[0]) + 1, 2):
            tbl.insert("", END, values=\
                tuple("{:^7.4g}".format(roots[0][i//2-1][j]) \
                if j not in [0, 1, 6, 8] else \
                "{:^15}".format(roots[0][i//2-1][j]) if j > 1 else
                roots[0][i//2-1][j] for j in range(len(roots[0][i//2-1]))))

            tbl.insert("", END, values=\
                tuple("{:^7.4g}".format(roots[1][i//2-1][j]) \
                if j not in [0, 1, 6, 8] else \
                "{:^15}".format(roots[1][i//2-1][j]) if j > 1 else
                roots[1][i//2-1][j] for j in range(len(roots[1][i//2-1]))))

        roots_tbl.grid(row=0, column=1)
Ejemplo n.º 5
0
 def createFoodMenuList(self):
     self.frame1 = Frame(self)
     self.frame2 = Frame(self)
     from tkinter.ttk import Treeview
     tv = Treeview(self)
     tv['columns'] = ('location', 'city', 'cutomer_count', 'total_table',
                      'total_waiter', 'sales')
     tv.heading("#0", text='Restaurant name', anchor='w')
     tv.column("#0", anchor="w")
     tv.heading('location', text='Location')
     tv.column('location', anchor='center', width=100)
     tv.heading('city', text='City')
     tv.column('city', anchor='center', width=100)
     tv.heading('cutomer_count', text='Customer Count')
     tv.column('cutomer_count', anchor='center', width=100)
     tv.heading('total_table', text='Total Table')
     tv.column('total_table', anchor='center', width=100)
     tv.heading('total_waiter', text='Total Waiter')
     tv.column('total_waiter', anchor='center', width=100)
     tv.heading('sales', text='Sales')
     tv.column('sales', anchor='center', width=100)
     tv.grid(sticky=(N, S, W, E))
     self.frame1.treeview = tv
     self.frame1.grid_rowconfigure(0, weight=1)
     self.frame1.grid_columnconfigure(0, weight=1)
     self.frame2.grid(row=0, column=1, sticky=N)
     self.button = Button(self.frame2, text="Add")
     self.button.grid(row=0, column=0)
     self.button1 = Button(self.frame2, text="Modify")
     self.button1.grid(row=1, column=0)
     self.button2 = Button(self.frame2, text="Delete")
     self.button2.grid(row=2, column=0)
     self.button3 = Button(self.frame2, text="Delete All")
     self.button3.grid(row=3, column=0)
Ejemplo n.º 6
0
    def CreateUI(self):
        tv_ident = Treeview(self)
        tv_ident['show'] = 'headings'
        tv_ident['columns'] = ('profile_id', 'profile_name',
                               'enrollment_speech_time',
                               'remaining_enrollment_speech_time',
                               'created_date_time', 'enrollment_status')

        tv_ident.heading("profile_id", text='Profile ID', anchor='w')
        tv_ident.column("profile_id", anchor="w", width=250)
        tv_ident.heading('profile_name', text='Profile name')
        tv_ident.column('profile_name', anchor='center', width=120)
        tv_ident.heading('enrollment_speech_time', text='Total length')
        tv_ident.column('enrollment_speech_time', anchor='center', width=100)
        tv_ident.heading('remaining_enrollment_speech_time',
                         text='Time remaining')
        tv_ident.column('remaining_enrollment_speech_time',
                        anchor='center',
                        width=100)
        tv_ident.heading('created_date_time', text='Created on')
        tv_ident.column('created_date_time', anchor='center', width=100)
        tv_ident.heading('enrollment_status', text='Status')
        tv_ident.column('enrollment_status', anchor='center', width=100)
        tv_ident.grid(sticky=(tk.N, tk.S, tk.W, tk.E))
        self.treeview_ident = tv_ident
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
Ejemplo n.º 7
0
    def CreateUI(self):
        tv_veri = Treeview(self)
        tv_veri['show'] = 'headings'
        tv_veri['columns'] = ('profile_id', 'profile_name',
                              'enrollments_count',
                              'remaining_enrollments_count',
                              'created_date_time', 'enrollment_status')

        tv_veri.heading("profile_id", text='Profile ID', anchor='w')
        tv_veri.column("profile_id", anchor="w", width=250)
        tv_veri.heading('profile_name', text='Profile name')
        tv_veri.column('profile_name', anchor='center', width=120)
        tv_veri.heading('enrollments_count', text='Enrollments count')
        tv_veri.column('enrollments_count', anchor='center', width=100)
        tv_veri.heading('remaining_enrollments_count',
                        text='Remaining enrollments')
        tv_veri.column('remaining_enrollments_count',
                       anchor='center',
                       width=100)
        tv_veri.heading('created_date_time', text='Created on')
        tv_veri.column('created_date_time', anchor='center', width=100)
        tv_veri.heading('enrollment_status', text='Status')
        tv_veri.column('enrollment_status', anchor='center', width=100)
        tv_veri.grid(sticky=(tk.N, tk.S, tk.W, tk.E))
        self.treeview_veri = tv_veri
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
Ejemplo n.º 8
0
 def CreateUI(self):
     self.frame1 = Frame(self)
     self.frame2 = Frame(self)
     from tkinter.ttk import Treeview
     tv = Treeview(self)
     tv['columns'] = ('address', 'phone_no', 'check_in', 'waiter', 'table',
                      'bill')
     tv.heading("#0", text='Customer Name', anchor='w')
     tv.column("#0", anchor="w")
     tv.heading('address', text='Address')
     tv.column('address', anchor='center', width=100)
     tv.heading('phone_no', text='Phone No.')
     tv.column('phone_no', anchor='center', width=100)
     tv.heading('check_in', text='Check In To')
     tv.column('check_in', anchor='center', width=100)
     tv.heading('waiter', text='Waiter')
     tv.column('waiter', anchor='center', width=100)
     tv.heading('table', text='Table No.')
     tv.column('table', anchor='center', width=100)
     tv.heading('bill', text='Current Bill')
     tv.column('bill', anchor='center', width=100)
     tv.grid(sticky=(N, S, W, E))
     self.frame1.treeview = tv
     self.frame1.grid_rowconfigure(0, weight=1)
     self.frame1.grid_columnconfigure(0, weight=1)
     self.frame2.grid(row=0, column=1, sticky=N)
     self.button = Button(self.frame2, text="Add")
     self.button.grid(row=0, column=0)
     self.button1 = Button(self.frame2, text="Modify")
     self.button1.grid(row=1, column=0)
     self.button2 = Button(self.frame2, text="Delete")
     self.button2.grid(row=2, column=0)
     self.button3 = Button(self.frame2, text="Delete All")
     self.button3.grid(row=3, column=0)
Ejemplo n.º 9
0
    def loadTableWindow2(self, secondWindowDF, columns, clicked_keyphrase):
        # TODO: make reusable for various df's
        self.secondWindowDF = secondWindowDF
        tv = Treeview(self)
        #tv['columns'] = columns

        tv.heading("#0", text='#')
        tv.column("#0", anchor="w", width=600)

        #for column in tv['columns']:
        #    tv.heading(column, text=column)
        #    tv.column(column, anchor='center', width=350)

        tv.grid(sticky=(N, S, W, E))
        self.treeview = tv
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        for (i, row) in self.secondWindowDF.iterrows():
            #print(clicked_keyphrase)
            #print(row["body"])
            highlighted_text = highlight(keyphrase=clicked_keyphrase,
                                         text=row['body'],
                                         words=5)
            self.treeview.insert('',
                                 'end',
                                 text=str(i) + " " + highlighted_text)

        self.treeview.bind("<Double-1>", self.onClick2)
Ejemplo n.º 10
0
class MultiColumnListboxWidget(MultiColumnListboxApp):
    """use a ttk.TreeView as a multicolumn ListBox"""
    def _setup_widgets(self):
        topf = Frame()
        topf.pack()
        refreshb = Button(topf, text="Refresh", command=refreshData)
        refreshb.pack(side=LEFT)
        global modeb, themeb
        modeb = Button(topf, text="App Mode", command=changeMode)
        modeb.pack(side=LEFT)
        themeb = Button(topf, text="Dark Mode", command=changeTheme)
        themeb.pack(side=LEFT)
        exitb = Button(topf, text="Exit", command=exitWidgetGui)
        exitb.pack(side=RIGHT)

        container = Frame()
        container.pack(fill='both', expand=True)
        # create a treeview with dual scrollbars
        self.tree = Treeview(columns=country_header, show="headings")
        vsb = Scrollbar(orient="vertical", command=self.tree.yview)
        hsb = Scrollbar(orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)
Ejemplo n.º 11
0
def main():
	root=Tk()
	frame1=Frame(root, width = 600, height = 500)
	frame= Frame(frame1, width = 600, height = 400)
	tv=Treeview(frame)
	redbutton = Button(frame1, text = "Upload Image",command=lambda : file_dialog(root,tv))
	redbutton.pack()
	tv["column"]=('q1','q2','q3','q4','t')
	tv.heading("#0", text='Id', anchor='w')
	tv.column("#0", anchor="w")
	width=70
	tv.heading('q1', text='Question 1')
	tv.column('q1', anchor='center', width=width)
	tv.heading('q2', text='Question 2')
	tv.column('q2', anchor='center', width=width)
	tv.heading('q3', text='Question 3')
	tv.column('q3', anchor='center', width=width)

	tv.heading('q4', text='Question 4')
	tv.column('q4', anchor='center', width=width)

	tv.heading('t', text='Total')
	tv.column('t', anchor='center', width=width)
	tv.grid(sticky = (N,S,W,E))
	conn = sqlite3.connect('student.db')
	cursor = conn.execute("SELECT * from STUDENT")
	for row in cursor:
		tv.insert('', 'end', text=f"{row[0]}", values=(f'{row[1]}',f'{row[2]}',\
					  f'{row[3]}',f'{row[4]}',f'{row[5]}'))
	conn.close()

	frame.pack()
	frame1.pack()
	root.mainloop()	
Ejemplo n.º 12
0
 def open_records(self):
     top = Toplevel()
     top.title('记录')
     top.maxsize(600, 600)
     Label(top, text='欢迎使用人脸识别系统', width=35, height=2,
           bg='#56764C').grid(row=0, columnspan=2, sticky=W + E)
     columns = ('所选目标', '出现时间', '消失时间', '持续时间')
     tree = Treeview(top, show='headings', columns=columns)
     tree.column('所选目标', width=150, anchor='center')
     tree.column('出现时间', width=150, anchor='center')
     tree.column('消失时间', width=150, anchor='center')
     tree.column('持续时间', width=150, anchor='center')
     tree.heading('所选目标', text='所选目标')
     tree.heading('出现时间', text='出现时间')
     tree.heading('消失时间', text='消失时间')
     tree.heading('持续时间', text='持续时间')
     sql = "select * from records where aid = '%s'" % user.id
     ret = sql_conn(sql)
     for i in range(len(ret)):
         tree.insert('', i,
                     values=(ret[i]['object_name'], ret[i]['appear'], ret[i]['disappear'], ret[i]['last_time']))
     tree.grid(row=1, column=0, sticky=NSEW)
     scrollbar = Scrollbar(top)
     scrollbar.grid(row=1, column=1, sticky=NS)
     scrollbar.config(command=tree.yview)
Ejemplo n.º 13
0
def show_result(_sorted_r):
    show_window = Toplevel()
    show_window.title("Results")

    label = Label(show_window, text=query_label.get(), font=("Arial", 30)).grid(row=0, columnspan=3)
    # create Treeview with 3 columns
    cols = ('Rank', 'Title', 'Year', 'Artist', 'Genera')

    listBox = ttk.Treeview(show_window, columns=cols, show='headings', selectmode='browse')

    listBox = Treeview(show_window, columns=cols, show='headings')
    # set column headings
    for col in cols:
        listBox.heading(col, text=col)
    listBox.grid(row=1, column=0, columnspan=2)
    show_window.resizable(width=0, height=0)
    tyag = []
    for doc in _sorted_r:
        full_hashed_address, hashed_path, restricted = get_hashed_directory(title_year_artist_genera_dir, str(doc), 255)

        with open(full_hashed_address, 'r') as file:
            for row in file:
                tyag = re.sub(r'"', ' ', row)
                tyag = tyag.split(",")
                break
        if len(tyag) == 3:
            listBox.insert("", "end", values=(_sorted_r.get(doc), tyag[0], tyag[1], tyag[2]))
        if len(tyag) == 4:
            listBox.insert("", "end", values=(_sorted_r.get(doc), tyag[0], tyag[1], tyag[2],tyag[3]))
Ejemplo n.º 14
0
    def loadTable(self, keyphraseDF, columns, searchResults):
        # TODO: make reusable for various df's
        self.keyphraseDF = keyphraseDF
        self.searchResults = searchResults
        tv = Treeview(self)
        tv['columns'] = columns

        tv.heading("#0", text='keyphrase_full')
        tv.column("#0", anchor="w", width=300)

        for column in tv['columns']:
            tv.heading(column,
                       text=column,
                       command=lambda _col=column: self.treeview_sort_column(
                           tv, _col, True))
            tv.column(column, anchor='center', width=100)

        tv.grid(sticky=(N, S, W, E))
        self.treeview = tv
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        for (i, row) in self.keyphraseDF.iterrows():
            self.treeview.insert('',
                                 'end',
                                 text=row["keyphrase_full"],
                                 values=tuple(row[column]
                                              for column in columns))

        self.treeview.bind("<Double-1>", self.onClick)

        self.treeview.bind("<Enter>", self.onEnter)
def fmenu():
    #import menu
    menu = Tk()
    menu.geometry("600x250+200+50")
    menu.title("ADMIN LOGIN")

    tree = Treeview(menu, columns=('food_id', 'name', 'price'))
    tree.heading('food_id', text='Food Id')
    tree.heading('name', text='Name')
    tree.heading('price', text='Price')
    tree.column("food_id")
    tree.column("name")
    tree.column("price")
    tree.grid()
    tree['show'] = 'headings'

    obj2.execute("SELECT food_id,name,price FROM food_item ")
    fetch = obj2.fetchall()
    for data in fetch:
        tree.insert('', '0', values=(data))


    menu.mainloop()
    obj2.close()
    fdb.close()
Ejemplo n.º 16
0
 def CreateUI(self):
     from tkinter.ttk import Treeview
     param = Treeview(self)
     param['columns'] = ('parametername', 'paramvalue', 'updatedvalue')
     param.heading("#0", text='Server', anchor='w')
     param.column("#0", anchor="w", minwidth=0, width=150, stretch=NO)
     param.heading('parametername', text='Parameter Name')
     param.column('parametername',
                  anchor="w",
                  minwidth=0,
                  width=350,
                  stretch=NO)
     param.heading('paramvalue', text='Parameter Value')
     param.column('paramvalue',
                  anchor="w",
                  minwidth=0,
                  width=100,
                  stretch=NO)
     param.heading('updatedvalue', text='Updated Value')
     param.column('updatedvalue', anchor='center')
     param.grid(sticky=(N, S, W, E))
     self.treeview = param
     self.grid_rowconfigure(0, weight=1)
     self.grid_columnconfigure(0, weight=1)
     self.treeview.bind("<Double-Button-1>", self.TableItemClick)
Ejemplo n.º 17
0
   def __init__(self, data):
       Page.__init__(self)
       self.data = data
       print('>>>>>>>>>>>>>>>>>>>',self.data)
       from defuse import knap
       a,b=knap(data)
       print('>>>>>>>>>>>> a , b',a,b)
       label = tk.Label(self, text="The set of executable query plans:")
       tree = Treeview(self, columns=('Execution Cost','Response Time','Reputation','Results number'))
       tree.heading('#0', text='Data Services')
       tree.heading('#1', text='Execution Cost')
       tree.heading('#2', text='Response Time')
       tree.heading('#4', text='Results number')
       tree.heading('#3', text='Reputation')
       tree.column('#4',stretch=tk.YES)
       tree.column('#3', stretch=tk.YES)
       tree.column('#1', stretch=tk.YES)
       tree.column('#2', stretch=tk.YES)
       tree.column('#0', stretch=tk.YES)
       tree.grid(row=4, columnspan=6, sticky='nsew')
       tree.insert('', 'end', text = "Data_Servcie1", values=(b,"----",a,"--"))
       tree.pack()

       b1 = Button(self, text='Execute', cursor='exchange')
       b1.pack(side=RIGHT, padx=5, pady=5)
       b2 = Button(self, text='Select', cursor='exchange')
       b2.pack(side=RIGHT, padx=5, pady=5)
       b3 = Button(self, text='Confirm', cursor='exchange')
       b3.pack(side=RIGHT, padx=5, pady=5)
Ejemplo n.º 18
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        for count in range(0, 10):
            Grid.rowconfigure(self, count, weight=1)
            Grid.columnconfigure(self, count, weight=1)

        # Paths subsection of settings page treeview + scrollbar + label + two buttons

        tv = Treeview(self)
        self.paths_tree_view = tv
        tv.grid(row=1, column=0, rowspan=3, columnspan=10, sticky=(N, E, W, S))
        tv['columns'] = 'Source'
        tv.heading('#0', text="Path")
        tv.heading('Source', text="Source")
        tv.column("#0", anchor='w', minwidth=200)
        tv.column('Source', width=100, minwidth=50)

        paths_label = Label(self,
                            text="PATHS OF YOUR GAME LIBRARY",
                            font=('Fixedsys', 16))
        paths_label.grid(row=0, column=0, columnspan=10, sticky=N + S + E + W)

        # TODO: Make these buttons do stuff? :D
        add_button = Button(self, text="Add", command=None)
        add_button.grid(row=4, column=8, sticky=N + S + E + W)

        remove_button = Button(self, text="Remove", command=None)
        remove_button.grid(row=4, column=9, sticky=N + S + E + W)

        ysb = Scrollbar(self, orient='vertical', command=tv.yview)
        tv.configure(yscroll=ysb.set)
        ysb.grid(row=1, column=9, rowspan=3, sticky='nse')

        # Video subsection

        video_label = Label(self, text='Video settings', font=('Courier', 14))
        video_label.grid(row=4, column=0, columnspan=2, sticky=N + S + E + W)

        video_label_w = Label(self, text='Width', font=('Courier', 11))
        video_label_w.grid(row=6, column=0, sticky=N + S + E + W)

        video_label_h = Label(self, text='Height', font=('Courier', 11))
        video_label_h.grid(row=7, column=0, sticky=N + S + E + W)

        width_entry = Entry(self, text='Default width', font=('Courier', 11))
        width_entry.grid(row=6, column=2, sticky=N + S + E + W)

        height_entry = Entry(self, text='Default height', font=('Courier', 11))
        height_entry.grid(row=7, column=2, sticky=N + S + E + W)
        # Buttons for the rest

        save_button = Button(self, text="Save", command=None)
        save_button.grid(row=10, column=8, sticky=N + S + E + W)

        cancel_button = Button(self,
                               text="Cancel",
                               command=lambda: controller.show_frame(MainPage))
        cancel_button.grid(row=10, column=9, sticky=N + S + E + W)
Ejemplo n.º 19
0
    def extraire_caracs(self):
        
        try:
            m=im     #Si im ou im_seg n'est pas définie (on n'a pas encore ouvert d'image ou pas encore segmentée l'image ouverte, on aura un NameError d'où un message de précaution de notre part
            n=im_seg
            scores = Tk()           #on va afficher une nouvelle fenêtre qui contiendra les résultats.
            scores.title('Extraction des caractéristiques')

            style = Style(scores)

            style.configure('Treeview', rowheight=40)                 #Permet de changer la taille du tableau qu'on va créer, ainsi que la police d'écriture
            style.configure('Treeview', font=(None, 15))
            style.configure('Treeview.Heading', font=(None, 18, 'bold'))                
            cols = ('Caractéristiques', 'Scores')
            listBox = Treeview(scores, height=7, columns=cols, show='headings') #Le tableau est un Treeview
            for col in cols:
                listBox.heading(col, text=col)       #on regle les titres des colonnes du tableau et leur taille
                listBox.column(col, width=int(1/6*GetSystemMetrics(0)))

            listBox.grid(row=0, column=0, columnspan=2)

            L=extraction_classification.ABCDbis(filepath,255*im_seg)   #les  résultats de l'extraction des caractéristiques
            A1,A2,B1,B2,C=L[0]
            
            global results
            results = [['',''],['A1 - Assymetry 1',str(A1)], ['A2 - Assymetry 2',str(A2)],['B1 - Borders 1',str(B1)], ['B2 - Borders 2',str(B2)], ['C - Colors' , str(C)]] 
            listDiag=extraction_classification.diagnostic(L)
            global lis
            lis=[]
            for x in listDiag:
                if x:
                    lis.append('Malin')
                else:
                    lis.append('Bénin')
            for i in range(len(results)):
                listBox.insert("", "end", values=(results[i][0], results[i][1]))  #on insère les caractéristiques extraites dans le tableau
                
            Label(scores, text="Linear Discriminant Analysis", font=("Helvetica 16 bold"), justify=LEFT).grid(row=1, columnspan=1,sticky=W)  #on donne les résultats de classification selon différentes méthodes
            Label(scores, text=lis[0], font=("Helvetica 16"), justify=LEFT).grid(row=1, column=1,sticky=W)
            Label(scores, text="Quadratic Discriminant Analysis", font=("Helvetica 16 bold"), justify=LEFT).grid(row=2, columnspan=1,sticky=W)
            Label(scores, text=lis[1], font=("Helvetica 16"), justify=LEFT).grid(row=2, column=1,sticky=W)
            Label(scores, text="Naive Bayes", font=("Helvetica 16 bold"),justify=LEFT).grid(row=3, columnspan=1,sticky=W)
            Label(scores, text=lis[2], font=("Helvetica 16"), justify=LEFT).grid(row=3, column=1,sticky=W)
            #Label(scores, text="K-NearestNeighbours", font=("Helvetica 16 bold"), justify=LEFT).grid(row=4, columnspan=1,sticky=W)
            #Label(scores, text="Malin", font=("Helvetica 16"), justify=LEFT).grid(row=4, column=1,sticky=W)
            Label(scores, text="Logistic Regression", font=("Helvetica 16 bold"), justify=LEFT).grid(row=4, columnspan=1,sticky=W)
            Label(scores, text=lis[3], font=("Helvetica 16"), justify=LEFT).grid(row=4, column=1,sticky=W)

            scores.mainloop()
            scores.destroy()

          
        except NameError:
            im_exists = 'im' in locals() or 'im' in globals()
            im_seg_exists = 'im_seg' in locals() or 'im_seg' in globals()
            if not im_exists:  #ce sont des messages de précaution si aucune image n'a encore été ouverte et qu'on appuie sur le bouton de segmentation ou si on veut extraire les caracs et que la segmentation n'a pas encore été faite
                showerror(title="Erreur", message="Vous n'avez pas ouvert d'image.", default=OK, icon=ERROR)
            elif not im_seg_exists:
                showerror(title="Erreur", message="Vous n'avez pas encore effectué la segmentation.", default=OK, icon=ERROR)
Ejemplo n.º 20
0
def leaderboard_window(window, Gamer_name):
    global leaderboard
    for widget in window.winfo_children():
        widget.destroy()
    frame = Frame(window)
    frame.grid(row=1, column=1)

    frame.grid_columnconfigure(0, weight=1)
    frame.grid_rowconfigure(0, weight=1)

    t = threading.Thread(target=getleaderboard)
    t.start()
    message1 = Label(frame,
                     text='Please Wait...',
                     fg='black',
                     font='Ariel 16 bold')
    message1.grid(row=0, column=0, pady=(5, 5))
    progress = Progressbar(frame,
                           orient=HORIZONTAL,
                           length=100,
                           mode='indeterminate')
    progress.grid(row=1, column=0, pady=(5, 5))
    bar(progress, frame)
    listt = frame.grid_slaves()
    for l in listt:
        l.destroy()

    name = Label(frame, text='Leaderboard', fg='black', font='Ariel 16 bold')
    name.grid(row=0, column=0, pady=(10, 10))

    i = 1
    for key in leaderboard.keys():
        i += 1
        name1 = Label(frame, text=key, fg='black', font='Ariel 10 bold')
        name1.grid(row=i, column=0, pady=(5, 5))
        tv = Treeview(frame, height=len(leaderboard[key]) - 1)
        tv['columns'] = (leaderboard[key][0][1])
        tv.heading("#0", text=leaderboard[key][0][0])
        tv.column("#0", anchor="center", width=100)
        tv.heading(leaderboard[key][0][1], text=leaderboard[key][0][1])
        tv.column(leaderboard[key][0][1], anchor='center', width=100)
        tv.grid(sticky=(N, S))
        treeview = tv
        for j in range(len(leaderboard[key]) - 1):
            j += 1
            treeview.insert('',
                            'end',
                            text=leaderboard[key][j][0],
                            values=(leaderboard[key][j][1]))
        i += 1
        treeview.grid(row=i, column=0, pady=(10, 10))

    bottonEasy = Button(frame,
                        text='Go back',
                        bg="green",
                        fg="white",
                        font='Ariel 12 bold',
                        command=lambda: start(window, Gamer_name))
    bottonEasy.grid(row=i + 1, column=0, pady=(5, 5))
Ejemplo n.º 21
0
class DeviceToFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(DeviceToFrame, self).__init__(master, config)

        self._state = state

        if self._state.action == 'copy':
            self._frame_lbl['text'] = 'Copy To Directory'
        elif self._state.action == 'delete':
            self._frame_lbl['text'] = 'Delete From Directory'

        self._next_btn['command'] = self._next_cmd

        self._tree = Treeview(self._master, columns=('size'))
        self._tree.heading('size', text='Size')
        self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._tree.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._tree.yview

        self._item_paths = {}
        self._populate_tree(self._state.to_device.part().mount())

    def _next_cmd(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            self._state.device_to_path = cur_path
            self._new_state_window(CopyFileFrame, self._state)

    def _populate_tree(self, tree_root):
        self._item_paths = {}

        def insert_path(tree, path, parent_id):
            dirs = [e for e in scandir(path) if e.is_dir()]
            dirs.sort(key=lambda e: e.name)

            for d in dirs:
                dir_name = d.name
                dir_id = '{}-{}'.format(parent_id, dir_name)
                dir_path = os.path.join(path, dir_name)
                tree.insert(parent_id,
                            'end',
                            dir_id,
                            text=dir_name,
                            tags=('dir'))
                self._item_paths[dir_id] = dir_path
                try:
                    insert_path(tree, dir_path, dir_id)
                except:
                    pass

        insert_path(self._tree, tree_root, '')

        tree = self._tree
        tree.tag_configure('dir', font=self._config.item_font)
        tree.tag_configure('file', font=self._config.item_font)
        tree.tag_configure('file_odd', background='light grey')
 def add_main_measurement_table(self, table_frame):
     main_angle = SymmetryAngleProportionValue(self.a.malar_middle)
     angle_label = tk.Label(table_frame, text=ms.get("main_measurement"))
     angle_label.grid(sticky=tk.W, padx=10)
     tm = Treeview(table_frame, height=1)
     tm.column("#0", width=1100)
     tm.insert("", 1100, text=ms.get("main_measurement_text").format(main_angle.get_orientation(),
                                                                     main_angle.get_differential()))
     tm.grid()
Ejemplo n.º 23
0
class Table(tk.Frame):

    def __init__(self, parent, controller):
        self.parent = parent
        self.controller = controller

        tk.Frame.__init__(self, parent)

        self.status = tk.Label(self, text="Player List", font=LARGE_FONT)
        self.status.grid(row = 0, column = 0)

        # Player list table
        columns = ["Name", "Rating", "Futbin Price", "Real Price", "Buy %", "Sell %"]

        self.router_tree_view = Treeview(self, columns=columns, show="headings", height=5)
        # self.router_tree_view.column("id", width=30)

        for col in columns:
            colwidth = 70
            if col == "Card name":
                colwidth = 135
            self.router_tree_view.column(col, width=colwidth)
            self.router_tree_view.heading(col, text=col)

        #router_tree_view.bind('<<TreeviewSelect>>', select_router)
        self.router_tree_view.grid(row=1,column=0)

        # LOAD IN TABLE
        txt = open("./data/player_list.txt", "r", encoding="utf8")

        self.playerlist = self.controller.playerfilters.playerlist

        conserve_bids, sleep_time, botspeed, bidexpiration_ceiling, buyceiling, sellceiling = getUserConfigNonClass()
        #self.playerlist = []
        for aline in txt:
            values2 = aline.strip("\n").split(",")
            # print(values2)
            self.playerlist.append(values2)
            cardname = values2[1]
            rating = values2[2]
            futbinprice = values2[9]
            realprice = values2[11]
            buypct = values2[12]

            values_small_view = []
            values_small_view.append(cardname)
            values_small_view.append(rating)
            values_small_view.append(futbinprice)

            values_small_view.append(realprice)
            values_small_view.append(buyceiling)
            values_small_view.append(sellceiling)

            # print(values_small_view)
            self.router_tree_view.insert('', 'end', values=values_small_view)
        txt.close()
Ejemplo n.º 24
0
    def init_remote(self):
        """远程文件列表"""

        if not self.remote_box:
            return False

        btn_bar = Frame(self.remote_box, relief="ridge", bd=1)
        btn_bar.pack(fill="x", expand=False, side="top")
        Label(btn_bar, text="远程:").pack(fill="x", expand=None, side="left")
        path = Entry(btn_bar, textvariable=self.path_remote)
        path.pack(fill="x", expand=True, side="left")

        Button(
            btn_bar, text="打开", command=self.select_path_remote).pack(
                fill="x", expand=None, side="left")
        Button(btn_bar, text="重连", command=self.ftp_login).pack(side="left")
        Button(btn_bar, text="断开", command=self.ftp_quit).pack(side="left")
        Button(
            btn_bar, text="刷新", command=self.flash_remote).pack(
                fill="x", expand=None, side="right")

        file_list = Frame(self.remote_box, relief="ridge", bd=0)
        file_list.pack(fill="both", expand=True, side="top")
        # Listbox
        # self.filelist_remote = Listbox(self.remote_box)
        # self.filelist_remote.bind("<Double-Button-1>", self.click_db)
        # self.filelist_remote.pack(fill="both", expand=True, side="top")

        tree = Treeview(file_list, show="headings")
        # 列索引ID
        tree["columns"] = ("pra", "id", "user", "group", "size", "date",
                           "name")
        # 表头设置
        tree.heading("pra", text="权限")
        tree.heading("id", text="ID")
        tree.heading("user", text="用户")
        tree.heading("group", text="组")
        tree.heading("size", text="大小")
        tree.heading("date", text="最后修改日期")
        tree.heading("name", text="文件名")

        tree.column("pra", width="100")
        tree.column("id", width="50", anchor="center")
        tree.column("user", width="50")
        tree.column("group", width="50")
        tree.column("size", width="50")
        tree.column("date", width="50")
        tree.column("name", width="50")

        self.filelist_remote = tree

        vbar = Scrollbar(file_list, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vbar.set)
        tree.grid(row=0, column=0, sticky="nswe")
        vbar.grid(row=0, column=1, sticky="ns")
Ejemplo n.º 25
0
class MultiColumnListboxApp(object):
    """use a ttk.TreeView as a multicolumn ListBox"""
    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        s = "Corona-Scraper"
        msg = Label(wraplength="4i",
                    justify="left",
                    anchor="n",
                    padding=(10, 2, 10, 6),
                    text=s)
        msg.pack(fill='x')
        topf = Frame()
        topf.pack(pady=10)
        refreshb = Button(topf, text="Refresh", command=refreshData)
        refreshb.pack(side=LEFT, padx=10)
        global modeb, themeb
        modeb = Button(topf, text="Widget Mode", command=changeMode)
        modeb.pack(side=LEFT, padx=10)
        themeb = Button(topf, text="Dark Mode", command=changeTheme)
        themeb.pack(side=LEFT, padx=10)
        exitb = Button(topf, text="Exit", command=exitAppGui)
        exitb.pack(side=RIGHT, padx=10)

        container = Frame()
        container.pack(fill='both', expand=True)
        # create a treeview with dual scrollbars
        self.tree = Treeview(columns=country_header, show="headings")
        vsb = Scrollbar(orient="vertical", command=self.tree.yview)
        hsb = Scrollbar(orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in country_header:
            self.tree.heading(col,
                              text=col.title(),
                              command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width to the header string
            self.tree.column(col, width=tkFont.Font().measure(col.title()))

        for item in country_list:
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value
            for ix, val in enumerate(item):
                col_w = tkFont.Font().measure(val)
                if self.tree.column(country_header[ix], width=None) < col_w:
                    self.tree.column(country_header[ix], width=col_w)
Ejemplo n.º 26
0
 def __init__(self, root, columns):
     """Initialites class."""
     frame = Treeview(root)
     frame['columns'] = columns
     frame.heading('#0', anchor="w")
     frame.column('#0', width=10)
     for column in columns:
         frame.heading(column, text=column, anchor="center")
         frame.column(column, anchor="e", width=125)
     frame.grid(sticky="news")
     self.frame = frame
Ejemplo n.º 27
0
 def CreateUI(self):
     tv = Treeview(self)
     tv['columns'] = ('rank')
     tv.heading("#0", text='Sources', anchor='w')
     tv.column("#0", anchor="w")
     tv.heading('rank', text='Rank')
     tv.column('rank', anchor='center', width=100)
     tv.grid(sticky = (N,S,W,E))
     self.treeview = tv
     self.treeview.grid_rowconfigure(0, weight = 1)
     self.treeview.grid_columnconfigure(0, weight = 1)
Ejemplo n.º 28
0
	def CreateUI(self, classInstance):

		self.headers = [ 
			"Customers", 
			"Inter-arrival time", 
			"Arrival time", 
			"Service time",
			"Waiting time in queue", 
			"Time when service begins", 
			"Time when service ends", 
			"Time customer spends in system",
			"Idle time of server"
		]

		self.contents =[]

		# populates the table from other class to generate the tkinter table
		def compilelist(classInstance):
			self.contents.append(classInstance.intarrival())
			self.contents.append(classInstance.arrival())
			self.contents.append(classInstance.service())
			self.contents.append(classInstance.queuewait())
			self.contents.append(classInstance.servbegin())
			self.contents.append(classInstance.servend())
			self.contents.append(classInstance.custspend())
			self.contents.append(classInstance.idle())

			return self.contents

		# Calling the function
		compilelist(classInstance)

		self.rearrange = []
		for row in zip(*self.contents):
			self.rearrange.append(row)

		self.headdata = []
		for x in range(len(self.contents[0])):
			self.headdata.append(x+1)

		header_lists = []
		tv = Treeview(self)
		tv['columns'] = (self.headers)

		for x in range(len(self.headers)):
			tv.heading("#%s"%x, text=self.headers[x], anchor='center')
			tv.column ("#%s"%x, anchor='center', width="150")

		tv.grid(sticky = (N,S,W,E))
		self.treeview = tv
		self.grid_rowconfigure(0, weight = 1)
		self.grid_columnconfigure(0, weight = 1)
Ejemplo n.º 29
0
class DeviceToFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(DeviceToFrame, self).__init__(master, config)

        self._state = state

        if self._state.action == 'copy':
            self._frame_lbl['text'] = 'Copy To Directory'
        elif self._state.action == 'delete':
            self._frame_lbl['text'] = 'Delete From Directory'

        self._next_btn['command'] = self._next_cmd

        self._tree = Treeview(self._master, columns=('size'))
        self._tree.heading('size', text='Size')
        self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._tree.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._tree.yview

        self._item_paths = {}
        self._populate_tree(self._state.to_device.part().mount())

    def _next_cmd(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            self._state.device_to_path = cur_path
            self._new_state_window(CopyFileFrame, self._state)

    def _populate_tree(self, tree_root):
        self._item_paths = {}
        def insert_path(tree, path, parent_id):
            dirs = [e for e in scandir(path) if e.is_dir()]
            dirs.sort(key=lambda e: e.name)

            for d in dirs:
                dir_name = d.name
                dir_id = '{}-{}'.format(parent_id, dir_name)
                dir_path = os.path.join(path, dir_name)
                tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir'))
                self._item_paths[dir_id] = dir_path
                try:
                    insert_path(tree, dir_path, dir_id)
                except:
                    pass

        insert_path(self._tree, tree_root, '')

        tree = self._tree
        tree.tag_configure('dir', font=self._config.item_font)
        tree.tag_configure('file', font=self._config.item_font)
        tree.tag_configure('file_odd', background='light grey')
Ejemplo n.º 30
0
 def createScoreTable(self):
     """Crée le tableau des scores."""
     tk.Label(self.master, text="Scores",
              font="-weight bold").grid(row=3, column=0, columnspan=2)
     tv = Treeview(self.master, height=3)
     tv['columns'] = ('Score', "Bomb")
     tv.heading("#0", text='User', anchor=tk.W)
     tv.heading('Bomb', text='Bombs available', anchor=tk.W)
     tv.column('Bomb', anchor=tk.W, width=100)
     tv.heading('Score', text='Score', anchor=tk.W)
     tv.column('Score', anchor=tk.W, width=100)
     tv.grid(row=4, column=0, columnspan=3, sticky=tk.EW)
     self.treeview = tv
 def add_breaking_point_table(self, table_frame):
     angle_label = tk.Label(table_frame, text=ms.get("break_point"))
     angle_label.grid(sticky=tk.W, padx=10)
     tm = Treeview(table_frame, height=1)
     tm["columns"] = "angle", "deviation", "", ""
     tm.heading("angle", text=ms.get("angle"))
     tm.heading("deviation", text=ms.get("deviation"))
     tm.heading("", text="")
     tm.heading("", text="")
     tm.column("#0", width=300)
     break_point_row = DisplacementAngleProportionValue(self.a.break_point_nose_point)
     tm.insert("", 0, text="{break_point}".format_map(ms),
               values=break_point_row.get_value())
     tm.grid()
 def add_chin_angle_table(self, table_frame):
     angle_label = tk.Label(table_frame, text=ms.get("chin_angles"))
     angle_label.grid(sticky=tk.W, padx=10)
     tm = Treeview(table_frame, height=3)
     tm["columns"] = "left", "right", "differential", "orientation"
     tm.heading("left", text=ms.get("right"))
     tm.heading("right", text=ms.get("left"))
     tm.heading("differential", text=ms.get("differential"))
     tm.heading("orientation", text=ms.get("orientation"))
     tm.column("#0", width=300)
     self.add_row(tm, SymmetryAngleProportionValue(self.a.cheek_chin), "{cheek} - {chin}".format_map(ms))
     self.add_row(tm, SymmetryAngleProportionValue(self.a.mouth_chin), "{mouth} - {chin}".format_map(ms))
     self.add_row(tm, SymmetryAngleProportionValue(self.a.cheekbone_chin), "{cheekbone} - {chin}".format_map(ms))
     tm.grid()
Ejemplo n.º 33
0
class SelectionFrame(Frame):
    def __init__(self, fruit_list, **kw):
        # init drop down
        super().__init__(**kw)
        self.fruit_list = fruit_list
        self.type_select = StringVar(self)
        header = Label(self)
        header.grid(row=0, column=0, columnspan=2, pady=10)
        type_options = OptionMenu(
            header, self.type_select, *models.TYPES, command=self.set_group)
        type_options.config(width=14)
        type_options.grid(row=0, column=0)
        # init start simulator button
        simulator_btn = Button(
            header, text="模拟器", command=lambda: sm.Simulator().mainloop())
        simulator_btn.grid(row=0, column=1)
        # init treeView
        self.tree = Treeview(self, columns=["名称", "效果"], show="headings")
        self.tree.column("名称", width=50, anchor='center')
        self.tree.column("效果", width=150, anchor='center')
        self.tree.heading("名称", text="名称")
        self.tree.heading("效果", text="效果")
        self.tree.grid(row=1, column=0)
        self.tree.bind("<Double-1>", self.select_item)
        self.select_item_callback = lambda x: x
        vbar = Scrollbar(self, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=vbar.set)
        vbar.grid(row=1, column=1, sticky=NS)
        # default value
        self.set_group(models.TYPES[0])

    def set_group(self, group):
        self.type_select.set(group)
        x = self.tree.get_children()
        for item in x:
            self.tree.delete(item)

        for x in self.fruit_list:
            if x.get_type() == group:
                self.tree.insert("", END, value=(x.name, x.description))

    def select_item(self, event):
        item = self.tree.selection()[0]
        name = self.tree.item(item, "value")[0]
        self.select_item_callback(
            next(filter(lambda x: x.name == name, self.fruit_list)))

    def set_select_callback(self, callback):
        self.select_item_callback = callback
Ejemplo n.º 34
0
class DialogOpenArchive(Toplevel):
    def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent # parent is cntlrWinMain
        else: # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                
                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append([potentialInstance, _type])
                                packageContentTypeCounts[potentialInstance] = packageContentTypeCounts.get(potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break 
                    if self.packageContainedInstances: # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][0] = "{} {}".format(_type, _dupNo)
                                    
                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return
    
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)
        
        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        
        self.wait_window(self)

    
        
        
    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""): 
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            if openType in (PLUGIN, PACKAGE): width = 770
            else: width = 500
            self.treeView.column("#0", width=width, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            self.isRss = getattr(self.filesource, "isRss", False)
            if self.isRss:
                self.treeView.column("#0", width=350, anchor="w")
                self.treeView["columns"] = ("descr", "date", "instDoc")
                self.treeView.column("descr", width=50, anchor="center", stretch=False)
                self.treeView.heading("descr", text="Form")
                self.treeView.column("date", width=170, anchor="w", stretch=False)
                self.treeView.heading("date", text="Pub Date")
                self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                self.treeView.heading("instDoc", text="Instance Document")
            elif openType == PLUGIN:
                self.treeView.column("#0", width=150, anchor="w")
                self.treeView["columns"] = ("name", "vers", "descr", "license")
                self.treeView.column("name", width=150, anchor="w", stretch=False)
                self.treeView.heading("name", text="Name")
                self.treeView.column("vers", width=60, anchor="w", stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr", width=300, anchor="w", stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license", width=60, anchor="w", stretch=False)
                self.treeView.heading("license", text="License")
            elif openType == PACKAGE:
                self.treeView.column("#0", width=200, anchor="w")
                self.treeView["columns"] = ("vers", "descr", "license")
                self.treeView.column("vers", width=100, anchor="w", stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr", width=400, anchor="w", stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license", width=70, anchor="w", stretch=False)
                self.treeView.heading("license", text="License")
            else:
                self.treeView["columns"] = tuple()
        
            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename,tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    elif openType == PLUGIN:
                        name, vers, descr, license = filename[3:7]
                    elif openType == PACKAGE:
                        vers, descr, license = filename[3:6]
                    filename = filename[0] # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                elif openType == PLUGIN:
                    self.treeView.set(node, "name", name)
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                elif openType == PACKAGE:
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=200, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=300, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for fileType, fileUrl in getattr(self, "packageContainedInstances", ()):
                self.treeView.insert("", "end", fileUrl, 
                                     values=fileType, 
                                     text=fileUrl or urls[0][2])
            for name, urls in sorted(self.taxonomyPackage["entryPoints"].items(), key=lambda i:i[0][2]):
                self.treeView.insert("", "end", name, 
                                     values="\n".join(url[1] for url in urls), 
                                     text=name or urls[0][2])
                
            self.hasToolTip = True
        else: # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries"))

        
    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if hasattr(self, "taxonomyPackage"):
                # load file source remappings
                self.filesource.mappedPaths = self.taxonomyPackage["remappings"]
            filename = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename,tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                # Greg Acsone reports [0] does not work for Corep 1.6 pkgs, need [1], old style packages
                filenames = []
                for _url, _type in self.packageContainedInstances: # check if selection was an inline instance
                    if _type == epName:
                        filenames.append(_url)
                if not filenames: # else if it's a named taxonomy entry point
                    for url in self.taxonomyPackage["entryPoints"][epName]:
                        filename = url[0]
                        if not filename.endswith("/"):
                            # check if it's an absolute URL rather than a path into the archive
                            if not isHttpUrl(filename) and self.metadataFilePrefix != self.taxonomyPkgMetaInf:
                                # assume it's a path inside the archive:
                                filename = self.metadataFilePrefix + filename
                        filenames.append(filename)
                if filenames:
                    self.filesource.select(filenames)
                    self.accepted = True
                    self.close()
                return
            elif self.openType in (PLUGIN, PACKAGE):
                filename = self.filenames[int(selection[0][4:])][2]
            if filename is not None and not filename.endswith("/"):
                if hasattr(self, "taxonomyPackage"):
                    # attempt to unmap the filename to original file
                    # will be mapped again in loading, but this allows schemaLocation to be unmapped
                    for prefix, remapping in self.taxonomyPackage["remappings"].items():
                        if isHttpUrl(remapping):
                            remapStart = remapping
                        else:
                            remapStart = self.metadataFilePrefix + remapping
                        if filename.startswith(remapStart):
                            # set unmmapped file
                            filename = prefix + filename[len(remapStart):]
                            break
                if self.openType in (PLUGIN, PACKAGE):
                    self.filesource.selection = filename
                else:
                    self.filesource.select(filename)
                self.accepted = True
                self.close()
                        
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
        
    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File"))
        
    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[ int(tvRowId[4:]) ]
                        if isinstance(text, tuple):
                            text = (text[1] or "").replace("\\n","\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    text = "{0}\n{1}".format(tvRowId, 
                             "\n".join(url[1] for url in self.taxonomyPackage["entryPoints"][tvRowId]))
                except KeyError:
                    pass
            self.setToolTip(text)
                
    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Ejemplo n.º 35
0
class DialogPackageManager(Toplevel):
    def __init__(self, mainWin, packageNamesWithNewerFileDates):
        super(DialogPackageManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.packagesConfig = PackageManager.packagesConfig
        self.packagesConfigChanged = False
        self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Taxonomy Packages Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system.  "
                                       "Select either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system.  "
                                     "URL may be either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName)
        ToolTip(manifestNameButton, text=_("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml).  "
                                           "Uses unix file name pattern matching.  "
                                           "Multiple manifest files are supported in archive (such as oasis catalogs).  "
                                           "(Replaces search for either .taxonomyPackage.xml or catalog.xml).  "), wraplength=240)
        self.manifestNamePattern = ""
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        manifestNameButton.grid(row=3, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (packages already known to arelle)
        packagesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL)
        self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect)
        hScrollbar["command"] = self.packagesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.packagesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        packagesFrame.columnconfigure(0, weight=1)
        packagesFrame.rowconfigure(0, weight=1)
        packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.packagesView.focus_set()

        self.packagesView.column("#0", width=120, anchor="w")
        self.packagesView.heading("#0", text=_("Name"))
        self.packagesView["columns"] = ("ver", "status", "date", "update", "descr")
        self.packagesView.column("ver", width=150, anchor="w", stretch=False)
        self.packagesView.heading("ver", text=_("Version"))
        self.packagesView.column("status", width=50, anchor="w", stretch=False)
        self.packagesView.heading("status", text=_("Status"))
        self.packagesView.column("date", width=170, anchor="w", stretch=False)
        self.packagesView.heading("date", text=_("File Date"))
        self.packagesView.column("update", width=50, anchor="w", stretch=False)
        self.packagesView.heading("update", text=_("Update"))
        self.packagesView.column("descr", width=200, anchor="w", stretch=False)
        self.packagesView.heading("descr", text=_("Description"))

        remappingsFrame = Frame(frame)
        vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL)
        self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.remappingsView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.remappingsView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        remappingsFrame.columnconfigure(0, weight=1)
        remappingsFrame.rowconfigure(0, weight=1)
        remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.remappingsView.focus_set()
        
        self.remappingsView.column("#0", width=200, anchor="w")
        self.remappingsView.heading("#0", text=_("Prefix"))
        self.remappingsView["columns"] = ("remapping")
        self.remappingsView.column("remapping", width=500, anchor="w", stretch=False)
        self.remappingsView.heading("remapping", text=_("Remapping"))
        
        # bottom frame package info details
        packageInfoFrame = Frame(frame, width=700)
        packageInfoFrame.columnconfigure(1, weight=1)
        
        self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", 
                                      font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W)
        self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED)
        self.packageVersionHdr.grid(row=1, column=0, sticky=W)
        self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W)
        self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED)
        self.packageDescrHdr.grid(row=2, column=0, sticky=W)
        self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W)
        self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED)
        self.packagePrefixesHdr.grid(row=3, column=0, sticky=W)
        self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W)
        ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240)
        self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED)
        self.packageUrlHdr.grid(row=4, column=0, sticky=W)
        self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240)
        self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED)
        self.packageDateHdr.grid(row=5, column=0, sticky=W)
        self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240)
        self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable)
        ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240)
        self.packageEnableButton.grid(row=6, column=1, sticky=E)
        self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp)
        ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240)
        self.packageMoveUpButton.grid(row=6, column=2, sticky=E)
        self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown)
        ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240)
        self.packageMoveDownButton.grid(row=6, column=3, sticky=E)
        self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload)
        ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240)
        self.packageReloadButton.grid(row=6, column=4, sticky=E)
        self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove)
        ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240)
        self.packageRemoveButton.grid(row=6, column=5, sticky=E)
        packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        packageInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeViews(self):
        self.selectedModule = None

        # clear previous treeview entries
        for previousNode in self.packagesView.get_children(""): 
            self.packagesView.delete(previousNode)

        for i, packageInfo in enumerate(self.packagesConfig.get("packages", [])):
            name = packageInfo.get("name", "package{}".format(i))
            node = self.packagesView.insert("", "end", "_{}".format(i), text=name)
            self.packagesView.set(node, "ver", packageInfo.get("version"))
            self.packagesView.set(node, "status", packageInfo.get("status"))
            self.packagesView.set(node, "date", packageInfo.get("fileDate"))
            if name in self.packageNamesWithNewerFileDates:
                self.packagesView.set(node, "update", _("available"))
            self.packagesView.set(node, "descr", packageInfo.get("description"))
        
        # clear previous treeview entries
        for previousNode in self.remappingsView.get_children(""): 
            self.remappingsView.delete(previousNode)

        for i, remappingItem in enumerate(sorted(self.packagesConfig.get("remappings", {}).items())):
            prefix, remapping = remappingItem
            node = self.remappingsView.insert("", "end", prefix, text=prefix)
            self.remappingsView.set(node, "remapping", remapping)
            
        self.packageSelect()  # clear out prior selection

    def ok(self, event=None):
        if self.packagesConfigChanged:
            PackageManager.packagesConfig = self.packagesConfig
            PackageManager.packagesConfigChanged = True
            self.cntlr.onPackageEnablementChanged()
        self.close()
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
                
    def packageSelect(self, *args):
        node = (self.packagesView.selection() or (None,))[0]
        try:
            nodeIndex = int(node[1:])
        except (ValueError, TypeError):
            nodeIndex = -1
        if 0 <= nodeIndex < len(self.packagesConfig["packages"]):
            packageInfo = self.packagesConfig["packages"][nodeIndex]
            self.selectedPackageIndex = nodeIndex
            name = packageInfo["name"]
            self.packageNameLabel.config(text=name)
            self.packageVersionHdr.config(state=ACTIVE)
            self.packageVersionLabel.config(text=packageInfo["version"])
            self.packageDescrHdr.config(state=ACTIVE)
            self.packageDescrLabel.config(text=packageInfo["description"])
            self.packagePrefixesHdr.config(state=ACTIVE)
            self.packagePrefixesLabel.config(text=', '.join(packageInfo["remappings"].keys()))
            self.packageUrlHdr.config(state=ACTIVE)
            self.packageUrlLabel.config(text=packageInfo["URL"])
            self.packageDateHdr.config(state=ACTIVE)
            self.packageDateLabel.config(text=packageInfo["fileDate"] + " " +
                    (_("(an update is available)") if name in self.packageNamesWithNewerFileDates else ""))
            self.packageEnableButton.config(state=ACTIVE,
                                           text={"enabled":self.DISABLE,
                                                 "disabled":self.ENABLE}[packageInfo["status"]])
            self.packageMoveUpButton.config(state=ACTIVE if 0 < nodeIndex else DISABLED)
            self.packageMoveDownButton.config(state=ACTIVE if nodeIndex < (len(self.packagesConfig["packages"]) - 1) else DISABLED)
            self.packageReloadButton.config(state=ACTIVE)
            self.packageRemoveButton.config(state=ACTIVE)
        else:
            self.selectedPackageIndex = -1
            self.packageNameLabel.config(text="")
            self.packageVersionHdr.config(state=DISABLED)
            self.packageVersionLabel.config(text="")
            self.packageDescrHdr.config(state=DISABLED)
            self.packageDescrLabel.config(text="")
            self.packagePrefixesHdr.config(state=DISABLED)
            self.packagePrefixesLabel.config(text="")
            self.packageUrlHdr.config(state=DISABLED)
            self.packageUrlLabel.config(text="")
            self.packageDateHdr.config(state=DISABLED)
            self.packageDateLabel.config(text="")

            self.packageEnableButton.config(state=DISABLED, text=self.ENABLE)
            self.packageMoveUpButton.config(state=DISABLED)
            self.packageMoveDownButton.config(state=DISABLED)
            self.packageReloadButton.config(state=DISABLED)
            self.packageRemoveButton.config(state=DISABLED)
        
    def findLocally(self):
        initialdir = self.cntlr.pluginDir # default plugin directory
        if not self.cntlr.isMac: # can't navigate within app easily, always start in default directory
            initialdir = self.cntlr.config.setdefault("packageOpenDir", initialdir)
        filename = self.cntlr.uiFileDialog("open",
                                           parent=self,
                                           title=_("Choose taxonomy package file"),
                                           initialdir=initialdir,
                                           filetypes=[(_("Taxonomy package files (*.zip)"), "*.zip"),
                                                      (_("Manifest (*.taxonomyPackage.xml)"), "*.taxonomyPackage.xml"),
                                                      (_("Oasis Catalog (*catalog.xml)"), "*catalog.xml")],
                                           defaultextension=".zip")
        if filename:
            # check if a package is selected (any file in a directory containing an __init__.py
            self.cntlr.config["packageOpenDir"] = os.path.dirname(filename)
            packageInfo = PackageManager.packageInfo(filename, packageManifestName=self.manifestNamePattern)
            self.loadFoundPackageInfo(packageInfo, filename)
                

    def findOnWeb(self):
        url = DialogURL.askURL(self)
        if url:  # url is the in-cache or local file
            packageInfo = PackageManager.packageInfo(url, packageManifestName=self.manifestNamePattern)
            self.cntlr.showStatus("") # clear web loading status
            self.loadFoundPackageInfo(packageInfo, url)
                
    def manifestName(self):
        self.manifestNamePattern = simpledialog.askstring(_("Archive manifest file name pattern"),
                                                          _("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml).  \n"
                                                            "Uses unix file name pattern matching.  \n"
                                                            "Multiple manifest files are supported in archive (such as oasis catalogs).  \n"
                                                            "(If blank, search for either .taxonomyPackage.xml or catalog.xml).  "),
                                                          initialvalue=self.manifestNamePattern,
                                                          parent=self)
                
    def loadFoundPackageInfo(self, packageInfo, url):
        if packageInfo and packageInfo.get("name"):
            self.addPackageInfo(packageInfo)
            self.loadTreeViews()
        else:
            messagebox.showwarning(_("Package is not itself a taxonomy package.  "),
                                   _("File does not itself contain a manifest file: \n\n{0}\n\n  "
                                     "If opening an archive file, the manifest file search pattern currently is \"\", please press \"Manifest\" to change manifest file name pattern, e.g.,, \"*.taxonomyPackage.xml\", if needed.  ")
                                   .format(url),
                                   parent=self)
            
    def removePackageInfo(self, name, version):
        # find package entry
        packagesList = self.packagesConfig["packages"]
        j = -1
        for i, packageInfo in enumerate(packagesList):
            if packageInfo['name'] == name and packageInfo['version'] == version:
                j = i
                break
        if 0 <= j < len(packagesList):
            del self.packagesConfig["packages"][i]
            self.packagesConfigChanged = True

    def addPackageInfo(self, packageInfo):
        name = packageInfo["name"]
        version = packageInfo["version"]
        self.removePackageInfo(name, version)  # remove any prior entry for this package
        self.packageNamesWithNewerFileDates.discard(name) # no longer has an update available
        self.packagesConfig["packages"].append(packageInfo)
        PackageManager.rebuildRemappings()
        self.packagesConfigChanged = True

    def packageEnable(self):
        if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]):
            packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex]
            if self.packageEnableButton['text'] == self.ENABLE:
                packageInfo["status"] = "enabled"
                self.packageEnableButton['text'] = self.DISABLE
            elif self.packageEnableButton['text'] == self.DISABLE:
                packageInfo["status"] = "disabled"
                self.packageEnableButton['text'] = self.ENABLE
            self.packagesConfigChanged = True
            PackageManager.rebuildRemappings()
            self.loadTreeViews()
            
    def packageMoveUp(self):
        if 1 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]):
            packages = self.packagesConfig["packages"]
            packageInfo = packages[self.selectedPackageIndex]
            del packages[self.selectedPackageIndex]
            packages.insert(self.selectedPackageIndex -1, packageInfo)
            self.packagesConfigChanged = True
            PackageManager.rebuildRemappings()
            self.loadTreeViews()
            
    def packageMoveDown(self):
        if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]) - 1:
            packages = self.packagesConfig["packages"]
            packageInfo = packages[self.selectedPackageIndex]
            del packages[self.selectedPackageIndex]
            packages.insert(self.selectedPackageIndex + 1, packageInfo)
            self.packagesConfigChanged = True
            PackageManager.rebuildRemappings()
            self.loadTreeViews()
            
    def packageReload(self):
        if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]):
            packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex]
            url = packageInfo.get("URL")
            if url:
                packageInfo = PackageManager.packageInfo(url, reload=True, packageManifestName=packageInfo.get("manifestName"))
                if packageInfo:
                    self.addPackageInfo(packageInfo)
                    PackageManager.rebuildRemappings()
                    self.loadTreeViews()
                    self.cntlr.showStatus(_("{0} reloaded").format(packageInfo.get("name")), clearAfter=5000)
                else:
                    messagebox.showwarning(_("Package error"),
                                           _("File or package cannot be reloaded: \n\n{0}")
                                           .format(url),
                                           parent=self)

    def packageRemove(self):
        if 0 <= self.selectedPackageIndex < len(self.packagesConfig["packages"]):
            packageInfo = self.packagesConfig["packages"][self.selectedPackageIndex]
            self.removePackageInfo(packageInfo["name"], packageInfo["version"])
            self.packagesConfigChanged = True
            PackageManager.rebuildRemappings()
            self.loadTreeViews()
Ejemplo n.º 36
0
class CopyFileFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(CopyFileFrame, self).__init__(master, config)

        self._state = state

        self._item_paths = {}

        self._tree = Treeview(self._master, columns=('size'))
        self._tree.heading('size', text='Size')
        self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._tree.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._tree.yview

        if self._state.action == 'copy':
            self._next_btn['text'] = 'Copy'
            self._frame_lbl['text'] = 'Copy File'
            self._populate_tree(self._config.file_root)
        elif self._state.action == 'delete':
            self._next_btn['text'] = 'Delete'
            self._frame_lbl['text'] = 'Delete File'
            self._populate_tree(self._state.to_device.part().mount())

        self._next_btn['command'] = self._next_cmd

    def _next_cmd(self):
        if self._state.action == 'copy':
            self._copy_file()
        elif self._state.action == 'delete':
            self._delete_file()

    def _copy_file(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            new_path = os.path.join(self._state.device_to_path, os.path.basename(cur_path))
            try:
                if os.path.exists(new_path):
                    if ConfirmFrame.show(
                        self._master, self._config,
                        'The file already exists in the destination.\n'
                        'Would you like to overwrite it?',
                        'Yes', 'No'
                    ):
                        shutil.copyfile(cur_path, new_path)
                else:
                    shutil.copyfile(cur_path, new_path)
            except PermissionError:
                OkFrame.show(
                    self._master, self._config,
                    'Error copying file:\n\nInvalid permissions'
                )
            except Exception as e:
                OkFrame.show(
                    self._master, self._config,
                    'An error occurred while copying the file:\n\n{}'.format(e)
                )

    def _delete_file(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            disp_path = cur_path[len(self._state.to_device.part().mount()):]
            try:
                if ConfirmFrame.show(
                    self._master, self._config,
                    'Are you sure you\'d like to delete this file?\n{}'.format(disp_path),
                    'Yes', 'No'
                ):
                    os.remove(cur_path)
                    self._tree.delete(self._tree.focus())
            except PermissionError:
                OkFrame.show(
                    self._master, self._config,
                    'Error deleting file:\n\nInvalid permissions'
                )
            except Exception as e:
                OkFrame.show(
                    self._master, self._config,
                    'An error occurred while deleting the file:\n\n{}'.format(e)
                )

    def _populate_tree(self, tree_root):
        self._item_paths = {}

        def insert_path(tree, path, parent_id):
            dirs = [e for e in scandir(path) if e.is_dir()]
            dirs.sort(key=lambda e: e.name)

            for d in dirs:
                dir_name = d.name
                dir_id = '{}-{}'.format(parent_id, dir_name)
                dir_path = os.path.join(path, dir_name)
                tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir'))
                try:
                    insert_path(tree, dir_path, dir_id)
                except:
                    pass

            files = [e for e in scandir(path) if e.is_file()]
            files.sort(key=lambda e: e.name)

            for idx, f in enumerate(files):
                file_name = f.name
                file_id = '{}-{}'.format(parent_id, file_name)
                file_stat = f.stat()
                file_size = sizeof_fmt(file_stat.st_size)
                file_path = os.path.join(path, file_name)
                self._item_paths[file_id] = file_path

                if idx % 2 == 0:
                    file_bg = 'file_even'
                else:
                    file_bg = 'file_odd'

                tree.insert(
                    parent_id,
                    'end',
                    file_id,
                    text=file_name,
                    tags=('file', file_bg),
                    values=(file_size)
                )

        insert_path(self._tree, tree_root, '')

        tree = self._tree
        tree.tag_configure('dir', font=self._config.item_font)
        tree.tag_configure('file', font=self._config.item_font)
        tree.tag_configure('file_odd', background='light grey')
Ejemplo n.º 37
0
class ElementListWidget(Frame):
	def __init__(self, parent, label, columns, showError):
		Frame.__init__(self, parent)
		
		self.showError = showError
		
		self.columnconfigure(0, weight = 1)
		self.rowconfigure(1, weight = 1)
		
		
		# Название таблицы
		self.titleLabel = Label(self, text = label)
		self.titleLabel.grid(column = 0, row = 0, sticky = W + E)
		
		
		# Таблица значений
		columns = ("Метка", "№") + columns
		self.tree = Treeview(self, columns = columns, displaycolumns = columns,
							 selectmode = "browse")
		self.tree.grid(column = 0, row = 1, sticky = W + N + E + S)
		
		# Настраиваем внешний вид таблицы (первые колонки)
		self.tree.column("#0", width = 0, stretch = 0)	# Прячем колонку с иконкой
		
		self.tree.column( columns[0], anchor = W, width = 150)
		self.tree.heading(columns[0], anchor = W, text = columns[0])
		
		self.tree.column( columns[1], anchor = E, width = 80)
		self.tree.heading(columns[1], anchor = E, text = columns[1])
		
		self.tree.bind("<<TreeviewSelect>>", self.onSelectionChanged)
		
		
		# Панель с кнопками
		self.buttonPanel = Frame(self)
		self.buttonPanel.grid(column = 0, row = 2, sticky = W + E)
		
		self.buttonPanel.columnconfigure(0, weight = 1)
		self.buttonPanel.columnconfigure(3, minsize = emptySpaceSize, weight = 0)
		self.buttonPanel.columnconfigure(6, minsize = emptySpaceSize, weight = 0)
		self.buttonPanel.columnconfigure(9, weight = 1)
		
		# Кнопки добавления/удаления элемента
		self.buttonAdd = Button(self.buttonPanel, text = "+", width = 3,
								command = self.onButtonAddClicked)
		self.buttonAdd.grid(column = 1, row = 0)
		
		self.buttonRemove = Button(self.buttonPanel, text = "-", width = 3, state = DISABLED,
								   command = self.onButtonRemoveClicked)
		self.buttonRemove.grid(column = 2, row = 0)
		
		# Кнопки перемещения элемента
		self.buttonUp = Button(self.buttonPanel, text = "↑", width = 3, state = DISABLED,
							   command = self.onButtonUpClicked)
		self.buttonUp.grid(column = 4, row = 0)
		
		self.buttonDown = Button(self.buttonPanel, text = "↓", width = 3, state = DISABLED,
								 command = self.onButtonDownClicked)
		self.buttonDown.grid(column = 5, row = 0)
		
		# Кнопки применить/отменить (для выбранного элемента)
		self.buttonCancel = Button(self.buttonPanel, text = "✗", width = 3,
								   command = self.updateSelectedFrame)
		self.buttonCancel.grid(column = 7, row = 0)
		
		self.buttonApply = Button(self.buttonPanel, text = "✓", width = 3,
								  command = self.onButtonApplyClicked)
		self.buttonApply.grid(column = 8, row = 0)
		
		
		# Редактирование выделенного элемента
		self.i     = StringVar()
		self.label = (StringVar(), StringVar())
		
		self.selectedFrame = Frame(self)
		self.selectedFrame.grid(column = 0, row = 3, sticky = W + E)
		
		# Номер
		Label(self.selectedFrame, text = "№:") \
			.grid(column = 0, row = 0)
		Label(self.selectedFrame, textvariable = self.i, width = 3, justify = RIGHT) \
			.grid(column = 1, row = 0)
		
		# Пустое пространство
		self.selectedFrame.columnconfigure(2, minsize = emptySpaceSize, weight = 0)
		
		# Метка
		Entry(self.selectedFrame, textvariable = self.label[0]) \
			.grid(column = 3, row = 0, sticky = W + E)
		
		Entry(self.selectedFrame, textvariable = self.label[1], bg = defaultValueBG) \
			.grid(column = 4, row = 0, sticky = W + E)
		
		# Виджет для элементов классов-потомков
		self.detailFrame = Frame(self.selectedFrame)
		self.detailFrame.grid(column = 3, row = 1, columnspan = 2, sticky = W + N + E + S)
		
		self.selectedFrame.columnconfigure(3, weight = 1)
		self.selectedFrame.columnconfigure(4, weight = 1)
		self.selectedFrame.rowconfigure(1, weight = 1)
	
	
	def onButtonUpClicked(self):
		item = self.selectedItem()
		if item is None: return
		
		prev = self.tree.prev(item)
		if prev != "":
			parent, index = self.tree.parent(item), self.tree.index(item)
			self.tree.move(item, parent, index - 1)
			
			# Корректируем номера элементов
			self.tree.set(item, "№", index - 1)
			self.tree.set(prev, "№", index)
			
			self.updateSelectedFrame(item)
	
	
	def onButtonDownClicked(self):
		item = self.selectedItem()
		if item is None: return
		
		next = self.tree.next(item)
		if next != "":
			parent, index = self.tree.parent(item), self.tree.index(item)
			self.tree.move(item, parent, index + 1)
			
			# Корректируем номера элементов
			self.tree.set(item, "№", index + 1)
			self.tree.set(next, "№", index)
			
			self.updateSelectedFrame(item)
	
	
	def onButtonAddClicked(self):
		pass
	
	
	def onButtonRemoveClicked(self):
		item = self.selectedItem()
		if item is None: return
		
		next = self.tree.next(item)
		self.tree.delete(item)
		
		while next != "":
			i = int(self.tree.set(next, "№"))
			self.tree.set(next, "№", i - 1)
			next = self.tree.next(next)
		
		self.onSelectionChanged()
	
	
	def onButtonApplyClicked(self, item = None):
		if item is None: item = self.selectedItem()
		if item is None: return None
		
		label = self.label[0].get()
		self.tree.set(item, "Метка", label)
		
		return item
	
	
	def onSelectionChanged(self, event = None):
		item = self.selectedItem()
		
		# Обновляем состояние кнопок
		state = DISABLED if item is None else NORMAL
		for x in (self.buttonRemove, self.buttonUp, self.buttonDown):
			x["state"] = state
		
		self.updateSelectedFrame(item)
	
	
	def selectedItem(self):
		selection = self.tree.selection()
		return None if type(selection) == type("") else selection[0]
	
	
	def clear(self):
		for item in self.tree.get_children():
			self.tree.delete(item)
	
	
	def updateSelectedFrame(self, item = None, values = None):
		if item is None: item = self.selectedItem()
		values = None
		
		if item is None:
			i     = ""
			label = ""
		else:
			if values is None: values = self.tree.set(item)
			
			i     = values["№"]
			label = values["Метка"]
		
		self.i.set(i)
		self.label[0].set(label)
		
		return (item, values)
	
	
	def addElement(self, values):
		self.tree.insert(parent = "", index = END, values = values)
	
	
	def setDefaultElement(self, label):
		self.label[1].set(label)
	
	
	def elementsCount(self):
		return len(self.tree.get_children())
	
	
	def elements(self, transform):
		return [ transform(item) for item in self.tree.get_children() ]
Ejemplo n.º 38
0
class Gr():
    def __init__(self,root,data,SCRY=None):
        self.data=data
        self.columns=[x for x in range(1,8)]+['day']
        root.rowconfigure(1,weight=1)
        root.columnconfigure(0,weight=1)
        root.columnconfigure(1,weight=1)
        root.columnconfigure(2,weight=1)
        f=Frame(root)
        f.columnconfigure(0,weight=1)
        f.rowconfigure(1,weight=1)
        self.v=Combobox(root)
        self.v.grid(row=0,column=0)
        self.v.bind('<<ComboboxSelected>>',self.select_ver)
        f.grid(row=1,column=0,columnspan=3,sticky=N+S)
        self.tree=Treeview(f,
                columns=self.columns,
                displaycolumns=['day']+self.columns[:-1],
                show='headings')
        #self.tree.tag_configure('odd',background='white')
        #self.tree.tag_configure('even',background='gray')
        self.tree.tag_configure('dif',foreground='brown')
        self.tree.tag_configure('work',background='white')
        self.tree.tag_configure('short',background='#F5EFE0')
        self.tree.tag_configure('rest',background='#E0B0B0')
        self.tree.tag_configure('holyday',background='#E7B7A4')
        for c in self.columns:
            self.tree.heading(c,text=c)
            self.tree.column(c,width=65,anchor='center')
        self.tree.column('day',width=30)
        scrX=Scrollbar(f,orient='horizontal',command=self.tree.xview)
        self.tree['xscrollcommand']=scrX.set
        if not SCRY:
            self.scrY=Scrollbar(f,orient='vertical',command=self.yview)
            self.tree['yscrollcommand']=self.scrY.set
        else:
            self.tree['yscrollcommand']=SCRY.set
        self.tree.grid(row=1,column=0,sticky=N+S)
        if not SCRY:
            self.scrY.grid(row=1,column=1,sticky=N+S)
        scrX.grid(row=2,column=0,sticky=E+W)
    def set(self,y,m):
        self.y=y
        self.m=m
        self.show()
    def yview(self,*args):
        self.tree.yview(*args)
        self.yview2(*args)
    def yview2(self,*args):
        pass
    def show(self):
        d=self.data[self.y][self.m]
        V=list(d['degur'].keys())
        self.v['values']=V
        self.v.set(V[0])
        self.select_ver()
    def select_ver(self,*e):
        self.tree.delete(*self.tree.get_children())
        d=self.data[self.y][self.m]
        offset=d['offset']
        v=self.v.get()
        col=[]
        for i,deg in enumerate(d['degurs']):
            self.tree.heading(i+1,text=deg)
            col.append(i+1)
        self.tree.configure(displaycolumns=['day']+col)
        items=dict()

        if 'табель' in d['degur']:
            a=[''.join(x) for x in zip(*[[x for x in d['degur']['план'][j]] \
                    for j in d['degurs']])]
            b=[''.join(x) for x in zip(*[[x for x in d['degur']['табель'][j]] \
                    for j in d['degurs']])]
            c=[x!=y for x,y  in zip(a,b)]
        else:
            c=[False]*32

        for i in range(1,d['days']+1):
            tag = (i+offset) % 7 in [0,6] and 'rest' or 'work'
            if i in d['holydays'] : tag='holyday'
            elif i in d['restdays'] : tag='rest'
            elif i in d['shortdays'] : tag='short'
            elif i in d['workdays'] : tag='work'
            if c[i]: tag=[tag,'dif']
            ii=self.tree.insert('','end',values=['-','-','-','-','-'],tag=tag)
            self.tree.set(ii,column='day',value=i)
            items[i]=ii

        
        for j,s in d['degur'][v].items(): # j-degur
            if not s: continue
            for i,val in enumerate(s[1:-1]):
                if val=='J':
                    val='до'
                elif val=='j':
                    val='од'
                elif val=='a':
                    val='10'
                self.tree.set(items[i+1],column=d['degurs'].index(j)+1,value=val)
            if s[0]=='Н':
                if s[1]=='-':
                    self.tree.set(items[1],column=d['degurs'].index(j)+1,value='Н(8)')
                else:
                    self.tree.set(items[1],column=d['degurs'].index(j)+1,value='!')
            if s[-2]=='Н':
                if s[-1]=='-':
                    self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='Н(4)')
                else:
                    self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='!')
        self.calc(self.y,self.m)
    def calc(self,y,m):
        d=self.data[y][m]
        offset=d['offset']
        WH=0
        for i in range(1,d['days']+1):
            if i in d['holydays']: wh=0
            elif i in d['restdays'] : wh=0
            elif i in d['shortdays'] : wh=7
            elif i in d['workdays'] : wh=8
            elif (i+offset) % 7 in [0,6]: wh=0
            else: wh=8
            WH+=wh
Ejemplo n.º 39
0
class statistic_xx():
    def __init__(self,data,y,v='план'):
        
        w=Toplevel()
        w.wm_title('Итоги по месяцам за {0} год ({1}) '.format(y,v))
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        cols=data[y]['degurs']  # ЗАГЛУШКА : список дежурных
        
        self.t=Treeview(w,columns=cols)
        self.t.column('#0',width=120)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=65,anchor='center')
        self.t.tag_configure('табель',background='green')
        self.t.tag_configure('ош',background='red')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)
        roots=dict()
        for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
            d0=data[y]
            if m not in d0: continue
            roots[m]=self.t.insert('','end',text=m+' ('+data[y][m]['month']+')')
        #r=self.t.insert('','end',text='рабочих')
        #x=self.t.insert('','end',text='xxx')
        #w=self.t.insert('','end',text='отработано')
        #e=self.t.insert('','end',text='дополнительные')
        #n=self.t.insert('','end',text='ночные')
        #h=self.t.insert('','end',text='праздничные')
        #rz_root=self.t.insert('','end',text='резерв')
        
        for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
            d0=data[y]
            if m not in d0: continue
            d=d0[m]

            rez=dict()
            tag=''
            if v=='авто':
                if 'табель' in d['degur']:
                    vv='табель'
                    tag=vv
                else:
                    vv='план'
            elif v=='табель':
                if 'табель' not in d['degur']:
                    vv='план'
                    tag='ош'
                else:
                    vv=v
                    tag=vv
            else:
                vv=v

            for j,s in d['degur'][vv].items():
                rez[j]=analyse2(s,d)
            NUL=(0,0,0,0,0,0,0)
            ww=[rez.get(j,NUL)[0] for j in cols]
            ee=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3]+rez.get(j,NUL)[4] for j in cols]
            xx=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3] for j in cols]
            nn=[rez.get(j,NUL)[1] for j in cols]
            hh=[rez.get(j,NUL)[2] for j in cols]
            rr=[rez.get(j,NUL)[3]-rez.get(j,NUL)[4] for j in cols]
            rz=[rez.get(j,NUL)[5] for j in cols]
            self.t.insert(roots[m],'end',text='отработано',values=ww,tag=tag)
            self.t.insert(roots[m],'end',text='рабочие',values=rr,tag=tag)
            self.t.insert(roots[m],'end',text='дополнительные',values=ee,tag=tag)
            self.t.insert(roots[m],'end',text='ночные',values=nn,tag=tag)
            self.t.insert(roots[m],'end',text='праздничные',values=hh,tag=tag)
Ejemplo n.º 40
0
class tabel():
    def __init__(self,data,y,m):
        w=Toplevel()
        w.geometry('{0}x{1}+0+0'.format(120+25*21,w.winfo_screenheight()-80))
        
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        d=data[y][m]
        v='план'
        if 'табель' in d['degur']:
            v='табель'
        w.wm_title('{0} {1} {2}'.format(v,y,m))
        #deg=data['2013']['11']['degurs']  # ЗАГЛУШКА : список дежурных
        deg=d['degurs']  # ЗАГЛУШКА : список дежурных
        cc=list(range(1,17))
        cols=[str(c) for c in cc]+['s','сум','ноч','пра','доп']
        
        self.t=Treeview(w,columns=cols)
        self.t.column('#0',width=100)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=25,anchor='center')
        self.t.tag_configure('title',background='gray')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)

        rez=dict()
        for j,s in d['degur'][v].items():
                rez[j]=analyse2(s,d)
        for j in deg:
            ww1=[]
            ww2=[]
            a=0
            nn1=[]
            for x in d['degur'][v].get(j,''):
                if a:
                    if x=='Д':
                        ww1.append('!!')
                        nn1+=[0,0]
                        y=a+12
                        a=0
                    elif x in [str(xx) for xx in range(1,10)]:
                        ww1.append('Я')
                        nn1+=[0,0]
                        y=a+int(x)
                        a=0
                    elif x=='Н':
                        ww1.append('!')
                        nn1+=[2,6]
                        y=a+4
                        a=8
                    elif x=='-':
                        ww1.append('Н')
                        nn1+=[0,0]
                        y=a+0
                        a=0
                    else:
                        ww1.append('!')
                        nn1+=[0,0]
                        y=a+0
                        a=0
                else:
                    if x=='Д':
                        ww1.append('Я')
                        nn1+=[0,0]
                        y=12
                        a=0
                    elif x in [str(xx) for xx in range(1,10)]:
                        ww1.append('Я')
                        nn1+=[0,0]
                        y=int(x)
                        a=0
                    elif x=='Н':
                        ww1.append(x)
                        nn1+=[2,6]
                        y=4
                        a=8
                    elif x=='-':
                        ww1.append('В')
                        nn1+=[0,0]
                        y=0
                        a=0
                    else:
                        ww1.append(x)
                        nn1+=[0,0]
                        y=0
                        a=0
                ww2.append(y)
            ww=rez.get(j,(0,0,0,0))[0]
            ee=rez.get(j,(0,0,0,0))[0] -rez.get(j,(0,0,0,0))[3]
            #ee=rez.get(j,(0,0,0,0))[3]
            nn=rez.get(j,(0,0,0,0))[1]
            hh=rez.get(j,(0,0,0,0))[2]
            s1=sum([x and 1 for x in ww2[1:16]])
            s2=sum([x and 1 for x in ww2[16:-1]])
            n0=sum([x=='Н' and 1 or 0 for x in ww1[1:-1]])

            z=self.t.insert('','end',text=j)
            self.t.insert(z,'end',text='',values=list(range(1,16)),tag='title')
            self.t.insert(z,'end',text='',values=ww1[1:16]+['',s1])
            self.t.insert(z,'end',text='',values=[x or '-' for x in ww2[1:16]]+ \
                    ['']+[sum(ww2[1:16])])
            self.t.insert(z,'end',text='',values=list(range(16,32)),tag='title')
            self.t.insert(z,'end',text='',values=ww1[16:-1]+['']*(33-len(ww1))+ \
                    [s2,s1+s2,n0])
            self.t.insert(z,'end',text='',values=[x or '-' for x in ww2[16:-1]]+ \
                    ['']*(16-len(ww2[16:-1]))+[sum(ww2[16:-1]),sum(ww2[1:-1]),sum(nn1[1:-3]),hh,ee])
Ejemplo n.º 41
0
class ComponentsDumpWindow(Toplevel):
	def __init__(self, application, barNumber = None, **kwargs):
		Toplevel.__init__(self)
		
		self.application = application
		self.barNumber = barNumber
		
		
		self.fromLabel = Label(self)
		self.fromLabel.grid(column = 0, row = 0)
		
		self.fromVar = StringVar()
		self.fromEntry = Entry(self, textvariable = self.fromVar, justify = RIGHT)
		self.fromEntry.grid(column = 1, row = 0, sticky = W + E)
		self.columnconfigure(1, weight = 1)
		
		
		self.toLabel = Label(self)
		self.toLabel.grid(column = 2, row = 0)
		
		self.toVar = StringVar()
		self.toEntry = Entry(self, textvariable = self.toVar, justify = RIGHT)
		self.toEntry.grid(column = 3, row = 0, sticky = W + E)
		self.columnconfigure(3, weight = 1)
		
		
		self.stepLabel = Label(self, text = "dx:")
		self.stepLabel.grid(column = 4, row = 0)
		
		self.stepVar = StringVar()
		self.stepEntry = Entry(self, textvariable = self.stepVar, justify = RIGHT)
		self.stepEntry.grid(column = 5, row = 0, sticky = W + E)
		self.columnconfigure(5, weight = 1)
		
		
		self.calculateButton = Button(self, text = "Рассчитать",
									  command = self.onCalculateButtonClicked)
		self.calculateButton.grid(column = 6, row = 0, columnspan = 2)
		
		
		# Таблица рассчитанных значений
		columns = ("№ стержня", "x", "Nx", "U", "σ")
		
		self.tree = Treeview(self, columns = columns, displaycolumns = columns)
		self.tree.grid(column = 0, row = 1, columnspan = 7, sticky = W + N + E + S)
		self.tree.column("#0", width = 0, stretch = 0)
		
		# Настройки отображения таблицы
		self.tree.column(columns[0], anchor = CENTER)
		self.tree.heading(columns[0], text = columns[0], anchor = CENTER)
		
		for x in columns[1:]:
			self.tree.column(x, anchor = E)
			self.tree.heading(x, text = x, anchor = E)
		
		self.rowconfigure(1, weight = 1)
		
		
		self.bind("<Destroy>", self.onWindowDestroy)
		
		
		self.updateTitles()
		self.onConstructionChanged(False)
	
	
	def updateTitles(self):
		if self.barNumber is None:
			titleDescStr = ""
			xDescStr     = "global"
		else:
			titleDescStr = "%sСтержень (%d)" % (self.application.nameDelim, self.barNumber)
			xDescStr     = "local"
		
		self.title("%s%sКомпоненты%s" \
				   % (self.application.name, self.application.nameDelim, titleDescStr))
		
		self.fromLabel["text"] = "От x(" + xDescStr + "):"
		self.toLabel["text"] = "До x(" + xDescStr + "):"
	
	
	def onWindowDestroy(self, event):
		self.application.onWindowDestroy(self)
	
	
	def onCalculateButtonClicked(self):
		try:
			self.calculate()
		except Exception as e:
			self.showError(e)
	
	
	def onConstructionChanged(self, constructed = True):
		if not constructed:
			for var in self.fromVar, self.toVar, self.stepVar:
				var.set("0")
			return
		
		try:
			self.calculate()
		except Exception:
			self.clear()
	
	
	def onPointCalculated(self, barNumber, x, N, U, Sigma):
		if self.barNumber is not None and barNumber != self.barNumber:
			return
		
		self.tree.insert(parent = "", index = "end",
						 values = ("—" if barNumber is None else str(barNumber),
								   "%.14f" % x, "%.14f" % N,
								   "%.14f" % U, "%.14f" % Sigma))
	
	
	def clear(self):
		self.tree.delete(*self.tree.get_children())
	
	
	def calculate(self):
		self.clear()
		
		if self.barNumber not in range(0, self.application.logic.barsCount()):
			self.barNumber = None
			self.updateTitles()
		
		for var in self.fromVar, self.toVar, self.stepVar:
			try:
				float(var.get())
			except ValueError:
				var.set("0")
		
		xFrom = float(self.fromVar.get())
		xTo = float(self.toVar.get())
		xStep = float(self.stepVar.get())
		
		self.application.logic.calculateComponents(xFrom, xTo, xStep, barNumber = self.barNumber,
												   onPointCalculated = self.onPointCalculated)
	
	
	def showError(self, message):
		tkinter.messagebox.showerror("Ошибка", message)
Ejemplo n.º 42
0
class DialogPluginManager(Toplevel):
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules")
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=7, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=7, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=7, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        self.loadTreeViews()

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeViews(self):
        self.selectedModule = None

        # clear previous treeview entries
        for previousNode in self.modulesView.get_children(""): 
            self.modulesView.delete(previousNode)

        for i, moduleItem in enumerate(sorted(self.pluginConfig.get("modules", {}).items())):
            moduleInfo = moduleItem[1]
            name = moduleInfo.get("name", moduleItem[0])
            node = self.modulesView.insert("", "end", name, text=name)
            self.modulesView.set(node, "author", moduleInfo.get("author"))
            self.modulesView.set(node, "ver", moduleInfo.get("version"))
            self.modulesView.set(node, "status", moduleInfo.get("status"))
            self.modulesView.set(node, "date", moduleInfo.get("fileDate"))
            if name in self.modulesWithNewerFileDates:
                self.modulesView.set(node, "update", _("available"))
            self.modulesView.set(node, "descr", moduleInfo.get("description"))
            self.modulesView.set(node, "license", moduleInfo.get("license"))
        
        # clear previous treeview entries
        for previousNode in self.classesView.get_children(""): 
            self.classesView.delete(previousNode)

        for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())):
            className, moduleList = classItem
            node = self.classesView.insert("", "end", className, text=className)
            self.classesView.set(node, "modules", ', '.join(moduleList))
            
        self.moduleSelect()  # clear out prior selection

    def ok(self, event=None):
        if self.pluginConfigChanged:
            PluginManager.pluginConfig = self.pluginConfig
            PluginManager.pluginConfigChanged = True
            PluginManager.reset()  # force reloading of modules
        if self.uiClassMethodsChanged:  # may require reloading UI
            if messagebox.askyesno(_("User interface plug-in change"),
                                   _("A change in plug-in class methods may have affected the menus "
                                     "of the user interface.  It may be necessary to restart Arelle to "
                                     "access the menu entries or the changes to their plug-in methods.  \n\n"
                                     "Should Arelle restart with changed user interface language, "
                                     "(if there are any unsaved changes they would be lost!)?"),
                                   parent=self):
                self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True]))
        self.close()
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
                
    def moduleSelect(self, *args):
        node = (self.modulesView.selection() or (None,))[0]
        moduleInfo = self.pluginConfig.get("modules", {}).get(node)
        if moduleInfo:
            self.selectedModule = node
            name = moduleInfo["name"]
            self.moduleNameLabel.config(text=name)
            self.moduleAuthorHdr.config(state=ACTIVE)
            self.moduleAuthorLabel.config(text=moduleInfo["author"])
            self.moduleDescrHdr.config(state=ACTIVE)
            self.moduleDescrLabel.config(text=moduleInfo["description"])
            self.moduleClassesHdr.config(state=ACTIVE)
            self.moduleClassesLabel.config(text=', '.join(moduleInfo["classMethods"]))
            self.moduleUrlHdr.config(state=ACTIVE)
            self.moduleUrlLabel.config(text=moduleInfo["moduleURL"])
            self.moduleDateHdr.config(state=ACTIVE)
            self.moduleDateLabel.config(text=moduleInfo["fileDate"] + " " +
                    (_("(an update is available)") if name in self.modulesWithNewerFileDates else ""))
            self.moduleLicenseHdr.config(state=ACTIVE)
            self.moduleLicenseLabel.config(text=moduleInfo["license"])
            self.moduleEnableButton.config(state=ACTIVE,
                                           text={"enabled":self.DISABLE,
                                                 "disabled":self.ENABLE}[moduleInfo["status"]])
            self.moduleReloadButton.config(state=ACTIVE)
            self.moduleRemoveButton.config(state=ACTIVE)
        else:
            self.selectedModule = None
            self.moduleNameLabel.config(text="")
            self.moduleAuthorHdr.config(state=DISABLED)
            self.moduleAuthorLabel.config(text="")
            self.moduleDescrHdr.config(state=DISABLED)
            self.moduleDescrLabel.config(text="")
            self.moduleClassesHdr.config(state=DISABLED)
            self.moduleClassesLabel.config(text="")
            self.moduleUrlHdr.config(state=DISABLED)
            self.moduleUrlLabel.config(text="")
            self.moduleDateHdr.config(state=DISABLED)
            self.moduleDateLabel.config(text="")
            self.moduleLicenseHdr.config(state=DISABLED)
            self.moduleLicenseLabel.config(text="")
            self.moduleEnableButton.config(state=DISABLED, text=self.ENABLE)
            self.moduleReloadButton.config(state=DISABLED)
            self.moduleRemoveButton.config(state=DISABLED)
        
    def findLocally(self):
        filename = self.cntlr.uiFileDialog("open",
                                           owner=self,
                                           title=_("Choose plug-in module file"),
                                           initialdir=self.cntlr.config.setdefault("pluginOpenDir","."),
                                           filetypes=[(_("Python files"), "*.py")],
                                           defaultextension=".py")
        if filename:
            self.cntlr.config["pluginOpenDir"] = os.path.dirname(filename)
            moduleInfo = PluginManager.moduleModuleInfo(filename)
            self.loadFoundModuleInfo(moduleInfo, filename)
                

    def findOnWeb(self):
        url = DialogURL.askURL(self)
        if url:  # url is the in-cache or local file
            moduleInfo = PluginManager.moduleModuleInfo(url)
            self.cntlr.showStatus("") # clear web loading status
            self.loadFoundModuleInfo(moduleInfo, url)
                
    def loadFoundModuleInfo(self, moduleInfo, url):
        if moduleInfo and moduleInfo.get("name"):
            self.addPluginConfigModuleInfo(moduleInfo)
            self.loadTreeViews()
        else:
            messagebox.showwarning(_("Module is not a plug-in"),
                                   _("File does not contain a python program with an appropriate __pluginInfo__ declaration: \n\n{0}")
                                   .format(url),
                                   parent=self)
            
    def removePluginConfigModuleInfo(self, name):
        moduleInfo = self.pluginConfig["modules"].get(name)
        if moduleInfo:
            for classMethod in moduleInfo["classMethods"]:
                classMethods = self.pluginConfig["classes"].get(classMethod)
                if classMethods and name in classMethods:
                    classMethods.remove(name)
                    if not classMethods: # list has become unused
                        del self.pluginConfig["classes"][classMethod] # remove class
                    if classMethod.startswith("CntlrWinMain.Menu"):
                        self.uiClassMethodsChanged = True  # may require reloading UI
            del self.pluginConfig["modules"][name]
            self.pluginConfigChanged = True

    def addPluginConfigModuleInfo(self, moduleInfo):
        name = moduleInfo["name"]
        self.removePluginConfigModuleInfo(name)  # remove any prior entry for this module
        self.modulesWithNewerFileDates.discard(name) # no longer has an update available
        self.pluginConfig["modules"][name] = moduleInfo
        # add classes
        for classMethod in moduleInfo["classMethods"]:
            classMethods = self.pluginConfig["classes"].setdefault(classMethod, [])
            if name not in classMethods:
                classMethods.append(name)
            if classMethod.startswith("CntlrWinMain.Menu"):
                self.uiClassMethodsChanged = True  # may require reloading UI
        self.pluginConfigChanged = True

    def moduleEnable(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            moduleInfo = self.pluginConfig["modules"][self.selectedModule]
            if self.moduleEnableButton['text'] == self.ENABLE:
                moduleInfo["status"] = "enabled"
                self.moduleEnableButton['text'] = self.DISABLE
            elif self.moduleEnableButton['text'] == self.DISABLE:
                moduleInfo["status"] = "disabled"
                self.moduleEnableButton['text'] = self.ENABLE
            self.pluginConfigChanged = True
            self.loadTreeViews()
            
    def moduleReload(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            url = self.pluginConfig["modules"][self.selectedModule].get("moduleURL")
            if url:
                moduleInfo = PluginManager.moduleModuleInfo(url, reload=True)
                if moduleInfo:
                    self.addPluginConfigModuleInfo(moduleInfo)
                    self.loadTreeViews()
                    self.cntlr.showStatus(_("{0} reloaded").format(moduleInfo.get("name")), clearAfter=5000)
                else:
                    messagebox.showwarning(_("Module error"),
                                           _("File or module cannot be reloaded: \n\n{0}")
                                           .format(url),
                                           parent=self)

    def moduleRemove(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            self.removePluginConfigModuleInfo(self.selectedModule)
            self.pluginConfigChanged = True
            self.loadTreeViews()
Ejemplo n.º 43
0
class DialogOpenArchive(Toplevel):
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                if len(metadataFiles) > 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                metadataFile = metadataFiles[0]
                metadata = filesource.file(filesource.url + os.sep + metadataFile)[0]
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += os.sep
        
                self.nameToUrls, self.remappings = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""): 
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM):
            self.treeView.column("#0", width=500, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            try:
                self.isRss = self.filesource.isRss
                if self.isRss:
                    self.treeView.column("#0", width=350, anchor="w")
                    self.treeView["columns"] = ("descr", "date", "instDoc")
                    self.treeView.column("descr", width=50, anchor="center", stretch=False)
                    self.treeView.heading("descr", text="Form")
                    self.treeView.column("date", width=170, anchor="w", stretch=False)
                    self.treeView.heading("date", text="Pub Date")
                    self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                    self.treeView.heading("instDoc", text="Instance Document")
            except AttributeError:
                self.isRss = False
                self.treeView["columns"] = tuple()
        
            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename,tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    filename = filename[0] # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=150, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=350, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for name, urls in self.nameToUrls.items():
                displayUrl = urls[1] # display the canonical URL
                self.treeView.insert("", "end", name, values=[displayUrl], text=name)
                
            self.hasToolTip = True
        else: # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries"))

        
    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename,tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
                if not filename.endswith("/"):
                    self.filesource.select(filename)
                    self.accepted = True
                    self.close()
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                urlOrFile = self.nameToUrls[epName][0]
                
                # load file source remappings
                self.filesource.mappedPaths = \
                    dict((prefix, 
                          remapping if isHttpUrl(remapping)
                          else (self.filesource.baseurl + os.sep + self.metadataFilePrefix +remapping.replace("/", os.sep)))
                          for prefix, remapping in self.remappings.items())
    
                if not urlOrFile.endswith("/"):
                    # check if it's an absolute URL rather than a path into the archive
                    if isHttpUrl(urlOrFile):
                        self.filesource.select(urlOrFile)  # absolute path selection
                    else:
                        # assume it's a path inside the archive:
                        self.filesource.select(self.metadataFilePrefix + urlOrFile)
                    self.accepted = True
                    self.close()
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
        
    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File"))
        
    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[ int(tvRowId[4:]) ]
                        if isinstance(text, tuple):
                            text = text[1].replace("\\n","\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    epUrl = self.nameToUrls[tvRowId][1]
                    text = "{0}\n{1}".format(tvRowId, epUrl)
                except KeyError:
                    pass
            self.setToolTip(text)
                
    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Ejemplo n.º 44
0
class MainWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.eventHandler = EventHandler(self)
        self.parent = parent
        self.initUI()

    def initUI(self):

        self.parent.title("File synchronizer")

        Style().configure("TButton", padding=(0, 5, 0, 5), font="serif 10")

        # 3X3 Grid
        self.columnconfigure(0, pad=3, weight=1)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3, weight=1)
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3, weight=1)
        self.rowconfigure(2, pad=3)

        ltf = Frame(self)
        ltf.grid(row=0, column=0, sticky=W + E)
        # 1X4 Grid
        ltf.columnconfigure(0, pad=3)
        ltf.columnconfigure(1, pad=3, weight=1)
        ltf.columnconfigure(2, pad=3, weight=1)
        ltf.columnconfigure(3, pad=3)
        ltf.rowconfigure(0, pad=3, weight=1)
        llabel = Label(ltf, text="Direcotry:")
        llabel.grid(row=0, column=0, sticky=W + E)
        self.leftDir = Entry(ltf)
        self.leftDir.bind("<Return>", self.eventHandler.leftDirChanged)
        self.leftDir.grid(row=0, column=1, columnspan=2, sticky=W + E)
        # Left browse button
        lBtn = Button(ltf, text="browse...", command=self.eventHandler.chooseLeftDirectory)
        lBtn.grid(row=0, column=3, sticky=E)

        rtf = Frame(self)
        rtf.grid(row=0, column=2, sticky=W + E)
        # 1X4 Grid
        rtf.columnconfigure(0, pad=3)
        rtf.columnconfigure(1, pad=3, weight=1)
        rtf.columnconfigure(2, pad=3, weight=1)
        rtf.columnconfigure(3, pad=3)
        rtf.rowconfigure(0, pad=3, weight=1)
        rlabel = Label(rtf, text="Direcotry:")
        rlabel.grid(row=0, column=0, sticky=W + E)
        self.rightDir = Entry(rtf)
        self.rightDir.bind("<Return>", self.eventHandler.rightDirChanged)
        self.rightDir.grid(row=0, column=1, columnspan=2, sticky=W + E)
        # Right browse button
        rBtn = Button(rtf, text="browse...", command=self.eventHandler.chooseRightDirectory)
        rBtn.grid(row=0, column=3, sticky=E)

        # Left TreeView frame
        ltf1 = Frame(self)
        ltf1.grid(row=1, column=0, sticky=N + S + W + E)
        # 2 X 2 Grid
        ltf1.columnconfigure(0, pad=3, weight=1)
        ltf1.columnconfigure(1, pad=3)
        ltf1.rowconfigure(0, pad=3, weight=1)
        ltf1.rowconfigure(1, pad=3)
        self.ltree = Treeview(ltf1, columns=("fullpath", "type", "size"), displaycolumns="size")
        self.ltree.grid(row=0, column=0, sticky=E + W + S + N)
        lysb = ttk.Scrollbar(ltf1, orient=VERTICAL, command=self.ltree.yview)
        lysb.grid(row=0, column=1, sticky=NS)
        lxsb = ttk.Scrollbar(ltf1, orient=HORIZONTAL, command=self.ltree.xview)
        lxsb.grid(row=1, column=0, columnspan=3, sticky=EW)
        self.ltree["yscroll"] = lysb.set
        self.ltree["xscroll"] = lxsb.set
        self.ltree.heading("#0", text="Directory Structure", anchor="w")
        self.ltree.heading("size", text="File Size", anchor="w")
        self.ltree.column("size", stretch=0, width=100)
        self.ltree.bind("<<TreeviewOpen>>", self.eventHandler.openTree)

        # Right TreeView frame
        rtf1 = Frame(self)
        rtf1.grid(row=1, column=2, sticky=N + S + W + E)
        # 2 X 2 Grid
        rtf1.columnconfigure(0, pad=3, weight=1)
        rtf1.columnconfigure(1, pad=3)
        rtf1.rowconfigure(0, pad=3, weight=1)
        rtf1.rowconfigure(1, pad=3)
        self.rtree = Treeview(rtf1, columns=("fullpath", "type", "size"), displaycolumns="size")
        self.rtree.grid(row=0, column=0, sticky=E + W + S + N)
        rysb = ttk.Scrollbar(rtf1, orient=VERTICAL, command=self.ltree.yview)
        rysb.grid(row=0, column=1, sticky=NS)
        rxsb = ttk.Scrollbar(rtf1, orient=HORIZONTAL, command=self.ltree.xview)
        rxsb.grid(row=1, column=0, columnspan=3, sticky=EW)
        self.rtree["yscroll"] = rysb.set
        self.rtree["xscroll"] = rxsb.set
        self.rtree.heading("#0", text="Directory Structure", anchor="w")
        self.rtree.heading("size", text="File Size", anchor="w")
        self.rtree.column("size", stretch=0, width=100)
        self.rtree.bind("<<TreeviewOpen>>", self.eventHandler.openTree)

        # Command Button frame
        btnf = Frame(self)
        btnf.grid(row=1, column=1, sticky=W + E + N + S)
        btnf.columnconfigure(0, pad=3, weight=1)
        btnf.rowconfigure(0, pad=3, weight=1)
        btnf.rowconfigure(1, pad=3, weight=1)
        btnf.rowconfigure(2, pad=3, weight=1)
        btnf.rowconfigure(3, pad=3, weight=1)
        btnf.rowconfigure(4, pad=3, weight=1)
        btnf.rowconfigure(5, pad=3, weight=1)
        btnf.rowconfigure(6, pad=3, weight=1)
        btnf.rowconfigure(7, pad=3, weight=1)
        l2rBtn = Button(btnf, text="Left >> Right", command=self.eventHandler.left2RightSynch)
        l2rBtn.grid(row=1, column=0, sticky=W + E)

        syncBtn = Button(btnf, text="<< Sync >>", command=self.eventHandler.leftRightSynch)
        syncBtn.grid(row=3, column=0, sticky=W + E)

        r2lBtn = Button(btnf, text="Left << Right", command=self.eventHandler.right2LeftSynch)
        r2lBtn.grid(row=5, column=0, sticky=W + E)

        closeBtn = Button(self, text="Close", command=self.eventHandler.quit)
        closeBtn.grid(row=2, column=2, sticky=E)

        self.pack(fill=BOTH, expand=1)
Ejemplo n.º 45
0
class ScrollableTreeview(Frame):
    """
    An enhanced Tkinter Treeview control.
    """

    def __init__(self, master, **args):
        super().__init__(master)

        # Parse Treeview options for the Treeview
        opts = {x:args[x] for x in args if x in tree_options}

        # Create child controls
        self._vscroll = Scrollbar(self)
        self._hscroll = Scrollbar(self, orient=HORIZONTAL)

        opts['yscrollcommand'] = self._vscroll.set
        opts['xscrollcommand'] = self._hscroll.set
        self._tree = Treeview(self, **opts)

        # Setup the child controls
        self._init_controls()

        # Link some of the treeview's controls to this control
        self.item = self._tree.item
        self.tag_bind = self._tree.tag_bind
        self.tag_bind = self._tree.tag_configure
        self.insert = self._tree.insert
        self.delete = self._tree.delete
        self.detach = self._tree.detach
        self.heading = self._tree.heading

        # If a header argument was passed in, then use it
        self.set_headers(args.get('headers'))

    def _init_controls(self):
        """
        Initialize various properties of the child-controls
        :return:
        """

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # Place the controls
        self._tree.grid(row=0, column=0, sticky=NSEW)
        self._vscroll.grid(row=0, column=1, sticky=NS)
        self._hscroll.grid(row=1, column=0, sticky=EW)

        # Setup scrollbars
        self._vscroll.config(command=self._tree.yview)
        self._hscroll.config(command=self._tree.xview)

    def set_headers(self, headers: dict):
        """
        Update any number of column headers.
        :param headers:
        :return:
        """

        # If no headers were defined, then return
        if headers is None:
            return

        # Iterate through all of the column headers and update their values
        for col in headers:
            tp = type(headers[col])

            # Dictionary of parameters
            if tp is dict:
                self.heading(col, **headers[col])

            # Just the title
            elif tp is str:
                self.heading(col, text=headers[col])
Ejemplo n.º 46
0
Archivo: tagview.py Proyecto: gokai/tim
class NameView(object):
    """Shows a treeview of unique names."""

    def __init__(self, master, names):
        self.widget = Frame(master)
        self._tree = Treeview(self.widget, columns='name')
        self._tree.grid(row=0,column=0, sticky=(N,S,W,E))
        self._tree.view = self
        self.widget.columnconfigure(0, weight=1)
        self.widget.rowconfigure(0,weight=1)
        self._tree.column('name', width=50)
        self._tree['show'] = 'tree'
        actions = {'edit': lambda e: self.edit(),
                'search': lambda e: self.search(),
                'focus_next': lambda e: self.focus_next(),
                'focus_prev': lambda e: self.focus_prev(),
                'select': lambda e: self._tree.selection_toggle(self._tree.focus()),
                'clear_selection': lambda e: self._tree.selection_set([])
                }
        kb.make_bindings(kb.tagview, actions, self._tree.bind)
        self._iids = dict()
        self._names = dict()
        logger.debug('Names: %s', names)
        self.widget.focus_set = self._tree.focus_set
        for name in sorted(names):
            iid = self._tree.insert('', 'end', text=name)
            self._names[iid] = name
            self._iids[name] = iid
        self._scroll = Scrollbar(self.widget, command=self._tree.yview)
        self._tree['yscrollcommand'] = self._scroll.set
        self._scroll.grid(row=0, column=1, sticky=(N, S))
        self.widget.columnconfigure(1, weight=0)


    def selection(self):
        logger.debug('Selection: %s', self._tree.selection())
        return [self._names[iid] for iid in self._tree.selection()]

    def edit(self):
        self._tree.event_generate('<<NameViewEdit>>')

    def search(self):
        if len(self._tree.selection()) == 0:
            self._tree.selection_add(self._tree.focus())
        self._tree.event_generate('<<NameViewSearch>>')

    def append(self, names):
        logger.debug('Append names: %s', names)
        for name in names:
            if name not in self._names.values():
                iid = self._tree.insert('', 'end', text=name)
                self._names[iid] = name
                self._iids[name] = iid

    def delete(self, name):
        self._tree.delete(self._iids[name])
        del self._names[self._iids[name]]
        del self._iids[name]

    def _focus(self, iid):
        self._tree.focus(iid)
        self._tree.see(iid)

    def focus_next(self):
        cur_iid = self._tree.focus()
        next_iid = self._tree.next(cur_iid)
        if next_iid == '':
            iids = self._tree.get_children()
            next_iid = iids[0]
        self._focus(next_iid)

    def focus_prev(self):
        cur_iid = self._tree.focus()
        prev_iid = self._tree.prev(cur_iid)
        if prev_iid == '':
            iids = self._tree.get_children()
            prev_iid = iids[-1]
        self._focus(prev_iid)

    def jump_to(self, name):
        try:
            iid = self._iids[name]
            self._focus(iid)
        except KeyError:
            pass

    def get_names(self):
        return tuple(self._names.values())

    def set(self, names):
        self._tree.delete(*self._iids.values())
        self._iids.clear()
        self._names.clear()
        for name in sorted(names):
            iid = self._tree.insert('', 'end', text=name)
            self._names[iid] = name
            self._iids[name] = iid
Ejemplo n.º 47
0
class statistic_q():
    def __init__(self,data,y,v='план'):
        
        w=Toplevel()
        w.wm_title('Поквартальная статистика за {0} год ({1})'.format(y,v))
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        cols=data[y]['degurs']  # ЗАГЛУШКА : список дежурных
        
        self.t=Treeview(w,columns=cols)
        self.t.column('#0',width=120)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=65,anchor='center')
        self.t.tag_configure('табель',background='green')
        self.t.tag_configure('ош',background='red')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)
        r=self.t.insert('','end',text='рабочих')
        w=self.t.insert('','end',text='отработано')
        e=self.t.insert('','end',text='дополнительные')
        n=self.t.insert('','end',text='ночные')
        h=self.t.insert('','end',text='праздничные')
        x=self.t.insert('','end',text='xxx')
        rz_root=self.t.insert('','end',text='резерв')
        
        rez=dict()
        wwY=[]
        rrY=[]
        eeY=[]
        xxY=[]
        nnY=[]
        hhY=[]
        rzY=[]
        for mm in [1,2,3,4]:
            mmm=[str((mm-1)*3+x).zfill(2) for x in [1,2,3]]
            mmm=[x for x in mmm if x in data[y]]
            tag=''
            
            k=['табель' in data[y][m]['degur'] for m in mmm]
            #print(k)
            if v=='авто':
                if k==[True, True, True]:
                    vv='табель'
                    tag=vv
                else:
                    vv='план'
            elif v=='табель':
                if k!=[True, True, True]:
                    vv='план'
                    tag='ош'
                else:
                    vv=v
                    tag=vv
            else:
                vv=v
            
            ww=[]
            rr=[]
            ee=[]
            xx=[]
            nn=[]
            hh=[]
            rz=[]
            for m in mmm:
                d=data[y][m]
                for j in cols:
                    s=d['degur'][vv].get(j,'*ООООООООООООООООООООООООООООООО*')
                    rez[j]=analyse2(s,d)
                NUL=(0,0,0,0,0,0,0)
                ww.append([rez.get(j,NUL)[0] for j in cols])
                ee.append([rez.get(j,NUL)[0]-rez.get(j,NUL)[3] + \
                        rez.get(j,NUL)[4] for j in cols])
                xx.append([rez.get(j,NUL)[0]-rez.get(j,NUL)[3] for j in cols])
                rr.append([rez.get(j,NUL)[3]-rez.get(j,NUL)[4] for j in cols])
                nn.append([rez.get(j,NUL)[1] for j in cols])
                hh.append([rez.get(j,NUL)[2] for j in cols])
                rz.append([rez.get(j,NUL)[5] for j in cols])
            ww=[sum(x) for x in zip(*ww)]
            rr=[sum(x) for x in zip(*rr)]
            ee=[sum(x) for x in zip(*ee)]
            xx=[sum(x) for x in zip(*xx)]
            nn=[sum(x) for x in zip(*nn)]
            hh=[sum(x) for x in zip(*hh)]
            rz=[sum(x) for x in zip(*rz)]
            wwY.append(ww)
            rrY.append(rr)
            eeY.append(ee)
            xxY.append(xx)
            nnY.append(nn)
            hhY.append(hh)
            rzY.append(rz)
            self.t.insert(w,'end',text=mm,values=ww,tag=tag)
            self.t.insert(r,'end',text=mm,values=rr,tag=tag)
            self.t.insert(n,'end',text=mm,values=nn,tag=tag)
            self.t.insert(h,'end',text=mm,values=hh,tag=tag)
            self.t.insert(e,'end',text=mm,values=ee,tag=tag)
            self.t.insert(x,'end',text=mm,values=xx,tag=tag)
            self.t.insert(rz_root,'end',text=mm,values=rz,tag=tag)
        wwY=[sum(x) for x in zip(*wwY)]
        rrY=[sum(x) for x in zip(*rrY)]
        eeY=[sum(x) for x in zip(*eeY)]
        xxY=[sum(x) for x in zip(*xxY)]
        nnY=[sum(x) for x in zip(*nnY)]
        hhY=[sum(x) for x in zip(*hhY)]
        rzY=[sum(x) for x in zip(*rzY)]
        self.t.insert(w,'end',text='итого',values=wwY,tag='Y')
        self.t.insert(r,'end',text='итого',values=rrY,tag='Y')
        self.t.insert(n,'end',text='итого',values=nnY,tag='Y')
        self.t.insert(h,'end',text='итого',values=hhY,tag='Y')
        self.t.insert(e,'end',text='итого',values=eeY,tag='Y')
        self.t.insert(x,'end',text='итого',values=xxY,tag='Y')
        self.t.insert(rz_root,'end',text='итого',values=rzY,tag='Y')
Ejemplo n.º 48
0
class Gui(Interface):
    """The GUI interface uses the tkinter module to generate
    a window using tk
    """

    TREE_COLUMNS = ("Number of probes : {nProbes}", "Probe address", "Status")
    RESULT_DIPLAY_HEIGHT = 10

    def __init__(self, ip):
        Interface.__init__(self, ip)
        self.commandHistory = []
        self.mainWin = Tk()
        self.command = StringVar(self.mainWin)
        self.status = StringVar(self.mainWin, value="Waiting for command ...")
        self.text = StringVar(self.mainWin, value="Enter a command :")
        self.result = None
        self.probesDisplay = None
        self.mainWin.title("Commander for probe with ip : " + ip)
        self.isRunning = True
        self.mainWin.protocol("WM_DELETE_WINDOW", self.quit)

        # define the threads
        self.thProbe = Thread(target=self.updateProbes, name="Probe updater", daemon=True)
        self.thResults = Thread(target=self.updateResults, name="Results Updater", daemon=True)

    def start(self):
        """Starts (opens) the commander window"""
        self.mainWin.geometry("800x600")
        txtText = Label(self.mainWin, textvariable=self.text)
        txtText.grid(row=0, column=0, sticky=W)

        txtInput = Entry(self.mainWin, textvariable=self.command, width=30)
        txtInput.grid(row=0, column=1, sticky=E + W)
        txtInput.bind("<Return>", self.doCommand)
        txtInput.bind("<Up>", self.recallCommand)

        button = Button(self.mainWin, text="Refresh", fg="blue", command=self.triggerFetchProbes)
        button.grid(row=1, column=0, sticky=N + S + E + W)

        txtStatus = Label(self.mainWin, textvariable=self.status, wraplength=600, justify=CENTER)
        txtStatus.grid(row=1, column=1, sticky=N + S + E + W)

        self.probesDisplay = Treeview(self.mainWin, columns=self.TREE_COLUMNS, show="headings")
        self.probesDisplay.grid(row=2, columnspan=2, sticky=N + S + E + W)
        for i in range(0, len(self.TREE_COLUMNS)):
            self.updateHeading(i, nProbes=0)

        self.result = Text(self.mainWin, textvariable=self.result, height=self.RESULT_DIPLAY_HEIGHT, wrap=WORD)
        self.result.configure(state=DISABLED)
        self.result.grid(row=3, columnspan=2, sticky=N + S + E + W)
        self.addResult("Awaiting results .... ")

        self.mainWin.grid_rowconfigure(2, weight=1)
        self.mainWin.grid_columnconfigure(1, weight=1)

        self.probeFetcherScheduler()
        self.thProbe.start()

        self.resultFetcherScheduler()
        self.thResults.start()

        self.logger.info("Commander : Starting main window")

        self.mainWin.mainloop()

        self.logger.debug("Commander : mainloop over")

    def recallCommand(self, event):
        """Function to rewrite previous command in box"""
        if len(self.commandHistory) != 0:
            self.command.set(self.commandHistory[-1])
        return "break"

    def doCommand(self, event):
        """Executes user command"""
        self.commandHistory.append(self.command.get())
        self.logger.info("Commander : executing command")
        cmd = super().doCommand(self.command.get())
        # cmd.join()
        self.command.set("")

    def updateStatus(self, status):
        """Update status of the probe in status label
        :param status: new status"""
        self.status.set(status)
        self.mainWin.update_idletasks()

    def addResult(self, result):
        """Add (prepend) a result in the result test area
        :param result: the result to add
        """
        self.result.configure(state=NORMAL)
        self.result.insert("1.0", result + "\n")
        self.result.configure(state=DISABLED)

    def setResult(self, result):
        """Put this result in the result area
        :param result: result to put
        """
        self.result.configure(state=NORMAL)
        self.result.set(result)
        self.result.configure(state=DISABLED)

    def updateProbes(self):
        """Update the list of probes in the Treeview"""
        while self.isRunning:
            try:
                probes = self.probesToItems(self.fetchProbes())
                self.probesDisplay.set_children("")
                self.updateHeading(0, nProbes=len(probes))
                for item in probes:
                    self.probesDisplay.insert("", "end", values=item)
                #             self.probesDisplay.set_children('', probes)
            except ProbeConnectionFailed:
                self.updateStatus("Cannot get list of probes")
                self.logger.error("Error while getting list of probes : connection failed", exc_info=1)
            finally:
                self.doFetchProbes.wait()

    def updateHeading(self, index, **kw):
        self.probesDisplay.heading(index, anchor=W, text=self.TREE_COLUMNS[index].format(**kw))

    @staticmethod
    def probesToItems(probes):
        """Transform probe object into lists for display
        :param probes: list of probes to transform
        """
        return [(str(probe.getId()), probe.getIp(), probe.getStatus()) for probe in probes]

    def updateResults(self):
        """Update the results is the box"""
        while self.isRunning:
            try:
                result = self.fetchResults()
                self.addResult(result)
            except ProbeConnectionFailed:
                self.updateStatus("Cannot fetch results")
                self.logger.error("Cannot fetch results : connection to probe failed", exc_info=1)
            finally:
                self.doFetchResults.wait()

    def quit(self):
        """Exit and close the commander window"""
        self.logger.info("Commander : exiting commander")
        self.isRunning = False
        self.triggerFetchProbes()
        self.thProbe.join()
        super().quit()
        # no join because answer is blocking...
        #         self.thResults.join()
        self.mainWin.quit()
Ejemplo n.º 49
-1
class DialogPluginManager(Toplevel):
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modelClassesChanged = False
        self.disclosureSystemTypesChanged = False
        self.hostSystemFeaturesChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules",)
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleImportsHdr = Label(moduleInfoFrame, text=_("imports:"), state=DISABLED)
        self.moduleImportsHdr.grid(row=7, column=0, sticky=W)
        self.moduleImportsLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleImportsLabel.grid(row=7, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=8, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=8, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=8, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        enableDisableFrame = Frame(frame)
        enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
        enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
        ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240)
        disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
        ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240)
        enableAllButton.grid(row=1, column=1)
        disableAllButton.grid(row=1, column=2)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeViews(self):
        self.selectedModule = None

        # clear previous treeview entries
        for previousNode in self.modulesView.get_children(""): 
            self.modulesView.delete(previousNode)
            
        def loadSubtree(parentNode, moduleItems):
            for moduleItem in sorted(moduleItems, key=lambda item: item[0]):
                moduleInfo = moduleItem[1]
                if parentNode or not moduleInfo.get("isImported"):
                    nodeName = moduleItem[0]
                    if parentNode:
                        nodeName = parentNode + GROUPSEP + nodeName
                    name = moduleInfo.get("name", nodeName)
                    node = self.modulesView.insert(parentNode, "end", nodeName, text=name)
                    self.modulesView.set(node, "author", moduleInfo.get("author"))
                    self.modulesView.set(node, "ver", moduleInfo.get("version"))
                    self.modulesView.set(node, "status", moduleInfo.get("status"))
                    self.modulesView.set(node, "date", moduleInfo.get("fileDate"))
                    if name in self.modulesWithNewerFileDates:
                        self.modulesView.set(node, "update", _("available"))
                    self.modulesView.set(node, "descr", moduleInfo.get("description"))
                    self.modulesView.set(node, "license", moduleInfo.get("license"))
                    if moduleInfo.get("imports"):
                        loadSubtree(node, [(importModuleInfo["name"],importModuleInfo)
                                           for importModuleInfo in moduleInfo["imports"]])
            
        loadSubtree("", self.pluginConfig.get("modules", {}).items())
        
        # clear previous treeview entries
        for previousNode in self.classesView.get_children(""): 
            self.classesView.delete(previousNode)

        for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())):
            className, moduleList = classItem
            node = self.classesView.insert("", "end", className, text=className)
            self.classesView.set(node, "modules", ', '.join(moduleList))
            
        self.moduleSelect()  # clear out prior selection

    def ok(self, event=None):
        if self.pluginConfigChanged:
            PluginManager.pluginConfig = self.pluginConfig
            PluginManager.pluginConfigChanged = True
            PluginManager.reset()  # force reloading of modules
        if self.uiClassMethodsChanged or self.modelClassesChanged or self.disclosureSystemTypesChanged or self.hostSystemFeaturesChanged:  # may require reloading UI
            affectedItems = ""
            if self.uiClassMethodsChanged:
                affectedItems += _("menus of the user interface")
            if self.modelClassesChanged:
                if affectedItems:
                    affectedItems += _(" and ")
                affectedItems += _("model objects of the processor")
            if self.disclosureSystemTypesChanged:
                if affectedItems:
                    affectedItems += _(" and ")
                affectedItems += _("disclosure system types")
            if self.hostSystemFeaturesChanged:
                if affectedItems:
                    affectedItems += _(" and ")
                affectedItems += _("host system features")
            if messagebox.askyesno(_("User interface plug-in change"),
                                   _("A change in plug-in class methods may have affected {0}.  " 
                                     "Please restart Arelle to due to these changes.  \n\n"
                                     "Should Arelle restart itself now "
                                     "(if there are any unsaved changes they would be lost!)?"
                                     ).format(affectedItems),
                                   parent=self):
                self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True]))
        self.close()
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
                
    def moduleSelect(self, *args):
        node = (self.modulesView.selection() or (None,))[0]
        if node:
            node = node.rpartition(GROUPSEP)[2] # drop leading path names for module name
        moduleInfo = self.pluginConfig.get("modules", {}).get(node)
        if moduleInfo:
            self.selectedModule = node
            name = moduleInfo["name"]
            self.moduleNameLabel.config(text=name)
            self.moduleAuthorHdr.config(state=ACTIVE)
            self.moduleAuthorLabel.config(text=moduleInfo["author"])
            self.moduleDescrHdr.config(state=ACTIVE)
            self.moduleDescrLabel.config(text=moduleInfo["description"])
            self.moduleClassesHdr.config(state=ACTIVE)
            self.moduleClassesLabel.config(text=', '.join(moduleInfo["classMethods"]))
            self.moduleUrlHdr.config(state=ACTIVE)
            self.moduleUrlLabel.config(text=moduleInfo["moduleURL"])
            self.moduleDateHdr.config(state=ACTIVE)
            self.moduleDateLabel.config(text=moduleInfo["fileDate"] + " " +
                    (_("(an update is available)") if name in self.modulesWithNewerFileDates else ""))
            self.moduleLicenseHdr.config(state=ACTIVE)
            self.moduleLicenseLabel.config(text=moduleInfo["license"])
            if moduleInfo.get("imports"):
                self.moduleImportsHdr.config(state=ACTIVE)
                _text = ", ".join(mi["name"] for mi in moduleInfo["imports"][:3])
                if len(moduleInfo["imports"]) >= 3:
                    _text += ", ..."
                self.moduleImportsLabel.config(text=_text)
            _buttonState = DISABLED if moduleInfo.get("isImported") else ACTIVE
            self.moduleEnableButton.config(state=_buttonState,
                                           text={"enabled":self.DISABLE,
                                                 "disabled":self.ENABLE}[moduleInfo["status"]])
            self.moduleReloadButton.config(state=_buttonState)
            self.moduleRemoveButton.config(state=_buttonState)
        else:
            self.selectedModule = None
            self.moduleNameLabel.config(text="")
            self.moduleAuthorHdr.config(state=DISABLED)
            self.moduleAuthorLabel.config(text="")
            self.moduleDescrHdr.config(state=DISABLED)
            self.moduleDescrLabel.config(text="")
            self.moduleClassesHdr.config(state=DISABLED)
            self.moduleClassesLabel.config(text="")
            self.moduleUrlHdr.config(state=DISABLED)
            self.moduleUrlLabel.config(text="")
            self.moduleDateHdr.config(state=DISABLED)
            self.moduleDateLabel.config(text="")
            self.moduleLicenseHdr.config(state=DISABLED)
            self.moduleLicenseLabel.config(text="")
            self.moduleImportsHdr.config(state=DISABLED)
            self.moduleImportsLabel.config(text="")
            self.moduleEnableButton.config(state=DISABLED, text=self.ENABLE)
            self.moduleReloadButton.config(state=DISABLED)
            self.moduleRemoveButton.config(state=DISABLED)
        
    def findLocally(self):
        initialdir = self.cntlr.pluginDir # default plugin directory
        if not self.cntlr.isMac: # can't navigate within app easily, always start in default directory
            initialdir = self.cntlr.config.setdefault("pluginOpenDir", initialdir)
        filename = self.cntlr.uiFileDialog("open",
                                           parent=self,
                                           title=_("Choose plug-in module file"),
                                           initialdir=initialdir,
                                           filetypes=[(_("Python files"), "*.py")],
                                           defaultextension=".py")
        if filename:
            # check if a package is selected (any file in a directory containing an __init__.py
            #if (os.path.basename(filename) == "__init__.py" and os.path.isdir(os.path.dirname(filename)) and
            #    os.path.isfile(filename)):
            #    filename = os.path.dirname(filename) # refer to the package instead
            self.cntlr.config["pluginOpenDir"] = os.path.dirname(filename)
            moduleInfo = PluginManager.moduleModuleInfo(filename)
            self.loadFoundModuleInfo(moduleInfo, filename)
                

    def findOnWeb(self):
        url = DialogURL.askURL(self)
        if url:  # url is the in-cache or local file
            moduleInfo = PluginManager.moduleModuleInfo(url)
            self.cntlr.showStatus("") # clear web loading status
            self.loadFoundModuleInfo(moduleInfo, url)
                
    def loadFoundModuleInfo(self, moduleInfo, url):
        if moduleInfo and moduleInfo.get("name"):
            self.addPluginConfigModuleInfo(moduleInfo)
            self.loadTreeViews()
        else:
            messagebox.showwarning(_("Module is not itself a plug-in or in a directory with package __init__.py plug-in.  "),
                                   _("File does not itself contain a python program with an appropriate __pluginInfo__ declaration: \n\n{0}")
                                   .format(url),
                                   parent=self)
        
    def checkIfImported(self, moduleInfo):
        if moduleInfo.get("isImported"):
            messagebox.showwarning(_("Plug-in is imported by a parent plug-in.  "),
                                   _("Plug-in has a parent, please request operation on the parent: \n\n{0}")
                                   .format(moduleInfo.get("name")),
                                   parent=self)
            return True
        return False
    
    def removePluginConfigModuleInfo(self, name):
        moduleInfo = self.pluginConfig["modules"].get(name)
        if moduleInfo:
            if self.checkIfImported(moduleInfo):
                return;
            def _removePluginConfigModuleInfo(moduleInfo):
                _name = moduleInfo.get("name")
                if _name:
                    for classMethod in moduleInfo["classMethods"]:
                        classMethods = self.pluginConfig["classes"].get(classMethod)
                        if classMethods and _name in classMethods:
                            classMethods.remove(_name)
                            if not classMethods: # list has become unused
                                del self.pluginConfig["classes"][classMethod] # remove class
                            if classMethod.startswith("CntlrWinMain.Menu"):
                                self.uiClassMethodsChanged = True  # may require reloading UI
                            elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses":
                                self.modelClassesChanged = True # model object factor classes changed
                            elif classMethod == "DisclosureSystem.Types":
                                self.disclosureSystemTypesChanged = True # disclosure system types changed
                            elif classMethod.startswith("Proxy."):
                                self.hostSystemFeaturesChanged = True # system features (e.g., proxy) changed
                    for importModuleInfo in moduleInfo.get("imports", EMPTYLIST):
                        _removePluginConfigModuleInfo(importModuleInfo)
                    self.pluginConfig["modules"].pop(_name, None)
            _removePluginConfigModuleInfo(moduleInfo)
            self.pluginConfigChanged = True

    def addPluginConfigModuleInfo(self, moduleInfo):
        if self.checkIfImported(moduleInfo):
            return;
        name = moduleInfo.get("name")
        self.removePluginConfigModuleInfo(name)  # remove any prior entry for this module
        def _addPlugin(moduleInfo):
            _name = moduleInfo.get("name")
            if _name:
                self.modulesWithNewerFileDates.discard(_name) # no longer has an update available
                self.pluginConfig["modules"][_name] = moduleInfo
                # add classes
                for classMethod in moduleInfo["classMethods"]:
                    classMethods = self.pluginConfig["classes"].setdefault(classMethod, [])
                    if name not in classMethods:
                        classMethods.append(_name)
                    if classMethod.startswith("CntlrWinMain.Menu"):
                        self.uiClassMethodsChanged = True  # may require reloading UI
                    elif classMethod == "ModelObjectFactory.ElementSubstitutionClasses":
                        self.modelClassesChanged = True # model object factor classes changed
                    elif classMethod == "DisclosureSystem.Types":
                        self.disclosureSystemTypesChanged = True # disclosure system types changed
                    elif classMethod.startswith("Proxy."):
                        self.hostSystemFeaturesChanged = True # system features (e.g., proxy) changed
            for importModuleInfo in moduleInfo.get("imports", EMPTYLIST):
                _addPlugin(importModuleInfo)
        _addPlugin(moduleInfo)
        self.pluginConfigChanged = True

    def moduleEnable(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            moduleInfo = self.pluginConfig["modules"][self.selectedModule]
            if self.checkIfImported(moduleInfo):
                return;
            def _moduleEnable(moduleInfo):
                if self.moduleEnableButton['text'] == self.ENABLE:
                    moduleInfo["status"] = "enabled"
                elif self.moduleEnableButton['text'] == self.DISABLE:
                    moduleInfo["status"] = "disabled"
                for importModuleInfo in moduleInfo.get("imports", EMPTYLIST):
                    _moduleEnable(importModuleInfo)
            _moduleEnable(moduleInfo)
            if self.moduleEnableButton['text'] == self.ENABLE:
                self.moduleEnableButton['text'] = self.DISABLE
            elif self.moduleEnableButton['text'] == self.DISABLE:
                self.moduleEnableButton['text'] = self.ENABLE
            self.pluginConfigChanged = True
            self.loadTreeViews()
            
    def moduleReload(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            url = self.pluginConfig["modules"][self.selectedModule].get("moduleURL")
            if url:
                moduleInfo = PluginManager.moduleModuleInfo(url, reload=True)
                if moduleInfo:
                    if self.checkIfImported(moduleInfo):
                        return;
                    self.addPluginConfigModuleInfo(moduleInfo)
                    self.loadTreeViews()
                    self.cntlr.showStatus(_("{0} reloaded").format(moduleInfo["name"]), clearAfter=5000)
                else:
                    messagebox.showwarning(_("Module error"),
                                           _("File or module cannot be reloaded: \n\n{0}")
                                           .format(url),
                                           parent=self)

    def moduleRemove(self):
        if self.selectedModule in self.pluginConfig["modules"]:
            self.removePluginConfigModuleInfo(self.selectedModule)
            self.pluginConfigChanged = True
            self.loadTreeViews()
                    
    def enableAll(self):
        self.enableDisableAll(True)
                    
    def disableAll(self):
        self.enableDisableAll(False)
                    
    def enableDisableAll(self, doEnable):
        for module in self.pluginConfig["modules"]:
            if not module.get("isImported"):
                moduleInfo = self.pluginConfig["modules"][module]
                def _enableDisableAll(moduleInfo):
                    if doEnable:
                        moduleInfo["status"] = "enabled"
                    else:
                        moduleInfo["status"] = "disabled"
                    for importModuleInfo in moduleInfo.get("imports", EMPTYLIST):
                        _enableDisableAll(importModuleInfo)
                _enableDisableAll(moduleInfo)
                if doEnable:
                    self.moduleEnableButton['text'] = self.DISABLE
                else:
                    self.moduleEnableButton['text'] = self.ENABLE
        self.pluginConfigChanged = True
        self.loadTreeViews()