def run_dwarf(): """ fire it up """ args = process_args() qapp = QApplication([]) qapp.setAttribute(Qt.AA_EnableHighDpiScaling) # set icon if os.name == 'nt': # windows stuff import ctypes try: # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\nIconResource=assets\dwarf.ico,0\n[ViewState]\nMode=\nVid=\nFolderType=Generic\n" try: with open('desktop.ini', 'w') as ini: ini.writelines(folder_stuff) FILE_ATTRIBUTE_HIDDEN = 0x02 FILE_ATTRIBUTE_SYSTEM = 0x04 # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( r'desktop.ini', FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM) except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) qapp.setWindowIcon(_icon) except: pass else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) qapp.setWindowIcon(_icon) app_window = AppWindow(args) app_window.setWindowIcon(_icon) app_window.onRestart.connect(_on_restart) try: sys.exit(qapp.exec_()) except SystemExit as sys_err: if sys_err.code == 0: # thanks for using dwarf print('Thank\'s for using Dwarf\nHave a nice day...') else: # something was wrong print('sysexit with: %d' % sys_err.code)
def __init__(self): path = utils.resource_path('settings.ini') if Settings._instance is not None: self._config = Settings._instance._config self._action_config = Settings._instance._action_config self._aciton = Settings._instance._actions else: Settings._instance = self self._config = configparser.ConfigParser() try: self._config.read(path) except: self.generate_settings() self._action_config = { 'show_names': 'tab', 'accelerate': 'w', 'decelerate': 's', 'turn_left': 'a', 'turn_right': 'd', 'nozzle_left': 'j', 'nozzle_right': 'i', 'shoot': 'space', 'bomb': 'shift' } self._actions = [ 'accelerate', 'decelerate', 'turn_left', 'turn_right', 'shoot', 'bomb', 'nozzle_left', 'nozzle_right', 'show_names' ] for key, value in self._config['key_bindings'].items(): if value == "space": self._config['key_bindings'][key] = ' ' elif value == "tab": self._config['key_bindings'][key] = '\t' elif value == "shift": self._config['key_bindings'][key] = "-" + str(pygame.K_LSHIFT)
def setup_ui(self): v_box = QVBoxLayout() head = QHBoxLayout() head.setContentsMargins(10, 10, 0, 10) # dwarf icon icon = QLabel() icon.setPixmap(QPixmap(utils.resource_path('assets/dwarf.svg'))) icon.setAlignment(Qt.AlignCenter) icon.setMinimumSize(QSize(125, 125)) icon.setMaximumSize(QSize(125, 125)) head.addWidget(icon) # main title v_box = QVBoxLayout() title = QLabel('Dwarf') title.setContentsMargins(0, 0, 0, 0) title.setFont(QFont('Anton', 100, QFont.Bold)) title.setMaximumHeight(125) title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) title.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) head.addWidget(title) v_box.addLayout(head) v_box.addWidget(QLabel('Copyright (C) 2019 Giovanni Rocca (iGio90)')) license_text = QTextEdit() # replace tabbed license_text.setText(self._gplv3.replace(' ', '')) license_text.setReadOnly(True) license_text.setMinimumWidth(550) v_box.addWidget(license_text) self.setLayout(v_box)
def generate_settings(self): path = utils.resource_path('settings.ini') print( "[WARNING] Found corrupted or missing 'settings.ini'. Generating new file." ) self._config['settings'] = {'max_fps': '60', 'resolution': '500x600'} self._config['key_bindings'] = self._action_config with utils.open_file('settings.ini', 'w') as config_file: self._config.write(config_file) self._config.read(path)
def get_tileset(self): path = utils.resource_path(constant.TILESET) image = pygame.image.load(path).convert_alpha() image_width, image_height = image.get_size() cols, rows = int(image_width / 16), int(image_height / 16) tileset = utils.array_2d(rows, cols) for x in range(cols): for y in range(rows): rect = pygame.Rect(x * 16, y * 16, 16, 16) tileset[x][y] = pygame.transform.scale2x( image.subsurface(rect)) #else: tileset[x][y] = image.subsurface(rect) return tileset
def set_theme(self, theme): if theme: theme = theme.replace(os.pardir, '').replace('.', '') theme = theme.join(theme.split()).lower() theme_style = 'assets/' + theme + '_style.qss' if not os.path.exists(utils.resource_path(theme_style)): return self.prefs.put('dwarf_ui_theme', theme) try: _app = QApplication.instance() with open(theme_style) as stylesheet: _app.setStyleSheet(_app.styleSheet() + '\n' + stylesheet.read()) except Exception as e: pass
def draw_text(self, surface, pos, text, size, font="bit1.fon", colour=(0, 0, 0), background=None, centre=True, bold=False): path = utils.resource_path(constant.FONTS + font) pyfont = pygame.font.Font(path, size) text = pyfont.render(text, True, colour) rx, ry = text.get_rect()[2:4] if centre: pos = pos[0] - text.get_rect().width * 0.5, pos[1] if background: fill = 2 bg = pygame.Surface((rx + fill * 2, ry + fill * 2)) bg.fill(background) if len(background) == 4: bg.set_alpha(background[-1]) surface.blit(bg, (pos[0] - fill, pos[1] - fill)) if bold: pyfont.set_bold(True) surface.blit(text, pos)
def run(self): IN = self.raw_data_folder.find('_IN') != -1 OUT = self.raw_data_folder.find('_OUT') != -1 # ========================================================================== # Variables and parameters definiton # ========================================================================== angular_position_SA = [] angular_position_SB = [] data_PD = [] eccentricity = [] laser_position = [] occlusion_position = [] original_time_SB = [] scan_number = [] speed_SA = [] speed_SB = [] time_PD = [] time_SA = [] time_SB = [] # We use a parameter file parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) IN_55rs_range = eval( config.get('OPS processing parameters', '55rs_IN_range')) IN_133rs_range = eval( config.get('OPS processing parameters', '133rs_IN_range')) OUT_55rs_range = eval( config.get('OPS processing parameters', '55rs_OUT_range')) OUT_133rs_range = eval( config.get('OPS processing parameters', '133rs_OUT_range')) sampling_frequency = eval( config.get('OPS processing parameters', 'sampling_frequency')) mat_files, dir_path = utils.mat_list_from_folder(self.raw_data_folder) mat = sio.loadmat(dir_path + '/' + mat_files[0]) speed = mat['speed'][0] INorOUT = mat['INorOUT'][0] if IN is True: print('------- OPS Processing IN -------') if speed == 55: StartTime = IN_55rs_range[0] elif speed == 133: StartTime = IN_133rs_range[0] self.notifyState.emit('OPS Processing IN') time.sleep(0.1) elif OUT is True: if speed == 55: StartTime = OUT_55rs_range[0] elif speed == 133: StartTime = OUT_133rs_range[0] print('------- OPS Processing OUT -------') self.notifyState.emit('OPS Processing OUT') time.sleep(0.1) # ========================================================================== # Raw data file names extraction # ========================================================================== # ========================================================================== # Main processing loop # ========================================================================== i = 0 for mat_file in tqdm(mat_files): if self.verbose is True: print(mat_file) self.notifyProgress.emit(int(i * 100 / len(mat_files))) time.sleep(0.1) self.notifyFile.emit(mat_file) time.sleep(0.1) mat = sio.loadmat(dir_path + '/' + mat_file) _data_SA = mat['data_SA'][0] _data_SB = mat['data_SB'][0] _data_PD = mat['data_PD'][0] Data_SA = process_position( _data_SA, utils.resource_path('data/parameters.cfg'), StartTime, showplot=0, filename=mat_file) Data_SB = process_position( _data_SB, utils.resource_path('data/parameters.cfg'), StartTime, showplot=0, filename=mat_file) Data_SB_R = utils.resample(Data_SB, Data_SA) Data_SA_R = utils.resample(Data_SA, Data_SB) # Eccentricity from OPS processing and saving in list _eccentricity = np.subtract(Data_SA[1], Data_SB_R[1]) / 2 eccentricity.append(_eccentricity) _eccentricity_B = np.subtract(Data_SB[1], Data_SA_R[1]) / 2 Data_SA[1] = np.subtract(Data_SA[1], _eccentricity) Data_SB[1] = np.subtract(Data_SB[1], _eccentricity_B) Data_SB_R[1] = np.add(Data_SB_R[1], _eccentricity) # OPS data saving in list angular_position_SA.append(Data_SA[1]) angular_position_SB.append(Data_SB[1]) # OPSA time saving in list time_SA.append(Data_SA[0]) time_SB.append(Data_SB[0]) # OPS speed processing and saving in list _speed_SA = np.divide(np.diff(Data_SA[1]), np.diff(Data_SA[0])) _speed_SB = np.divide(np.diff(Data_SB[1]), np.diff(Data_SB[0])) speed_SA.append(_speed_SA) speed_SB.append(_speed_SB) # Finding of occlusions and saving into a list _time_PD = StartTime + np.arange( 0, _data_PD.size) * 1 / sampling_frequency occlusions = find_occlusions(_data_PD, IN) # if occlusions is -1: # log.log_no_peaks(mat_file, IN) Data_SA_R = utils.resample(Data_SA, np.array([_time_PD, _data_PD])) occ1 = Data_SA_R[1][int(occlusions[0])] occ2 = Data_SA_R[1][int(occlusions[1])] _occlusion = (occ2 - occ1) / 2 + occ1 test_range = np.array([0, np.pi]) # if _occlusion < test_range[0] or _occlusion > test_range[1]: # log.log_peaks_out_of_range(test_range, _occlusion, mat_file, IN) occlusion_position.append(_occlusion) # Laser position and scan number extraction from file name and saving in list _laser_position, _scan_number = utils.find_scan_info(mat_file) scan_number.append(int(_scan_number)) laser_position.append(float(_laser_position)) i += 1 if IN is True: filename = 'PROCESSED_IN.mat' 'done IN' elif OUT is True: filename = 'PROCESSED_OUT.mat' # ========================================================================== # Matfile Saving # ========================================================================== sio.savemat(self.destination_folder + '/' + filename, { 'angular_position_SA': angular_position_SA, 'angular_position_SB': angular_position_SB, 'data_PD': data_PD, 'eccentricity': eccentricity, 'laser_position': laser_position, 'occlusion_position': occlusion_position, 'original_time_SB': original_time_SB, 'scan_number': scan_number, 'speed_SA': speed_SA, 'speed_SB': speed_SB, 'time_PD': time_PD, 'time_SA': time_SA, 'time_SB': time_SB }, do_compression=True) # log.log_file_saved(filename) if IN is True: filename = 'PROCESSED_IN.mat' self.notifyState.emit('done IN') time.sleep(0.1) elif OUT is True: filename = 'PROCESSED_OUT.mat' self.notifyState.emit('done OUT') time.sleep(0.1)
def find_occlusions(data, IN=True, diagnostic_plot=False, StartTime=0, return_processing=False): """ TO DO """ # Cutting of the first part wich can contain parasite peaks # beginingoff = lambda x: x[int(x.size/4)::] # data = beginingoff(data) # We use a parameter file parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) sampling_frequency = eval( config.get('OPS processing parameters', 'sampling_frequency')) peaks_detection_filter_freq = eval( config.get('OPS processing parameters', 'peaks_detection_filter_freq')) or_data = data data = np.abs(-data) filtered_data = utils.butter_lowpass_filter(data, peaks_detection_filter_freq, sampling_frequency, order=5) pcks = utils.peakdet(filtered_data, np.amax(data) / 4)[0] pcks = np.transpose(pcks) try: locs = pcks[0] except: plt.figure() plt.plot(filtered_data) plt.show() return -1 pcks = pcks[1] sorted_indexes = np.argsort(locs) if IN is False: sorted_indexes = sorted_indexes[::-1] locs = locs[sorted_indexes].astype(int) # + int(data.size/4) if diagnostic_plot == True: plt.figure() mplt.nice_style() plt.plot(StartTime + 20e-6 * np.arange(0, filtered_data.size), filtered_data) plt.plot(StartTime + 20e-6 * locs, filtered_data[locs], '.') plt.show(block=False) if return_processing is True: return [ StartTime + 1 / sampling_frequency * locs[0:2], or_data[locs[0:2]] ] else: return locs[0:2]
def __init__(self, parent=None): # pylint: disable=too-many-statements super(HooksPanel, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('HooksPanel created before Dwarf exists') return # connect to dwarf self._app_window.dwarf.onAddJavaHook.connect(self._on_add_hook) self._app_window.dwarf.onAddNativeHook.connect(self._on_add_hook) self._app_window.dwarf.onAddNativeOnLoadHook.connect(self._on_add_hook) self._app_window.dwarf.onAddJavaOnLoadHook.connect(self._on_add_hook) self._app_window.dwarf.onHitNativeOnLoad.connect( self._on_hit_native_on_load) self._app_window.dwarf.onHitJavaOnLoad.connect( self._on_hit_java_on_load) self._app_window.dwarf.onDeleteHook.connect(self._on_hook_deleted) self._hooks_list = DwarfListView() self._hooks_list.doubleClicked.connect(self._on_dblclicked) self._hooks_list.setContextMenuPolicy(Qt.CustomContextMenu) self._hooks_list.customContextMenuRequested.connect( self._on_context_menu) self._hooks_model = QStandardItemModel(0, 5) self._hooks_model.setHeaderData(0, Qt.Horizontal, 'Address') self._hooks_model.setHeaderData(1, Qt.Horizontal, 'T') self._hooks_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._hooks_model.setHeaderData(2, Qt.Horizontal, 'Input') self._hooks_model.setHeaderData(3, Qt.Horizontal, '{}') self._hooks_model.setHeaderData(3, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._hooks_model.setHeaderData(4, Qt.Horizontal, '<>') self._hooks_model.setHeaderData(4, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._hooks_list.setModel(self._hooks_model) self._hooks_list.header().setStretchLastSection(False) self._hooks_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents | QHeaderView.Interactive) self._hooks_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self._hooks_list.header().setSectionResizeMode(2, QHeaderView.Stretch) self._hooks_list.header().setSectionResizeMode( 3, QHeaderView.ResizeToContents) self._hooks_list.header().setSectionResizeMode( 4, QHeaderView.ResizeToContents) v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) v_box.addWidget(self._hooks_list) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) self.btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') self.btn1.setFixedSize(20, 20) self.btn1.clicked.connect(self._on_additem_clicked) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(self.btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) self.setLayout(v_box) self._bold_font = QFont(self._hooks_list.font()) self._bold_font.setBold(True) shortcut_addnative = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_N), self._app_window, self._on_addnative) shortcut_addnative.setAutoRepeat(False) shortcut_addjava = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_J), self._app_window, self._on_addjava) shortcut_addjava.setAutoRepeat(False) shortcut_add_native_on_load = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_O), self._app_window, self._on_add_native_on_load) shortcut_add_native_on_load.setAutoRepeat(False) # new menu self.new_menu = QMenu('New') self.new_menu.addAction('Native', self._on_addnative) self.new_menu.addAction('Java', self._on_addjava) self.new_menu.addAction('Module loading', self._on_add_native_on_load)
def __init__(self, parent=None): # pylint: disable=too-many-statements super(WatchersPanel, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('Watcherpanel created before Dwarf exists') return self._uppercase_hex = True self.setAutoFillBackground(True) # connect to dwarf self._app_window.dwarf.onWatcherAdded.connect(self._on_watcher_added) self._app_window.dwarf.onWatcherRemoved.connect( self._on_watcher_removed) # setup our model self._watchers_model = QStandardItemModel(0, 5) self._watchers_model.setHeaderData(0, Qt.Horizontal, 'Address') self._watchers_model.setHeaderData(1, Qt.Horizontal, 'R') self._watchers_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchers_model.setHeaderData(2, Qt.Horizontal, 'W') self._watchers_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchers_model.setHeaderData(3, Qt.Horizontal, 'X') self._watchers_model.setHeaderData(3, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchers_model.setHeaderData(4, Qt.Horizontal, 'S') self._watchers_model.setHeaderData(4, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) # setup ui v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) self.list_view = DwarfListView() self.list_view.setModel(self._watchers_model) self.list_view.header().setSectionResizeMode(0, QHeaderView.Stretch) self.list_view.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 3, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 4, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setStretchLastSection(False) self.list_view.doubleClicked.connect(self._on_item_dblclick) self.list_view.setContextMenuPolicy(Qt.CustomContextMenu) self.list_view.customContextMenuRequested.connect(self._on_contextmenu) v_box.addWidget(self.list_view) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) btn1 = QPushButton(QIcon(utils.resource_path('assets/icons/plus.svg')), '') btn1.setFixedSize(20, 20) btn1.clicked.connect(self._on_additem_clicked) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) # create a centered dot icon _section_width = self.list_view.header().sectionSize(2) self._new_pixmap = QPixmap(_section_width, 20) self._new_pixmap.fill(Qt.transparent) painter = QPainter(self._new_pixmap) rect = QRect((_section_width * 0.5), 0, 20, 20) painter.setBrush(QColor('#666')) painter.setPen(QColor('#666')) painter.drawEllipse(rect) self._dot_icon = QIcon(self._new_pixmap) # shortcuts shortcut_add = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_W), self._app_window, self._on_additem_clicked) shortcut_add.setAutoRepeat(False) self.setLayout(v_box)
def setup_ui(self): """ Setup Ui """ main_wrap = QVBoxLayout() main_wrap.setContentsMargins(0, 0, 0, 0) # updatebar on top self.update_bar = UpdateBar(self) self.update_bar.onUpdateNowClicked.connect(self._update_dwarf) self.update_bar.setVisible(False) main_wrap.addWidget(self.update_bar) # main content h_box = QHBoxLayout() h_box.setContentsMargins(15, 15, 15, 15) wrapper = QVBoxLayout() #wrapper.setGeometry(QRect(0, 0, 400, 200)) head = QHBoxLayout() # dwarf icon icon = QLabel() icon.setContentsMargins(100, 0, 20, 0) icon.setPixmap(QPixmap(utils.resource_path('assets/dwarf.png'))) head.addWidget(icon) # main title title = QLabel('Dwarf') title.setFont(QFont('Anton', 85, QFont.Bold)) title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) head.addWidget(title) wrapper.addLayout(head) recent = QLabel('Last saved Sessions') font = recent.font() font.setBold(True) font.setPointSize(10) recent.setFont(font) wrapper.addWidget(recent) wrapper.addWidget(self.recent_list) h_box.addLayout(wrapper, stretch=False) buttonSpacer = QSpacerItem(15, 100, QSizePolicy.Fixed, QSizePolicy.Minimum) h_box.addItem(buttonSpacer) wrapper = QVBoxLayout() btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/android.png'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Android Session') btn.clicked.connect(self._on_android_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/apple.png'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New iOS Session') wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/local.png'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Local Session') btn.clicked.connect(self._on_local_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/remote.png'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Remote Session') wrapper.addWidget(btn) h_box.addLayout(wrapper, stretch=False) main_wrap.addLayout(h_box) self.setLayout(main_wrap)
def run_dwarf(): """ fire it up """ args = process_args() os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" if os.name == 'nt': # windows stuff import ctypes try: # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\n" folder_stuff += "IconResource=assets\\dwarf.ico,0\n" folder_stuff += "[ViewState]\n" folder_stuff += "Mode=\n" folder_stuff += "Vid=\n" folder_stuff += "FolderType=Generic\n" try: with open('desktop.ini', 'w') as ini: ini.writelines(folder_stuff) # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( r'desktop.ini', 0x02 | 0x04 ) # FILE_ATTRIBUTE_HIDDEN = 0x02 | FILE_ATTRIBUTE_SYSTEM = 0x04 except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) ctypes.windll.user32.SetProcessDPIAware() except Exception: # pylint: disable=broad-except pass qapp = QApplication([]) qapp.setDesktopSettingsAware(True) qapp.setAttribute(Qt.AA_EnableHighDpiScaling) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) qapp.setLayoutDirection(Qt.LeftToRight) qapp.setOrganizationName("https://github.com/iGio90/Dwarf") qapp.setApplicationName("dwarf") # set icon if os.name == "nt" and os.path.exists( utils.resource_path('assets/dwarf.ico')): _icon = QIcon(utils.resource_path('assets/dwarf.ico')) qapp.setWindowIcon(_icon) else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) qapp.setWindowIcon(_icon) app_window = AppWindow(args) app_window.setWindowIcon(_icon) app_window.onRestart.connect(_on_restart) try: sys.exit(qapp.exec_()) except SystemExit as sys_err: if sys_err.code == 0: # thanks for using dwarf print('Thank\'s for using Dwarf\nHave a nice day...') else: # something was wrong print('sysexit with: %d' % sys_err.code)
def __init__(self, dwarf_args, flags=None): super(AppWindow, self).__init__(flags) self.dwarf_args = dwarf_args self.session_manager = SessionManager(self) self.session_manager.sessionCreated.connect(self.session_created) self.session_manager.sessionStopped.connect(self.session_stopped) self.session_manager.sessionClosed.connect(self.session_closed) self._tab_order = [ 'memory', 'modules', 'ranges', 'jvm-inspector', 'jvm-debugger' ] self.menu = self.menuBar() self._is_newer_dwarf = False self.view_menu = None #dockwidgets self.watchers_dwidget = None self.hooks_dwiget = None self.bookmarks_dwiget = None self.registers_dock = None self.console_dock = None self.backtrace_dock = None self.threads_dock = None #panels self.asm_panel = None self.console_panel = None self.context_panel = None self.backtrace_panel = None self.contexts_list_panel = None self.data_panel = None self.emulator_panel = None self.ftrace_panel = None self.hooks_panel = None self.bookmarks_panel = None self.smali_panel = None self.java_inspector_panel = None self.java_explorer_panel = None self.java_trace_panel = None self.memory_panel = None self.modules_panel = None self.ranges_panel = None self.search_panel = None self.trace_panel = None self.watchers_panel = None self.welcome_window = None self._ui_elems = [] self.setWindowTitle( 'Dwarf - A debugger for reverse engineers, crackers and security analyst' ) # load external assets _app = QApplication.instance() self.remove_tmp_dir() # themes self.prefs = Prefs() self.set_theme(self.prefs.get('dwarf_ui_theme', 'black')) # load font if os.path.exists(utils.resource_path('assets/Anton.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/Anton.ttf')) if os.path.exists(utils.resource_path('assets/OpenSans-Regular.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/OpenSans-Regular.ttf')) _app.setFont(QFont("OpenSans", 9, QFont.Normal)) if os.path.exists(utils.resource_path('assets/OpenSans-Bold.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/OpenSans-Bold.ttf')) # mainwindow statusbar self.progressbar = QProgressBar() self.progressbar.setRange(0, 0) self.progressbar.setVisible(False) self.progressbar.setFixedHeight(15) self.progressbar.setFixedWidth(100) self.progressbar.setTextVisible(False) self.progressbar.setValue(30) self.statusbar = QStatusBar(self) self.statusbar.setAutoFillBackground(False) self.statusbar.addPermanentWidget(self.progressbar) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.main_tabs = QTabWidget(self) self.main_tabs.setMovable(False) self.main_tabs.setTabsClosable(True) self.main_tabs.setAutoFillBackground(True) self.main_tabs.tabCloseRequested.connect(self._on_close_tab) self.setCentralWidget(self.main_tabs) if self.dwarf_args.package is None: self.welcome_window = WelcomeDialog(self) self.welcome_window.setModal(True) self.welcome_window.onIsNewerVersion.connect( self._enable_update_menu) self.welcome_window.onUpdateComplete.connect( self._on_dwarf_updated) self.welcome_window.setWindowTitle( 'Welcome to Dwarf - A debugger for reverse engineers, crackers and security analyst' ) self.welcome_window.onSessionSelected.connect(self._start_session) self.welcome_window.onSessionRestore.connect(self._restore_session) # wait for welcome screen self.hide() self.welcome_window.show() else: if dwarf_args.package is not None: if dwarf_args.type is None: # no device given check if package is local path if os.path.exists(dwarf_args.package): print('* Starting new LocalSession') self._start_session('local') else: print('use -t to set sessiontype') exit(0) else: print('* Starting new Session') self._start_session(dwarf_args.type)
def __init__(self, app, *__args): super().__init__(app) self.app = app self.app.dwarf.onJavaTraceEvent.connect(self.on_event) self.app.dwarf.onEnumerateJavaClassesStart.connect(self.on_enumeration_start) self.app.dwarf.onEnumerateJavaClassesMatch.connect(self.on_enumeration_match) self.app.dwarf.onEnumerateJavaClassesComplete.connect(self.on_enumeration_complete) self.tracing = False self.trace_classes = [] self.trace_depth = 0 layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self._record_icon = QIcon(utils.resource_path('assets/icons/record.png')) self._pause_icon = QIcon(utils.resource_path('assets/icons/pause.png')) self._stop_icon = QIcon(utils.resource_path('assets/icons/stop.png')) self._tool_bar = QToolBar() self._tool_bar.addAction('Start', self.start_trace) self._tool_bar.addAction('Pause', self.pause_trace) self._tool_bar.addAction('Stop', self.stop_trace) self._tool_bar.addSeparator() self._entries_lbl = QLabel('Entries: 0') self._entries_lbl.setStyleSheet('color: #ef5350;') self._entries_lbl.setContentsMargins(10, 0, 10, 2) self._entries_lbl.setAttribute(Qt.WA_TranslucentBackground, True) # keep this self._entries_lbl.setAlignment(Qt.AlignRight| Qt.AlignVCenter) self._entries_lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self._tool_bar.addWidget(self._entries_lbl) layout.addWidget(self._tool_bar) self.setup_splitter = QSplitter() self.events_list = JavaTraceView(self) self.events_list.setVisible(False) self.trace_list = QListWidget() self.class_list = QListWidget() self.trace_list.itemDoubleClicked.connect(self.trace_list_double_click) self.class_list.setContextMenuPolicy(Qt.CustomContextMenu) self.class_list.customContextMenuRequested.connect(self.show_class_list_menu) self.class_list.itemDoubleClicked.connect(self.class_list_double_click) self.current_class_search = '' bar = QScrollBar() bar.setFixedWidth(0) bar.setFixedHeight(0) self.trace_list.setHorizontalScrollBar(bar) bar = QScrollBar() bar.setFixedWidth(0) bar.setFixedHeight(0) self.class_list.setHorizontalScrollBar(bar) self.setup_splitter.addWidget(self.trace_list) self.setup_splitter.addWidget(self.class_list) layout.addWidget(self.setup_splitter) layout.addWidget(self.events_list) self.setLayout(layout)
along with this program. If not, see <https://www.gnu.org/licenses/> """ import argparse import sys import qdarkstyle from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication from lib import utils from ui.app import AppWindow if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-s", "--script", action='store_true', help="an additional script to load with " "dwarf and frida js api") parser.add_argument("-p", "--package", help="package name or pid") args = parser.parse_args() app = QApplication([]) app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) with open('ui/style.qss', 'r') as f: app.setStyleSheet(app.styleSheet() + '\n' + f.read()) app.setWindowIcon(QIcon(utils.resource_path('ui/dwarf.png'))) app_window = AppWindow(args) app_window.showMaximized() app.exec_() app_window.get_app_instance().get_dwarf().detach()
def __init__(self, parent=None): ''' Main Widget of the window to display all the tab :param parent: ''' super(QMain, self).__init__(parent) self.setWindowTitle('OPS Processing') self.mainLayout = QVBoxLayout() self.header = QHBoxLayout() self.Title = QLabel('BWS protoype analysis tool') f = QtGui.QFont('Arial', 20, QtGui.QFont.Bold) f.setStyleStrategy(QtGui.QFont.PreferAntialias) self.Title.setFont(QtGui.QFont('Arial', 20, QtGui.QFont.Bold)) self.Title.setContentsMargins(10, 10, 10, 10) self.CERN_logo = QLabel() self.CERN_logo_image = QtGui.QPixmap( utils.resource_path("images/cern_logo.jpg")) self.CERN_logo_image = self.CERN_logo_image.scaledToHeight( 60, QtCore.Qt.SmoothTransformation) self.CERN_logo.setPixmap(self.CERN_logo_image) self.header.addWidget(self.Title) self.header.addWidget(self.CERN_logo, 0, QtCore.Qt.AlignRight) self.global_tab = QTabWidget() self.ProcessedAnalysisisTab = QProcessedAnalysisTab.QProcessedAnalysisTab( self) self.TabFileProcessing = QTabFileProcessing.QTabFileProcessing(self) self.MultipleCalibrationAnalysis = QMultipleCalibrationAnalysis.QMultipleCalibrationAnalysis( self) self.SingleScanAnalysis = QTabSingleScanAnalysis.QTabSingleScanAnalysis( self) self.LogDialog = QLogDialog.QLogDialog() self.global_tab.addTab(self.ProcessedAnalysisisTab, "Single calibration analysis") self.global_tab.addTab(self.MultipleCalibrationAnalysis, "Multiple calibration analysis") self.global_tab.addTab(self.SingleScanAnalysis, "Scan raw data analysis") self.global_tab.addTab(self.TabFileProcessing, "Calibration processing") self.mainLayout.addLayout(self.header) self.mainLayout.addWidget(self.global_tab) self.mainLayout.addWidget(self.LogDialog) self.setLayout(self.mainLayout) # Window properties self.setWindowTitle('OPS Processing') self.setMinimumSize(1200, 900)
def show_parameters_window(self): os.system('Notepad ' + utils.resource_path('data/parameters.cfg'))
def setup_ui(self): """ Setup Ui """ main_wrap = QVBoxLayout() main_wrap.setContentsMargins(0, 0, 0, 0) # updatebar on top self.update_bar = UpdateBar(self) self.update_bar.onUpdateNowClicked.connect(self._update_dwarf) self.update_bar.setVisible(False) main_wrap.addWidget(self.update_bar) # main content h_box = QHBoxLayout() h_box.setContentsMargins(15, 15, 15, 15) wrapper = QVBoxLayout() head = QHBoxLayout() head.setContentsMargins(10, 10, 0, 10) # dwarf icon icon = QLabel() icon.setPixmap(QPixmap(utils.resource_path('assets/dwarf.svg'))) icon.setAlignment(Qt.AlignCenter) icon.setMinimumSize(QSize(125, 125)) icon.setMaximumSize(QSize(125, 125)) head.addWidget(icon) # main title v_box = QVBoxLayout() title = QLabel('Dwarf') title.setContentsMargins(0, 0, 0, 0) font = QFont('Anton', 80, QFont.Bold) font.setPixelSize(100) title.setFont(font) title.setMaximumHeight(105) title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) title.setAlignment(Qt.AlignCenter) head.addWidget(title) sub_title_text = (self._pick_random_word(0) + ' ' + self._pick_random_word(1) + ' ' + self._pick_random_word(2) + ' ' + self._pick_random_word(3) + ' ' + self._pick_random_word(4)) sub_title_text = sub_title_text[:1].upper() + sub_title_text[1:] self._sub_title = QLabel(sub_title_text) font = QFont('OpenSans', 14, QFont.Bold) font.setPixelSize(18) self._sub_title.setFont(font) font_metric = QFontMetrics(self._sub_title.font()) self._char_width = font_metric.widthChar('#') self._sub_title.setAlignment(Qt.AlignCenter) self._sub_title.setContentsMargins(0, 0, 0, 20) self._sub_title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) v_box.addLayout(head) v_box.addWidget(self._sub_title) wrapper.addLayout(v_box) h_box.addLayout(wrapper, stretch=False) buttonSpacer = QSpacerItem(15, 100, QSizePolicy.Fixed, QSizePolicy.Minimum) h_box.addItem(buttonSpacer) wrapper = QVBoxLayout() btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/android.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Android Session') btn.clicked.connect(self._on_android_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/apple.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New iOS Session') btn.clicked.connect(self._on_ios_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/local.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Local Session') btn.clicked.connect(self._on_local_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/remote.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Remote Session') btn.clicked.connect(self._on_remote_button) wrapper.addWidget(btn) h_box.addLayout(wrapper, stretch=False) main_wrap.addLayout(h_box) self.setLayout(main_wrap)
def simulate_wire_profile_measurements(reference_fit_parameters_file, fit_parameters_file, gauss_beam_position=0, gauss_beam_sigma=0, diagnostic=False, save=False, saving_name=None, position_random_error=15e-6): ########################## # Loading files and data # ########################## param_file = sio.loadmat(fit_parameters_file + '/calibration_results.mat', struct_as_record=False, squeeze_me=True) fit_parameters = param_file['f_parameters_IN'] param_file = sio.loadmat(reference_fit_parameters_file, struct_as_record=False, squeeze_me=True) reference_fit_parameters = param_file['f_parameters_IN'] parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) measurement_sigma = position_random_error # gauss_beam_position = eval(config.get('Beam characteristics', 'gauss_beam_position')) # gauss_beam_sigma = eval(config.get('Beam characteristics', 'gauss_beam_sigma')) scan_speed = eval(config.get('Simulation', 'scan_speed')) cycle_period = eval(config.get('Simulation', 'cycle_period')) point_per_sigma = gauss_beam_sigma / scan_speed / cycle_period ############################# # Sigma and Mean extraction # ############################# if diagnostic is True : fig = plt.figure(figsize=(8, 2.5)) prairie.use() ax = fig.add_subplot(111) sigmas = [] extended_std = 15 * gauss_beam_sigma beam_offset_center = utils.theoretical_laser_position( utils.inverse_theoretical_laser_position(gauss_beam_position, *reference_fit_parameters), *fit_parameters) ideal_beam_measurement_positions = np.arange(gauss_beam_position - extended_std / 2, gauss_beam_position + extended_std / 2, gauss_beam_sigma / point_per_sigma) disk_measurement_positions = utils.inverse_theoretical_laser_position(ideal_beam_measurement_positions, *reference_fit_parameters) beam_measurement_positions = utils.theoretical_laser_position(disk_measurement_positions, *fit_parameters) def gauss(x, a, mu, sigma): return a * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) for i in np.arange(0, 1000, 1): sim_measured_positions = [] sim_amplitudes = [] for mu in beam_measurement_positions: sim_pos = mu + np.random.normal(0, measurement_sigma) sim_measured_positions.append(sim_pos) sim_amp = gauss(mu, 1, beam_offset_center, gauss_beam_sigma) sim_amplitudes.append(sim_amp) x = sim_measured_positions y = sim_amplitudes parameters, trash = curve_fit(gauss, x, y, p0=[2, beam_offset_center, gauss_beam_sigma]) if diagnostic is True: arange = np.arange(beam_measurement_positions[0], beam_measurement_positions[::-1][0], (beam_measurement_positions[1]-beam_measurement_positions[0])/100) ax.plot(1e3*arange, gauss(arange, *parameters), linewidth=0.2) ax.plot(1e3*np.asarray(x), y, '.k', markersize=4) scan_speed = 133 * 150e-3 cycle_period = 20e-6 pps = gauss_beam_sigma / scan_speed / cycle_period ax.set_title('Beam profile simulation' + ' [ \u03C3:' + "{:3.0f}".format(1e6*gauss_beam_sigma) + '\u03BCm ' + '\u03BC:' + "{:3.0f}".format(1e6*gauss_beam_position) + ' \u03BCm ] - 1000 profiles\n' + "{:3.2f}".format(pps) + ' points per sigma', loc='left') ax.set_xlabel('Transverse dimension (mm)') ax.set_ylabel('Secondary shower intensity (a.u)') ax.legend(['Beam gaussian fits', 'Measurement points']) sigmas.append(parameters[2]) if diagnostic is True: prairie.style(ax) plt.tight_layout() if save is True: plt.show(block=False) if saving_name is not None: plt.savefig(saving_name + '.png', format='png', dpi=DPI) plt.close('all') else: print('saving_name is None - Figure not saved') else: plt.show(block=True) return [np.mean(sigmas), np.std(sigmas), beam_offset_center]
def main(): """Main""" parser = argparse.ArgumentParser() parser.add_argument("-i", "--interactive", help="Interactively install/upgrade akromanode (Default: False)", \ action='store_true') parser.add_argument("-g", "--geth", help="Geth version to use (Default: stable)", type=str, \ choices=['latest', 'stable'], default=None) parser.add_argument("-s", "--scripts", help="Script version to use (Default: stable)", type=str, \ choices=['latest', 'stable'], default=None) parser.add_argument("-r", "--remove", help="Uninstall akromanode (Default: False)", action='store_true') parser.add_argument("-p", "--rpcport", help="RPC Port (Default: 8545)", type=int, default=None) parser.add_argument("--port", help="Network listening port (Default: 30303)", type=int, default=None) parser.add_argument("-u", "--user", help="Run akromanode as non-root user (Default: akroma)", nargs='?', \ const='akroma', type=str, default=None) parser.add_argument("--rpcuser", help="RPC User (Optional)", type=str) parser.add_argument("--rpcpassword", help="RPC Password (Optional)", type=str) parser.add_argument("--no-rpcuser", help="Remove RPC User/Password (Optional)", action='store_true') parser.add_argument("--no-rpcpassword", help="Remove RPC User/Password (Optional)", dest="no_rpcuser", \ action='store_true') parser.add_argument("--ufw", help="Configure UFW (Optional)", action='store_true') parser.add_argument( "--update-only", help="Update geth and scripts only. Disables auto-update cron", action='store_true') parser.add_argument("-v", "--version", help="Script Version", action='store_true') args = parser.parse_args() # Display script version if args.version: print "Version: %s" % VERSION sys.exit(0) # Get the OS, OS family (ie, Debian or RedHat), OS version, and machine architecture os_name, os_family, os_ver, os_arch = utils.os_detect() if os_name not in COMPAT_MATRIX or os_ver not in COMPAT_MATRIX[os_name]: print "Unsupported OS and/or version. Please refer to installation guide for supported OS and version" sys.exit(2) # Migrate old masternode service to akromanode restart_service = False if utils.service_status('masternode', 'is-active'): utils.print_cmd('Migrating masternode service...') if utils.service_status('masternode', 'stop'): os.rename('/etc/systemd/system/masternode.service', '/etc/systemd/system/akromanode.service') ret, _ = utils.timed_run('/bin/systemctl daemon-reload') if ret is None or int(ret) != 0: raise Exception( 'ERROR: Migration of masternode service failed') restart_service = True else: raise Exception('ERROR: Failed to stop masternode service') # Remove Akroma MasterNode if args.interactive: res = utils.input_bool('Remove masternode installation [y|N]', 'N') args.remove = True if res == 'Y' else False if args.remove: res = utils.input_bool('Remove masternode installation [y|N]', 'N') if res != 'Y': sys.exit(0) utils.print_cmd('Removing masternode installation...') f = '/etc/systemd/system/akromanode.service' if os.path.isfile(f): for status in ('stop', 'disable'): if not utils.service_status('akromanode', status): raise Exception("ERROR: Failed to %s akromanode service" % status) # If service file was a symlink, systemctl would have removed it # Check if the file still exists if os.path.isfile(f): os.remove(f) utils.autoupdate_cron(os_family, remove=True) # Remove scripts for f in ('geth-akroma', 'akroma-mn-setup', 'akroma-mn-utils'): f = '/usr/sbin/' + f if os.path.isfile(f): os.remove(f) sys.exit(0) # Get current geth version, and those returned by API geth_versions = api.get_script_versions(GETH_VERSIONS_URI, '/usr/sbin/geth-akroma version') service_file = utils.parse_service_file( args) # Parse akromanode.service, if it exists, and override defaults # Gather data for interactive mode if args.interactive: # User while True: args.user = '******' if args.user is None else args.user res = utils.input_text( 'Run akromanode as non-root user (Default: akroma):', args.user) res = None if res.isspace() or res == '' else res if res is None or (res and utils.isvalidusername(res)): args.user = res if res != 'root' else res break else: print "Please provide valid username." # Network Listening Port while True: res = utils.input_text('Network listening port (Default: 30303):', args.port) res = 30303 if res.isspace() or res == '' else res if isinstance(res, (int)) or res.isdigit(): args.port = int(res) break else: print "Invalid Network listening Port" # RPC Port while True: res = utils.input_text('RPC Port (Default: 8545):', args.rpcport) res = 8545 if res.isspace() or res == '' else res if isinstance(res, (int)) or res.isdigit(): args.rpcport = int(res) break else: print "Invalid RPC Port" # Remove RPC User/Password if args.rpcuser or args.rpcpassword: res = utils.input_bool('Remove RPC User/Password [y|N]', 'N') if res == 'Y': args.no_rpcuser = True args.no_rpcpassword = True args.rpcuser = None args.rpcpassword = None if not args.no_rpcuser: # RPC User while True: res = utils.input_text('RPC User (Optional):', args.rpcuser) res = None if res.isspace() or res == '' else res if res is None or (res and utils.isvalidrpcinfo(res)): args.rpcuser = res break else: print "Invalid RPC User" # RPC Password while True: res = utils.input_text('RPC Password (Optional):', args.rpcpassword) res = None if res.isspace() or res == '' else res if res is None or (res and utils.isvalidrpcinfo(res)): args.rpcpassword = res break else: print "Invalid RPC Password" # Ensure all appropriate arguments have been set if (args.rpcuser and args.rpcpassword is None) or (args.rpcuser is None and args.rpcpassword): parser.error("--rpcuser requires --rpcpassword.") if (args.rpcuser and not utils.isvalidrpcinfo(args.rpcuser)) or \ (args.rpcpassword and not utils.isvalidrpcinfo(args.rpcpassword)): parser.error("Please provide valid rpcuser/password.") if args.user is not None and not utils.isvalidusername(args.user): parser.error("Please provide valid username.") # Create/verify user to run akromanode exists if args.user and not args.update_only: utils.print_cmd('User configuration.') try: pwd.getpwnam(args.user) print "User %s found." % args.user except KeyError: print "Creating user %s." % args.user if os_family == 'RedHat': ret, _ = utils.timed_run( '/usr/sbin/adduser -r %s -s /bin/false -b /home -m' % args.user) else: ret, _ = utils.timed_run( '/usr/sbin/adduser %s --gecos "" --disabled-password --system --group' % args.user) if ret is None or int(ret) != 0: raise Exception("ERROR: Failed to create user %s" % args.user) # Install OS Family specific dependencies utils.print_cmd('Installing dependencies...') if os_family == 'RedHat': ret, _ = utils.timed_run('/usr/bin/yum -d1 -y install curl') else: ret, _ = utils.timed_run('/usr/bin/apt-get install curl -y') if ret is None or int(ret) != 0: raise Exception("ERROR: Failed to install curl") # Install and configure UFW, if True if args.interactive: res = utils.input_bool('Install and configure ufw [y|N]', 'N') args.ufw = True if res == 'Y' else False if args.ufw: if os_arch == 'x86_64' or os_family == 'Debian': ufw_rules = [ '/usr/sbin/ufw --force reset', '/usr/sbin/ufw --force disable', '/usr/sbin/ufw default deny incoming', '/usr/sbin/ufw default allow outgoing', '/usr/sbin/ufw allow ssh', '/usr/sbin/ufw allow %s/tcp' % args.rpcport, '/usr/sbin/ufw allow %s/tcp' % args.port, '/usr/sbin/ufw allow %s/udp' % args.port, '/usr/sbin/ufw --force enable', '/usr/sbin/ufw status' ] utils.print_cmd('Installing/configuring ufw...') if os_family == 'RedHat': ret, _ = utils.timed_run('/usr/bin/yum -d1 -y install ufw') else: ret, _ = utils.timed_run('/usr/bin/apt-get install ufw -y') if ret is None or int(ret) != 0: raise Exception("ERROR: Failed to install ufw") for rule in ufw_rules: ret, _ = utils.timed_run(rule) if ret is None or int(ret) != 0: raise Exception("ERROR: Failed to configure ufw") for status in ('enable', 'start'): utils.service_status('ufw', status) else: print "ufw is only compatible with 64-bit architectures or Debian based OS'" # Determine if geth version needs to be updated if args.geth is None or geth_versions['current'] == geth_versions[ args.geth]: args.geth = utils.has_update(geth_versions) # Swap geth from stable <-> latest if args.interactive: while True: res = utils.input_text('Geth version to use (Default: stable):', args.geth) res = None if res.isspace() or res == '' else res if res is None or res in ('stable', 'latest'): args.geth = res break else: print "Geth version must be stable or latest" # If geth version update required, download and install new version if args.geth: utils.print_cmd('Installing/upgrading geth %s...' % geth_versions[args.geth]) if not api.download_geth(os_arch, geth_versions[args.geth], GETH_URI): raise Exception('ERROR: Failed to download geth') restart_service = True # If auto-generated service file != on-disk service file, rewrite it # Load and render template if not args.update_only: jinja2_env = Environment( loader=FileSystemLoader(utils.resource_path('templates'))) template = jinja2_env.get_template('akromanode.service.tmpl') new_service_file = template.render(args=args, os_family=os_family) if service_file != new_service_file: utils.print_cmd('Creating/updating akromanode service file...') f = '/etc/systemd/system/akromanode.service' with open(f, 'w') as fd: fd.write(new_service_file) utils.check_perms(f, '0644') ret, _ = utils.timed_run('/bin/systemctl daemon-reload') if ret is None or int(ret) != 0: raise Exception('ERROR: Failed to reload systemctl') restart_service = True # Enable and restart akromanode if service or geth updates have been made if not utils.service_status('akromanode', 'is-active') or restart_service: utils.print_cmd('Enabling and (re)starting akromanode service...') for status in ('enable', 'restart'): utils.service_status('akromanode', status) # Enable auto-update and update scripts if args.update_only: utils.autoupdate_cron(os_family, remove=True) else: utils.autoupdate_cron(os_family) # Get current setup version, and those returned by API script_versions = api.get_script_versions(SCRIPTS_VERSIONS_URI, '/usr/sbin/akroma-mn-setup -v') # Determine if setup/utils version needs to be updated if args.scripts is None or script_versions['current'] == script_versions[ args.scripts]: args.scripts = utils.has_update(script_versions) if args.scripts: api.autoupdate_scripts(os_arch, script_versions[args.scripts], SCRIPTS_URI) utils.print_cmd('Akroma MasterNode up-to-date...')
def run(self): print('Calibration Results Processing') if self.reference_folder is not None: origin_file = self.reference_folder + '/mean_fit.mat' self.reference_file = self.reference_folder + '/mean_fit.mat' else: origin_file = 'None' for folder_name in self.folders: print('.processing' + folder_name) if os.path.exists(folder_name + '/PROCESSED_IN.mat'): self.notifyProgress.emit('Processing ' + folder_name.split('/')[::-1][0]) newname = folder_name.split('file:///', 2) if len(newname) == 2: folder_name = folder_name.split('file:///', 2)[1] parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) positions_for_fit = eval( config.get('OPS processing parameters', 'positions_for_fit')) positions_for_analysis = eval( config.get('OPS processing parameters', 'positions_for_analysis')) tank_center = eval( config.get('OPS processing parameters', 'offset_center')) if self.reference_file is not None: fit_file = sio.loadmat(self.reference_file, struct_as_record=False, squeeze_me=True) origin_file = self.reference_file # IN filename = 'PROCESSED_IN.mat' data = sio.loadmat(folder_name + '/' + filename, struct_as_record=False, squeeze_me=True) occlusion_position = data['occlusion_position'] laser_position = data['laser_position'] idxs = np.argsort(laser_position) occlusion_position = occlusion_position[idxs] laser_position = laser_position[idxs] laser_position = -laser_position + tank_center unique_laser_position = np.unique(laser_position) occlusion_position_mean = [] for laser_pos in unique_laser_position: occlusion_position_mean.append( np.mean(occlusion_position[np.where( laser_position == laser_pos)[0]])) off1 = [ int(positions_for_fit[0] / 100 * unique_laser_position.size), int(positions_for_fit[1] / 100 * unique_laser_position.size) ] occlusion_position_mean = np.asarray(occlusion_position_mean) popt, pcov = curve_fit( utils.theoretical_laser_position, occlusion_position_mean[off1[0]:off1[1]], unique_laser_position[off1[0]:off1[1]], bounds=([-10, 70, 90], [5, 1000, 1000])) theoretical_laser_position_mean = utils.theoretical_laser_position( occlusion_position_mean, popt[0], popt[1], popt[2]) theoretical_laser_position = utils.theoretical_laser_position( occlusion_position, popt[0], popt[1], popt[2]) if self.reference_file is not None: theoretical_laser_position_origin = utils.theoretical_laser_position( occlusion_position, fit_file['f_parameters_IN'][0], fit_file['f_parameters_IN'][1], fit_file['f_parameters_IN'][2]) theoretical_laser_position_origin_mean = utils.theoretical_laser_position( occlusion_position_mean, fit_file['f_parameters_IN'][0], fit_file['f_parameters_IN'][1], fit_file['f_parameters_IN'][2]) else: theoretical_laser_position_origin = theoretical_laser_position theoretical_laser_position_origin_mean = theoretical_laser_position_mean param = popt def theor_laser_position_i(y, a, b, c): """ theoretical angular position of the wire in respect to the laser position """ return np.pi + a - np.arccos((b - y) / c) center_IN = theor_laser_position_i(0, popt[0], popt[1], popt[2]) f_parameters_IN = popt off2 = [ int(positions_for_analysis[0] / 100 * laser_position.size), int(positions_for_analysis[1] / 100 * laser_position.size) ] laser_position = laser_position[off2[0]:off2[1]] theorical_laser_position = theoretical_laser_position[ off2[0]:off2[1]] occlusion_position = occlusion_position[off2[0]:off2[1]] residuals = laser_position - theorical_laser_position residuals_mean = unique_laser_position - theoretical_laser_position_mean if self.reference_file is not None: residuals_origin = laser_position - theoretical_laser_position_origin residuals_origin_mean = unique_laser_position - theoretical_laser_position_origin_mean else: residuals_origin = residuals residuals_origin_mean = residuals_mean residuals = residuals[off2[0]:off2[1]] (mu, sigma) = norm.fit(residuals * 1e3) sigma_IN = sigma / np.sqrt(2) residuals_IN = residuals residuals_IN_origin = residuals_origin laser_position_IN = laser_position laser_position_IN_mean = unique_laser_position residuals_IN_mean = residuals_mean residuals_IN_origin_mean = residuals_origin_mean ##################################################### # OUT #################################################### filename = 'PROCESSED_OUT.mat' data = sio.loadmat(folder_name + '/' + filename, struct_as_record=False, squeeze_me=True) occlusion_position = data['occlusion_position'] laser_position = data['laser_position'] idxs = np.argsort(laser_position) occlusion_position = occlusion_position[idxs] laser_position = laser_position[idxs] laser_position = -laser_position + tank_center occlusion_position = np.pi / 2 - occlusion_position unique_laser_position = np.unique(laser_position) occlusion_position_mean = [] for laser_pos in unique_laser_position: occlusion_position_mean.append( np.mean(occlusion_position[np.where( laser_position == laser_pos)[0]])) off1 = [ int(positions_for_fit[0] / 100 * unique_laser_position.size), int(positions_for_fit[1] / 100 * unique_laser_position.size) ] occlusion_position_mean = np.asarray(occlusion_position_mean) popt, pcov = curve_fit( utils.theoretical_laser_position, occlusion_position_mean[off1[0]:off1[1]], unique_laser_position[off1[0]:off1[1]], bounds=([-10, 70, 90], [5, 1000, 1000])) theoretical_laser_position_mean = utils.theoretical_laser_position( occlusion_position_mean, popt[0], popt[1], popt[2]) theorical_laser_position = utils.theoretical_laser_position( occlusion_position, popt[0], popt[1], popt[2]) if self.reference_file is not None: theoretical_laser_position_origin = utils.theoretical_laser_position( occlusion_position, fit_file['f_parameters_OUT'][0], fit_file['f_parameters_OUT'][1], fit_file['f_parameters_OUT'][2]) theoretical_laser_position_origin_mean = utils.theoretical_laser_position( occlusion_position_mean, fit_file['f_parameters_OUT'][0], fit_file['f_parameters_OUT'][1], fit_file['f_parameters_OUT'][2]) origin_file = self.reference_file else: theoretical_laser_position_origin = theoretical_laser_position theoretical_laser_position_origin_mean = theoretical_laser_position_mean param = popt def theor_laser_position_i(y, a, b, c): return np.pi + a - np.arccos((b - y) / c) center_OUT = theor_laser_position_i(0, popt[0], popt[1], popt[2]) f_parameters_OUT = popt off2 = [ int(positions_for_analysis[0] / 100 * laser_position.size), int(positions_for_analysis[1] / 100 * laser_position.size) ] laser_position = laser_position[off2[0]:off2[1]] theoretical_laser_position = theorical_laser_position[ off2[0]:off2[1]] occlusion_position = occlusion_position[off2[0]:off2[1]] residuals = laser_position - theorical_laser_position residuals_mean = unique_laser_position - theoretical_laser_position_mean if self.reference_file is not None: residuals_origin = laser_position - theoretical_laser_position_origin residuals_origin_mean = unique_laser_position - theoretical_laser_position_origin_mean else: residuals_origin = residuals residuals_origin_mean = residuals_mean residuals = residuals[off2[0]:off2[1]] residuals_OUT = residuals residuals_OUT_origin = residuals_origin residuals_OUT_mean = residuals_mean residuals_OUT_origin_mean = residuals_origin_mean (mu, sigma) = norm.fit(residuals * 1e3) sigma_OUT = sigma / np.sqrt(2) laser_position_OUT = laser_position laser_position_OUT_mean = unique_laser_position utils.create_results_file_from_calibration( folder_name=newname[0], center_IN=center_IN, center_OUT=center_OUT, sigma_IN=sigma_IN, sigma_OUT=sigma_OUT, f_parameters_IN=f_parameters_IN, f_parameters_OUT=f_parameters_OUT, residuals_IN=residuals_IN, residuals_IN_mean=residuals_IN_mean, residuals_OUT=residuals_OUT, residuals_OUT_mean=residuals_OUT_mean, residuals_IN_origin=residuals_IN_origin, residuals_IN_origin_mean=residuals_IN_origin_mean, residuals_OUT_origin=residuals_OUT_origin, residuals_OUT_origin_mean=residuals_OUT_origin_mean, laser_position_IN=laser_position_IN, laser_position_IN_mean=laser_position_IN_mean, laser_position_OUT=laser_position_OUT, laser_position_OUT_mean=laser_position_OUT_mean, origin_file=origin_file) else: self.notifyProgress.emit( folder_name.split('/')[::-1][0] + ' not recognized as a PROCESSED folder') mean_fit_parameters(self.folders, folders_name=self.folders) self.notifyProgress.emit('Calibration results processing done!')
def __init__(self, dwarf_args, flags=None): super(AppWindow, self).__init__(flags) self.dwarf_args = dwarf_args self.session_manager = SessionManager(self) self.session_manager.sessionCreated.connect(self.session_created) self.session_manager.sessionStopped.connect(self.session_stopped) self.session_manager.sessionClosed.connect(self.session_closed) self.menu = self.menuBar() self._is_newer_dwarf = False self.view_menu = None self.asm_panel = None self.console_panel = None self.context_panel = None self.backtrace_panel = None self.contexts_list_panel = None self.data_panel = None self.emulator_panel = None self.ftrace_panel = None self.hooks_panel = None self.smali_panel = None self.java_inspector_panel = None self.java_explorer_panel = None self.java_trace_panel = None self.memory_panel = None self.modules_panel = None self.ranges_panel = None self.search_panel = None self.trace_panel = None self.watchers_panel = None self.welcome_window = None self._ui_elems = [] self.setWindowTitle( 'Dwarf - A debugger for reverse engineers, crackers and security analyst' ) # load external assets _app = QApplication.instance() self.remove_tmp_dir() # themes self.prefs = Prefs() self.set_theme(self.prefs.get('dwarf_ui_theme', 'black')) # set icon if os.name == 'nt': # windows stuff import ctypes try: # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\nIconResource=assets\dwarf.ico,0\n[ViewState]\nMode=\nVid=\nFolderType=Generic\n" try: with open('desktop.ini', 'w') as ini: ini.writelines(folder_stuff) FILE_ATTRIBUTE_HIDDEN = 0x02 FILE_ATTRIBUTE_SYSTEM = 0x04 # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( r'desktop.ini', FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM) except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) _app.setWindowIcon(_icon) self.setWindowIcon(_icon) except: pass else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) _app.setWindowIcon(_icon) self.setWindowIcon(_icon) # load font if os.path.exists(utils.resource_path('assets/Anton.ttf')): QFontDatabase.addApplicationFont('assets/Anton.ttf') if os.path.exists(utils.resource_path('assets/OpenSans-Regular.ttf')): QFontDatabase.addApplicationFont('assets/OpenSans-Regular.ttf') _app.setFont(QFont("OpenSans", 9, QFont.Normal)) if os.path.exists(utils.resource_path('assets/OpenSans-Bold.ttf')): QFontDatabase.addApplicationFont('assets/OpenSans-Bold.ttf') # mainwindow statusbar self.progressbar = QProgressBar() self.progressbar.setRange(0, 0) self.progressbar.setVisible(False) self.progressbar.setFixedHeight(15) self.progressbar.setFixedWidth(100) self.progressbar.setTextVisible(False) self.progressbar.setValue(30) self.statusbar = QStatusBar(self) self.statusbar.setAutoFillBackground(False) self.statusbar.addPermanentWidget(self.progressbar) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.main_tabs = QTabWidget(self) self.main_tabs.setMovable(True) self.main_tabs.setAutoFillBackground(True) self.setCentralWidget(self.main_tabs) if self.dwarf_args.package is None: self.welcome_window = WelcomeDialog(self) self.welcome_window.setModal(True) self.welcome_window.onIsNewerVersion.connect( self._enable_update_menu) self.welcome_window.onUpdateComplete.connect( self._on_dwarf_updated) self.welcome_window.setWindowTitle( 'Welcome to Dwarf - A debugger for reverse engineers, crackers and security analyst' ) self.welcome_window.onSessionSelected.connect(self._start_session) # wait for welcome screen self.hide() self.welcome_window.show() else: if dwarf_args.package is not None: if dwarf_args.type is None: # no device given check if package is local path if os.path.exists(dwarf_args.package): print('* Starting new LocalSession') self._start_session('local') else: print('use -t to set sessiontype') exit(0) else: print('* Starting new Session') self._start_session(dwarf_args.type)
def setup_ui(self): """ Setup Ui """ main_wrap = QVBoxLayout() main_wrap.setContentsMargins(0, 0, 0, 0) # updatebar on top self.update_bar = UpdateBar(self) self.update_bar.onUpdateNowClicked.connect(self._update_dwarf) self.update_bar.setVisible(False) main_wrap.addWidget(self.update_bar) # main content h_box = QHBoxLayout() h_box.setContentsMargins(15, 15, 15, 15) wrapper = QVBoxLayout() head = QHBoxLayout() head.setContentsMargins(50, 10, 0, 10) # dwarf icon icon = QLabel() icon.setPixmap(QPixmap(utils.resource_path('assets/dwarf.svg'))) icon.setAlignment(Qt.AlignCenter) icon.setMinimumSize(QSize(125, 125)) icon.setMaximumSize(QSize(125, 125)) head.addWidget(icon) # main title v_box = QVBoxLayout() title = QLabel('Dwarf') title.setContentsMargins(0, 0, 0, 0) title.setFont(QFont('Anton', 100, QFont.Bold)) title.setMaximumHeight(125) title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) title.setAlignment(Qt.AlignCenter) head.addWidget(title) sub_title_text = (self._pick_random_word(0) + ' ' + self._pick_random_word(1) + ' ' + self._pick_random_word(2) + ' ' + self._pick_random_word(3) + ' ' + self._pick_random_word(4)) sub_title_text = sub_title_text[:1].upper() + sub_title_text[1:] self._sub_title = QLabel(sub_title_text) self._sub_title.setFont(QFont('OpenSans', 16, QFont.Bold)) font_metric = QFontMetrics(self._sub_title.font()) self._char_width = font_metric.widthChar('#') self._sub_title.setAlignment(Qt.AlignCenter) self._sub_title.setContentsMargins(175, 0, 0, 20) self._sub_title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) v_box.addLayout(head) v_box.addWidget(self._sub_title) wrapper.addLayout(v_box) recent = QLabel('Last saved Sessions') font = recent.font() font.setPointSize(11) font.setBold(True) #font.setPointSize(10) recent.setFont(font) wrapper.addWidget(recent) wrapper.addWidget(self._recent_list) h_box.addLayout(wrapper, stretch=False) buttonSpacer = QSpacerItem(15, 100, QSizePolicy.Fixed, QSizePolicy.Minimum) h_box.addItem(buttonSpacer) wrapper = QVBoxLayout() btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/android.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Android Session') btn.clicked.connect(self._on_android_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/apple.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New iOS Session') btn.clicked.connect(self._on_ios_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/local.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Local Session') btn.clicked.connect(self._on_local_button) wrapper.addWidget(btn) btn = QPushButton() ico = QIcon(QPixmap(utils.resource_path('assets/remote.svg'))) btn.setIconSize(QSize(75, 75)) btn.setIcon(ico) btn.setToolTip('New Remote Session') btn.clicked.connect(self._on_remote_button) wrapper.addWidget(btn) session_history = self._prefs.get(prefs.RECENT_SESSIONS, default=[]) invalid_session_files = [] for recent_session_file in session_history: if os.path.exists(recent_session_file): with open(recent_session_file, 'r') as f: exported_session = json.load(f) hooks = '0' watchers = '0' on_loads = 0 bookmarks = '0' #have_user_script = False if 'hooks' in exported_session and exported_session[ 'hooks'] is not None: hooks = str(len(exported_session['hooks'])) if 'watchers' in exported_session and exported_session[ 'watchers'] is not None: watchers = str(len(exported_session['watchers'])) if 'nativeOnLoads' in exported_session and exported_session[ 'nativeOnLoads'] is not None: on_loads += len(exported_session['nativeOnLoads']) if 'javaOnLoads' in exported_session and exported_session[ 'javaOnLoads'] is not None: on_loads += len(exported_session['javaOnLoads']) if 'bookmarks' in exported_session and exported_session[ 'bookmarks'] is not None: bookmarks = str(len(exported_session['bookmarks'])) if 'user_script' in exported_session and exported_session[ 'user_script']: have_user_script = exported_session['user_script'] != '' #user_script_item = QStandardItem() #if have_user_script: #user_script_item.setIcon(self._dot_icon) on_loads = str(on_loads) recent_session_file_item = QStandardItem(recent_session_file) recent_session_file_item.setData(exported_session, Qt.UserRole + 2) item_1 = QStandardItem(exported_session['session']) item_1.setTextAlignment(Qt.AlignCenter) item_2 = QStandardItem(hooks) item_2.setTextAlignment(Qt.AlignCenter) item_3 = QStandardItem(watchers) item_3.setTextAlignment(Qt.AlignCenter) item_4 = QStandardItem(on_loads) item_4.setTextAlignment(Qt.AlignCenter) item_5 = QStandardItem(bookmarks) item_5.setTextAlignment(Qt.AlignCenter) #item_6 = QStandardItem(user_script_item) #item_6.setTextAlignment(Qt.AlignCenter) self._recent_list_model.insertRow( self._recent_list_model.rowCount(), [ recent_session_file_item, item_1, item_2, item_3, item_4, item_5 ]) else: invalid_session_files.append(recent_session_file) for invalid in invalid_session_files: session_history.pop(session_history.index(invalid)) self._prefs.put(prefs.RECENT_SESSIONS, session_history) h_box.addLayout(wrapper, stretch=False) main_wrap.addLayout(h_box) self.setLayout(main_wrap)
def compute_initial_figure(self): parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) rdcp = eval( config.get('OPS processing parameters', 'relative_distance_correction_prameters')) self.fig.clear() color_A = '#018BCF' color_B = self.color = '#CF2A1B' time_SA = self.x_IN_A time_SB = self.x_OUT_A offset = 0 ax1 = self.fig.add_subplot(2, 1, 1) ax1.axhspan(rdcp[1], rdcp[0], color='black', alpha=0.1) for i in np.arange(0, time_SA.shape[0] - 1): distances_A = np.diff(time_SA[i])[offset:time_SA[i].size - 1 - offset] rel_distances_A = np.divide(distances_A[1::], distances_A[0:distances_A.size - 1]) distances_B = np.diff(time_SB[i])[offset:time_SB[i].size - 1 - offset] rel_distances_B = np.divide(distances_B[1::], distances_B[0:distances_B.size - 1]) ax1.plot(1e3 * time_SA[i][offset:time_SA[i].size - 2 - offset], rel_distances_A, '.', color=color_A) ax1.plot(1e3 * time_SB[i][offset:time_SB[i].size - 2 - offset], rel_distances_B, '.', color=color_B) ax1.set_xlabel('Time (' + '\u03BC' + 's)') ax1.set_ylabel('Relative distance') ax1.set_title('RDS plot - IN', loc='left') red_patch = mpatches.Patch(color=color_A, label='Sensor A') blue_patch = mpatches.Patch(color=color_B, label='Sensor B') ax1.legend(handles=[blue_patch, red_patch]) prairie.style(ax1) time_SA = self.y_IN_A time_SB = self.y_OUT_A ax2 = self.fig.add_subplot(2, 1, 2) ax2.axhspan(rdcp[1], rdcp[0], color='black', alpha=0.1) for i in np.arange(0, time_SA.shape[0] - 1): distances_A = np.diff(time_SA[i])[offset:time_SA[i].size - 1 - offset] rel_distances_A = np.divide(distances_A[1::], distances_A[0:distances_A.size - 1]) distances_B = np.diff(time_SB[i])[offset:time_SB[i].size - 1 - offset] rel_distances_B = np.divide(distances_B[1::], distances_B[0:distances_B.size - 1]) ax2.plot(1e3 * time_SA[i][offset:time_SA[i].size - 2 - offset], rel_distances_A, '.', color=color_A) ax2.plot(1e3 * time_SB[i][offset:time_SB[i].size - 2 - offset], rel_distances_B, '.', color=color_B) ax2.set_xlabel('Time (' + '\u03BC' + 's)') ax2.set_ylabel('Relative distance') ax2.set_title('RDS plot - OUT', loc='left') red_patch = mpatches.Patch(color=color_A, label='Sensor A') blue_patch = mpatches.Patch(color=color_B, label='Sensor B') ax2.legend(handles=[blue_patch, red_patch]) prairie.style(ax2) self.fig.tight_layout()
def compute_initial_figure(self): self.fig.clear() laser_position = self.y_IN_A occlusion_position = self.x_IN_A if self.in_or_out is 'IN': self.color = '#018BCF' elif self.in_or_out is 'OUT': self.color = '#CF2A1B' occlusion_position = np.pi / 2 - occlusion_position parameter_file = utils.resource_path('data/parameters.cfg') config = configparser.RawConfigParser() config.read(parameter_file) positions_for_fit = eval( config.get('OPS processing parameters', 'positions_for_fit')) positions_for_analysis = eval( config.get('OPS processing parameters', 'positions_for_analysis')) tank_center = eval( config.get('OPS processing parameters', 'offset_center')) self.idxs = np.argsort(laser_position) occlusion_position = occlusion_position[self.idxs] laser_position = laser_position[self.idxs] self.focus = np.where(self.idxs == self.focus)[0] laser_position = -laser_position + tank_center self.y_IN_A = laser_position self.x_IN_A = occlusion_position unique_laser_position = np.unique(laser_position) occlusion_position_mean = [] for laser_pos in unique_laser_position: occlusion_position_mean.append( np.mean(occlusion_position[np.where( laser_position == laser_pos)[0]])) off1 = [ int(positions_for_fit[0] / 100 * unique_laser_position.size), int(positions_for_fit[1] / 100 * unique_laser_position.size) ] occlusion_position_mean = np.asarray(occlusion_position_mean) popt, pcov = curve_fit(utils.theoretical_laser_position, occlusion_position_mean[off1[0]:off1[1]], unique_laser_position[off1[0]:off1[1]], bounds=([-5, 80, 100], [5, 500, 500])) theorical_laser_position_mean = utils.theoretical_laser_position( occlusion_position_mean, popt[0], popt[1], popt[2]) theoretical_laser_position = utils.theoretical_laser_position( occlusion_position, popt[0], popt[1], popt[2]) param = popt off2 = [ int(positions_for_analysis[0] / 100 * laser_position.size), int(positions_for_analysis[1] / 100 * laser_position.size) ] laser_position = laser_position[off2[0]:off2[1]] theoretical_laser_position = theoretical_laser_position[ off2[0]:off2[1]] occlusion_position = occlusion_position[off2[0]:off2[1]] residuals = laser_position - theoretical_laser_position plt.figure(figsize=(6.5, 7.5)) prairie.use() ax2 = self.fig.add_subplot(2, 2, 4) residuals = residuals[off2[0]:off2[1]] dt.make_histogram(1e3 * residuals, [-300, 300], '\u03BCm', axe=ax2, color=self.color) ax2.set_title('Wire position error histogram', loc='left') ax2.set_xlabel('Wire position error (\u03BCm)') ax2.set_ylabel('Occurrence') prairie.style(ax2) ax3 = self.fig.add_subplot(2, 2, 3) ax3.plot(laser_position, 1e3 * residuals, '.', color=self.color, markersize=1.5) ax3.set_ylim([-300, 300]) ax3.set_title('Wire position error', loc='left') ax3.set_ylabel('Wire position error (\u03BCm)') ax3.set_xlabel('Laser position (mm)') prairie.style(ax3) equation = "{:3.2f}".format(param[1]) + '-' + "{:3.2f}".format( param[2]) + '*' + 'cos(\u03C0-x+' + "{:3.2f}".format( param[0]) + ')' legend = 'Theoretical Wire position: ' + equation self.ax1 = self.fig.add_subplot(2, 1, 1) self.ax1.plot(occlusion_position_mean, theorical_laser_position_mean, linewidth=0.5, color='black') self.ax1.plot(occlusion_position, laser_position, '.', color=self.color, markersize=4) self.foc_marker, = self.ax1.plot(occlusion_position[self.focus], laser_position[self.focus], 'o', color=self.color, fillstyle='none', markersize=10) self.ax1.legend([legend, 'Measured positions']) # ax1.set_title(folder_name + ' ' + in_or_out + '\n\n\n Theoretical wire positions vs. measured positions', # loc='left') self.ax1.set_title('Theoretical wire positions vs. measured positions', loc='left') self.ax1.set_xlabel('Angular position at laser crossing (rad)') self.ax1.set_ylabel('Laser position (mm)') prairie.style(self.ax1) # ax4 = plt.subplot2grid((3, 2), (2, 0), colspan=2) # ax4.plot(1e3 * residuals, '.', color=color, markersize=1.5) # ax4.plot(1e3 * residuals, color=color, linewidth=0.5) # ax4.set_title('Wire position error over scans', loc='left') # ax4.set_ylabel('Wire position error (\u03BCm)') # ax4.set_xlabel('Scan #') # prairie.apply(ax4) # # plt.tight_layout() # ax1 = self.fig.add_subplot(2, 1, 1) # ax1.set_title('Position error and eccentricity compensation - IN', loc='left') # ax1.set_xlabel('Angular position (rad)') # ax1.set_ylabel('Position error (rad)') # ax1.plot(self.x1, self.y1) # ax1.set_xlim([self.x1[0], self.x1[::-1][0]]) # prairie.apply(ax1) # # print(self.x1) # # ax2 = self.fig.add_subplot(2, 1, 2) # ax2.set_title('Position error and eccentricity compensation - OUT', loc='left') # ax2.set_xlabel('Angular position (rad)') # ax2.set_ylabel('Position error (rad)') # ax2.plot(self.x2, self.y2) # ax2.set_xlim([self.x2[0], self.x2[::-1][0]]) # prairie.apply(ax2) self.fig.tight_layout()
def __init__(self, parent=None): # pylint: disable=too-many-statements super(BookmarksPanel, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('BookmarksPanel created before Dwarf exists') return self._bookmarks_list = DwarfListView() self._bookmarks_list.doubleClicked.connect(self._on_dblclicked) self._bookmarks_list.setContextMenuPolicy(Qt.CustomContextMenu) self._bookmarks_list.customContextMenuRequested.connect( self._on_contextmenu) self._bookmarks_model = QStandardItemModel(0, 2) self._bookmarks_model.setHeaderData(0, Qt.Horizontal, 'Address') self._bookmarks_model.setHeaderData(1, Qt.Horizontal, 'Notes') self._bookmarks_list.setModel(self._bookmarks_model) self._bookmarks_list.header().setStretchLastSection(False) self._bookmarks_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents | QHeaderView.Interactive) self._bookmarks_list.header().setSectionResizeMode( 1, QHeaderView.Stretch | QHeaderView.Interactive) v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) v_box.addWidget(self._bookmarks_list) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) self.btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') self.btn1.setFixedSize(20, 20) self.btn1.clicked.connect(lambda: self._create_bookmark(-1)) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(self.btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) self.setLayout(v_box) self._bold_font = QFont(self._bookmarks_list.font()) self._bold_font.setBold(True) shortcut_addnative = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_A), self._app_window, self._create_bookmark) shortcut_addnative.setAutoRepeat(False)
def compute_initial_figure(self): self.fig.clear() color_IN = '#018BCF' color_OUT = '#CF2A1B' black = [0.3, 0.3, 0.3] parameter_file = utils.resource_path('data/parameters.cfg') if len(self.x_IN_A) == 200: ax1 = self.fig.add_subplot(2, 2, 1) ax1.plot(self.t1, self.x_IN_A, linewidth=0.5) prairie.style(ax1) ax2 = self.fig.add_subplot(2, 2, 2) ax2.plot(self.t1, self.y_IN_A, linewidth=0.5) prairie.style(ax2) ax3 = self.fig.add_subplot(2, 2, 3) ax3.plot(self.t2, self.x_OUT_A, linewidth=0.5) prairie.style(ax3) ax4 = self.fig.add_subplot(2, 2, 4) ax4.plot(self.t2, self.y_OUT_A, linewidth=0.5) prairie.style(ax4) self.fig.tight_layout() else: P = ops.process_position(self.x_IN_A, parameter_file, self.t1[0], return_processing=True) ax1 = self.fig.add_subplot(3, 2, 1) ax1.axhspan(0, P[8], color='black', alpha=0.05) ax1.plot(1e-3 * P[0], P[1], linewidth=0.5) ax1.plot(1e-3 * P[2], P[3], '.', markersize=2) ax1.plot(1e-3 * P[4], P[5], '.', markersize=2) ax1.plot(1e-3 * P[6], P[7], '-', linewidth=0.5, color=black) ax1.set_title('OPS processing SA - IN', loc='left') ax1.set_xlabel('Time (s)') ax1.set_ylabel('Normalized amplitude') ax1.legend(['OPS data', 'Maxs', 'Mins', 'Threshold']) prairie.style(ax1) P = ops.process_position(self.y_IN_A, parameter_file, self.t1[0], return_processing=True) ax2 = self.fig.add_subplot(3, 2, 3) ax2.axhspan(0, P[8], color='black', alpha=0.05) ax2.plot(1e-3 * P[0], P[1], linewidth=0.5) ax2.plot(1e-3 * P[2], P[3], '.', markersize=2) ax2.plot(1e-3 * P[4], P[5], '.', markersize=2) ax2.plot(1e-3 * P[6], P[7], '-', linewidth=0.5, color=black) ax2.set_title('OPS processing SB - IN', loc='left') ax2.set_xlabel('Time (s)') ax2.set_ylabel('Normalized amplitude') prairie.style(ax2) P = ops.process_position(self.x_OUT_A, parameter_file, self.t2[0], return_processing=True) ax3 = self.fig.add_subplot(3, 2, 2) ax3.axhspan(0, P[8], color='black', alpha=0.05) ax3.plot(1e-3 * P[0], P[1], linewidth=0.5) ax3.plot(1e-3 * P[2], P[3], '.', markersize=2) ax3.plot(1e-3 * P[4], P[5], '.', markersize=2) ax3.plot(1e-3 * P[6], P[7], '-', linewidth=0.5, color=black) ax3.set_title('OPS processing SA - OUT', loc='left') ax3.set_xlabel('Time (s)') ax3.set_ylabel('Normalized amplitude') prairie.style(ax3) P = ops.process_position(self.y_OUT_A, parameter_file, self.t2[0], return_processing=True) ax4 = self.fig.add_subplot(3, 2, 4) ax4.axhspan(0, P[8], color='black', alpha=0.05) ax4.plot(1e-3 * P[0], P[1], linewidth=0.5) ax4.plot(1e-3 * P[2], P[3], '.', markersize=2) ax4.plot(1e-3 * P[4], P[5], '.', markersize=2) ax4.plot(1e-3 * P[6], P[7], '-', linewidth=0.5, color=black) ax4.set_title('OPS processing SB - OUT', loc='left') ax4.set_xlabel('Time (s)') ax4.set_ylabel('Normalized amplitude') prairie.style(ax4) occ_IN = ops.find_occlusions(self.pd1, IN=True, StartTime=self.t1[0], return_processing=True) occ_OUT = ops.find_occlusions(self.pd2, IN=False, StartTime=self.t2[0], return_processing=True) ax5 = self.fig.add_subplot(3, 2, 5) ax5.set_title('Processing PH - IN', loc='left') ax5.set_xlabel('Time (s)') ax5.set_ylabel('a.u.') ax5.plot(self.t1, self.pd1, linewidth=1) ax5.plot(occ_IN[0], occ_IN[1], '.', markersize=3, color=black) ax5.legend(['PD data', 'Detected occlusions']) prairie.style(ax5) ax6 = self.fig.add_subplot(3, 2, 6) ax6.set_title('Processing PH - OUT', loc='left') ax6.set_xlabel('Time (s)') ax6.set_ylabel('a.u.') ax6.plot(self.t2, self.pd2, linewidth=1) ax6.plot(occ_OUT[0], occ_OUT[1], '.', markersize=3, color=black) prairie.style(ax6) self.fig.tight_layout()
def __init__(self, dwarf_args, flags=None): super(AppWindow, self).__init__(flags) self.dwarf_args = dwarf_args self.session_manager = SessionManager(self) self.session_manager.sessionCreated.connect(self.session_created) self.session_manager.sessionStopped.connect(self.session_stopped) self.session_manager.sessionClosed.connect(self.session_closed) self._tab_order = [ 'debug', 'modules', 'ranges', 'jvm-inspector', 'jvm-debugger' ] self._is_newer_dwarf = False self.q_settings = QSettings("dwarf_window_pos.ini", QSettings.IniFormat) self.menu = self.menuBar() self.view_menu = None self._initialize_ui_elements() self.setWindowTitle( 'Dwarf - A debugger for reverse engineers, crackers and security analyst' ) # load external assets _app = QApplication.instance() self.remove_tmp_dir() # themes self.prefs = Prefs() utils.set_theme(self.prefs.get('dwarf_ui_theme', 'black'), self.prefs) # load font if os.path.exists(utils.resource_path('assets/Anton.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/Anton.ttf')) if os.path.exists(utils.resource_path('assets/OpenSans-Regular.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/OpenSans-Regular.ttf')) font = QFont("OpenSans", 9, QFont.Normal) # TODO: add settingsdlg font_size = self.prefs.get('dwarf_ui_font_size', 12) font.setPixelSize(font_size) _app.setFont(font) if os.path.exists(utils.resource_path('assets/OpenSans-Bold.ttf')): QFontDatabase.addApplicationFont( utils.resource_path('assets/OpenSans-Bold.ttf')) # mainwindow statusbar self.progressbar = QProgressBar() self.progressbar.setRange(0, 0) self.progressbar.setVisible(False) self.progressbar.setFixedHeight(15) self.progressbar.setFixedWidth(100) self.progressbar.setTextVisible(False) self.progressbar.setValue(30) self.statusbar = QStatusBar(self) self.statusbar.setAutoFillBackground(False) self.statusbar.addPermanentWidget(self.progressbar) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.main_tabs = QTabWidget(self) self.main_tabs.setMovable(False) self.main_tabs.setTabsClosable(True) self.main_tabs.setAutoFillBackground(True) self.main_tabs.tabCloseRequested.connect(self._on_close_tab) self.setCentralWidget(self.main_tabs) # pluginmanager self.plugin_manager = PluginManager(self) self.plugin_manager.reload_plugins() if dwarf_args.any == '': self.welcome_window = WelcomeDialog(self) self.welcome_window.setModal(True) self.welcome_window.onIsNewerVersion.connect( self._enable_update_menu) self.welcome_window.onUpdateComplete.connect( self._on_dwarf_updated) self.welcome_window.setWindowTitle( 'Welcome to Dwarf - A debugger for reverse engineers, crackers and security analyst' ) self.welcome_window.onSessionSelected.connect(self._start_session) # wait for welcome screen self.hide() self.welcome_window.show() else: print('* Starting new Session') self._start_session(dwarf_args.target)
def run_dwarf(): """ fire it up """ #os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" os.environ["QT_SCALE_FACTOR"] = "1" os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "0" os.environ["QT_SCREEN_SCALE_FACTORS"] = "1" args = process_args() #_check_dependencies() # not enabled atm from lib import utils from lib.git import Git from lib.prefs import Prefs from ui.app import AppWindow _prefs = Prefs() local_update_disabled = _prefs.get('disable_local_frida_update', False) if not local_update_disabled: _git = Git() import frida remote_frida = _git.get_frida_version() local_frida = frida.__version__ if remote_frida and local_frida != remote_frida[0]['tag_name']: print('Updating local frida version to ' + remote_frida[0]['tag_name']) try: res = utils.do_shell_command('pip3 install frida --upgrade --user') if 'Successfully installed frida-' + remote_frida[0]['tag_name'] in res: _on_restart() elif 'Requirement already up-to-date' in res: if os.path.exists('.git_cache'): shutil.rmtree('.git_cache', ignore_errors=True) else: print('failed to update local frida') print(res) except Exception as e: # pylint: disable=broad-except, invalid-name print('failed to update local frida') print(str(e)) if os.name == 'nt': # windows stuff import ctypes try: # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\n" folder_stuff += "IconResource=assets\\dwarf.ico,0\n" folder_stuff += "[ViewState]\n" folder_stuff += "Mode=\n" folder_stuff += "Vid=\n" folder_stuff += "FolderType=Generic\n" try: with open('desktop.ini', 'w') as ini: ini.writelines(folder_stuff) # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( r'desktop.ini', 0x02 | 0x04 ) # FILE_ATTRIBUTE_HIDDEN = 0x02 | FILE_ATTRIBUTE_SYSTEM = 0x04 except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) ctypes.windll.user32.SetProcessDPIAware() except Exception: # pylint: disable=broad-except pass from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication qapp = QApplication([]) qapp.setDesktopSettingsAware(True) qapp.setAttribute(Qt.AA_EnableHighDpiScaling) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) qapp.setLayoutDirection(Qt.LeftToRight) qapp.setOrganizationName("https://github.com/iGio90/Dwarf") qapp.setApplicationName("dwarf") # set icon if os.name == "nt" and os.path.exists( utils.resource_path('assets/dwarf.ico')): _icon = QIcon(utils.resource_path('assets/dwarf.ico')) qapp.setWindowIcon(_icon) else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) qapp.setWindowIcon(_icon) app_window = AppWindow(args) app_window.setWindowIcon(_icon) app_window.onRestart.connect(_on_restart) try: sys.exit(qapp.exec_()) except SystemExit as sys_err: if sys_err.code == 0: # thanks for using dwarf print('Thank\'s for using Dwarf\nHave a nice day...') else: # something was wrong print('sysexit with: %d' % sys_err.code)