def CORE(S,M,f,port="z11",RS=0,RL=oo): Bode(fraction(f)[0], fraction(f)[1],port,fraction(f)[0],fraction(f)[1]) if S==0: caer1(f,port=port,RS=RS,RL=RL) elif S==M: caer2(f,port=port,RS=RS,RL=RL) else: bias={"type":"w","label":"unkw","dirrection":"right","parallel":False} print("solution one for",f) Append("solution one for "+str(f)) s1=caer1(f,repeat=abs(S-M)) s2=caer2(s1[2],gener=s1[1],repeat=S) s1[0].append(bias) for i in s2[0]: s1[0].append(i) #draw(s1[0],port,RS,RL) Append(40*"- ") ans1=s1[0] print("\n","solution two for",f) Append("solution two for "+str(f)) s2=caer2(f,repeat=S) s1=caer1(s2[2],gener=s2[1],repeat=abs(S-M)) s2[0].append(bias) for i in s1[0]: s2[0].append(i) Append("",finish=True) #draw(s2[0],port=port,rs=RS,rl=RL) window =ThemedTk(theme="adapta") window.title('Please choose to plot') window.rowconfigure([0,1], weight=1) window.columnconfigure([0], weight=1) label = ttk.Label(window,text='For any solution you can draw a schematic',anchor=tk.CENTER) label.grid(row=0,column=0,sticky=tk.N+tk.S+tk.E+tk.W) card_frame = ttk.Frame(window) card_frame.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W) card_frame.rowconfigure([0], weight=1) card_frame.columnconfigure([0,1], weight=1) solution1 = ttk.Button(card_frame,text="plot solution one",width=15, command=lambda: draw(ans1,port,RS,RL)) solution1.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W) solution2 = ttk.Button(card_frame,text="plot solution two",width=15, command=lambda: draw(s2[0],port,RS,RL)) solution2.grid(row=0, column=1, sticky=tk.N+tk.S+tk.E+tk.W) window.resizable(width=False, height=False) window.deiconify() window.mainloop()
class GUI: """This handles the GUI for ESMB""" def __init__(self): logging.debug("\tBuilding GUI...") # Build the application window self.gui = ThemedTk(theme="plastik") self.gui.title("ESMissionBuilder") self.gui.configure(bg="orange") # enable window resizing self.gui.columnconfigure(2, weight=1) self.gui.rowconfigure(0, weight=1) # set disabled styles self.disabledEntryStyle = ttk.Style() self.disabledEntryStyle.configure('D.TEntry', background='#D3D3D3') self.disabledComboboxStyle = ttk.Style() self.disabledComboboxStyle.configure('D.TCombobox', background='#D3D3D3') # Declare the frames self.option_pane = editor.OptionPane(self.gui) self.option_pane.grid(row=0, column=0, sticky="ns") self.center_pane = editor.MissionEditorPane(self.gui) self.center_pane.grid(row=0, column=1, sticky="ns") self.item_text_pane = editor.ItemTextPane(self.gui) self.item_text_pane.grid(row=0, column=2, sticky="nsew") config.gui = self self.gui.mainloop() #end init def update_option_pane(self): self.option_pane.update_pane() #end update_option_pane def update_center_pane(self): self.center_pane.update_pane() #end update_center_pane def update_item_text_pane(self): self.item_text_pane.update_pane()
class GUI(object): """This handles the GUI for ESMB""" def __init__(self, debug_mode): logging.debug("\tBuilding GUI...") self.debugging = debug_mode #TODO: Look into changing this to not need the dictionary self.missionList = [] self.missionNameToObjectDict = {} self.missionNames = [] if self.debugging: self.missionList = [Mission("Debugging", default=True)] self.missionNameToObjectDict = { self.missionList[0].missionName: self.missionList[0] } self.missionNames.append(self.missionList[0].missionName) #end if # Build the application window self.gui = ThemedTk(theme="plastik") self.gui.title("ESMissionBuilder") self.gui.configure(bg="orange") # enable window resizing self.gui.columnconfigure(0, weight=1) self.gui.rowconfigure(0, weight=1) self.disabledEntryStyle = ttk.Style() self.disabledEntryStyle.configure('D.TEntry', background='#D3D3D3') self.disabledComboboxStyle = ttk.Style() self.disabledComboboxStyle.configure('D.TCombobox', background='#D3D3D3') self.ofWidth = None self.cfWidth = None self.mfWidth = None # Declare the frames self.optionFrame = None self.centerFrame = None self.missionFrame = None # declare optionFrame components self.missionComboBox = None self.activeMission = None # declare centerFrame components self.displayNameComponent = None self.descriptionComponent = None self.blockedComponent = None self.deadlineComponent = None self.cargoComponent = None self.passengersComponent = None self.illegalComponent = None self.stealthComponent = None self.invisibleComponent = None self.priorityLevelComponent = None self.whereShownComponent = None self.repeatComponent = None self.clearanceComponent = None self.infiltratingComponent = None self.waypointComponent = None self.stopoverComponent = None self.sourceComponent = None self.destinationComponent = None # Triggers self.triggersFrame = None self.activeTrigger = None # declare missionFrame components self.missionTextBox = None # Build the different parts of the main window #self.buildMenu(self.gui) self.build_main_view(self.gui) self.activeMission = None if self.debugging: self.activeMission = self.missionList[0] # Run the program self.gui.mainloop() #end init # This may be used later, after shortcuts are introduced ''' def buildMenu(self, window): #TODO: IMPLEMENT THIS # creating a menu instance menu = Menu() window.config(menu=menu) # create the file object file = Menu(menu) edit = Menu(menu) # adds a command to the menu option, names it, and set the command to run file.add_command(label="New", command=lambda: newFile(self)) file.add_command(label="Open", command=lambda: open_file(self)) file.add_command(label="Save", command=lambda: save_file(self)) file.add_command(label="Exit", command=exit) # added "File" to our menu menu.add_cascade(label="File", menu=file) # adds a command to the menu option, names it, and set the command to run edit.add_command(label="Undo", command=lambda: undoAction(self)) # added "Edit" to our menu menu.add_cascade(label="Edit", menu=edit) #end buildMenu ''' def build_main_view(self, window): """ Instantiate the three major frames, and call methods to build the respective GUI areas :param window: The ThemedTK object that the rest of the GUI is built off of """ option_frame = ttk.Frame(window) center_frame = ScrollingCenterFrame(self, window) mission_frame = ttk.Frame(window) self.optionFrame = option_frame self.centerFrame = center_frame self.missionFrame = mission_frame # set up each of the frames self.build_option_frame() self.build_center_frame() self.build_mission_frame() logging.debug("\tGUI built") #end build_main_view ### BUILDING FRAMES ### def build_option_frame(self): """Add widgets to the optionFrame""" logging.debug("\tBuilding optionFrame...") self.optionFrame.grid(row=0, column=0, sticky="ns") of_title = ttk.Label(self.optionFrame, text="Mission") of_title.pack() # declare the combobox here, fill with missionNames self.missionComboBox = ttk.Combobox(self.optionFrame, state="readonly", values=self.missionNames) self.missionComboBox.bind("<<ComboboxSelected>>", self.mission_selected) self.missionComboBox.pack() if self.debugging: self.missionComboBox.current(0) # add function buttons new_mission_button = ttk.Button(self.optionFrame, text="New Mission", command=lambda: new_mission(self)) new_mission_button.pack(fill='x') save_mission_file_button = ttk.Button(self.optionFrame, text="Save Mission File", command=lambda: save_file(self)) save_mission_file_button.pack(fill='x') open_mission_file_button = ttk.Button(self.optionFrame, text="Open Mission File", command=lambda: open_file(self)) open_mission_file_button.pack(fill='x') compile_mission_file_button = ttk.Button( self.optionFrame, text="Compile Mission", command=lambda: compile_mission(self)) compile_mission_file_button.pack(fill='x') help_button = ttk.Button(self.optionFrame, text="Help", command=help_user) help_button.pack(fill='x') #TODO: Add functionality to change missionName and delete mission. Also, update button grouping to reflect #end build_option_frame def build_center_frame(self): """Add widgets to the centerFrame""" logging.debug("\tBuilding centerFrame...") self.centerFrame.grid(row=0, column=1, sticky="ns") cf = self.centerFrame.inner # Display name self.displayNameComponent = build_component_frame( cf, "Mission Display Name", 1, 0, ["<text>"]) self.displayNameComponent.grid(row=0, column=0, sticky="ew") # Description self.descriptionComponent = build_component_frame( cf, "Description", 1, 0, ["<description>"]) self.descriptionComponent.grid(row=1, column=0, sticky="ew") # isBlocked self.blockedComponent = build_component_frame(cf, "Blocked", 1, 0, ["<message>"]) self.blockedComponent.grid(row=2, column=0, sticky="ew") # Deadline self.deadlineComponent = build_component_frame( cf, "Deadline", 0, 2, ["[<days#>]", "[<multiplier#>]"]) self.deadlineComponent.grid(row=3, column=0, sticky="ew") # Cargo self.cargoComponent = build_component_frame(cf, "Cargo", 2, 2, [ "(random | <name>)", "<number#>", "[<number#>]", "[<probability#>]" ]) self.cargoComponent.grid(row=4, column=0, sticky="ew") # Passengers self.passengersComponent = build_component_frame( cf, "Passengers", 1, 2, ["<number#>", "[<number#>]", "[<probability#>]"]) self.passengersComponent.grid(row=5, column=0, sticky="ew") # Illegal self.illegalComponent = build_component_frame( cf, "Illegal", 1, 1, ["<fine#>", "[<message>]"]) self.illegalComponent.grid(row=6, column=0, sticky="ew") # Stealth self.stealthComponent = build_component_frame(cf, "Stealth", 0, 0, []) self.stealthComponent.grid(row=7, column=0, sticky="ew") # Invisible self.invisibleComponent = build_component_frame( cf, "Invisible", 0, 0, []) self.invisibleComponent.grid(row=8, column=0, sticky="ew") # priorityLevel self.priorityLevelComponent = build_combo_component_frame( cf, "Priority Level", ["Priority", "Minor"]) self.priorityLevelComponent.grid(row=9, column=0, sticky="ew") # whereShown self.whereShownComponent = build_combo_component_frame( cf, "Where Shown", ["Job", "Landing", "Assisting", "Boarding"]) self.whereShownComponent.grid(row=10, column=0, sticky="ew") # Repeat self.repeatComponent = build_component_frame(cf, "Repeat", 0, 1, ["[<times#>]"]) self.repeatComponent.grid(row=11, column=0, sticky="ew") # Clearance self.clearanceComponent = build_component_frame( cf, "Clearance", 0, 1, ["[<message>]"]) self.clearanceComponent.grid(row=12, column=0, sticky="ew") # Infiltrating self.infiltratingComponent = build_component_frame( cf, "Infiltrating", 0, 0, []) self.infiltratingComponent.grid(row=13, column=0, sticky="ew") # Waypoint self.waypointComponent = build_component_frame(cf, "Waypoint", 1, 0, ["[<system>]"]) self.waypointComponent.grid(row=14, column=0, sticky="ew") # Stopover self.stopoverComponent = build_component_frame(cf, "Stopover", 1, 0, ["[<planet>]"]) self.stopoverComponent.grid(row=15, column=0, sticky="ew") # Source self.sourceComponent = build_component_frame(cf, "Source", 1, 0, ["[<planet>]"]) self.sourceComponent.grid(row=16, column=0, sticky="ew") # Destination self.destinationComponent = build_component_frame( cf, "Destination", 1, 0, ["[<planet>]"]) self.destinationComponent.grid(row=17, column=0, sticky="ew") # triggers self.triggersFrame = AggregatedTriggerFrame(self, cf) self.triggersFrame.grid(row=18, column=0, sticky="ew") # add a blank label to pad the bottom of the frame bl1 = ttk.Label(cf, textvariable=" ") bl1.grid(row=19, column=0, sticky="ew") #end build_center_frame def build_mission_frame(self): """Add widgets to the missionFrame""" logging.debug("\tBuilding missionFrame...") #Display a default mission template on launch self.missionFrame.grid(row=0, column=2, sticky="nsew") mf_title = ttk.Label(self.missionFrame, text="Mission Text") mf_title.pack() # Populate the Text with a mission template self.missionTextBox = Text(self.missionFrame, wrap=WORD, height=50, width=100) self.missionTextBox.pack(expand=1, fill='both') welcome_message = "\n" welcome_message += "\t\t\tWelcome to Endless Sky Mission Builder!\n" welcome_message += "\n\t - Click \"New Mission\" to get started\n" welcome_message += "\n\t - Click \"Save Mission File\" to save all the missions to a text file\n" welcome_message += "\n\t - Click \"Open Mission File\" to open a mission file for editing\n" welcome_message += "\n\t - Click \"Compile Mission\" to save save the current mission\n" welcome_message += "\n\t - Click \"Help\" to be directed to the Mission Creation wiki\n" self.missionTextBox.insert(END, welcome_message) self.missionTextBox.config(state=DISABLED) #end build_mission_frame ### UPDATING FRAMES ### def update_option_frame(self): """Update optionFrame to use the most recent data""" logging.debug("Updating optionFrame...") ### Start updating combobox ml = self.missionList self.missionNames = [] for m in ml: self.missionNames.append(m.missionName) logging.debug("\tNew mission options: %s" % str(self.missionNames)) # update options in the combobox self.missionComboBox['values'] = self.missionNames self.missionComboBox.current(0) ### Finish updating combobox # update the other two frames to reflect the current mission self.update_center_frame() self.update_mission_frame() #end update_option_frame def update_center_frame(self): """Update missionFrame to use the most recent data""" logging.debug("Updating centerFrame...") components = self.activeMission.components # missionDisplayName self.displayNameComponent.reset() if components.missionDisplayName is not None: self.displayNameComponent.set(0, 0, components.missionDisplayName) # description self.descriptionComponent.reset() if components.description is not None: description = components.description self.descriptionComponent.set(0, 0, description) #end if # blocked self.blockedComponent.reset() if components.blocked is not None: self.blockedComponent.set(0, 0, components.blocked) # deadline self.deadlineComponent.reset() if components.deadline.isDeadline is True: self.deadlineComponent.set(0, None, "isDeadlineCheckbutton") if components.deadline.deadline[0] is not None: self.deadlineComponent.set(1, 0, components.deadline.deadline[0]) if components.deadline.deadline[1] is not None: self.deadlineComponent.set(2, 1, components.deadline.deadline[1]) #end if #end if # cargo self.cargoComponent.reset() if components.cargo.isCargo is True: self.cargoComponent.set(0, 0, components.cargo.cargo[0]) self.cargoComponent.set(0, 1, components.cargo.cargo[1]) if components.cargo.cargo[2] is not None: self.cargoComponent.set(1, 2, components.cargo.cargo[2]) if components.cargo.cargo[2] is not None: self.cargoComponent.set(2, 3, components.cargo.cargo[3]) #end if #end if # passengers self.passengersComponent.reset() if components.passengers.isPassengers is True: self.passengersComponent.set(0, 0, components.passengers.passengers[0]) if components.passengers.passengers[1] is not None: self.passengersComponent.set( 1, 1, components.passengers.passengers[1]) if components.passengers.passengers[2] is not None: self.passengersComponent.set( 2, 2, components.passengers.passengers[2]) #end if #end if # illegal self.illegalComponent.reset() if components.illegal.isIllegal is True: self.illegalComponent.set(0, 0, components.illegal.illegal[0]) if components.illegal.illegal[1] is not None: self.illegalComponent.set(1, 1, components.illegal.illegal[1]) # end if # end if # stealth self.stealthComponent.reset() if components.isStealth is True: self.stealthComponent.set(0, None, "stealthCheckbutton") # invisible self.invisibleComponent.reset() if components.isInvisible is True: self.invisibleComponent.set(0, None, "isInvisibleCheckbutton") # priorityLevel self.priorityLevelComponent.reset() if components.priorityLevel is not None: self.priorityLevelComponent.set(components.priorityLevel) # whereShown self.whereShownComponent.reset() if components.whereShown is not None: self.whereShownComponent.set(components.whereShown) # repeat self.repeatComponent.reset() if components.isRepeat is True: self.repeatComponent.set(0, None, "isRepeatCheckbutton") if components.repeat is not None: self.repeatComponent.set(1, 0, components.repeat) #end if # clearance self.clearanceComponent.reset() if components.clearance.isClearance is True: self.clearanceComponent.set(0, None, "isClearanceCheckbutton") if components.clearance.clearance is not None: self.clearanceComponent.set(1, 0, components.clearance.clearance) #end if # infiltrating self.infiltratingComponent.reset() if components.isInfiltrating is True: self.infiltratingComponent.set(0, None, "isInfiltratingCheckbutton") # waypoint self.waypointComponent.reset() if components.waypoint is not None: self.waypointComponent.set(0, 0, components.waypoint) # stopover self.stopoverComponent.reset() if components.stopover.isStopover is True: self.stopoverComponent.set(0, 0, components.stopover.stopover) # source self.sourceComponent.reset() if components.source.isSource is True: self.sourceComponent.set(0, 0, components.source.source) # destination self.destinationComponent.reset() if components.destination.isDestination is True: self.destinationComponent.set(0, 0, components.destination.destination) # Clear out the AggregatedTriggerFrame self.triggersFrame.grid_forget() self.triggersFrame = AggregatedTriggerFrame(self, self.centerFrame.inner) self.triggersFrame.grid(row=18, column=0, sticky="ew") # Triggers if components.triggerList: logging.debug("\tTriggers found") for trigger in components.triggerList: self.triggersFrame.populate_trigger(trigger) #end update_center_frame def update_mission_frame(self): """Update missionFrame to use the most recent data""" logging.debug("Updating missionFrame...") self.missionTextBox.forget() self.missionTextBox = Text(self.missionFrame, height=50, width=100, wrap=WORD) self.missionTextBox.pack() self.missionTextBox.insert( END, self.activeMission.print_mission_lines_to_text()) self.missionTextBox.config(state=DISABLED) #end update_mission_frame ### MISC METHODS ### def mission_selected(self, event=None): """Set activeMission to the combobox option selected by the user""" selected_mission_name = self.missionComboBox.get() logging.debug("Opening mission \"%s\"" % selected_mission_name) self.activeMission = self.missionNameToObjectDict.get( selected_mission_name) self.update_center_frame() self.update_mission_frame()
def main(): root = ThemedTk() root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) makeGUI = MakeGUI(root) root.mainloop()
content.grid(column=0, row=0) subframe.grid(column=0, row=2, columnspan=5, pady=5) imageframe.grid(column=0, row=0, columnspan=3, rowspan=2, padx=5) c1.grid(column=0, row=2, padx=5) c2.grid(column=1, row=2, padx=5) c3.grid(column=2, row=2, padx=5) ok.grid(column=3, row=2, columnspan=2, padx=5) label.grid(column=3, row=0, columnspan=2, padx=15) # pad edges nicely box.grid(column=3, row=1, columnspan=2, padx=15) pic.grid() namelbl.grid(sticky=E) # give weights to the row and column expansions root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) content.columnconfigure(0, weight=1) content.columnconfigure(1, weight=1) content.columnconfigure(2, weight=1) content.columnconfigure(3, weight=1) content.columnconfigure(4, weight=1) content.rowconfigure(0, weight=1) content.rowconfigure(1, weight=1) content.rowconfigure(2, weight=1) subframe.columnconfigure(0, weight=1) subframe.columnconfigure(1, weight=1) subframe.columnconfigure(2, weight=1) subframe.columnconfigure(3, weight=1)
save_config() # only run once, no listener cmd = "python3 /usr/bin/apod_linux.py & disown" array = cmd.split() # non-blocking subprocess subprocess.Popen(array) # NB: don't close window # create the main window (titlebar and frame) # https://ttkthemes.readthedocs.io/en/latest/themes.html main_window = ThemedTk(theme="equilux") main_window.title("APOD_Linux config") main_window.columnconfigure(0, weight=1) main_window.rowconfigure(0, weight=1) main_window.resizable(False, False) # set main womdow's icon icon = PhotoImage( file = "/usr/share/icons/hicolor/128x128/apps/apod_linux_icon.png") main_window.iconphoto(False, icon) # register the validate function with the main window (%S is the user input, # whether typed or pasted) validate_func = (main_window.register(validate), "%S") # set variables/defults # NB: needs to be done after main window creation var_enabled = IntVar()
def main(): print("Scanner App Started...") # UI Updating Method def update_left_header_label(value): """UI Updating Method :param value: value to be set in left header """ if value is None: # if the provided value is none, then update to the default header host_count = DataShare.get_hosts_total() host_count_text = f"({host_count}) Hosts Scanned".format() left_frame_header_label_var.set(host_count_text) else: # else left_frame_header_label_var.set(value) def update_left_header_label_random_waiting_msg(): """Update waiting header randomly""" random_waiting_responses = [ "This may take a while...", "I'm sorry this will be a while...", "Scanning...", "Scanning in Process..." ] update_left_header_label(random.choice(random_waiting_responses)) def reset_left_header_label(): """Update left header with number of hosts scanned""" host_count = DataShare.get_hosts_total() host_count_text = f"({host_count}) Hosts Scanned".format() left_frame_header_label_var.set(host_count_text) def reload_hosts_tableview(): """Update hosts box with scanned hosts""" # hosts_listbox.delete(0, tk.END) sorted_scanned_hosts = None # Sort according to the Host Sort Setting reverse_sort = False if System.Settings.get_host_sort_type() == System.SortType.alphaDESC: reverse_sort = True if DataShare.get_hosts(): sorted_scanned_hosts = sorted(DataShare.get_hosts(), key=lambda x: (x.get_display_name()), reverse=reverse_sort) if sorted_scanned_hosts is None: return # Update hosts to the sorted version to ensure details on select are correct DataShare.set_hosts(sorted_scanned_hosts) reset_left_header_label() data = list( map( lambda host: (host.get_ip(), host.get_display_name(), host.get_vendor()), sorted_scanned_hosts)) # We need to reverse the data shown here because the table view will display the data in the reversed order # this is needed so that clicking the tableview will result in the correct host being selected: Task189 hosts_table_view.reload_data(data[::-1]) def scan_thread_completion(): """Scan given inputs, update associated ui, and save scan data""" scan_start_date = datetime.datetime.now() update_left_header_label("Scan in process...") scan_button.config(state="disabled") waiting_scanner1 = STimer.do_after( update_left_header_label_random_waiting_msg, 15) waiting_scanner2 = STimer.do_after( update_left_header_label_random_waiting_msg, 30) waiting_scanner3 = STimer.do_after( update_left_header_label_random_waiting_msg, 45) ports = f'{port_start_entry_var.get()}-{port_end_entry_var.get()}' hosts = scan_host_entry_var.get() scanner = Scanner(hosts, ports) set_host(scanner.get_scan_details(System.Settings.get_scan_type())) set_cpes_vulns(scanner.get_cpes()) scan_button.config(state="normal") scan_details_view.check_vulnerabilities_button.config(state="normal") scan_end_date = datetime.datetime.now() timedelta = scan_end_date - scan_start_date timedelta.total_seconds() last_row_id = df.DBFunctions.save_scan(scan_start_date, timedelta.total_seconds()) for host in get_hosts(): df.DBFunctions.save_host(host, last_row_id) query = "SELECT * FROM Hosts WHERE ScanID = ?" host_tuple = df.DBFunctions.get_all_where(query, (last_row_id, )) hosts_with_ID = [] for id_host in host_tuple: temp = Host(id_host[0], id_host[1], "Old Host", id_host[5], id_host[3], id_host[4], id_host[6], id_host[2]) hosts_with_ID.append(temp) set_host(hosts_with_ID) ip_list = [*DataShare.get_cpes()] cpe_list = DataShare.get_cpes() for ip in ip_list: for item in hosts_with_ID: if item.get_ip() == ip: cpe_list[item.get_id()] = cpe_list.pop(ip) DataShare.set_cpes(cpe_list) cves_with_host = df.DBFunctions.query_cves(cpe_list) for i in cves_with_host: for j in i: df.DBFunctions.save_cve_by_host(i, j) update_left_header_label(f"Scan finished in {timedelta} seconds") STimer.do_after(reset_left_header_label, 2) waiting_scanner1.cancel() waiting_scanner2.cancel() waiting_scanner3.cancel() def set_host(h): """Set scanned hosts for ui :param h: hosts found """ if h: DataShare.set_hosts(h) reload_hosts_tableview() def get_hosts(): """Get scanned hosts""" return DataShare.get_hosts() def set_cpes_vulns(c): """Set vulnerabilities from cps""" print("Main 172 set_cpes_vulns cpes:\n") print(c) DataShare.set_cpes(c) # Sort according to the Vulnerability Sort Setting reverse_sort = False if System.Settings.get_vuln_sort_type() == System.SortType.alphaDESC: reverse_sort = True sorted_vulns = sorted(df.DBFunctions.query_cves(c), reverse=reverse_sort) print('From Main 184, sorted_vulns: ', sorted_vulns) DataShare.set_vulns(sorted_vulns) # reload ui # Click Handlers def on_scan(): """Click handler for scan btn to start scanner thread""" # MAKE SURE TO VALIDATE INPUT scan_thread = SThread(0, "SCAN_THREAD_1", 5, scan_thread_completion) scan_thread.start() def on_select_scan(id): query = "SELECT * FROM Hosts WHERE ScanID = ?" params = (id, ) data = df.DBFunctions.get_all_where(query, params) test = df.DBFunctions.retrieve_scanID_data(id) print('\n\n\n\nGetting Data\n') print(data) print('\n') print(test) # these need to be set, but not sure if the cpes and vulns are differentiate # by scans like hosts are # todo: set cpes and vulns in DataShare print('\n\n\n\nCPES') #todo this changes depending on if a scan has been run print(DataShare.get_cpes()) print('\n\nVULNS') #todo these are 2.2 cpes... print(DataShare.get_vulns()) print('\n\n\n\n') curr_hosts = [] # for each host scanned for host_raw in data: host_id = host_raw[0] ip = host_raw[1] state = "Old Host" mac = host_raw[2] os_gen = host_raw[3] os_family = host_raw[4] name = host_raw[5] vendor = host_raw[6] curr_hosts.append( Host(host_id, ip, state, name, os_family, os_gen, vendor, mac)) set_host(curr_hosts) def find_exploit(cve): if cve: if exploit_view: exploit_view.update_cve(cve) else: print('No CVE selected') def update_exploit_tab(cve): main_note_book.select(2) exploit_view.cve_var.set(cve) exploit_view.on_search() def on_host_tableview_select(event): """Click handler to update right ui when user clicks on a host in left box""" index = hosts_table_view.get_selected_index() hosts = DataShare.get_hosts() scan_details_view.host_name_entry_var.set( hosts[index].get_display_name()) scan_details_view.mac_address_entry_var.set( hosts[index].get_mac_address()) scan_details_view.port_number_entry_var.set(hosts[index].get_ip()) def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() def update_import(): # Only takes json currently. path = askopenfilename(title='Select Database file to import...', # defaultextension='.db', filetypes=(("database files", "*.db"),("datafeeds", "*.json"),("all files", "*.*"))) path = askopenfilename(title='Select Database file to import...', filetypes=[('Json', '*.json')]) # ntpath for os compatibility with differing separators # head and tail if path ends in backslash head, tail = ntpath.split(path) fname = tail or ntpath.basename(head) if fname.endswith('.json'): # for use to support multiple file types # elif json_fp.endswith(('.json', '.db', '.xml'): df.DBFunctions.import_NVD_JSON(fname) else: tk.messagebox.showerror("Error", "File must be of type: json") # Set up tree columns to display IP and Device Names after a completed scan class TreeColumns(enum.Enum): name = 0 mac_address = 1 @staticmethod def display_name_for_column(col): display_names = { 0: "IP", 1: "Name", } return display_names[col] @staticmethod def all_cases(): cases = [] for col in TreeColumns: cases.append(TreeColumns.display_name_for_column(col.value)) return cases # Setup root ui root = ThemedTk() root.ttkStyle = ThemedStyle() theme = System.Settings.get_theme() root.ttkStyle.set_theme(theme) root.title("AnyScan") root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(1, weight=1) ################# # Setup LeftFrame ################# left_frame = ttk.Frame(root) left_frame.grid(row=0, column=0, sticky="nsew") left_frame.grid_rowconfigure(1, weight=1) left_frame.grid_columnconfigure(1, weight=1) # Setup Left Frame header Label left_frame_header_label_var = tk.StringVar() update_left_header_label(None) left_frame_header_label = ttk.Label( left_frame, textvariable=left_frame_header_label_var) left_frame_header_label.grid(row=0, column=0) # Setup Left Frame Host TableView sections_tuple = TreeColumns.all_cases() data = [] hosts_table_view = TableView(left_frame, 1, sections_tuple, data) hosts_table_view.bind_method('<ButtonRelease-1>', on_host_tableview_select) reload_hosts_tableview() # Setup scan host frame scan_host_frame = ttk.Frame(left_frame) scan_host_frame.grid(row=2, column=0) # Setup scan host label scan_host_label = ttk.Label(scan_host_frame, text="Hosts:") scan_host_label.grid(row=0, column=0) # Setup scan host entry scan_host_entry_var = tk.StringVar() scan_host_entry_var.set("192.168.1.0/28") scan_host_entry = ttk.Entry(scan_host_frame, textvariable=scan_host_entry_var) scan_host_entry.grid(row=0, column=1) # Setup scan port label frame scan_port_label_frame = ttk.Frame(left_frame) scan_port_label_frame.grid(row=3, column=0) # Setup scan port label port_start_label = ttk.Label(scan_port_label_frame, text="Start Port") port_start_label.grid(row=0, column=0, padx=(0, 8)) port_end_label = ttk.Label(scan_port_label_frame, text="End Port") port_end_label.grid(row=0, column=1, padx=(8, 0)) # Setup scan port frame scan_port_frame = ttk.Frame(left_frame) scan_port_frame.grid(row=4, column=0) # Setup scan port entries port_start_entry_var = tk.StringVar() port_start_entry_var.set("21") port_start_entry = ttk.Entry(scan_port_frame, width=4, textvariable=port_start_entry_var) port_start_entry.grid(row=0, column=0, padx=(0, 16)) port_end_entry_var = tk.StringVar() port_end_entry_var.set("30") port_end_entry = ttk.Entry(scan_port_frame, width=4, textvariable=port_end_entry_var) port_end_entry.grid(row=0, column=1, padx=(16, 0)) scan_button_frame = ttk.Frame(left_frame) scan_button_frame.grid(row=5, column=0) # Setup Left frame scan button scan_button = ttk.Button(scan_button_frame, text="Scan", command=on_scan) scan_button.grid(row=0, column=0, pady=(8, 8)) ################# # Setup RightFrame ################# # Setup Notebook for right frame rows = 0 while rows < 50: root.columnconfigure(rows + 1, weight=1) rows += 1 # Setup Root Notebook main_note_book = ttk.Notebook(root) main_note_book.grid(row=0, column=1, columnspan=50, rowspan=49, sticky="NESW") # Setup Scan Details Tab scan_details_view = ScanDetailsView() scan_details_tab = scan_details_view.get_view(main_note_book) main_note_book.add(scan_details_tab, text="Scan Details") # Setup Vulnerabilities Tab vulnerabilities_view = VulnerabilitiesView() vulnerabilities_tab = vulnerabilities_view.get_view(main_note_book) main_note_book.add(vulnerabilities_tab, text="Vulnerabilities") vulnerabilities_view.on_selected_cve = find_exploit vulnerabilities_view.move_to_exploit = update_exploit_tab # Setup Exploits Tab exploit_view = ExploitView() exploit_tab = exploit_view.get_view(main_note_book) main_note_book.add(exploit_tab, text='Exploits') # Setup Scan History Tab scan_history_view = ScanHistoryView() scan_history_tab = scan_history_view.get_view(main_note_book) main_note_book.add(scan_history_tab, text="Scan History") scan_history_view.on_selected_scan_completion = on_select_scan # File Menu Bar menubar = Menu(root) # create menu bar filemenu = Menu(menubar, tearoff=0) # create a menu to add some stuff too # Save Vulnerability in file menu bar savemenu = Menu(menubar, tearoff=0) savemenu.add_command(label="Save Vulnerability", command=VulnPopup.new_popup) filemenu.add_cascade(label='Save', menu=savemenu) # DB import in file menu bar importmenu = Menu(menubar, tearoff=0) importmenu.add_command(label="Database", command=update_import) filemenu.add_cascade(label="Import", menu=importmenu) filemenu.add_separator() # more prettiness # Scan settings in file menu bar settingsmenu = Menu(menubar, tearoff=0) settingsmenu.add_command(label="Scan Settings", command=scan_details_view.on_settings) filemenu.add_cascade(label='Settings', menu=settingsmenu) filemenu.add_separator() # pretty # Helper method to change application themes def change_theme(theme): root.ttkStyle.set_theme(theme) System.Settings.set_theme(theme) # Added the ability for the user to change themes from the cascading file menu themes_menu = Menu(menubar, tearoff=0) themes_menu.add_command(label="Alt", command=lambda: change_theme("alt")) themes_menu.add_command(label="Aqua", command=lambda: change_theme("aqua")) themes_menu.add_command(label="Clam", command=lambda: change_theme("clam")) themes_menu.add_command(label="Classic", command=lambda: change_theme("classic")) themes_menu.add_command(label="Default", command=lambda: change_theme("default")) themes_menu.add_command(label="Equilux", command=lambda: change_theme("equilux")) themes_menu.add_separator() themes_menu.add_command(label="Scidblue", command=lambda: change_theme("scidblue")) themes_menu.add_command(label="Scidgreen", command=lambda: change_theme("scidgreen")) themes_menu.add_command(label="Scidgrey", command=lambda: change_theme("scidgrey")) themes_menu.add_command(label="Scidmint", command=lambda: change_theme("scidmint")) themes_menu.add_command(label="Scidpink", command=lambda: change_theme("scidpink")) themes_menu.add_command(label="Scidpurple", command=lambda: change_theme("scidpurple")) themes_menu.add_command(label="Scidsand", command=lambda: change_theme("scidsand")) filemenu.add_cascade(label='Change Theme', menu=themes_menu) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) editmenu = Menu(menubar, tearoff=0) # create another menu to add some stuff too editmenu.add_command(label="Undo", command=donothing) menubar.add_cascade(label="File", menu=filemenu) # add file to menu bar # On macOS there are some default things added to this menu, but are not added to the same menu # under File. menubar.add_cascade(label='Edit', menu=editmenu) # add edit to menu bar too, for fun # Run the program with UI root.config(menu=menubar) root.geometry("1600x1000") root.minsize(800, 500) # add this to ensure app comes to front on start up root.lift() root.attributes('-topmost', True) root.after_idle(root.attributes, '-topmost', False) # start GUI root.mainloop()
class MainForm(): def __init__(self): """ Inicializa as variaveis usadas e também carrega o form principal """ # Dicionário de ambientes (aba + exame) self.envDict = {} # Dicionário de exames self.examDict = {} # Lista de threads para carregar os exames self.loaderList = [] self.envActive = None self.setForm() self.root.mainloop() def setForm(self): """ Basicamente chama os metodos de construção do form, separado por estrutura (menus, abas, etc) """ self.setRoot() self.setMainFrame() self.setEditMenu() self.setNotebook() self.setTopMenu() def setRoot(self): self.root = ThemedTk(theme="Adapta") self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) self.root.state('zoomed') def setMainFrame(self): self.mainFrame = ttk.Frame(self.root) self.mainFrame.grid(row=0, column=0, sticky=tk.NSEW) self.mainFrame.rowconfigure(1, weight=1) self.mainFrame.columnconfigure(0, weight=1, uniform="mainframe") self.mainFrame.columnconfigure(1, weight=4, uniform="mainframe") self.mainFrame.bind(("<Escape>", self.clearCursor)) def setEditMenu(self): self.drawThickness = tk.DoubleVar(self.root) self.editMenu = ttk.Frame(self.mainFrame) self.editMenu.grid(row=1, column=0, sticky=tk.NSEW) #self.editMenu.columnconfigure(0,weight=1) ttk.Button(self.editMenu, text=btns.RECTANGLE, command=lambda: self.cbRoi(Shape.RECTANGLE)).grid( row=1, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.CIRCLE, command=lambda: self.cbRoi(Shape.CIRCLE)).grid(row=2, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.DRAW, command=lambda: self.cbDraw()).grid(row=3, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.ZOOM_IN, command=lambda: self.cbZoom(True)).grid(row=4, column=0, sticky=tk.NW) ttk.Button(self.editMenu, text=btns.ZOOM_OUT, command=lambda: self.cbZoom(False)).grid(row=5, column=0, sticky=tk.NW) ttk.Scale(self.editMenu, orient=tk.HORIZONTAL, variable=self.drawThickness).grid(row=3, column=1, sticky=tk.NW) def setNotebook(self): self.notebook = ttk.Notebook(self.mainFrame, name=txt.NOTEBOOK) self.notebook.grid(row=1, column=1, sticky=tk.NSEW) self.root.update() self.notebook.bind("<<NotebookTabChanged>>", self.onEnvChange) def setTopMenu(self): #self.menubar = tk.Menu(self.root,tearoff=False) self.ttkMenubar = ttk.Menubutton(self.root) self.menubar = tk.Menu(self.root, tearoff=False) self.ttkMenubar['menu'] = self.menubar self.fileMenu = tk.Menu(self.menubar, tearoff=False) self.menubar.add_cascade(label=lblsTop.FILE, underline=0, menu=self.fileMenu) self.fileMenu.add_command(label=lblsTop.LOADEXAM, underline=0, compound=tk.LEFT, command=self.loadExam) self.root.config(menu=self.menubar) def loader(self, examID, dicomList): """ Alvo da thread para criação de novos ambientes (abas) """ self.envActive = Environment(examID, dicomList) self.loadImageNotebook() def loadExam(self): """ Carrega os exames através do handler """ examDict = dcmHandler.openDicomFiles() for examID, dicomList in examDict.items(): self.loader(examID, dicomList) # t = Thread(target=self.loader,args=(img,)) # loaderList.append(t) # t.start() def onEnvChange(self, event): print(self.notebook.index('current')) self.envActive = self.envDict[self.notebook.index( self.notebook.select())] self.clearCursor() def cbRoi(self, shape): cnv = self.envActive.resultCanvas cnv.bind( "<ButtonPress-1>", lambda event: edit.callbackRoi( env=self.envActive, event=event, shape=shape)) cnv.bind("<B1-Motion>", lambda event: edit.onMoveRoi(env=self.envActive, event=event)) cnv.bind( "<ButtonRelease-1>", lambda event: edit.releaseRoi(env=self.envActive, event=event)) def cbDraw(self): cnv = self.envActive.resultCanvas # cnv.bind("<ButtonPress-1>", lambda event: edit.callbackDraw(event=event)) cnv.bind( "<B1-Motion>", lambda event: edit.onMoveDraw(event=event, env=self.envActive, thickness=self.drawThickness.get())) # cnv.bind("<ButtonRelease-1>", lambda event: edit.releaseDraw(event=event)) def cbZoom(self, zoomIn): cnv = self.envActive.resultCanvas cnv.bind( "<ButtonRelease-1>", lambda event: edit.zoom( env=self.envActive, zoomIn=zoomIn, event=event)) def loadImageNotebook(self): """ Create a image in the notebook for the environment. The image is loaded in a tab in the notebook Input: Environment (env) Output: Frame inside the tab where the image is set (frm) """ try: # Cria o frame e o canvas do exame usando o frame # definido como tab dentro do notebook self.envActive.createExamViewer( self.createTab(self.envActive.examID)) self.envActive.updateImage() # self.envDict[len(self.notebook.tabs())-1] = self.envActive # self.notebook.select(len(self.notebook.tabs())-1) self.envDict[len(self.notebook.tabs())] = self.envActive self.root.update() self.notebook.select(len(self.notebook.tabs()) - 1) except Exception as ex: printLog(LOGTYPE.ERROR_LOAD_IMG_NOTEBOOK, ex) def createTab(self, exam): frm = ttk.Frame(self.notebook, name=exam) self.notebook.add(frm, text=exam) frm.rowconfigure(0, weight=1) frm.columnconfigure(0, weight=2, uniform='notebook') frm.columnconfigure(1, weight=1, uniform='notebook') return frm def clearCursor(self): frmName = self.notebook.select() frm = self.root.nametowidget(frmName) for cnvName in frm.children[txt.EXAMIMAGE].children: # Pega o canvas atual cnv = self.root.nametowidget(".".join( (frmName, txt.EXAMIMAGE, cnvName))) cnv.unbind("<ButtonPress-1>") cnv.unbind("<B1-Motion>") cnv.unbind("<ButtonRelease-1>")
print('is eco') if mode == 1: print('is normal') if mode == 2: print('is sport') BUTTON_W = 25 BUTTON_H = int(BUTTON_W/2) m = ThemedTk(className="Start Screen", theme="xpnative") m.geometry('480x360') rows = 0 while rows < 50: m.rowconfigure(rows, weight=1) m.columnconfigure(rows, weight=1) rows += 1 nb = ttk.Notebook(m) nb.grid(row=1, column=0, columnspan='50', rowspan='49', sticky='NESW') hometab = ttk.Frame(nb) nb.add(hometab, text='Home') measurement_tab = ttk.Frame(nb) nb.add(measurement_tab, text='Measurements') # displaying SOC soc = 50 soc_label = ttk.Label(hometab, text=soc) soc_label.pack()