def initializeUI(self): self.mainWidget = QWidget() #Size self.resize(1024,768) #MenuBar menuBar = QMenuBar() self.fileMenu = DSPToolFileMenu(self) menuBar.addMenu(self.fileMenu) self.signalMenu = DSPToolSignalsMenu(self) menuBar.addMenu(self.signalMenu) self.setMenuBar(menuBar) #Table Widget self.table = QTableWidget() self.table.setFixedWidth(824) scrollTable = QScrollArea() scrollTable.setWidget(self.table) scrollTable.setWidgetResizable(True) #Side and Property Bar self.sideBar = SideBar() self.propertyBar = PropertyBar(self) #Layouts hLayout = QHBoxLayout() hLayout.addWidget(self.table) hLayout.addWidget(self.sideBar) hWidget = QWidget() hWidget.setLayout(hLayout) vLayout = QVBoxLayout() vLayout.addWidget(hWidget) vLayout.addWidget(self.propertyBar) self.mainWidget.setLayout(vLayout) self.setCentralWidget(self.mainWidget) #Signals self.table.cellClicked.connect(self.oneClickedEvent)
def __init__(self): QMainWindow.__init__(self) self.project = None menuBar = QMenuBar() self.fileMenu = DSPToolFileMenu(self) menuBar.addMenu(self.fileMenu) self.signalMenu = DSPToolSignalsMenu(self) menuBar.addMenu(self.signalMenu) self.setMenuBar(menuBar) self.mainWidget=QTableWidget() self.mainWidget.setRowCount(0) self.mainWidget.setColumnCount(0) scrollWidget = QScrollArea() scrollWidget.setWidget(self.mainWidget) scrollWidget.setWidgetResizable(True) self.setCentralWidget(scrollWidget)
class ConfigEditor(QMainWindow): def __init__(self, app, cfg, title='Config Editor'): super(ConfigEditor, self).__init__() self.app = app self.config = cfg self.title = title def setup(self): self.dirty = False self.def_cfg = copy.deepcopy(self.config) self.config.update_from_user_file() self.base_cfg = copy.deepcopy(self.config) self.categories = QListWidget() #self.categories.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding) self.settings = QStackedWidget() #self.categories.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Expanding) QObject.connect(self.categories, SIGNAL('itemSelectionChanged()'), self.category_selected) self.widget_list = {} for cat in self.config.get_categories(): self.widget_list[cat] = {} longest_cat = 0 for cat in self.config.get_categories(): if len(cat) > longest_cat: longest_cat = len(cat) self.categories.addItem(cat) settings_layout = QGridLayout() r = 0 c = 0 for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) s = QWidget() s.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) sl = QVBoxLayout() label = QLabel() if info.has_key('alias'): label.setText(info['alias']) else: label.setText(setting) if info.has_key('about'): label.setToolTip(info['about']) sl.addWidget(label) if info['type'] == constants.CT_LINEEDIT: w = LineEdit(self, self.config,cat,setting,info) elif info['type'] == constants.CT_CHECKBOX: w = CheckBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_SPINBOX: w = SpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_DBLSPINBOX: w = DoubleSpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_COMBO: w = ComboBox(self, self.config,cat,setting,info) w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) self.widget_list[cat][setting] = w sl.addWidget(w) s.setLayout(sl) c = self.config.config[cat].index(setting) % 2 settings_layout.addWidget(s, r, c) if c == 1: r += 1 settings = QWidget() settings.setLayout(settings_layout) settings_scroller = QScrollArea() settings_scroller.setWidget(settings) settings_scroller.setWidgetResizable(True) self.settings.addWidget(settings_scroller) font = self.categories.font() fm = QFontMetrics(font) self.categories.setMaximumWidth(fm.widthChar('X')*(longest_cat+4)) self.main = QWidget() self.main_layout = QVBoxLayout() self.config_layout = QHBoxLayout() self.config_layout.addWidget(self.categories) self.config_layout.addWidget(self.settings) self.mainButtons = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Reset | QDialogButtonBox.Apply) self.main_apply = self.mainButtons.button(QDialogButtonBox.StandardButton.Apply) self.main_reset = self.mainButtons.button(QDialogButtonBox.StandardButton.Reset) self.main_defaults = self.mainButtons.button(QDialogButtonBox.StandardButton.LastButton) QObject.connect(self.mainButtons, SIGNAL('clicked(QAbstractButton *)'), self.mainbutton_clicked) self.dirty_check() self.main_layout.addLayout(self.config_layout) self.main_layout.addWidget(self.mainButtons) self.main.setLayout(self.main_layout) self.setCentralWidget(self.main) self.setWindowTitle(self.title) self.setUnifiedTitleAndToolBarOnMac(True) self.categories.setCurrentItem(self.categories.item(0)) self.menuBar = QMenuBar() self.filemenu = QMenu('&File') self.quitAction = QAction(self) self.quitAction.setText('&Quit') if platform.system() != 'Darwin': self.quitAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q)) QObject.connect(self.quitAction, SIGNAL('triggered()'), self.quitApp) self.filemenu.addAction(self.quitAction) self.menuBar.addMenu(self.filemenu) self.setMenuBar(self.menuBar) self.show() self.activateWindow() self.raise_() self.setMinimumWidth(self.geometry().width()*1.2) screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) def category_selected(self): self.settings.setCurrentIndex(self.config.config.index(self.categories.selectedItems()[0].text())) def mainbutton_clicked(self, button): if button == self.main_reset: for cat in self.base_cfg.get_categories(): for setting in self.base_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.base_cfg.get_setting(cat,setting)) elif button == self.main_defaults: for cat in self.def_cfg.get_categories(): for setting in self.def_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.def_cfg.get_setting(cat,setting)) elif button == self.main_apply: bad_settings = self.validate_settings() if bad_settings == []: self.save_settings() self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) else: msgBox = QMessageBox() msgBox.setText("Must fix the following invalid settings before quitting:") msgBox.setStandardButtons(QMessageBox.Ok) info = '' for setting in bad_settings: new = '%s,%s<br>' % setting info = '%s%s' % (info, new) msgBox.setInformativeText(info) msgBox.exec_() def quitApp(self): self.app.closeAllWindows() def get_changes(self): enc = MyEncoder() if enc.encode(self.def_cfg.config) == enc.encode(self.config.config): return False if enc.encode(self.base_cfg.config) != enc.encode(self.config.config): newC = Config() for c in self.config.config.keys(): for s in self.config.config[c].keys(): if self.config.config[c][s]['value'] != self.def_cfg.config[c][s]['value']: newC.add_setting(c, s, self.config.config[c][s]['value'], stub=True) return json.dumps(newC.config, separators=(',',': '), indent=4, sort_keys=True) else: return None def validate_settings(self): ret = [] for cat in self.config.get_categories(): for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) if info.has_key('validate'): if not info['validate'](info): ret.append((cat,setting)) return ret def dirty_check(self): if str(self.base_cfg) != str(self.config): self.dirty = True self.main_apply.setEnabled(True) self.main_reset.setEnabled(True) else: self.dirty = False self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) if str(self.def_cfg) == str(self.config): self.main_defaults.setEnabled(False) else: self.main_defaults.setEnabled(True) def save_settings(self): config = self.get_changes() if config == False: if os.path.isfile(self.config.user_file): os.remove(self.config.user_file) elif config != None: with open(self.config.user_file, 'w+') as f: f.write(config) self.base_cfg = copy.deepcopy(self.config) def closeEvent(self, event=None): self.quitApp()
class ClassyWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QVBoxLayout(self) horiz_layout = QHBoxLayout() self.conditional_legend_widget = EdgeWidget(self, True) self.conditional_legend_widget.setMinimumHeight(15) horiz_layout.addWidget(self.conditional_legend_widget) self.conditional_legend_label = QLabel("Conditional transition", self) horiz_layout.addWidget(self.conditional_legend_label) self.unconditional_legend_widget = EdgeWidget(self, False) self.unconditional_legend_widget.setMinimumHeight(15) horiz_layout.addWidget(self.unconditional_legend_widget) self.unconditional_legend_label = QLabel("Non-conditional transition", self) horiz_layout.addWidget(self.unconditional_legend_label) layout.addLayout(horiz_layout) self.splitter = QSplitter(self) layout.addWidget(self.splitter) self.view = ClassyView(self.splitter) # layout.addWidget(self.view) self.scene = ClassyScene(self) self.view.setScene(self.scene) self._menu_bar = QMenuBar(self) self._menu = QMenu("&File") self._menu_bar.addMenu(self._menu) layout.setMenuBar(self._menu_bar) self.open_action = QAction("O&pen", self) self.exit_action = QAction("E&xit", self) self._menu.addAction(self.open_action) self._menu.addAction(self.exit_action) self.connect(self.open_action, SIGNAL("triggered()"), self.open_file) self.connect(self.exit_action, SIGNAL("triggered()"), self.close) self.settings = QSettings("CD Projekt RED", "TweakDB") self.log_window = QPlainTextEdit(self.splitter) self.splitter.setOrientation(Qt.Vertical) self.setWindowTitle("Classy nodes") @Slot() def open_file(self): last_dir = self.settings.value("last_dir") if last_dir is None: last_dir = '' # noinspection PyCallByClass file_path = QFileDialog.getOpenFileName(self, "Select tweakdb file", last_dir, "*.tweak") if file_path[0]: tweak_file = file_path[0] self.settings.setValue("last_dir", os.path.dirname(tweak_file)) else: return try: self._process_db_file(file_path[0]) except Exception as e: # noinspection PyCallByClass QMessageBox.critical( self, "Error", "Error while loading {0}: {1}".format(file_path, str(e))) self.setWindowTitle("Classy nodes - {0}".format(file_path[0])) @Slot(str) def log(self, value): self.log_window.appendPlainText(str(value)) self.log_window.verticalScrollBar().scroll( 0, self.log_window.verticalScrollBar().maximum()) def _process_db_file(self, file_path): class TweakClass(object): def __init__(self, name, base=""): self.name = name self.base = base self.transitions_to = [] self.transitions_conditions = [] def has_transition(self, name): return name in self.transitions_to def transition_conditional(self, name): if len(self.transitions_to) != len( self.transitions_conditions): raise ValueError( "Transitions length does not match conditions length in {0}" .format(self.name)) if name not in name: raise ValueError( "Class {0} has no transition to {1}".format( self.name, name)) return self.transitions_conditions[self.transitions_to.index( name)] with open(file_path, "r") as f: contents = f.read() lines = contents.split("\n") is_in_class = False is_class_declared = False current_class = None classes = {} parsed_line = 0 for line in lines: parsed_line += 1 if line.startswith("package"): continue if line.startswith("using"): continue if not line.strip(): continue if line.startswith("//"): continue if not is_in_class and not is_class_declared: if line.find("=") > 0: # static variable continue spl = [x.strip() for x in line.strip().split(":")] if len(spl) == 1: c = TweakClass(spl[0]) else: c = TweakClass(spl[0], spl[1]) is_class_declared = True current_class = c classes[c.name] = c continue if not is_in_class and not line.find("{") >= 0: raise ValueError( "Failed to parse the file {0} in line: {1}".format( file_path, parsed_line)) else: is_in_class = True if line.find("}") >= 0: is_in_class = False is_class_declared = False continue if re.match(".+transitionTo( +||\t+)+=( +||\t+)+\[.+\]$", line.strip()): spl = line.split("=")[1].strip()[1:-1] transitions = [x.strip().strip("\"") for x in spl.split(",")] current_class.transitions_to = transitions continue if re.match(".+transitionCondition( +||\t+)+=( +||\t+)+\[.+\]$", line.strip()): spl = "=".join(line.split("=")[1:]).strip()[1:-1] transitions = [x.strip().strip("\"") for x in spl.split(",")] current_class.transitions_conditions = [ True if x.strip() == '=' else False for x in transitions ] continue self.scene.clear() # --- Create nodes for node_key in classes: # g.add_node(str(node_key), # shape_fill="#aaaa33", # shape="roundrectangle", # font_style="bolditalic", # label=classes.get(node_key).name) self.scene.add_node(node_key) edges_created = [] # --- Create edges for node_key in classes: # --- Get each node current_node = classes.get(node_key) # --- Iterate it's "transition_to" list for t in current_node.transitions_to: # --- Find node to create transition edge to transition_to_node = classes.get(t) if transition_to_node is None: self.log("Invalid transition in class {0} -> {1}".format( node_key, t)) continue # --- Check if it's a two way transition two_way = False if transition_to_node.has_transition(node_key): two_way = True # --- make sure that these edges were not created yet edges_to_create = ["{0}!@#{1}".format(node_key, t)] if two_way: edges_to_create = ["{0}!@#{1}".format(t, node_key)] edge_already_created = False for e in edges_to_create: if e in edges_created: edge_already_created = True break if edge_already_created: continue # --- Check if the transitions are conditional or not try: conditional_to = current_node.transition_conditional(t) except ValueError as e: self.log(str(e)) continue conditional_from = False if two_way: conditional_from = transition_to_node.transition_conditional( node_key) self.scene.add_edge(current_node.name, transition_to_node.name, conditional_to=conditional_to, two_way=two_way, conditional_from=conditional_from) edges_created += edges_to_create self.scene.layout_nodes()
class MainWindow(QDialog): """monkey_linux UI""" def __init__(self,parent=None): super(MainWindow, self).__init__() self.init_conf() self.setParent(parent) common.Log.info("set up ui") self.setup_ui() self.findDeviceAction.triggered.connect(self.get_device_status) self.deleteDeviceAction.triggered.connect(self.del_device) # self.storeButton.clicked.connect(self.set_conf) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stop) self.checkLogButton.clicked.connect(self.check) self.monkeyButton.clicked.connect(self.checkMonkeyLog) self.exportButton.clicked.connect(self.exportConf) self.importButton.clicked.connect(self.importConf) self.setAbout.triggered.connect(self.about) self.startTime = datetime.datetime.now() self.secsTime = float(1) * 60 * 60 def setup_ui(self): # main window width hand height # self.setMinimumWidth(600) self.setMaximumWidth(800) self.setMinimumHeight(600) # main window title self.setWindowTitle(static.title) # file menu bar self.menuBar = QMenuBar() self.menuBar.setMaximumHeight(23) # self.menuFile = self.menuBar.addMenu(static.menuFile) # self.importAction = QAction(QIcon(static.importPNG), static.importFile, self) # self.exportAction = QAction(QIcon(static.exportPNG), static.exportFile, self) # self.menuFile.addAction(self.importAction) # self.menuFile.addAction(self.exportAction) self.setEnvActioin = QAction(QIcon(static.setPNG), static.pcSet, self) self.menuSet = self.menuBar.addMenu(static.menuSet) self.menuSet.addAction(self.setEnvActioin) self.setAbout = QAction(QIcon(static.setPNG), static.menuAbout, self) self.setAbout.setStatusTip('About') # 状态栏提示 self.menuHelp = self.menuBar.addMenu(static.menuHelp) self.menuHelp.addAction(self.setAbout) # set all layout self.hbox = QHBoxLayout(self) # device ======== self.topLeft = QFrame(self) self.topLeft.setMaximumSize(218, 300) self.topLeft.setMinimumSize(218, 200) self.topLeft.setFrameShape(QFrame.StyledPanel) self.topLeftLayout = QVBoxLayout(self.topLeft) self.toolBar = QToolBar() # self.androidDeviceAction = QRadioButton('Android', self) # self.androidDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction = QRadioButton('IP', self) # self.ipDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction.move(10, 10) # self.ipDeviceAction.toggle() self.findDeviceAction = QAction(QIcon(static.findDevice), static.findDeviceButton, self) self.deleteDeviceAction = QAction(QIcon(static.deleteDevice), static.deleteDeviceButton, self) # self.toolBar.addWidget(self.androidDeviceAction) # self.toolBar.addWidget(self.ipDeviceAction) self.toolBar.addAction(self.findDeviceAction) self.toolBar.addAction(self.deleteDeviceAction) self.deviceLab = QLabel(static.deviceName, self) self.device = QTableWidget(1, 2) self.device.setHorizontalHeaderLabels(['name', 'status']) self.device.setColumnWidth(0, 100) self.device.setColumnWidth(1, 80) self.topLeftLayout.addWidget(self.deviceLab) self.topLeftLayout.addWidget(self.toolBar) self.topLeftLayout.addWidget(self.device) # set button or other for running monkey or not and status of device and log ======== self.topRight = QFrame(self) self.topRight.setFrameShape(QFrame.StyledPanel) self.topRight.setMaximumHeight(40) self.startButton = QPushButton(QIcon(static.startPNG), "") self.stopButton = QPushButton(QIcon(static.stopPNG), "") self.status = QLabel(static.status) self.statusEdit = QLineEdit(self) self.statusEdit.setReadOnly(True) self.statusEdit.setMaximumWidth(80) self.statusEdit.setMinimumWidth(80) self.statusEdit.setText("") # check log self.checkLogButton = QPushButton(static.checkLog) self.checkLogButton.setMaximumHeight(20) self.checkLogButton.setMinimumHeight(20) self.checkLogButton.setMaximumWidth(60) self.selectLog = QLabel(static.selectlog) self.logfile = QComboBox() self.dirlist = os.listdir(os.path.join(DIR, "Result")) for d in self.dirlist: if d != "AutoMonkey.log": self.logfile.insertItem(0, d) self.logfile.setMaximumWidth(150) self.logfile.setMaximumHeight(20) self.logfile.setMinimumHeight(20) self.topLayout = QHBoxLayout(self.topRight) self.topLayout.addWidget(self.startButton) self.topLayout.addWidget(self.stopButton) self.topLayout.addWidget(self.status) self.topLayout.addWidget(self.statusEdit) self.topLayout.addWidget(self.selectLog) self.topLayout.addWidget(self.logfile) self.topLayout.addWidget(self.checkLogButton) # set parameter for monkey ======= self.midRight = QFrame(self) self.midRight.setMaximumSize(555, 200) self.midRight.setMinimumSize(555, 200) self.midRight.setFrameShape(QFrame.StyledPanel) self.midRightLayout = QVBoxLayout(self.midRight) self.subLayout0 = QVBoxLayout() self.subLayout1 = QVBoxLayout() self.subLayout2 = QHBoxLayout() self.subLayout3 = QVBoxLayout() self.subLayout4 = QVBoxLayout() self.subLayout5 = QHBoxLayout() self.subLayout6 = QHBoxLayout() self.toolBar = QToolBar() # self.storeAction = QAction(QIcon(static.storePNG), static.storeButton, self) self.startAction = QAction(QIcon(static.startPNG), static.startButton, self) self.stopAction = QAction(QIcon(static.stopPNG), static.stopButton, self) # self.toolBar.addAction(self.storeAction) self.toolBar.addAction(self.startAction) self.toolBar.addAction(self.stopAction) self.timeLongLbl = QLabel(static.timeString, self) self.timeLong = QLineEdit(self) self.timeLong.setMaximumWidth(100) self.timeLong.setMinimumWidth(100) self.timeLong.setPlaceholderText(static.timeLong) self.timeLongUnit = QLabel("H") self.etSetLbl = QLabel(static.eventTypeSet) self.etSet = QTableWidget(2, 2) self.etSet.setMaximumHeight(150) self.etSet.setHorizontalHeaderLabels(['option', 'value']) self.etSet.horizontalHeader().setStretchLastSection(True) self.etSet.setItem(0, 0, QTableWidgetItem("--throttle")) self.etSet.setItem(0, 1, QTableWidgetItem(str(static.eventType["--throttle"]))) # set event type percent self.etPercentLbl = QLabel(static.eventTpyePercent, self) self.etPercent = QTableWidget(2, 2) self.etPercent.setMaximumHeight(150) self.etPercent.setHorizontalHeaderLabels(['option', 'value']) self.etPercent.horizontalHeader().setStretchLastSection(True) self.etPercent.setItem(0, 0, QTableWidgetItem("--pct-touch")) self.etPercent.setItem(0, 1, QTableWidgetItem(str(static.eventPercent["--pct-touch"]))) self.etPercent.setItem(1, 0, QTableWidgetItem("--pct-motion")) self.etPercent.setItem(1, 1, QTableWidgetItem(str(static.eventPercent["--pct-motion"]))) # self.storeButton = QPushButton(QIcon(static.storePNG), static.storeButton) # self.storeButton.setToolTip(static.storeButton) self.exportButton = QPushButton(QIcon(static.exportPNG), static.exportFile) self.exportButton.setToolTip(static.exportFile) self.importButton = QPushButton(QIcon(static.importPNG), static.importFile) self.importButton.setToolTip(static.importFile) self.subLayout2.addWidget(self.timeLongLbl) self.subLayout2.addWidget(self.timeLong) self.subLayout2.addWidget(self.timeLongUnit) self.subLayout2.addWidget(QLabel(" " * 300)) # self.subLayout2.addWidget(self.storeButton) self.subLayout2.addWidget(self.exportButton) self.subLayout2.addWidget(self.importButton) self.subLayout0.addLayout(self.subLayout2) self.subLayout3.addWidget(self.etSetLbl) self.subLayout3.addWidget(self.etSet) self.subLayout4.addWidget(self.etPercentLbl) self.subLayout4.addWidget(self.etPercent) self.subLayout5.addLayout(self.subLayout0) self.subLayout6.addLayout(self.subLayout3) self.subLayout6.addLayout(self.subLayout4) self.midRightLayout.addLayout(self.subLayout5) self.midRightLayout.addLayout(self.subLayout6) # log ======== self.bottom = QFrame(self) self.bottom.setFrameShape(QFrame.StyledPanel) # log information self.logInfo = QLabel(static.logInfo) # information filter self.logFilter = QLabel(static.logFilter) self.monkeyButton = QPushButton(static.openMonkeyLog) self.combo = QComboBox() for i in range(len(static.logLevel)): self.combo.addItem(static.logLevel[i]) self.combo.setMaximumWidth(55) self.combo.setMaximumHeight(20) self.combo.setMinimumHeight(20) # information details self.bottomLayout = QVBoxLayout(self.bottom) self.subLayout = QHBoxLayout() self.subLayout.addWidget(self.logInfo) for i in range(10): self.subLayout.addWidget(QLabel("")) self.subLayout.addWidget(self.monkeyButton) self.subLayout.addWidget(self.logFilter) self.subLayout.addWidget(self.combo) self.bottomLayout.addLayout(self.subLayout) self.tabwidget = TabWidget() self.tabwidget.setMinimumHeight(100) self.bottomLayout.addWidget(self.tabwidget) # splitter mainWindow ++++++++++++++++++++++++++++++++++++ self.splitter2 = QSplitter(Qt.Vertical) self.splitter2.addWidget(self.topRight) self.splitter2.addWidget(self.midRight) self.splitter0 = QSplitter(Qt.Horizontal) self.splitter0.addWidget(self.topLeft) self.splitter0.addWidget(self.splitter2) self.splitter1 = QSplitter(Qt.Vertical) self.splitter1.addWidget(self.menuBar) self.splitter1.addWidget(self.splitter0) self.splitter1.addWidget(self.bottom) self.hbox.addWidget(self.splitter1) self.setLayout(self.hbox) self.show() def about(self): common.showDialog(static.menuAbout, static.dialogAbout) def init_conf(self): common.Log.info("init monkey conf") with open(monkeyConfFile, "w") as f: f.write("deviceList = []" + "\n") f.write("times = " + static.times + "\n") f.write("--throttle = " + static.eventType["--throttle"] + "\n") f.write("--pct-touch = " + static.eventPercent["--pct-touch"] + "\n") f.write("--pct-motion = " + static.eventPercent["--pct-motion"] + "\n") def setup_env(self): pass def _set_eventType(self, confFile): try: option = self.etSet.item(0, 0).text() value = self.etSet.item(0, 1).text() if value > "0": with open(confFile, 'a+') as f: f.write(option + " = " + value + "\n") except AttributeError, e: pass
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setStyleSheet("* {font-size:%s;}" % font_size) # Menu bar for defaults self.menubar = QMenuBar() defaults_menu = self.menubar.addMenu('&Show defaults and bibliography for a module...') menu_actions = {} for kind in _kinds: submenu = defaults_menu.addMenu(subfolders[kind]) modules = get_available_modules(kind) menu_actions[kind] = {} for module in modules: menu_actions[kind][module] = QAction(module, self) menu_actions[kind][module].setData((kind, module)) menu_actions[kind][module].triggered.connect(self.show_defaults) submenu.addAction(menu_actions[kind][module]) # Main layout self.menu_layout = QVBoxLayout() self.menu_layout.addWidget(self.menubar) self.setLayout(self.menu_layout) self.layout = QHBoxLayout() self.menu_layout.addLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) titles = odict([ ["Presets", odict([["preset", "Presets"]])], ["Cosmological Model", odict([ ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Hubble parameter constraint"], ["matter", "Matter sector"], ["neutrinos", "Neutrinos and other extra matter"], ["dark_energy", "Lambda / Dark energy"], ["bbn", "BBN"], ["reionization", "Reionization history"]])], ["Data sets", odict([ ["like_cmb", "CMB experiments"], ["like_bao", "BAO experiments"], ["like_des", "DES measurements"], ["like_sn", "SN experiments"], ["like_H0", "Local H0 measurements"]])], ["Sampler", odict([["sampler", "Samplers"]])]]) self.combos = odict() for group, fields in titles.items(): group_box = QGroupBox(group) self.layout_options.addWidget(group_box) group_layout = QVBoxLayout(group_box) for a, desc in fields.items(): self.combos[a] = QComboBox() if len(fields) > 1: label = QLabel(desc) group_layout.addWidget(label) group_layout.addWidget(self.combos[a]) self.combos[a].addItems( [text(k, v) for k, v in getattr(input_database, a).items()]) # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED # if a == "theory": # # Add Planck-naming checkbox # self.planck_names = QCheckBox( # "Keep common parameter names " # "(useful for fast CLASS/CAMB switching)") # group_layout.addWidget(self.planck_names) # Connect to refreshers -- needs to be after adding all elements for field, combo in self.combos.items(): if field == "preset": combo.currentIndexChanged.connect(self.refresh_preset) else: combo.currentIndexChanged.connect(self.refresh) # self.planck_names.stateChanged.connect(self.refresh_keep_preset) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python", "bibliography"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave) self.read_settings() self.show() def read_settings(self): settings = get_settings() screen = QApplication.desktop().screenGeometry() h = min(screen.height() * 5 / 6., 900) size = QSize(min(screen.width() * 5 / 6., 1200), h) pos = settings.value("pos", None) savesize = settings.value("size", size) if savesize.width() > screen.width(): savesize.setWidth(size.width()) if savesize.height() > screen.height(): savesize.setHeight(size.height()) self.resize(savesize) if ((pos is None or pos.x() + savesize.width() > screen.width() or pos.y() + savesize.height() > screen.height())): self.move(screen.center() - self.rect().center()) else: self.move(pos) def write_settings(self): settings = get_settings() settings.setValue("pos", self.pos()) settings.setValue("size", self.size()) def closeEvent(self, event): self.write_settings() event.accept() def create_input(self): return create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), **{field: list(getattr(input_database, field).keys())[combo.currentIndex()] for field, combo in self.combos.items() if field is not "preset"}) @Slot() def refresh_keep_preset(self): self.refresh_display(self.create_input()) @Slot() def refresh(self): self.combos["preset"].blockSignals(True) self.combos["preset"].setCurrentIndex(0) self.combos["preset"].blockSignals(False) self.refresh_display(self.create_input()) @Slot() def refresh_preset(self): preset = list(getattr(input_database, "preset").keys())[ self.combos["preset"].currentIndex()] if preset is input_database._none: return info = create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), preset=preset) self.refresh_display(info) # Update combo boxes to reflect the preset values, without triggering update for k, v in input_database.preset[preset].items(): if k in [input_database._desc]: continue self.combos[k].blockSignals(True) self.combos[k].setCurrentIndex( self.combos[k].findText( text(v, getattr(input_database, k).get(v)))) self.combos[k].blockSignals(False) def refresh_display(self, info): try: comments = info.pop(input_database._comment, None) comments_text = "\n# " + "\n# ".join(comments) except (TypeError, # No comments AttributeError): # Failed to generate info (returned str instead) comments_text = "" self.display["python"].setText( "from collections import OrderedDict\n\ninfo = " + pformat(info) + comments_text) self.display["yaml"].setText(yaml_dump(info) + comments_text) self.display["bibliography"].setText(prettyprint_bib(get_bib_info(info))) @Slot() def save_file(self): ftype = next(k for k, w in self.display.items() if w is self.display_tabs.currentWidget()) ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)", "bibliography": "(*.txt)"}[ftype] fsuffix = {"yaml": ".yaml", "python": ".py", "bibliography": ".txt"}[ftype] fname, path = self.save_dialog.getSaveFileName( self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd()) if not fname.endswith(fsuffix): fname += fsuffix with open(fname, "w+") as f: f.write(self.display_tabs.currentWidget().toPlainText()) @Slot() def copy_clipb(self): self.clipboard.setText(self.display_tabs.currentWidget().toPlainText()) def show_defaults(self): kind, module = self.sender().data() self.current_defaults_diag = DefaultsDialog(kind, module, parent=self)