def key_press(self, interactor, event): key = interactor.GetKeySym() #XXX this is annoying in dwm (and probably elsewhere) #if self.pickerName is None: #error_msg('You must select the pick segment in the Picker tab') #return def checkPickerName(): if self.pickerName is None: error_msg('You must select the pick segment in the Picker tab') return False return True if key.lower() == 'q': #hehehe gtk.main_quit() if key.lower() == 'i': if not checkPickerName(): return print "Inserting Marker" x, y = interactor.GetEventPosition() picker = vtk.vtkCellPicker() picker.PickFromListOn() o = self.paramd[self.pickerName] picker.AddPickList(o.isoActor) picker.SetTolerance(0.005) picker.Pick(x, y, 0, self.sr.renderer) points = picker.GetPickedPositions() numPoints = points.GetNumberOfPoints() if numPoints < 1: return pnt = points.GetPoint(0) marker = Marker(xyz=pnt, rgb=EventHandler().get_default_color()) EventHandler().add_marker(marker) elif key.lower() == 'x': if not checkPickerName(): return x, y = interactor.GetEventPosition() picker = vtk.vtkCellPicker() picker.PickFromListOn() for o in self.paramd.values(): picker.AddPickList(o.isoActor) picker.SetTolerance(0.01) picker.Pick(x, y, 0, self.sr.renderer) cellId = picker.GetCellId() if cellId == -1: pass else: o = self.paramd.values()[0] o.remove.RemoveCell(cellId) interactor.Render() elif key.lower() == 'e': if not checkPickerName(): return o = self.paramd.values()[0] pw = o.planeWidget if pw.GetEnabled(): pw.EnabledOff() else: pw.EnabledOn()
def game(): config = GameConfig() event_handler = EventHandler() screen = pygame.display.set_mode([config.w, config.h]) config.screen = screen render_handler = RenderHandler() scene_handler = SceneHandler() config.scene_handler = scene_handler last_ticks = pygame.time.get_ticks() ticks_since_render = pygame.time.get_ticks() while config.running: for event in pygame.event.get(): if event.type == pygame.QUIT: config.running = False else: event_handler.dispatch(event) current_ticks = pygame.time.get_ticks() dt = current_ticks - last_ticks # Update scene_handler.update(dt) # Render ticks_since_render += dt last_ticks = current_ticks if ticks_since_render > config.min_mspf: screen.fill((0, 0, 0)) render_handler.draw() pygame.display.flip() ticks_since_render = 0
def load_mri(self, *args): print "loc3djr_maintoolbar.load_mri()" if self.niftiFilename is not None: fname=self.niftiFilename else: dialog = gtk.FileSelection('Choose nifti file') dialog.set_transient_for(widgets['dlgReader']) dialog.set_filename(shared.get_last_dir()) response = dialog.run() fname = dialog.get_filename() dialog.destroy() if response == gtk.RESPONSE_OK: print fname else: return #reader = vtkNiftiImageReader() #reader.SetFileName(fname) #reader.Update() pars = Params() if fname.endswith(".nii.gz"): pars.extension=".".join(fname.split(".")[-2:]) pars.pattern=".".join(fname.split(os.path.sep)[-1].split(".")[:-2]) #elif fname.endswith(".nii"): # pars.extension=".nii" else: pars.extension=".".join(fname.split(".")[-1:]) pars.pattern=".".join(fname.split(os.path.sep)[-1].split(".")[:-1]) print "pars.extension", pars.extension print "pars.pattern", pars.pattern pars.dir=os.path.dirname(fname)#sep.join(fname.split(os.path.sep)[:-1]) print "pars.dir", pars.dir pars.readerClass='vtkNiftiImageReader' reader=widgets.get_reader(pars) pars.first=1 pars.last=reader.GetDepth() print "reader=", reader if not reader: print "hit cancel, see if we can survive" else: pars=widgets.get_params() pars=widgets.validate(pars) imageData = reader.GetOutput() #stupid workaround, somehow imageData.Extent is not written. dunno why #maybe its in vtkImageImportFromArray imageData.SetExtent(reader.GetDataExtent()) print "loc3djr_maintoolbar.load_mri(): reader.GetOutput() is " , imageData print "load_mri(): imageData.SetSpacing(", reader.GetDataSpacing(), " )" imageData.SetSpacing(reader.GetDataSpacing()) print "calling EventHandler().notify('set image data', imageData)" EventHandler().notify('set image data', imageData) print "calling EventHandler().setNifti()" EventHandler().setNifti(reader.GetQForm(),reader.GetDataSpacing())
def __init__(self, name): self.name = name self.model = {} self._log = MessageLogger() self.log = self._log.log self.get_message = self._log.get_message self.get_log = self._log.get_log self.clock = Clock(name + " clock") self.rect = Rect((1, 1), (0, 0)) self.controllers = [] self.control_freeze = False self.visible = True self._graphics = None self._style = {} self.sounds = {} self.meters = {} self.event = None self.event_handler = EventHandler(self) self.handle_event = self.event_handler.handle_event self.queue_events({"name": "on_spawn"})
def button_down(*args): marker = self.get_marker_at_point() if marker is None: return isSelected = EventHandler().is_selected(marker) if self.interactor.GetControlKey(): if isSelected: EventHandler().remove_selection(marker) else: EventHandler().add_selection(marker) else: EventHandler().select_new(marker)
def button_down(*args): marker = self.get_marker_at_point() if marker is None: return color = EventHandler().get_default_color() oldColor = marker.get_color() UndoRegistry().push_command(EventHandler().notify, 'color marker', marker, oldColor) EventHandler().notify('color marker', marker, color)
class AudioTransport(Thread): def __init__(self): super(AudioTransport, self).__init__() self.play_state = PlayStates.stopped self.tempo_bpm = 100 self.ms_between_ticks = 0 self.time_signature = TimeSignature(numerator=4, denumerator=4, ticks_per_quarter_note=4) self.playhead = PlayHead() self.event_list = EventList([]) self.event_handler = EventHandler() self.recalculate_tick_time() self.keep_thread_active = True self.start() def start_playback(self): self.play_state = PlayStates.playing def stop_playback(self): self.play_state = PlayStates.stopped def set_events(self, event_list: EventList): self.event_list = event_list self.playhead.set_looping( 0, self.event_list.find_looping_point_for_time_signature( self.time_signature)) def run(self): while self.keep_thread_active: if self.play_state == PlayStates.playing: self.handle_all_events_for_playhead_position() self.playhead.advance_tick() self.wait_for_next_tick() def handle_all_events_for_playhead_position(self): for e in self.event_list.get_all_events_with_time_stamp( self.playhead.position_in_ticks): self.event_handler.handle(e) def wait_for_next_tick(self): time.sleep(self.ms_between_ticks / 1000) def recalculate_tick_time(self): num_ticks_per_minute = self.time_signature.ticks_per_quarter_note * self.tempo_bpm ms_per_minute = 60_000 self.ms_between_ticks = ms_per_minute / num_ticks_per_minute def set_tempo_bpm(self, tempo: float): if tempo > 0: self.tempo_bpm = tempo self.recalculate_tick_time() else: print('tempo change ignored, can\'t play non-positive tempo') def rewind(self): self.playhead.rewind()
def cleanup(self): # kill thread count thread EventHandler.kill_thread_count_thread() # fix prompt os.system("stty echo") # exit sys.exit(0)
def load_image(self, *args): print "loc3djr_maintoolbar.load_image()" debug = False reader = None pars = None if debug: reader = vtk.vtkImageReader2() reader.SetDataScalarTypeToUnsignedShort() reader.SetDataByteOrderToLittleEndian() reader.SetFileNameSliceOffset(120) reader.SetDataExtent(0, 511, 0, 511, 0, 106) reader.SetFilePrefix( '/home/jdhunter/seizure/data/ThompsonK/CT/raw/1.2.840.113619.2.55.1.1762864819.1957.1074338393.' ) reader.SetFilePattern('%s%d.raw') reader.SetDataSpacing(25.0 / 512, 25.0 / 512, 0.125) reader.Update() else: dlg = widgets['dlgReader'] response = dlg.run() if response == gtk.RESPONSE_OK: try: reader = widgets.reader except AttributeError: pars = widgets.get_params() pars = widgets.validate(pars) if pars is None: error_msg('Could not validate the parameters', dlg) return reader = widgets.get_reader(pars) pars = widgets.get_params() pars = widgets.validate(pars) dlg.hide() print "reader=", reader if not reader: print "hit cancel, see if we can survive" else: imageData = reader.GetOutput() print "pars=", pars print "loc3djr_maintoolbar.load_image(): reader.GetOutput() is ", imageData print "load_image(): imageData.SetSpacing(", reader.GetDataSpacing( ), " )" imageData.SetSpacing(reader.GetDataSpacing()) print "calling EventHandler().notify('set image data', imageData)" EventHandler().notify('set image data', imageData) if type(reader) == vtkNiftiImageReader: print "calling EventHandler().setNifti()" #XXX EventHandler().setNifti(reader.GetFilename()) EventHandler().setNifti(reader.GetQForm())
def cleanup(self): # kill thread count thread EventHandler.kill_thread_count_thread() # fix prompt os.system("stty echo") # exit sys.exit(0)
def loadModule(self, type, dirpath, filename): module_str = "" mod_name = filename.split('.')[0] mod_dispname = '/'.join(re.split('/modules/' + type + "/", dirpath)[-1].split('/') + [mod_name]) mod_loadname = mod_dispname.replace('/', '_') mod_loadpath = os.path.join(dirpath, filename) mod_file = open(mod_loadpath) try: # import the module into memory imp.load_source(mod_loadname, mod_loadpath, mod_file) # find the module and make an instace of it _module = __import__(mod_loadname) _class = getattr(_module, mod_name) _instance = _class(self.config, self.display, self.modulelock) valid = True for r in _instance.getRequirements(): if (not r in self.config): path = Utils.validateExecutable(r) if (path): self.config[r] = path else: valid = False if (valid): module_str = "%s %s [TYPE = %s] [VALID = TRUE ]" % ( mod_name.ljust(25), _instance.getTitle().ljust(40), type.ljust(6)) else: module_str = "%s %s [TYPE = %s] [VALID = FALSE]" % ( mod_name.ljust(25), _instance.getTitle().ljust(40), type.ljust(6)) # add the module to the framework's loaded modules if (valid): if (type == "action"): if (self.config["safe_level"] > _instance.getSafeLevel()): self.display.error( 'Module \'%s\' disabled. Safety_level (%i) is below specified requirement (%i)' % ( mod_name, _instance.getSafeLevel(), self.config["safe_level"])) else: self.actionModules[mod_dispname] = _instance for t in _instance.getTriggers(): EventHandler.add(_instance, t) elif (type == "input"): self.inputModules[mod_dispname] = _instance else: self.display.error( 'Module \'%s\' disabled. Dependency required: \'%s\'' % (mod_name, _instance.getRequirements())) except ImportError as e: # notify the user of missing dependencies self.display.error('Module \'%s\' disabled. Dependency required: \'%s\'' % (mod_name, e)) except Exception as e: # notify the user of errors print e self.display.error('Module \'%s\' disabled.' % (mod_name)) return module_str
def cleanup(self): #kill key press thread if it has been set up if self.keyevent_thread: self.keyevent_thread.stop() # kill thread count thread EventHandler.kill_thread_count_thread() # fix prompt os.system("stty echo") # exit sys.exit(0)
def cleanup(self): #kill key press thread if it has been set up if self.keyevent_thread: self.keyevent_thread.stop() # kill thread count thread EventHandler.kill_thread_count_thread() # fix prompt os.system("stty echo") # exit sys.exit(0)
def __init__(self, **kwargs): self.__Port = kwargs['port'] if ( ('port' in kwargs) and (type(kwargs['port']) == int)) else DEFAULT_PORT_ADDRESS self.__StartLocker = Lock() self.__RunThread = None self.__IsRunning = False self.__Socket = None self.__HostAddress = None self.__BackLogConnections = DEFAULT_BACK_LOG_CONNECTION self.__Accepted = EventHandler() self.__Closed = EventHandler() self.__Started = EventHandler()
def __init__(self, parent= tk.Tk()): super().__init__(master = parent,background="white", width =500, relief=tk.FLAT, height=250, bd=1) self.parent = parent; self.parent.title("Signal Calculator"); self.pack(); self.__acceptValue =""; self.SetUI(); self.Clicked = EventHandler(); self.ValueChanged = EventHandler(); self.Result = 0.0
def __init__(self): super(AudioTransport, self).__init__() self.play_state = PlayStates.stopped self.tempo_bpm = 100 self.ms_between_ticks = 0 self.time_signature = TimeSignature(numerator=4, denumerator=4, ticks_per_quarter_note=4) self.playhead = PlayHead() self.event_list = EventList([]) self.event_handler = EventHandler() self.recalculate_tick_time() self.keep_thread_active = True self.start()
def __init__(self, interval=1): self.__StartTime = dt.datetime.now() self.__IsStarted = False self.__RunThread = None self.__Interval = interval if ((type(interval) == float) or (type(interval) == int)) else 1 self.__Locker = threading.Lock() #Event Handler self.Completed = EventHandler() self.Progressed = EventHandler() self.Started = EventHandler() self.Failured = EventHandler() pass
def add_ring_actor(self, marker): ringActor = RingActor(marker, self.pw, lineWidth=self.defaultRingLine) vis = ringActor.update() self.renderer.AddActor(ringActor) self.ringActors.AddItem(ringActor) # a hack to keep vtk from casting my class when I put it in # the collection. If I don't register some func, I lose all # the derived methods self.observer.AddObserver('EndInteractionEvent', ringActor.silly_hack) text = vtk.vtkVectorText() text.SetText(marker.get_label()) textMapper = vtk.vtkPolyDataMapper() textMapper.SetInput(text.GetOutput()) textActor = vtk.vtkFollower() textActor.SetMapper(textMapper) size = 2 * marker.get_size() textActor.SetScale(size, size, size) x, y, z = marker.get_center() textActor.SetPosition(x, y, z) textActor.SetCamera(self.camera) textActor.GetProperty().SetColor(marker.get_label_color()) if EventHandler().get_labels_on() and vis: textActor.VisibilityOn() else: textActor.VisibilityOff() self.textActors[marker] = textActor self.renderer.AddActor(textActor)
def save(self, button): try: self.fileName except AttributeError: self.save_as(button=None) else: EventHandler().save_markers_as(self.fileName)
def set_marker_size(bar): val = bar.get_value() for marker in EventHandler().get_markers_as_seq(): marker.set_size(val) self.owner.pwxyz.Render() self.owner.pwxyz.Render()
def __init__(self): GtkGLExtVTKRenderWindowInteractor.__init__(self) EventHandler().attach(self) self.interactButtons = (1, 2, 3) self.renderOn = 1 self.Initialize() self.Start() self.renderer = vtk.vtkRenderer() self.renWin = self.GetRenderWindow() self.renWin.AddRenderer(self.renderer) self.interactor = self.renWin.GetInteractor() #self.camera = self.renderer.GetActiveCamera() self.pressFuncs = { 1: self._Iren.LeftButtonPressEvent, 2: self._Iren.MiddleButtonPressEvent, 3: self._Iren.RightButtonPressEvent } self.releaseFuncs = { 1: self._Iren.LeftButtonReleaseEvent, 2: self._Iren.MiddleButtonReleaseEvent, 3: self._Iren.RightButtonReleaseEvent } self.pressHooks = {} self.releaseHooks = {} self.lastLabel = None self.vtk_interact_mode = False
def add_marker(self, marker): if debug: print "PlaneWidgetsXYZ.add_marker(): self.renderer.AddActor(marker)" self.renderer.AddActor(marker) text = vtk.vtkVectorText() text.SetText(marker.get_label()) textMapper = vtk.vtkPolyDataMapper() textMapper.SetInput(text.GetOutput()) textActor = vtk.vtkFollower() textActor.SetMapper(textMapper) size = marker.get_size() textActor.SetScale(size, size, size) x,y,z = marker.get_center() textActor.SetPosition(x+size, y+size, z+size) textActor.SetCamera(self.camera) textActor.GetProperty().SetColor(marker.get_label_color()) if EventHandler().get_labels_on(): if debug: print "VisibilityOn" textActor.VisibilityOn() else: if debug: print "VisibilityOff" textActor.VisibilityOff() self.textActors[marker] = textActor if debug: print "PlaneWidgetsXYZ.add_marker(): self.renderer.AddActor(textActor)" self.renderer.AddActor(textActor)
def set_plane_points_xyz(self, pxyz): px, py, pz = pxyz self.set_plane_points(self.pwX, px) self.set_plane_points(self.pwY, py) self.set_plane_points(self.pwZ, pz) self.Render() EventHandler().notify('observers update plane')
def get_marker_at_point(self): x, y = self.GetEventPosition() picker = vtk.vtkPropPicker() picker.PickProp(x, y, self.renderer, EventHandler().get_markers()) actor = picker.GetActor() return actor
def __init__(self, master, form, line, *args, **kargs): ''' master = The frame to bind the widgets to. form = Name of the form to bind the events to. line = The line number of the line, displayed as a label ''' self.logger = Logger(self, level=Logger.DEBUG) self.logger.debug("Line Widget enter constructor") self.data = Database.get_instance() super().__init__(master, *args, **kargs) self.form = form self.events = EventHandler.get_instance() #self.data = Database.get_instance() self.values = self.data.populate_list('InventoryItem', 'name') self.values.insert(0, '') # first line is blank tk.Label(self, text='%d' % (int(line))).grid(row=0, column=0) self.quan = tk.Spinbox(self, from_=1, to=99, width=2) self.quan.grid(row=0, column=1, padx=5, pady=5) self.prod = ttk.Combobox(self, values=self.values, width=40) self.prod.grid(row=0, column=2) self.logger.debug("Line Widget leave constructor")
def __init__(self, master, form=None, *args, **kargs): ''' master = The frame to bind the widgets to. name_id = The id of the line containing the customer to associate form = Name of the form to bind the events to. ''' self.logger = Logger(self, level=Logger.DEBUG) self.logger.debug("Line Widget enter constructor") super().__init__(master, bd=1, relief=tk.RIDGE, *args, **kargs) #self.name_id = int(name_id) self.form = form self.events = EventHandler.get_instance() self.data = Database.get_instance() self.line_list = [] self.crnt_index = 0 self.events.register_event('next_button', self.clear) self.events.register_event('prev_button', self.clear) # add button tk.Button(self, text="Add", command=self.add).grid(row=0, column=0) # reset button tk.Button(self, text="Reset", command=self.clear).grid(row=0, column=1) # add one line widget self.add() # self.row = {'table': None, 'column':None, 'self':self, 'hasid':None} self.logger.debug("Line Widget leave constructor")
def coplanar(self): numSelected = EventHandler().get_num_selected() if numSelected !=3: error_msg("You must first select exactly 3 markers", ) return # SetNormal is missing from the 4.2 python API so this is # a long winded way of setting the pw to intersect 3 # selected markers m1, m2, m3 = EventHandler().get_selected() p1 = m1.get_center() p2 = m2.get_center() p3 = m3.get_center() pw = pwo.get_pw() planeO = vtk.vtkPlaneSource() planeO.SetOrigin(pw.GetOrigin()) planeO.SetPoint1(pw.GetPoint1()) planeO.SetPoint2(pw.GetPoint2()) planeO.Update() planeN = vtk.vtkPlaneSource() planeN.SetOrigin(p1) planeN.SetPoint1(p2) planeN.SetPoint2(p3) planeN.Update() normal = planeN.GetNormal() planeO.SetNormal(normal) planeO.SetCenter( (p1[0] + p2[0] + p3[0])/3, (p1[1] + p2[1] + p3[1])/3, (p1[2] + p2[2] + p3[2])/3, ) planeO.Update() pwxyz = pwo.get_pwxyz() pw.SetOrigin(planeO.GetOrigin()) pw.SetPoint1(planeO.GetPoint1()) pw.SetPoint2(planeO.GetPoint2()) pw.UpdatePlacement() pwo.update_plane() pwo.Render() pwxyz.Render()
def choose_color(self, button): dialog = gtk.ColorSelectionDialog('Choose default marker color') colorsel = dialog.colorsel colorsel.set_previous_color(self.lastColor) colorsel.set_current_color(self.lastColor) colorsel.set_has_palette(True) response = dialog.run() if response == gtk.RESPONSE_OK: color = colorsel.get_current_color() self.lastColor = color EventHandler().set_default_color( self.get_normed_rgb(color)) #DEBUG dialog.destroy() print "******************", EventHandler().get_default_color()
def __init__(self, owner): EventHandler.__init__(self) self.__owner = owner # Activity has its own clock self.__clock = GameClock() self.__cursor = 0 self.__prevcursor = -1 self.__advance = 0.0 self.__ended = False self.__clock.start() self.__prevtime = self.__clock.get_real_time() self.__time = self.__prevtime self._animation = None
def ok_clicked(w): fname = dialog.get_filename() shared.set_file_selection(fname) try: EventHandler().save_registration_as(fname) except IOError: error_msg('Could not save data to %s' % fname, ) else: self.fileName = fname dialog.destroy()
def OnKeyPress(self, wid, event=None): if (event.keyval == gdk.keyval_from_name("i") or event.keyval == gdk.keyval_from_name("I")): xyz = self.get_cursor_position_world() if xyz is None: return marker = Marker(xyz=xyz, rgb=EventHandler().get_default_color()) EventHandler().add_marker(marker) return True elif (event.keyval == gdk.keyval_from_name("r") or event.keyval == gdk.keyval_from_name("R")): self.set_camera(self.resetCamera) return True return MarkerWindowInteractor.OnKeyPress(self, wid, event)
def __init__(self, master, form, disable_select=False, disable_new=False, *args, **kargs): ''' master = The frame to bind the widgets to. form = Name of the form to bind the events to. ''' self.logger = Logger(self, level=Logger.INFO) self.logger.debug("NotesBox enter constructor") super().__init__(master, *args, **kargs) row = 0 col = 0 self.form = form self.events = EventHandler.get_instance() tk.Button(self, text='Prev', command=self.prev_btn).grid(row=row, column=col, padx=5, pady=5) col += 1 tk.Button(self, text='Next', command=self.next_btn).grid(row=row, column=col, padx=5, pady=5) if not disable_select: col += 1 tk.Button(self, text='Select', command=self.select_btn).grid(row=row, column=col, padx=5, pady=5) if not disable_new: col += 1 tk.Button(self, text='New', command=self.new_btn).grid(row=row, column=col, padx=5, pady=5) col += 1 tk.Button(self, text='Save', command=self.save_btn).grid(row=row, column=col, padx=5, pady=5) col += 1 tk.Button(self, text='Delete', command=self.delete_btn).grid(row=row, column=col, padx=5, pady=5)
def main(): """Function for running the application""" config = Config(CONFIG_PATH) screen = Screen(config.window_width, config.window_height, config.font_size) event_handler = EventHandler() database_connection = get_database_connection(config.database_path) main_menu = create_main_menu(screen, event_handler, config, database_connection) main_menu.run()
def snap_view_to_point(self, xyz): # project the point onto the plane, find the distance between # xyz and the projected point, then move the plane along it's # normal that distance #todo: undo move_pw_to_point(self.pwX, xyz) move_pw_to_point(self.pwY, xyz) move_pw_to_point(self.pwZ, xyz) self.Render() EventHandler().notify('observers update plane')
def __init__(self, master, table, empty_ok=False): self.logger = Logger(self, level=Logger.DEBUG) self.logger.debug("Setup Dialog start constructor") self.master = master self.table = table self.empty_ok = empty_ok self.data = Database.get_instance() self.events = EventHandler.get_instance() self.id_list = self.get_id_list() self.crnt_index = 0
def runScan(self): if (self.config["scan_target"]): nm = mynmap(self.config, self.display) nm.run(target=self.config["scan_target"], ports=self.config["scan_port_range"], flags="-s" + self.config["scan_type"] + " " + self.config["scan_flags"], vector="nmapScan", filetag="nmapScan" + self.config["scan_target"]) elif (self.config["scan_target_list"]): nm = mynmap(self.config, self.display) nm.run(target="", ports=self.config["scan_port_range"], flags="-s" + self.config["scan_type"] + " " + self.config["scan_flags"] + " -iL " + self.config[ "scan_target_list"], vector="nmapScan") # begin main loop while not EventHandler.finished() or not self.allFinished: if (EventHandler.finished() and not self.allFinished): EventHandler.fire("allFinished") self.allFinished = True EventHandler.processNext(self.display, int(self.config['max_modulethreads']))
def runScan(self): if (self.config["scan_target"]): nm = mynmap(self.config, self.display) nm.run(target=self.config["scan_target"], ports=self.config["scan_port_range"], flags="-s" + self.config["scan_type"] + " " + self.config["scan_flags"], vector="nmapScan", filetag="nmapScan" + self.config["scan_target"]) elif (self.config["scan_target_list"]): nm = mynmap(self.config, self.display) nm.run(target="", ports=self.config["scan_port_range"], flags="-s" + self.config["scan_type"] + " " + self.config["scan_flags"] + " -iL " + self.config[ "scan_target_list"], vector="nmapScan") # begin main loop self.keyevent_thread = KeyEventThread(self.display) self.keyevent_thread.start() while not EventHandler.finished() or not self.allFinished: if (EventHandler.finished() and not self.allFinished): EventHandler.fire("allFinished") self.allFinished = True if not self.keyevent_thread.isPaused(): EventHandler.processNext(self.display, int(self.config['max_modulethreads'])) # kb.save(self.kbSaveFile) #scan is done, stop checking for keypresses in case we go back to the menu self.keyevent_thread.stop()
def loadModule(self, type, dirpath, filename): module_dict = {} # remove the beginning string of the dirpath basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dirpath_orig = dirpath dirpath = dirpath[len(basepath)+1:] mod_name = filename.split('.')[0] mod_dispname = '/'.join(re.split('/modules/' + type + "/", dirpath)[-1].split('/') + [mod_name]) mod_loadname = mod_dispname.replace('/', '_') mod_loadpath = os.path.join(dirpath_orig, filename) mod_file = open(mod_loadpath) try: # import the module into memory imp.load_source(mod_loadname, mod_loadpath, mod_file) # find the module and make an instace of it _module = __import__(mod_loadname) _class = getattr(_module, mod_name) _instance = _class(self.config, self.display, self.modulelock) reasons = [] valid = True for r in _instance.getRequirements(): if r == 'disable': reasons.append("Module Manually Disabled !!!") elif r == 'APIKEY': key_name = mod_name + "_apikey" if not key_name in self.config: reasons.append("API key is missing") valid = False elif not r in self.config: path = Utils.validateExecutable(r) if path: self.config[r] = path else: reasons.append("Requirement not met: %s" % r) valid = False if valid: module_dict = {'name': mod_name.ljust(25), 'description': _instance.getTitle().ljust(40), 'type': type.ljust(6), 'valid': True} else: module_dict = {'name': mod_name.ljust(25), 'description': _instance.getTitle().ljust(40), 'type': type.ljust(6), 'valid': False} if type == 'action': module_dict['safelevel'] = _instance.getSafeLevel() else: module_dict['safelevel'] = None # add the module to the framework's loaded modules if valid: if type == "action": if self.config["safe_level"] > _instance.getSafeLevel(): reasons.append("Safety_Level (%i) is below requirement: %i" % (_instance.getSafeLevel(), self.config["safe_level"])) #self.display.error( # 'Module \'%s\' disabled. Safety_level (%i) is below specified requirement (%i)' % ( # mod_name, _instance.getSafeLevel(), self.config["safe_level"])) elif self.checkExcludeTypes(_instance.getTypes()) == True: True #self.display.error( # 'Module \'%s\' disabled. One or more of the following module types were excluded %s' % ( # mod_name, _instance.getTypes())) else: self.actionModules[mod_dispname] = _instance for t in _instance.getTriggers(): EventHandler.add(_instance, t) elif type == "input": self.inputModules[mod_dispname] = _instance elif type == "report": self.reportModules[mod_dispname] = _instance #else: # self.display.error( # 'Module \'%s\' disabled. Dependency required: \'%s\'' % (mod_name, _instance.getRequirements())) if reasons: self.display.error('Module \'%s\' disabled:' % mod_name) for r in reasons: self.display.error(' ' + r) except ImportError as e: # notify the user of missing dependencies self.display.error('Module \'%s\' disabled. Dependency required: \'%s\'' % (mod_name, e)) return None except Exception as e: # notify the user of errors print e self.display.error('Module \'%s\' disabled.' % (mod_name)) return None return module_dict
def populateInitEvents(self): EventHandler.fire("always:initial")
def toggle_labels(self, *args): eh = EventHandler() if eh.get_labels_on(): eh.set_labels_off() else: eh.set_labels_on()