def __init__(self, padre, interfazdatos, porterodatos): from Driza.datos.conversion import AgenteConversion self.__portero = porterodatos QTabWidget.__init__(self, padre, "Grid") self.setTabPosition(QTabWidget.Bottom) self.tab = QWidget(self, "tab") tabLayout = QVBoxLayout(self.tab, 11, 6, "tabLayout") self.table1 = QTable(self.tab, "table1") tabLayout.addWidget(self.table1) self.insertTab(self.tab, QString.fromLatin1("&Registros")) self.tab_2 = QWidget(self, "tab_2") tabLayout_2 = QVBoxLayout(self.tab_2, 11, 6, "tabLayout_2") self.table2 = QTable(self.tab_2, "table2") tabLayout_2.addWidget(self.table2) self.insertTab(self.tab_2, QString.fromLatin1("&Variables")) from Driza.iuqt3.vprincipal.dcasos import DCasos self.dcasos = DCasos(self.table1, interfazdatos) self.modoetiqueta = False # Variable que guarda si estamos en modo etiqueta o normal self.__nreg = 10 self.__nvar = 10 self.__idu = interfazdatos self.__init_t_reg() self.__init_t_var() self.__conexiones() self.__agenteconversion = AgenteConversion(self.__idu)
def test_profile_button_clicked(self): self.__run_test(self.__runner.run_profile) profile = self.__runner.profile_data dialog = QDialog(self) tabs = QTabWidget(dialog) for i, output in enumerate(profile): browser = QTextEdit(tabs, 'profile') browser.setReadOnly(True) browser.setWordWrap(browser.NoWrap) browser.setTextFormat(browser.PlainText) browser.setFamily('Monospace') browser.setText(output) tabs.addTab(browser, "profile %d" % i) layout = QVBoxLayout(dialog, 1, 1, "DialogLayout") layout.setResizeMode(QVBoxLayout.FreeResize) layout.addWidget(tabs) dialog.setCaption(self.tr("Profile")) dialog.setMinimumSize(QSize(400,500)) dialog.show()
def build_param_widget(self): self.dual_level_tab = QTabWidget() self.simpler_widget = self.simp_widg_in() self.advanced_widget = ParamAdvancedWidget(phl_obj=self.my_phl_obj, parent=self) self.advanced_widget.scrollable_widget.item_changed.connect(self.update_lin_txt) try: self.simpler_widget.item_changed.connect(self.update_advanced_widget) except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info("Caught unknown exception #2 type %s: %s", type(e).__name__, e) logger.info("found self.simpler_widget without << item_changed >> signal") try: self.simpler_widget.item_to_remove.connect(self.remove_one_par) except AttributeError: pass self.reset_btn = self.simpler_widget.inner_reset_btn self.dual_level_tab.addTab(self.simpler_widget, "Simple") self.dual_level_tab.addTab(self.advanced_widget, "Advanced") self.reset_btn.clicked.connect(self.reset_par)
def __init__(self, *args): apply(KMainWindow.__init__, (self, ) + args) self.lastDir = "/var/log" self.setGeometry(0, 0, 600, 400) # self.grid = QGridLayout(self, 1, 1) self.tab = QTabWidget(self) self.tab.addTab(QMultiLineEdit(self.tab), "Tab") self.layout().addWidget(self.tab, 0, 0) self.setCaption(str(i18n("%s - lovi")) % str(i18n("(none)"))) self.initActions() self.initMenus()
def __init__(self, scene): QWidget.__init__(self) self.scene = scene decorateWindow(self, i18n('Scoring for this Hand')) self.nameLabels = [None] * 4 self.spValues = [None] * 4 self.windLabels = [None] * 4 self.wonBoxes = [None] * 4 self.detailsLayout = [None] * 4 self.details = [None] * 4 self.__tilePixMaps = [] self.__meldPixMaps = [] grid = QGridLayout(self) pGrid = QGridLayout() grid.addLayout(pGrid, 0, 0, 2, 1) pGrid.addWidget(QLabel(i18nc('kajongg', "Player")), 0, 0) pGrid.addWidget(QLabel(i18nc('kajongg', "Wind")), 0, 1) pGrid.addWidget(QLabel(i18nc('kajongg', 'Score')), 0, 2) pGrid.addWidget(QLabel(i18n("Winner")), 0, 3) self.detailTabs = QTabWidget() self.detailTabs.setDocumentMode(True) pGrid.addWidget(self.detailTabs, 0, 4, 8, 1) for idx in range(4): self.setupUiForPlayer(pGrid, idx) self.draw = QCheckBox(i18nc('kajongg', 'Draw')) self.draw.clicked.connect(self.wonChanged) btnPenalties = QPushButton(i18n("&Penalties")) btnPenalties.clicked.connect(self.penalty) self.btnSave = QPushButton(i18n('&Save Hand')) self.btnSave.clicked.connect(self.game.nextScoringHand) self.btnSave.setEnabled(False) self.setupUILastTileMeld(pGrid) pGrid.setRowStretch(87, 10) pGrid.addWidget(self.draw, 7, 3) self.cbLastTile.currentIndexChanged.connect(self.slotLastTile) self.cbLastMeld.currentIndexChanged.connect(self.slotInputChanged) btnBox = QHBoxLayout() btnBox.addWidget(btnPenalties) btnBox.addWidget(self.btnSave) pGrid.addLayout(btnBox, 8, 4) StateSaver(self) self.refresh()
def __init__(self, *args): apply(KMainWindow.__init__, (self,) + args) self.lastDir = "/var/log" self.setGeometry(0, 0, 600, 400) # self.grid = QGridLayout(self, 1, 1) self.tab = QTabWidget(self) self.tab.addTab(QMultiLineEdit(self.tab), "Tab") self.layout().addWidget(self.tab, 0, 0) self.setCaption(str(i18n("%s - lovi")) % str(i18n("(none)"))) self.initActions() self.initMenus()
def __init__(self, scene): QWidget.__init__(self) self.scene = scene decorateWindow(self, m18n("Scoring for this Hand")) self.nameLabels = [None] * 4 self.spValues = [None] * 4 self.windLabels = [None] * 4 self.wonBoxes = [None] * 4 self.detailsLayout = [None] * 4 self.details = [None] * 4 self.__tilePixMaps = [] self.__meldPixMaps = [] grid = QGridLayout(self) pGrid = QGridLayout() grid.addLayout(pGrid, 0, 0, 2, 1) pGrid.addWidget(QLabel(m18nc("kajongg", "Player")), 0, 0) pGrid.addWidget(QLabel(m18nc("kajongg", "Wind")), 0, 1) pGrid.addWidget(QLabel(m18nc("kajongg", "Score")), 0, 2) pGrid.addWidget(QLabel(m18n("Winner")), 0, 3) self.detailTabs = QTabWidget() self.detailTabs.setDocumentMode(True) pGrid.addWidget(self.detailTabs, 0, 4, 8, 1) for idx in range(4): self.setupUiForPlayer(pGrid, idx) self.draw = QCheckBox(m18nc("kajongg", "Draw")) self.draw.clicked.connect(self.wonChanged) btnPenalties = QPushButton(m18n("&Penalties")) btnPenalties.clicked.connect(self.penalty) self.btnSave = QPushButton(m18n("&Save Hand")) self.btnSave.clicked.connect(self.game.nextScoringHand) self.btnSave.setEnabled(False) self.setupUILastTileMeld(pGrid) pGrid.setRowStretch(87, 10) pGrid.addWidget(self.draw, 7, 3) self.cbLastTile.currentIndexChanged.connect(self.slotLastTile) self.cbLastMeld.currentIndexChanged.connect(self.slotInputChanged) btnBox = QHBoxLayout() btnBox.addWidget(btnPenalties) btnBox.addWidget(self.btnSave) pGrid.addLayout(btnBox, 8, 4) StateSaver(self) self.refresh()
def __init__(self): super(MainWidget, self).__init__() self.my_pop = None # Any child popup windows. Only bravais_table ATM self.storage_path = sys_arg.directory refresh_gui = False # Load the previous state of DUI, if present dui_files_path = os.path.join(self.storage_path, "dui_files") if os.path.isfile(os.path.join(dui_files_path, "bkp.pickle")): try: self.idials_runner = load_previous_state(dui_files_path) except Exception as e: # Something went wrong - tell the user then close msg = traceback.format_exc() logger.error("ERROR LOADING PREVIOUS DATA:\n%s", msg) raise_from(DUIDataLoadingError(msg), e) refresh_gui = True else: # No dui_files path - start with a fresh state if not os.path.isdir(dui_files_path): os.mkdir(dui_files_path) self.idials_runner = Runner() self.gui2_log = {"pairs_list": []} self.cli_tree_output = TreeShow() self.cli_tree_output(self.idials_runner) self.cur_html = None self.cur_pick = None self.cur_json = None self.cur_log = None self.cur_cmd_name = "None" main_box = QVBoxLayout() self.centre_par_widget = ControlWidget() self.centre_par_widget.pass_sys_arg_object_to_import(sys_arg) self.stop_run_retry = StopRunRetry() self.tree_out = TreeNavWidget() left_control_box = QHBoxLayout() left_top_control_box = QVBoxLayout() left_top_control_box.addWidget(self.centre_par_widget) left_top_control_box.addStretch() left_control_box.addLayout(left_top_control_box) centre_control_box = QVBoxLayout() v_control_splitter = QSplitter() v_control_splitter.setOrientation(Qt.Vertical) v_control_splitter.addWidget(self.tree_out) v_control_splitter.addWidget(self.centre_par_widget.step_param_widg) centre_control_box.addWidget(v_control_splitter) centre_control_box.addWidget(self.stop_run_retry) left_control_box.addLayout(centre_control_box) dummy_left_widget = QWidget() dummy_h_layout = QHBoxLayout() dummy_h_layout.addLayout(left_control_box) dummy_left_widget.setLayout(dummy_h_layout) dummy_left_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) h_main_splitter = QSplitter() h_main_splitter.setOrientation(Qt.Horizontal) h_main_splitter.addWidget(dummy_left_widget) self.cli_out = CliOutView() self.web_view = WebTab() self.img_view = MyImgWin() self.ext_view = OuterCaller() self.info_widget = InfoWidget() self.output_info_tabs = QTabWidget() self.output_info_tabs.addTab(self.img_view, "Image") self.output_info_tabs.addTab(self.cli_out, "Log") self.output_info_tabs.addTab(self.web_view, "Report") self.output_info_tabs.addTab(self.ext_view, "Tools") self.output_info_tabs.addTab(self.info_widget, "Experiment") self.view_tab_num = 0 self.output_info_tabs.currentChanged.connect(self.tab_changed) self.img_view.mask_applied.connect(self.pop_mask_list) self.img_view.predic_changed.connect(self.tab_changed) self.img_view.bc_applied.connect(self.pop_b_centr_coord) self.img_view.new_pars_applied.connect(self.pass_parmams) # self.ext_view.pass_parmam_lst.connect(self.pass_parmams) self.centre_par_widget.finished_masking.connect(self.img_view.unchec_my_mask) self.centre_par_widget.click_mask.connect(self.img_view.chec_my_mask) self.centre_par_widget.finished_b_centr.connect(self.img_view.unchec_b_centr) self.centre_par_widget.click_b_centr.connect(self.img_view.chec_b_centr) v_info_splitter = QSplitter() v_info_splitter.setOrientation(Qt.Vertical) v_info_splitter.addWidget(self.output_info_tabs) h_main_splitter.addWidget(v_info_splitter) main_box.addWidget(h_main_splitter) self.txt_bar = Text_w_Bar() main_box.addWidget(self.txt_bar) self.connect_all() self.custom_thread = CommandThread() self.custom_thread.finished.connect(self.update_after_finished) self.custom_thread.str_fail_signal.connect(self.after_failed) self.custom_thread.str_print_signal.connect(self.cli_out.add_txt) self.custom_thread.str_print_signal.connect(self.txt_bar.setText) self.custom_thread.busy_box_on.connect(self.pop_busy_box) self.custom_thread.busy_box_off.connect(self.close_busy_box) self.main_widget = QWidget() self.main_widget.setLayout(main_box) self.setCentralWidget(self.main_widget) self.setWindowTitle("CCP4 DUI - {}: {}".format(__version__, dui_files_path)) self.setWindowIcon(QIcon(self.stop_run_retry.dials_logo_path)) self.just_reindexed = False self.user_stoped = False self.reconnect_when_ready() self.my_pop = None if refresh_gui: self.refresh_my_gui()
class MainWidget(QMainWindow): def __init__(self): super(MainWidget, self).__init__() self.my_pop = None # Any child popup windows. Only bravais_table ATM self.storage_path = sys_arg.directory refresh_gui = False # Load the previous state of DUI, if present dui_files_path = os.path.join(self.storage_path, "dui_files") if os.path.isfile(os.path.join(dui_files_path, "bkp.pickle")): try: self.idials_runner = load_previous_state(dui_files_path) except Exception as e: # Something went wrong - tell the user then close msg = traceback.format_exc() logger.error("ERROR LOADING PREVIOUS DATA:\n%s", msg) raise_from(DUIDataLoadingError(msg), e) refresh_gui = True else: # No dui_files path - start with a fresh state if not os.path.isdir(dui_files_path): os.mkdir(dui_files_path) self.idials_runner = Runner() self.gui2_log = {"pairs_list": []} self.cli_tree_output = TreeShow() self.cli_tree_output(self.idials_runner) self.cur_html = None self.cur_pick = None self.cur_json = None self.cur_log = None self.cur_cmd_name = "None" main_box = QVBoxLayout() self.centre_par_widget = ControlWidget() self.centre_par_widget.pass_sys_arg_object_to_import(sys_arg) self.stop_run_retry = StopRunRetry() self.tree_out = TreeNavWidget() left_control_box = QHBoxLayout() left_top_control_box = QVBoxLayout() left_top_control_box.addWidget(self.centre_par_widget) left_top_control_box.addStretch() left_control_box.addLayout(left_top_control_box) centre_control_box = QVBoxLayout() v_control_splitter = QSplitter() v_control_splitter.setOrientation(Qt.Vertical) v_control_splitter.addWidget(self.tree_out) v_control_splitter.addWidget(self.centre_par_widget.step_param_widg) centre_control_box.addWidget(v_control_splitter) centre_control_box.addWidget(self.stop_run_retry) left_control_box.addLayout(centre_control_box) dummy_left_widget = QWidget() dummy_h_layout = QHBoxLayout() dummy_h_layout.addLayout(left_control_box) dummy_left_widget.setLayout(dummy_h_layout) dummy_left_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) h_main_splitter = QSplitter() h_main_splitter.setOrientation(Qt.Horizontal) h_main_splitter.addWidget(dummy_left_widget) self.cli_out = CliOutView() self.web_view = WebTab() self.img_view = MyImgWin() self.ext_view = OuterCaller() self.info_widget = InfoWidget() self.output_info_tabs = QTabWidget() self.output_info_tabs.addTab(self.img_view, "Image") self.output_info_tabs.addTab(self.cli_out, "Log") self.output_info_tabs.addTab(self.web_view, "Report") self.output_info_tabs.addTab(self.ext_view, "Tools") self.output_info_tabs.addTab(self.info_widget, "Experiment") self.view_tab_num = 0 self.output_info_tabs.currentChanged.connect(self.tab_changed) self.img_view.mask_applied.connect(self.pop_mask_list) self.img_view.predic_changed.connect(self.tab_changed) self.img_view.bc_applied.connect(self.pop_b_centr_coord) self.img_view.new_pars_applied.connect(self.pass_parmams) # self.ext_view.pass_parmam_lst.connect(self.pass_parmams) self.centre_par_widget.finished_masking.connect(self.img_view.unchec_my_mask) self.centre_par_widget.click_mask.connect(self.img_view.chec_my_mask) self.centre_par_widget.finished_b_centr.connect(self.img_view.unchec_b_centr) self.centre_par_widget.click_b_centr.connect(self.img_view.chec_b_centr) v_info_splitter = QSplitter() v_info_splitter.setOrientation(Qt.Vertical) v_info_splitter.addWidget(self.output_info_tabs) h_main_splitter.addWidget(v_info_splitter) main_box.addWidget(h_main_splitter) self.txt_bar = Text_w_Bar() main_box.addWidget(self.txt_bar) self.connect_all() self.custom_thread = CommandThread() self.custom_thread.finished.connect(self.update_after_finished) self.custom_thread.str_fail_signal.connect(self.after_failed) self.custom_thread.str_print_signal.connect(self.cli_out.add_txt) self.custom_thread.str_print_signal.connect(self.txt_bar.setText) self.custom_thread.busy_box_on.connect(self.pop_busy_box) self.custom_thread.busy_box_off.connect(self.close_busy_box) self.main_widget = QWidget() self.main_widget.setLayout(main_box) self.setCentralWidget(self.main_widget) self.setWindowTitle("CCP4 DUI - {}: {}".format(__version__, dui_files_path)) self.setWindowIcon(QIcon(self.stop_run_retry.dials_logo_path)) self.just_reindexed = False self.user_stoped = False self.reconnect_when_ready() self.my_pop = None if refresh_gui: self.refresh_my_gui() def pop_mask_list(self, mask_itm_lst): tmp_cmd_lst = build_mask_command_lst(mask_itm_lst) self.centre_par_widget.mask_page.set_par(tmp_cmd_lst) self.centre_par_widget.step_param_widg.setCurrentWidget( self.centre_par_widget.mask_page ) def pop_b_centr_coord(self, new_b_centr): logger.info("New b_centr =", new_b_centr) self.centre_par_widget.b_centr_page.set_par(new_b_centr) self.centre_par_widget.step_param_widg.setCurrentWidget( self.centre_par_widget.b_centr_page ) def connect_all(self): self.setCursor(Qt.ArrowCursor) self.tree_clickable = True self.tree_out.clicked[QModelIndex].connect(self.node_clicked) self.stop_run_retry.repeat_btn.clicked.connect(self.rep_clicked) self.stop_run_retry.run_btn.clicked.connect(self.run_clicked) self.stop_run_retry.stop_btn.clicked.connect(self.stop_clicked) self.centre_par_widget.user_changed.connect(self.cmd_changed_by_user) self.centre_par_widget.update_command_lst_high_level.connect( self.update_low_level_command_lst ) self.centre_par_widget.step_param_widg.currentChanged.connect( self.cmd_changed_by_any ) self.check_gray_outs() def disconnect_while_running(self): self.setCursor(Qt.BusyCursor) self.tree_clickable = False self.stop_run_retry.repeat_btn.setEnabled(False) self.stop_run_retry.run_btn.setEnabled(False) self.stop_run_retry.stop_btn.setEnabled(True) self.centre_par_widget.gray_outs_all() self.centre_par_widget.step_param_widg.currentWidget().my_widget.gray_me_out() self.user_stoped = False def reconnect_when_ready(self): self.setCursor(Qt.ArrowCursor) self.tree_clickable = True self.stop_run_retry.repeat_btn.setEnabled(False) self.stop_run_retry.stop_btn.setEnabled(False) self.stop_run_retry.run_btn.setEnabled(False) if self.user_stoped: self.idials_runner.current_node.success = None my_widget = self.centre_par_widget.step_param_widg.currentWidget().my_widget if self.idials_runner.current_node.success is None: self.stop_run_retry.run_btn.setEnabled(True) my_widget.activate_me(cur_nod=self.idials_runner.current_node) else: if self.idials_runner.current_node.ll_command_lst[0][0] != "export": self.stop_run_retry.repeat_btn.setEnabled(True) my_widget.gray_me_out() if self.idials_runner.current_node.ll_command_lst[0][0] == "reindex": self.stop_run_retry.run_btn.setEnabled(False) self.stop_run_retry.repeat_btn.setEnabled(False) self.check_gray_outs() self.user_stoped = False self.update_nav_tree() def chouse_if_predict_or_report(self): if ( self.idials_runner.current_node.ll_command_lst[0][0] != "refine_bravais_settings" ): if self.view_tab_num == 0 and self.img_view.rad_but_pre_hkl.checkState(): self.pop_busy_box(text_in_bar="Generating Predictions") self.idials_runner.current_node.gen_repr_n_pred(to_run="predict") self.close_busy_box() elif self.view_tab_num == 2: """ ########################################################################## tmp_bar = ProgBarBox(min_val=0, max_val=10, text=text_in_bar) tmp_bar(5) tmp_bar.ended() ################################################################################ """ tmp_bar = ProgBarBox(min_val=0, max_val=10, text="Generating Report") tmp_bar(5) self.idials_runner.current_node.gen_repr_n_pred(to_run="report") tmp_bar.ended() def tab_changed(self, num=0): self.view_tab_num = num self.chouse_if_predict_or_report() update_info(self) def pass_parmams(self, cmd_lst): """(We've been passed a parameter by the external tool signal)""" current_parameter_widget = ( self.centre_par_widget.step_param_widg.currentWidget() ) action_name = current_parameter_widget.my_widget.command_lst[0][0] to_remove = """ if ( action_name in ["find_spots", "integrate"] and self.idials_runner.current_node.success is None ): """ if ( action_name == "find_spots" and self.idials_runner.current_node.success is None ): gain = cmd_lst[0] size = cmd_lst[1] nsig_b = cmd_lst[2] nsig_s = cmd_lst[3] global_threshold = cmd_lst[4] min_count = cmd_lst[5] full_command = [ "find_spots", "spotfinder.threshold.dispersion.gain=" + str(gain), "spotfinder.threshold.dispersion.kernel_size=" + str(size[0]) + "," + str(size[1]), "spotfinder.threshold.dispersion.sigma_background=" + str(nsig_b), "spotfinder.threshold.dispersion.sigma_strong=" + str(nsig_s), "spotfinder.threshold.dispersion.min_local=" + str(min_count), "spotfinder.threshold.dispersion.global_threshold=" + str(global_threshold), ] current_parameter_widget.my_widget.update_param_w_lst(full_command) else: logger.debug("No need to feed back params") """ logger.info( "my_widget_now.my_widget.command_lst = %s", current_parameter_widget.my_widget.command_lst, ) """ def update_low_level_command_lst(self, command_lst): self.idials_runner.current_node.ll_command_lst = command_lst self.reconnect_when_ready() def cmd_changed_by_user(self, my_label): logger.debug("cmd_changed_by_user()") tmp_curr = self.idials_runner.current_node if tmp_curr.success is True: self.cmd_exe(["mkchi"]) self.idials_runner.current_node.ll_command_lst = [[str(my_label)]] self.centre_par_widget.step_param_widg.currentWidget().my_widget.reset_par() path_to_mask_pickle = None if self.idials_runner.current_node.ll_command_lst[0][0] == "integrate": logger.debug("Running: try_find_prev_mask_pickle") path_to_mask_pickle = try_find_prev_mask_pickle( self.idials_runner.current_node ) if path_to_mask_pickle is not None: self.pass_parmams(["lookup.mask=" + path_to_mask_pickle]) self.cmd_exe(["clean"]) elif tmp_curr.success is None: self.idials_runner.current_node.ll_command_lst[0] = [str(my_label)] self.reconnect_when_ready() def cmd_changed_by_any(self): tmp_curr_widg = self.centre_par_widget.step_param_widg.currentWidget() self.cur_cmd_name = tmp_curr_widg.my_widget.command_lst[0][0] self.reconnect_when_ready() def rep_clicked(self): logger.debug("rep_clicked") self.cmd_exe(["mksib"]) self.cmd_exe(["clean"]) self.check_gray_outs() def stop_clicked(self): logger.debug("\n\n <<< Stop clicked >>> \n\n") # TODO fix spelling on << dials_command >> pr_to_kill = self.idials_runner.current_node.dials_command.my_pid logger.debug( "self.idials_runner.current_node.dials_command.my_pid = %s", pr_to_kill ) self.user_stoped = True kill_w_child(pr_to_kill) def run_clicked(self): logger.debug("run_clicked") logger.debug( "...currentWidget(ref) = %s", self.centre_par_widget.step_param_widg.currentWidget(), ) self.img_view.draw_img_img() cmd_tmp = ( self.centre_par_widget.step_param_widg.currentWidget().my_widget.command_lst ) self.cmd_launch(cmd_tmp) def cmd_exe(self, new_cmd): # Running NOT in parallel update_info(self) self.idials_runner.run(command=new_cmd, ref_to_class=None) self.check_reindex_pop() self.reconnect_when_ready() def cmd_launch(self, new_cmd): # Running WITH threading self.cli_out.clear() self.cli_out.make_green() self.txt_bar.start_motion() self.txt_bar.setText("Running") self.disconnect_while_running() self.custom_thread(new_cmd, self.idials_runner) def update_after_finished(self): self.chouse_if_predict_or_report() update_info(self) self.txt_bar.end_motion() self.just_reindexed = False tmp_curr = self.idials_runner.current_node prn_lst_lst_cmd(tmp_curr) if ( tmp_curr.ll_command_lst[0][0] == "refine_bravais_settings" and tmp_curr.success is True ): self.idials_runner.run(command=["mkchi"], ref_to_class=None) self.idials_runner.current_node.ll_command_lst = [["reindex"]] elif tmp_curr.ll_command_lst[0][0] == "reindex" and tmp_curr.success is True: self.just_reindexed = True try: self.my_pop.close() except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.debug( "Caught unknown exception type %s: %s", type(e).__name__, e ) logger.debug("no need to close reindex table") elif tmp_curr.ll_command_lst[0][0] == "export" and tmp_curr.success is True: self.gui2_log = try_move_last_info(tmp_curr, self.gui2_log) self.check_reindex_pop() self.check_gray_outs() self.reconnect_when_ready() if ( tmp_curr.ll_command_lst[0][0] == "generate_mask" and tmp_curr.success is True ): self.img_view.my_painter.reset_mask_tool(None) elif ( tmp_curr.ll_command_lst[0][0] == "modify_geometry" and tmp_curr.success is True ): self.img_view.my_painter.reset_bc_tool(None) with open(self.storage_path + "/dui_files/bkp.pickle", "wb") as bkp_out: pickle.dump(self.idials_runner, bkp_out) def pop_busy_box(self, text_in_bar): #logger.info("OPENING busy pop bar with the text: ", text_in_bar) if ( self.idials_runner.current_node.ll_command_lst[0][0] != "refine_bravais_settings" ): self.my_bar = ProgBarBox(min_val=0, max_val=10, text=text_in_bar) self.my_bar(5) def close_busy_box(self): logger.info("trying to close busy pop bar") try: self.my_bar.ended() except AttributeError: logger.info("no need to close busy pop bar") def check_gray_outs(self): tmp_curr = self.idials_runner.current_node if tmp_curr.success is not True: tmp_curr = tmp_curr.prev_step # TODO fix "generate_mask" and "modify_geometry" : it should be the same as the previous step # This dictionary defines which tasks can be performed at each step and # which should be grayed out cmd_connects = { "Root": ["import"], "import": ["find_spots"], "find_spots": ["index"], "index": ["refine_bravais_settings", "refine", "integrate"], "refine_bravais_settings": [None], "reindex": ["refine", "integrate", "index"], "refine": [ "refine_bravais_settings", "refine", "integrate", "index", ], "integrate": ["symmetry", "scale", "export", "index", "export"], "symmetry": ["refine_bravais_settings", "scale", "export"], "scale": ["refine_bravais_settings", "symmetry", "export"], "export": [None], "generate_mask": ["find_spots"], "modify_geometry": ["find_spots"], "None": [None], } more_conservative = """ cmd_connects = { "Root": ["import"], "import": ["find_spots"], "find_spots": ["index"], "index": ["refine_bravais_settings", "refine", "integrate"], "refine_bravais_settings": [None], "reindex": ["refine", "integrate"], "refine": ["refine_bravais_settings", "refine", "integrate"], "integrate": ["symmetry", "scale", "export"], "symmetry": ["scale", "export"], "scale": ["symmetry", "export"], "export": [None], "generate_mask": ["find_spots"], "modify_geometry":["find_spots"], "None": [None], } """ lst_nxt = cmd_connects[str(tmp_curr.ll_command_lst[0][0])] self.centre_par_widget.gray_outs_from_lst(lst_nxt) def check_reindex_pop(self): tmp_curr = self.idials_runner.current_node #logger.info("\n_________________________ check_reindex_pop 01 \n") if tmp_curr.ll_command_lst[0][0] == "reindex" and not self.just_reindexed: #logger.info("\n_________________________ check_reindex_pop 02 \n") try: self.my_pop = MyReindexOpts() self.my_pop.set_ref( in_json_path=tmp_curr.prev_step.json_file_out, lin_num=tmp_curr.prev_step.lin_num, ) self.my_pop.my_inner_table.opt_signal.connect(self.opt_dobl_clicked) except Exception as my_err: logger.info("ERROR in check_reindex_pop(m_idials_gui) \n") logger.info("str(my_err) = ", str(my_err)) logger.info("my_err.__doc__ = ", my_err.__doc__) logger.info("my_err.message = ", my_err.message) # TODO find an elegant way to interrupt and remove nodes else: try: self.my_pop.close() except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.debug( "Caught unknown exception type %s: %s", type(e).__name__, e ) logger.debug("no need to close reindex table") self.just_reindexed = False def update_nav_tree(self): self.tree_out.update_me( self.idials_runner.step_list[0], self.idials_runner.current_line ) update_pbar_msg(self) self.img_view.my_painter.repaint() def after_failed(self): logger.info("\n FAILED STEP:") self.update_nav_tree() self.txt_bar.end_motion() curr_step = self.idials_runner.current_node for err_lin in curr_step.dials_command.tmp_std_all: logger.debug(err_lin) err_log_file_out = ( self.storage_path + "/dui_files" + os.sep + str(curr_step.lin_num) + "_err_out.log" ) logger.info("\n ERROR \n err_log_file_out = %s %s", err_log_file_out, "\n") fil_obj = open(err_log_file_out, "w") for err_lin in curr_step.dials_command.tmp_std_all: fil_obj.write(err_lin) fil_obj.write("\n") fil_obj.close() self.idials_runner.current_node.err_file_out = err_log_file_out def opt_dobl_clicked(self, row): re_idx = row + 1 logger.debug("Solution clicked = %s", re_idx) cmd_tmp = ["reindex", "solution=" + str(re_idx)] self.cmd_launch([cmd_tmp]) def node_clicked(self, it_index): logger.debug("\n it_index = %s", it_index) logger.debug(" type(it_index) = %s", type(it_index)) if self.tree_clickable: # TODO Think of a more robust way to "disconnect" ... next line try: self.centre_par_widget.update_command_lst_high_level.disconnect( self.update_low_level_command_lst ) except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info(" Caught unknown exception type %s: %s", type(e).__name__, e) logger.info("\n Tst A1 \n") item = self.tree_out.std_mod.itemFromIndex(it_index) prn_lst_lst_cmd(item.idials_node) lin_num = item.idials_node.lin_num cmd_ovr = "goto " + str(lin_num) self.cmd_exe(cmd_ovr) self.centre_par_widget.set_widget( nxt_cmd=item.idials_node.ll_command_lst[0][0], curr_step=self.idials_runner.current_node, ) self.check_reindex_pop() self.chouse_if_predict_or_report() update_info(self) self.check_gray_outs() self.reconnect_when_ready() self.centre_par_widget.update_command_lst_high_level.connect( self.update_low_level_command_lst ) def refresh_my_gui(self): lin_num = self.idials_runner.current_node.lin_num logger.debug("doing goto: %s", lin_num) cmd_ovr = "goto " + str(lin_num) self.cmd_exe(cmd_ovr) self.centre_par_widget.set_widget( nxt_cmd=self.idials_runner.current_node.ll_command_lst[0][0], curr_step=self.idials_runner.current_node, ) self.check_reindex_pop() self.chouse_if_predict_or_report() update_info(self) self.check_gray_outs() self.reconnect_when_ready() logger.info("\n ... recovering from previous run of GUI \n") def closeEvent(self, event): if self.my_pop: self.my_pop.close()
class ScoringDialog(QWidget): """a dialog for entering the scores""" # pylint: disable=too-many-instance-attributes def __init__(self, scene): QWidget.__init__(self) self.scene = scene decorateWindow(self, m18n("Scoring for this Hand")) self.nameLabels = [None] * 4 self.spValues = [None] * 4 self.windLabels = [None] * 4 self.wonBoxes = [None] * 4 self.detailsLayout = [None] * 4 self.details = [None] * 4 self.__tilePixMaps = [] self.__meldPixMaps = [] grid = QGridLayout(self) pGrid = QGridLayout() grid.addLayout(pGrid, 0, 0, 2, 1) pGrid.addWidget(QLabel(m18nc("kajongg", "Player")), 0, 0) pGrid.addWidget(QLabel(m18nc("kajongg", "Wind")), 0, 1) pGrid.addWidget(QLabel(m18nc("kajongg", "Score")), 0, 2) pGrid.addWidget(QLabel(m18n("Winner")), 0, 3) self.detailTabs = QTabWidget() self.detailTabs.setDocumentMode(True) pGrid.addWidget(self.detailTabs, 0, 4, 8, 1) for idx in range(4): self.setupUiForPlayer(pGrid, idx) self.draw = QCheckBox(m18nc("kajongg", "Draw")) self.draw.clicked.connect(self.wonChanged) btnPenalties = QPushButton(m18n("&Penalties")) btnPenalties.clicked.connect(self.penalty) self.btnSave = QPushButton(m18n("&Save Hand")) self.btnSave.clicked.connect(self.game.nextScoringHand) self.btnSave.setEnabled(False) self.setupUILastTileMeld(pGrid) pGrid.setRowStretch(87, 10) pGrid.addWidget(self.draw, 7, 3) self.cbLastTile.currentIndexChanged.connect(self.slotLastTile) self.cbLastMeld.currentIndexChanged.connect(self.slotInputChanged) btnBox = QHBoxLayout() btnBox.addWidget(btnPenalties) btnBox.addWidget(self.btnSave) pGrid.addLayout(btnBox, 8, 4) StateSaver(self) self.refresh() @property def game(self): """proxy""" return self.scene.game def setupUILastTileMeld(self, pGrid): """setup UI elements for last tile and last meld""" self.lblLastTile = QLabel(m18n("&Last Tile:")) self.cbLastTile = QComboBox() self.cbLastTile.setMinimumContentsLength(1) vpol = QSizePolicy() vpol.setHorizontalPolicy(QSizePolicy.Fixed) self.cbLastTile.setSizePolicy(vpol) self.cbLastTile.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lblLastTile.setBuddy(self.cbLastTile) self.lblLastMeld = QLabel(m18n("L&ast Meld:")) self.prevLastTile = None self.cbLastMeld = QComboBox() self.cbLastMeld.setMinimumContentsLength(1) self.cbLastMeld.setSizePolicy(vpol) self.cbLastMeld.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lblLastMeld.setBuddy(self.cbLastMeld) self.comboTilePairs = set() pGrid.setRowStretch(6, 5) pGrid.addWidget(self.lblLastTile, 7, 0, 1, 2) pGrid.addWidget(self.cbLastTile, 7, 2, 1, 1) pGrid.addWidget(self.lblLastMeld, 8, 0, 1, 2) pGrid.addWidget(self.cbLastMeld, 8, 2, 1, 2) def setupUiForPlayer(self, pGrid, idx): """setup UI elements for a player""" self.spValues[idx] = QSpinBox() self.nameLabels[idx] = QLabel() self.nameLabels[idx].setBuddy(self.spValues[idx]) self.windLabels[idx] = WindLabel() pGrid.addWidget(self.nameLabels[idx], idx + 2, 0) pGrid.addWidget(self.windLabels[idx], idx + 2, 1) pGrid.addWidget(self.spValues[idx], idx + 2, 2) self.wonBoxes[idx] = QCheckBox("") pGrid.addWidget(self.wonBoxes[idx], idx + 2, 3) self.wonBoxes[idx].clicked.connect(self.wonChanged) self.spValues[idx].valueChanged.connect(self.slotInputChanged) detailTab = QWidget() self.detailTabs.addTab(detailTab, "") self.details[idx] = QWidget() detailTabLayout = QVBoxLayout(detailTab) detailTabLayout.addWidget(self.details[idx]) detailTabLayout.addStretch() self.detailsLayout[idx] = QVBoxLayout(self.details[idx]) def refresh(self): """reload game""" self.clear() game = self.game self.setVisible(game is not None and not game.finished()) if game: for idx, player in enumerate(game.players): for child in self.details[idx].children(): if isinstance(child, RuleBox): child.hide() self.detailsLayout[idx].removeWidget(child) del child if game: self.spValues[idx].setRange(0, game.ruleset.limit or 99999) self.nameLabels[idx].setText(player.localName) self.windLabels[idx].wind = player.wind self.windLabels[idx].roundsFinished = game.roundsFinished self.detailTabs.setTabText(idx, player.localName) player.manualRuleBoxes = [RuleBox(x) for x in game.ruleset.allRules if x.hasSelectable] for ruleBox in player.manualRuleBoxes: self.detailsLayout[idx].addWidget(ruleBox) ruleBox.clicked.connect(self.slotInputChanged) player.refreshManualRules() def show(self): """only now compute content""" if self.game and not self.game.finished(): self.slotInputChanged() QWidget.show(self) def penalty(self): """penalty button clicked""" dlg = PenaltyDialog(self.game) dlg.exec_() def slotLastTile(self): """called when the last tile changes""" newLastTile = self.computeLastTile() if not newLastTile: return if self.prevLastTile and self.prevLastTile.isExposed != newLastTile.isExposed: # state of last tile (concealed/exposed) changed: # for all checked boxes check if they still are applicable winner = self.game.winner if winner: for box in winner.manualRuleBoxes: if box.isChecked(): box.setChecked(False) if winner.hand.manualRuleMayApply(box.rule): box.setChecked(True) self.prevLastTile = newLastTile self.fillLastMeldCombo() self.slotInputChanged() def computeLastTile(self): """returns the currently selected last tile""" idx = self.cbLastTile.currentIndex() if idx >= 0: return variantValue(self.cbLastTile.itemData(idx)) def clickedPlayerIdx(self, checkbox): """the player whose box has been clicked""" for idx in range(4): if checkbox == self.wonBoxes[idx]: return idx assert False def wonChanged(self): """if a new winner has been defined, uncheck any previous winner""" newWinner = None if self.sender() != self.draw: clicked = self.clickedPlayerIdx(self.sender()) if self.wonBoxes[clicked].isChecked(): newWinner = self.game.players[clicked] else: newWinner = None self.game.winner = newWinner for idx in range(4): if newWinner != self.game.players[idx]: self.wonBoxes[idx].setChecked(False) if newWinner: self.draw.setChecked(False) self.fillLastTileCombo() self.slotInputChanged() def updateManualRules(self): """enable/disable them""" # if an exclusive rule has been activated, deactivate it for # all other players ruleBox = self.sender() if isinstance(ruleBox, RuleBox) and ruleBox.isChecked() and ruleBox.rule.exclusive(): for idx, player in enumerate(self.game.players): if ruleBox.parentWidget() != self.details[idx]: for pBox in player.manualRuleBoxes: if pBox.rule.name == ruleBox.rule.name: pBox.setChecked(False) try: newState = bool(self.game.winner.handBoard.uiTiles) except AttributeError: newState = False self.lblLastTile.setEnabled(newState) self.cbLastTile.setEnabled(newState) self.lblLastMeld.setEnabled(newState) self.cbLastMeld.setEnabled(newState) if self.game: for player in self.game.players: player.refreshManualRules(self.sender()) def clear(self): """prepare for next hand""" if self.game: for idx, player in enumerate(self.game.players): self.spValues[idx].clear() self.spValues[idx].setValue(0) self.wonBoxes[idx].setChecked(False) player.payment = 0 player.invalidateHand() for box in self.wonBoxes: box.setVisible(False) self.draw.setChecked(False) self.updateManualRules() if self.game is None: self.hide() else: for idx, player in enumerate(self.game.players): self.windLabels[idx].setPixmap(WINDPIXMAPS[(player.wind, player.wind == self.game.roundWind)]) self.computeScores() self.spValues[0].setFocus() self.spValues[0].selectAll() def computeScores(self): """if tiles have been selected, compute their value""" # pylint: disable=too-many-branches # too many branches if not self.game: return if self.game.finished(): self.hide() return for nameLabel, wonBox, spValue, player in zip(self.nameLabels, self.wonBoxes, self.spValues, self.game.players): with BlockSignals([spValue, wonBox]): # we do not want that change to call computeScores again if player.handBoard and player.handBoard.uiTiles: spValue.setEnabled(False) nameLabel.setBuddy(wonBox) for _ in range(10): prevTotal = player.handTotal player.invalidateHand() wonBox.setVisible(player.hand.won) if not wonBox.isVisibleTo(self) and wonBox.isChecked(): wonBox.setChecked(False) self.game.winner = None elif prevTotal == player.handTotal: break player.refreshManualRules() spValue.setValue(player.handTotal) else: if not spValue.isEnabled(): spValue.clear() spValue.setValue(0) spValue.setEnabled(True) nameLabel.setBuddy(spValue) wonBox.setVisible(player.handTotal >= self.game.ruleset.minMJTotal()) if not wonBox.isVisibleTo(self) and wonBox.isChecked(): wonBox.setChecked(False) if not wonBox.isVisibleTo(self) and player is self.game.winner: self.game.winner = None if Internal.scene.explainView: Internal.scene.explainView.refresh() def __lastMeldContent(self): """prepare content for lastmeld combo""" lastTiles = set() winnerTiles = [] if self.game.winner and self.game.winner.handBoard: winnerTiles = self.game.winner.handBoard.uiTiles pairs = [] for meld in self.game.winner.hand.melds: if len(meld) < 4: pairs.extend(meld) for tile in winnerTiles: if tile.tile in pairs and not tile.isBonus: lastTiles.add(tile.tile) return lastTiles, winnerTiles def __fillLastTileComboWith(self, lastTiles, winnerTiles): """fill last meld combo with prepared content""" self.comboTilePairs = lastTiles idx = self.cbLastTile.currentIndex() if idx < 0: idx = 0 indexedTile = variantValue(self.cbLastTile.itemData(idx)) restoredIdx = None self.cbLastTile.clear() if not winnerTiles: return pmSize = winnerTiles[0].board.tileset.faceSize pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5) self.cbLastTile.setIconSize(pmSize) QPixmapCache.clear() self.__tilePixMaps = [] shownTiles = set() for tile in winnerTiles: if tile.tile in lastTiles and tile.tile not in shownTiles: shownTiles.add(tile.tile) self.cbLastTile.addItem(QIcon(tile.pixmapFromSvg(pmSize, withBorders=False)), "", toQVariant(tile.tile)) if indexedTile is tile.tile: restoredIdx = self.cbLastTile.count() - 1 if not restoredIdx and indexedTile: # try again, maybe the tile changed between concealed and exposed indexedTile = indexedTile.exposed for idx in range(self.cbLastTile.count()): if indexedTile is variantValue(self.cbLastTile.itemData(idx)).exposed: restoredIdx = idx break if not restoredIdx: restoredIdx = 0 self.cbLastTile.setCurrentIndex(restoredIdx) self.prevLastTile = self.computeLastTile() def clearLastTileCombo(self): """as the name says""" self.comboTilePairs = None self.cbLastTile.clear() def fillLastTileCombo(self): """fill the drop down list with all possible tiles. If the drop down had content before try to preserve the current index. Even if the tile changed state meanwhile.""" if self.game is None: return lastTiles, winnerTiles = self.__lastMeldContent() if self.comboTilePairs == lastTiles: return with BlockSignals(self.cbLastTile): # we only want to emit the changed signal once self.__fillLastTileComboWith(lastTiles, winnerTiles) self.cbLastTile.currentIndexChanged.emit(0) def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile): """fill last meld combo with prepared content""" winner = self.game.winner faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5 faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5 restoredIdx = None for meld in winnerMelds: pixMap = QPixmap(faceWidth * len(meld), faceHeight) pixMap.fill(Qt.transparent) self.__meldPixMaps.append(pixMap) painter = QPainter(pixMap) for element in meld: painter.drawPixmap( 0, 0, winner.handBoard.tilesByElement(element)[0].pixmapFromSvg( QSize(faceWidth, faceHeight), withBorders=False ), ) painter.translate(QPointF(faceWidth, 0.0)) self.cbLastMeld.addItem(QIcon(pixMap), "", toQVariant(str(meld))) if indexedMeld == str(meld): restoredIdx = self.cbLastMeld.count() - 1 if not restoredIdx and indexedMeld: # try again, maybe the meld changed between concealed and exposed indexedMeld = indexedMeld.lower() for idx in range(self.cbLastMeld.count()): meldContent = str(variantValue(self.cbLastMeld.itemData(idx))) if indexedMeld == meldContent.lower(): restoredIdx = idx if lastTile not in meldContent: lastTile = lastTile.swapped assert lastTile in meldContent with BlockSignals(self.cbLastTile): # we want to continue right here idx = self.cbLastTile.findData(toQVariant(lastTile)) self.cbLastTile.setCurrentIndex(idx) break if not restoredIdx: restoredIdx = 0 self.cbLastMeld.setCurrentIndex(restoredIdx) self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight)) def fillLastMeldCombo(self): """fill the drop down list with all possible melds. If the drop down had content before try to preserve the current index. Even if the meld changed state meanwhile.""" with BlockSignals(self.cbLastMeld): # we only want to emit the changed signal once showCombo = False idx = self.cbLastMeld.currentIndex() if idx < 0: idx = 0 indexedMeld = str(variantValue(self.cbLastMeld.itemData(idx))) self.cbLastMeld.clear() self.__meldPixMaps = [] if not self.game.winner: return if self.cbLastTile.count() == 0: return lastTile = Internal.scene.computeLastTile() winnerMelds = [m for m in self.game.winner.hand.melds if len(m) < 4 and lastTile in m] assert len(winnerMelds), "lastTile %s missing in %s" % (lastTile, self.game.winner.hand.melds) if len(winnerMelds) == 1: self.cbLastMeld.addItem(QIcon(), "", toQVariant(str(winnerMelds[0]))) self.cbLastMeld.setCurrentIndex(0) return showCombo = True self.__fillLastMeldComboWith(winnerMelds, indexedMeld, lastTile) self.lblLastMeld.setVisible(showCombo) self.cbLastMeld.setVisible(showCombo) self.cbLastMeld.currentIndexChanged.emit(0) def slotInputChanged(self): """some input fields changed: update""" for player in self.game.players: player.invalidateHand() self.updateManualRules() self.computeScores() self.validate() for player in self.game.players: self.game.wall.decoratePlayer(player) Internal.mainWindow.updateGUI() def validate(self): """update the status of the OK button""" game = self.game if game: valid = True if game.winner and game.winner.handTotal < game.ruleset.minMJTotal(): valid = False elif not game.winner and not self.draw.isChecked(): valid = False self.btnSave.setEnabled(valid)
class MainWin(KMainWindow): """ Constructor. """ def __init__(self, *args): apply(KMainWindow.__init__, (self,) + args) self.lastDir = "/var/log" self.setGeometry(0, 0, 600, 400) # self.grid = QGridLayout(self, 1, 1) self.tab = QTabWidget(self) self.tab.addTab(QMultiLineEdit(self.tab), "Tab") self.layout().addWidget(self.tab, 0, 0) self.setCaption(str(i18n("%s - lovi")) % str(i18n("(none)"))) self.initActions() self.initMenus() """ Initialize actions. """ def initActions(self): actions = self.actionCollection() self.openAction = KStdAction.open(self.slotOpen, actions) self.quitAction = KStdAction.quit(self.slotQuit, actions) """ Initialize menus. """ def initMenus(self): fileMenu = QPopupMenu(self) self.openAction.plug(fileMenu) fileMenu.insertSeparator() self.quitAction.plug(fileMenu) self.menuBar().insertItem(i18n("&File"), fileMenu) helpMenu = self.helpMenu("") self.menuBar().insertItem(i18n("&Help"), helpMenu) """ Open a file. """ def slotOpen(self, id = -1): fileName = KFileDialog.getOpenFileName(self.lastDir, "*", self, str(i18n("Open Log File"))) print fileName if not fileName.isEmpty(): self.lastDir = os.path.dirname(str(fileName)) self.monitor(str(fileName)) """ Quit application. """ def slotQuit(self, id = -1): self.close() """ Monitor a file. @param fileName File to monitor """ def monitor(self, fileName): try: tailer = Tail(fileName) except: KMessageBox.error(self, str(i18n("Cannot open file for monitoring:\n%s")) % fileName, i18n("Error - lovi")) return self.tab.addTab(Monitor(tailer), os.path.basename(fileName))
class MainWin(KMainWindow): """ Constructor. """ def __init__(self, *args): apply(KMainWindow.__init__, (self, ) + args) self.lastDir = "/var/log" self.setGeometry(0, 0, 600, 400) # self.grid = QGridLayout(self, 1, 1) self.tab = QTabWidget(self) self.tab.addTab(QMultiLineEdit(self.tab), "Tab") self.layout().addWidget(self.tab, 0, 0) self.setCaption(str(i18n("%s - lovi")) % str(i18n("(none)"))) self.initActions() self.initMenus() """ Initialize actions. """ def initActions(self): actions = self.actionCollection() self.openAction = KStdAction.open(self.slotOpen, actions) self.quitAction = KStdAction.quit(self.slotQuit, actions) """ Initialize menus. """ def initMenus(self): fileMenu = QPopupMenu(self) self.openAction.plug(fileMenu) fileMenu.insertSeparator() self.quitAction.plug(fileMenu) self.menuBar().insertItem(i18n("&File"), fileMenu) helpMenu = self.helpMenu("") self.menuBar().insertItem(i18n("&Help"), helpMenu) """ Open a file. """ def slotOpen(self, id=-1): fileName = KFileDialog.getOpenFileName(self.lastDir, "*", self, str(i18n("Open Log File"))) print fileName if not fileName.isEmpty(): self.lastDir = os.path.dirname(str(fileName)) self.monitor(str(fileName)) """ Quit application. """ def slotQuit(self, id=-1): self.close() """ Monitor a file. @param fileName File to monitor """ def monitor(self, fileName): try: tailer = Tail(fileName) except: KMessageBox.error( self, str(i18n("Cannot open file for monitoring:\n%s")) % fileName, i18n("Error - lovi")) return self.tab.addTab(Monitor(tailer), os.path.basename(fileName))
def showEvent(self, event): """Redefinición del show de la clase base""" self.myUpdate() QTabWidget.showEvent(self, event)
class ParamMainWidget(QWidget): update_command_lst_low_level = Signal(list) def __init__(self, phl_obj=None, simp_widg=None, parent=None, upper_label=None): super(ParamMainWidget, self).__init__() self.command_lst = [[None]] self.lst_pair = [] try: self.my_phl_obj = phl_obj self.simp_widg_in = simp_widg except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info("Caught unknown exception #1 type %s: %s", type(e).__name__, e) logger.info("\n\n\n something went wrong here wiht the phil object \n\n\n") self.build_param_widget() label_font = QFont() sys_font_point_size = label_font.pointSize() label_font.setPointSize(sys_font_point_size + 2) self.step_label = QLabel(str(upper_label)) self.step_label.setFont(label_font) self._vbox = QVBoxLayout() self._vbox.addWidget(self.step_label) self._vbox.addWidget(self.dual_level_tab) self.setLayout(self._vbox) # self.show() def build_param_widget(self): self.dual_level_tab = QTabWidget() self.simpler_widget = self.simp_widg_in() self.advanced_widget = ParamAdvancedWidget(phl_obj=self.my_phl_obj, parent=self) self.advanced_widget.scrollable_widget.item_changed.connect(self.update_lin_txt) try: self.simpler_widget.item_changed.connect(self.update_advanced_widget) except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info("Caught unknown exception #2 type %s: %s", type(e).__name__, e) logger.info("found self.simpler_widget without << item_changed >> signal") try: self.simpler_widget.item_to_remove.connect(self.remove_one_par) except AttributeError: pass self.reset_btn = self.simpler_widget.inner_reset_btn self.dual_level_tab.addTab(self.simpler_widget, "Simple") self.dual_level_tab.addTab(self.advanced_widget, "Advanced") self.reset_btn.clicked.connect(self.reset_par) def reset_par(self): for i in reversed(list(range(self._vbox.count()))): widgetToRemove = self._vbox.itemAt(i).widget() self._vbox.removeWidget(widgetToRemove) widgetToRemove.setParent(None) self.build_param_widget() self._vbox.addWidget(self.step_label) self._vbox.addWidget(self.dual_level_tab) self.command_lst[0] = [self.command_lst[0][0]] self.lst_pair = [] self.update_command_lst_low_level.emit(self.command_lst[0]) try: max_nproc = self.simpler_widget.set_max_nproc() if max_nproc > 1: self.raise_nproc_str = ( str(self.simpler_widget.box_nproc.local_path) + "=" + str(max_nproc) ) QTimer.singleShot(1000, self.raise_nproc_to_max) except AttributeError: pass def raise_nproc_to_max(self): found_nproc = False for single_par in self.command_lst[0]: if "mp.nproc" in single_par: found_nproc = True if not found_nproc: self.command_lst[0].append(self.raise_nproc_str) self.update_command_lst_low_level.emit(self.command_lst[0]) def update_advanced_widget(self, str_path, str_value): for bg_widg in ( self.advanced_widget.scrollable_widget.lst_var_widg, self.simpler_widget.lst_var_widg, ): for widg in bg_widg: try: if widg.local_path == str_path: if not hasattr(widg, "tmp_lst") or widg.tmp_lst is None: try: num_val = float(str_value) widg.setValue(num_val) except BaseException: try: str_val = str(str_value) widg.setText(str_val) logger.debug( "widg.local_path = %s", widg.local_path ) except BaseException as ee: logger.info("ee = ", ee) else: for pos, val in enumerate(widg.tmp_lst): if val == str_value: try: widg.setCurrentIndex(pos) except BaseException as e: # We don't want to catch bare exceptions but # dont know what this was supposed to catch. logger.info( "Caught unknown exception #5 type: %s", e ) logger.info("failed to:") logger.info("widg.setCurrentIndex(pos)") except AttributeError: pass def update_simpler_widget(self, str_path, str_value): for widg in self.simpler_widget.lst_var_widg: try: if widg.local_path == str_path: logger.debug("found << widg.local_path == str_path >> ") try: num_val = float(str_value) widg.setValue(num_val) except ValueError: for pos, val in enumerate(widg.tmp_lst): if val == str_value: logger.info("found val, v= %s", val) widg.setCurrentIndex(pos) except AttributeError: pass def update_lin_txt(self, str_path, str_value): # cmd_to_run = str_path + "=" + str_value self.update_advanced_widget(str_path, str_value) self.update_simpler_widget(str_path, str_value) self.lst_pair = update_lst_pair(self.lst_pair, str_path, str_value) self.command_lst[0] = build_lst_str(self.command_lst[0][0], self.lst_pair) self.update_command_lst_low_level.emit(self.command_lst[0]) def update_param_w_lst(self, lst_in, do_reset=True): if do_reset: self.reset_par() if len(lst_in) > 1: self.lst_pair = buils_lst_pair(lst_in) self.command_lst[0] = build_lst_str(lst_in[0], self.lst_pair) for pair in self.lst_pair: self.update_advanced_widget(pair[0], pair[1]) else: self.lst_pair = [] self.command_lst[0] = lst_in def remove_one_par(self, path_str): nxt_lst = [] for single_param in self.command_lst[0]: if str(path_str) in single_param: pass else: nxt_lst.append(str(single_param)) self.update_param_w_lst(nxt_lst, do_reset=False) def gray_me_out(self): self.reset_btn.setEnabled(False) palt_gray = QPalette() palt_gray.setColor(QPalette.WindowText, QColor(88, 88, 88, 88)) for bg_widg in ( self.advanced_widget.scrollable_widget.lst_var_widg, self.advanced_widget.scrollable_widget.lst_label_widg, self.simpler_widget.lst_var_widg, ): for widg in bg_widg: widg.setStyleSheet("color: rgba(88, 88, 88, 88)") try: widg.setEnabled(False) except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info( "Caught unknown exception #9 type %s: %s", type(e).__name__, e ) pass def activate_me(self, cur_nod=None): self.reset_btn.setEnabled(True) for bg_widg in ( self.advanced_widget.scrollable_widget.lst_var_widg, self.advanced_widget.scrollable_widget.lst_label_widg, self.simpler_widget.lst_var_widg, ): for widg in bg_widg: widg.setStyleSheet("color: rgba(0, 0, 0, 255)") try: widg.setStyleSheet(widg.style_orign) except AttributeError: pass try: widg.setEnabled(True) except BaseException as e: # We don't want to catch bare exceptions but don't know # what this was supposed to catch. Log it. logger.info( "Caught unknown exception #11 type %s: %s", type(e).__name__, e )
class MainWin(KMainWindow): """Main window""" SB_TEXT = 1 SB_TIMEOUT = 10000 MON_TIMEOUT = 1000 CHANGE_TIMEOUT = 3001 def __init__(self, *args): apply(KMainWindow.__init__, (self,) + args) self.lastDir = "/var/log" self.monitors = [] self.currentPage = None self.tab = QTabWidget(self) self.settingsDlg = SettingsDlg(self) self.cfg = LoviConfig().getInstance() self.bellIcon = \ QIconSet(KIconLoader().loadIcon("idea", KIcon.Small, 11)) self.noIcon = QIconSet() self.findDlg = KEdFind(self, "find", False) self.connect(self.findDlg, SIGNAL("search()"), self.doFind) self.setCentralWidget(self.tab) self.connect(self.tab, SIGNAL("currentChanged(QWidget *)"), self.onPageChange) self.setGeometry(0, 0, 600, 400) self.setCaption(makeCaption("(none)")) # Timers self.timer = QTimer(self) self.timer.start(MainWin.MON_TIMEOUT) self.statusTimer = QTimer(self) self.connect(self.statusTimer, SIGNAL("timeout()"), self.onStatusTimeout) self.changeTimer = QTimer(self) self.changeTimer.start(MainWin.CHANGE_TIMEOUT) self.connect(self.changeTimer, SIGNAL("timeout()"), self.onChangeTimeout) # Initialize actions actions = self.actionCollection() self.openAction = KStdAction.open(self.onOpen, actions) self.closeAction = KStdAction.close(self.onClose, actions) self.closeAction.setEnabled(False) self.quitAction = KStdAction.quit(self.onQuit, actions) self.copyAction = KStdAction.copy(self.onCopy, actions) self.copyAction.setEnabled(False) self.clearAction = KStdAction.clear(self.onClear, actions) self.clearAction.setEnabled(False) self.selectAllAction = KStdAction.selectAll(self.onSelectAll, actions) self.selectAllAction.setEnabled(False) self.addBookmarkAction = \ KStdAction.addBookmark(self.onAddBookmark, actions) self.addBookmarkAction.setEnabled(False) self.settingsAction = KStdAction.preferences(self.onSettings, actions) self.findAction = KStdAction.find(self.onFind, actions) self.findAction.setEnabled(False) self.findNextAction = KStdAction.findNext(self.onFindNext, actions) self.findNextAction.setEnabled(False) self.findPrevAction = KStdAction.findPrev(self.onFindPrev, actions) self.findPrevAction.setEnabled(False) # Initialize menus fileMenu = QPopupMenu(self) self.openAction.plug(fileMenu) self.closeAction.plug(fileMenu) fileMenu.insertSeparator() self.quitAction.plug(fileMenu) self.menuBar().insertItem(i18n("&File"), fileMenu) editMenu = QPopupMenu(self) self.copyAction.plug(editMenu) self.clearAction.plug(editMenu) editMenu.insertSeparator() self.selectAllAction.plug(editMenu) self.addBookmarkAction.plug(editMenu) editMenu.insertSeparator() self.findAction.plug(editMenu) self.findNextAction.plug(editMenu) self.findPrevAction.plug(editMenu) self.menuBar().insertItem(i18n("&Edit"), editMenu) settingsMenu = QPopupMenu(self) self.settingsAction.plug(settingsMenu) self.menuBar().insertItem(i18n("&Settings"), settingsMenu) helpMenu = self.helpMenu("") self.menuBar().insertItem(i18n("&Help"), helpMenu) # Initialize status bar self.sb = self.statusBar() self.bell = BellButton(None) self.displayStatus(False, "") def displayStatus(self, changed, msg): """Display a message in the status bar.""" self.statusTimer.stop() self.sb.removeWidget(self.bell) self.sb.removeItem(MainWin.SB_TEXT) if changed: self.sb.addWidget(self.bell, 1, False) self.sb.insertItem(msg, MainWin.SB_TEXT, 1000, True) self.sb.setItemAlignment(MainWin.SB_TEXT, Qt.AlignLeft|Qt.AlignVCenter) self.statusTimer.start(MainWin.SB_TIMEOUT, True) def onOpen(self, id = -1): """Open file for monitoring.""" fileName = KFileDialog.getOpenFileName(self.lastDir, "*", self, str(i18n("Open Log File"))) if not fileName.isEmpty(): fileName = str(fileName) self.lastDir = os.path.dirname(fileName) self.monitor(fileName) def onClose(self, id = -1): """Close a monitored file.""" self.monitors.remove(self.currentPage) self.currentPage.close() self.tab.removePage(self.currentPage) self.displayStatus(False, "") self.saveFileList() if len(self.monitors) == 0: # Update interface when the last page is deleted self.setCaption(makeCaption("(none)")) self.closeAction.setEnabled(False) self.copyAction.setEnabled(False) self.selectAllAction.setEnabled(False) self.clearAction.setEnabled(False) self.addBookmarkAction.setEnabled(False) self.findAction.setEnabled(False) self.findNextAction.setEnabled(False) self.findPrevAction.setEnabled(False) def onQuit(self, id = -1): """Quit application.""" self.close() def onCopy(self, id = -1): """Copy text to clipboard.""" self.currentPage.copy() def onClear(self, id = -1): """Clear text window.""" self.currentPage.setText("") def onSelectAll(self, id = -1): """Select all text.""" self.currentPage.selectAll(True) def onAddBookmark(self, id = -1): """Add a bookmark to the log.""" bookmark = "<font color=\"blue\">" bookmark += datetime.datetime.now().strftime("%b %d %H:%M:%S ") bookmark += "--------------------------------------------------------" bookmark += "</font>" self.currentPage.append(bookmark) def onSettings(self, id = -1): """Display settings dialog""" if self.settingsDlg.exec_loop(): self.cfg.writeConfig() self.cfg.processConfig() self.reconfigure() def onPageChange(self, page): """Update widget when the top level tab changes.""" self.currentPage = page self.setCaption(makeCaption(os.path.basename(page.getFileName()))) self.copyAction.setEnabled(page.hasSelectedText()) # self.tab.setTabIconSet(page, self.noIcon) def onStatusTimeout(self): """Clear status bar on timeout.""" self.displayStatus(False, "") for m in self.monitors: self.tab.setTabIconSet(m, self.noIcon) def onChangeTimeout(self): """Look for changes in monitored files. """ changeList = [] for m in self.monitors: if m.isChanged(): changeList.append(os.path.basename(m.getFileName())) self.tab.setTabIconSet(m, self.bellIcon) if len(changeList): msg = changeList[0] for f in changeList[1:]: msg += ", %s" % f msg = str(i18n("Change to %s")) % msg self.displayStatus(True, msg) def onCopyAvailable(self, available): """Update Copy menu item when there is a selection available.""" self.copyAction.setEnabled(available) def onFind(self): self.findDlg.show() def onFindPrev(self): if self.findDlg.getText() == "": self.onFind() else: self.currentPage.find(self.findDlg.getText(), self.findDlg.case_sensitive(), True) def onFindNext(self): if self.findDlg.getText() == "": self.onFind() else: self.currentPage.find(self.findDlg.getText(), self.findDlg.case_sensitive(), False) def monitor(self, fileName): """Start monitoring a file.""" try: tailer = Tail(fileName) except: KMessageBox.error(self, str(i18n("Cannot open file for monitoring:\n%s")) % fileName, makeCaption("Error")) return mon = Monitor(self.tab, tailer) base = os.path.basename(fileName) self.monitors.append(mon) self.tab.addTab(mon, base) self.tab.showPage(mon) self.tab.setTabToolTip(mon, fileName) self.currentPage = mon self.setCaption(makeCaption(base)) self.displayStatus(False, str(i18n("Monitoring %s")) % fileName) self.connect(self.timer, SIGNAL("timeout()"), mon.follow) self.saveFileList() self.connect(mon, SIGNAL("copyAvailable(bool)"), self.onCopyAvailable) self.closeAction.setEnabled(True) self.copyAction.setEnabled(False) self.clearAction.setEnabled(True) self.selectAllAction.setEnabled(True) self.addBookmarkAction.setEnabled(True) self.findAction.setEnabled(True) self.findNextAction.setEnabled(True) self.findPrevAction.setEnabled(True) def saveFileList(self): """Update the list of monitored files in the configuration file.""" files = [] for mon in self.monitors: files.append(mon.getFileName()) cfg = KApplication.kApplication().config() cfg.setGroup("Monitor") cfg.writeEntry("files", files) def reconfigure(self): """Update self with configuration changes.""" for mon in self.monitors: mon.reconfigure() def doFind(self): self.currentPage.find(self.findDlg.getText(), self.findDlg.case_sensitive(), self.findDlg.get_direction())
def __init__(self, *args): apply(KMainWindow.__init__, (self,) + args) self.lastDir = "/var/log" self.monitors = [] self.currentPage = None self.tab = QTabWidget(self) self.settingsDlg = SettingsDlg(self) self.cfg = LoviConfig().getInstance() self.bellIcon = \ QIconSet(KIconLoader().loadIcon("idea", KIcon.Small, 11)) self.noIcon = QIconSet() self.findDlg = KEdFind(self, "find", False) self.connect(self.findDlg, SIGNAL("search()"), self.doFind) self.setCentralWidget(self.tab) self.connect(self.tab, SIGNAL("currentChanged(QWidget *)"), self.onPageChange) self.setGeometry(0, 0, 600, 400) self.setCaption(makeCaption("(none)")) # Timers self.timer = QTimer(self) self.timer.start(MainWin.MON_TIMEOUT) self.statusTimer = QTimer(self) self.connect(self.statusTimer, SIGNAL("timeout()"), self.onStatusTimeout) self.changeTimer = QTimer(self) self.changeTimer.start(MainWin.CHANGE_TIMEOUT) self.connect(self.changeTimer, SIGNAL("timeout()"), self.onChangeTimeout) # Initialize actions actions = self.actionCollection() self.openAction = KStdAction.open(self.onOpen, actions) self.closeAction = KStdAction.close(self.onClose, actions) self.closeAction.setEnabled(False) self.quitAction = KStdAction.quit(self.onQuit, actions) self.copyAction = KStdAction.copy(self.onCopy, actions) self.copyAction.setEnabled(False) self.clearAction = KStdAction.clear(self.onClear, actions) self.clearAction.setEnabled(False) self.selectAllAction = KStdAction.selectAll(self.onSelectAll, actions) self.selectAllAction.setEnabled(False) self.addBookmarkAction = \ KStdAction.addBookmark(self.onAddBookmark, actions) self.addBookmarkAction.setEnabled(False) self.settingsAction = KStdAction.preferences(self.onSettings, actions) self.findAction = KStdAction.find(self.onFind, actions) self.findAction.setEnabled(False) self.findNextAction = KStdAction.findNext(self.onFindNext, actions) self.findNextAction.setEnabled(False) self.findPrevAction = KStdAction.findPrev(self.onFindPrev, actions) self.findPrevAction.setEnabled(False) # Initialize menus fileMenu = QPopupMenu(self) self.openAction.plug(fileMenu) self.closeAction.plug(fileMenu) fileMenu.insertSeparator() self.quitAction.plug(fileMenu) self.menuBar().insertItem(i18n("&File"), fileMenu) editMenu = QPopupMenu(self) self.copyAction.plug(editMenu) self.clearAction.plug(editMenu) editMenu.insertSeparator() self.selectAllAction.plug(editMenu) self.addBookmarkAction.plug(editMenu) editMenu.insertSeparator() self.findAction.plug(editMenu) self.findNextAction.plug(editMenu) self.findPrevAction.plug(editMenu) self.menuBar().insertItem(i18n("&Edit"), editMenu) settingsMenu = QPopupMenu(self) self.settingsAction.plug(settingsMenu) self.menuBar().insertItem(i18n("&Settings"), settingsMenu) helpMenu = self.helpMenu("") self.menuBar().insertItem(i18n("&Help"), helpMenu) # Initialize status bar self.sb = self.statusBar() self.bell = BellButton(None) self.displayStatus(False, "")
class ScoringDialog(QWidget): """a dialog for entering the scores""" # pylint: disable=too-many-instance-attributes def __init__(self, scene): QWidget.__init__(self) self.scene = scene decorateWindow(self, i18n('Scoring for this Hand')) self.nameLabels = [None] * 4 self.spValues = [None] * 4 self.windLabels = [None] * 4 self.wonBoxes = [None] * 4 self.detailsLayout = [None] * 4 self.details = [None] * 4 self.__tilePixMaps = [] self.__meldPixMaps = [] grid = QGridLayout(self) pGrid = QGridLayout() grid.addLayout(pGrid, 0, 0, 2, 1) pGrid.addWidget(QLabel(i18nc('kajongg', "Player")), 0, 0) pGrid.addWidget(QLabel(i18nc('kajongg', "Wind")), 0, 1) pGrid.addWidget(QLabel(i18nc('kajongg', 'Score')), 0, 2) pGrid.addWidget(QLabel(i18n("Winner")), 0, 3) self.detailTabs = QTabWidget() self.detailTabs.setDocumentMode(True) pGrid.addWidget(self.detailTabs, 0, 4, 8, 1) for idx in range(4): self.setupUiForPlayer(pGrid, idx) self.draw = QCheckBox(i18nc('kajongg', 'Draw')) self.draw.clicked.connect(self.wonChanged) btnPenalties = QPushButton(i18n("&Penalties")) btnPenalties.clicked.connect(self.penalty) self.btnSave = QPushButton(i18n('&Save Hand')) self.btnSave.clicked.connect(self.game.nextScoringHand) self.btnSave.setEnabled(False) self.setupUILastTileMeld(pGrid) pGrid.setRowStretch(87, 10) pGrid.addWidget(self.draw, 7, 3) self.cbLastTile.currentIndexChanged.connect(self.slotLastTile) self.cbLastMeld.currentIndexChanged.connect(self.slotInputChanged) btnBox = QHBoxLayout() btnBox.addWidget(btnPenalties) btnBox.addWidget(self.btnSave) pGrid.addLayout(btnBox, 8, 4) StateSaver(self) self.refresh() @property def game(self): """proxy""" return self.scene.game def setupUILastTileMeld(self, pGrid): """setup UI elements for last tile and last meld""" self.lblLastTile = QLabel(i18n('&Last Tile:')) self.cbLastTile = QComboBox() self.cbLastTile.setMinimumContentsLength(1) vpol = QSizePolicy() vpol.setHorizontalPolicy(QSizePolicy.Fixed) self.cbLastTile.setSizePolicy(vpol) self.cbLastTile.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lblLastTile.setBuddy(self.cbLastTile) self.lblLastMeld = QLabel(i18n('L&ast Meld:')) self.prevLastTile = None self.cbLastMeld = QComboBox() self.cbLastMeld.setMinimumContentsLength(1) self.cbLastMeld.setSizePolicy(vpol) self.cbLastMeld.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lblLastMeld.setBuddy(self.cbLastMeld) self.comboTilePairs = set() pGrid.setRowStretch(6, 5) pGrid.addWidget(self.lblLastTile, 7, 0, 1, 2) pGrid.addWidget(self.cbLastTile, 7, 2, 1, 1) pGrid.addWidget(self.lblLastMeld, 8, 0, 1, 2) pGrid.addWidget(self.cbLastMeld, 8, 2, 1, 2) def setupUiForPlayer(self, pGrid, idx): """setup UI elements for a player""" self.spValues[idx] = QSpinBox() self.nameLabels[idx] = QLabel() self.nameLabels[idx].setBuddy(self.spValues[idx]) self.windLabels[idx] = WindLabel() pGrid.addWidget(self.nameLabels[idx], idx + 2, 0) pGrid.addWidget(self.windLabels[idx], idx + 2, 1) pGrid.addWidget(self.spValues[idx], idx + 2, 2) self.wonBoxes[idx] = QCheckBox("") pGrid.addWidget(self.wonBoxes[idx], idx + 2, 3) self.wonBoxes[idx].clicked.connect(self.wonChanged) self.spValues[idx].valueChanged.connect(self.slotInputChanged) detailTab = QWidget() self.detailTabs.addTab(detailTab, '') self.details[idx] = QWidget() detailTabLayout = QVBoxLayout(detailTab) detailTabLayout.addWidget(self.details[idx]) detailTabLayout.addStretch() self.detailsLayout[idx] = QVBoxLayout(self.details[idx]) def refresh(self): """reload game""" self.clear() game = self.game self.setVisible(game is not None and not game.finished()) if game: for idx, player in enumerate(game.players): for child in self.details[idx].children(): if isinstance(child, RuleBox): child.hide() self.detailsLayout[idx].removeWidget(child) del child if game: self.spValues[idx].setRange(0, game.ruleset.limit or 99999) self.nameLabels[idx].setText(player.localName) self.refreshWindLabels() self.detailTabs.setTabText(idx, player.localName) player.manualRuleBoxes = [ RuleBox(x) for x in game.ruleset.allRules if x.hasSelectable ] for ruleBox in player.manualRuleBoxes: self.detailsLayout[idx].addWidget(ruleBox) ruleBox.clicked.connect(self.slotInputChanged) player.refreshManualRules() def show(self): """only now compute content""" if self.game and not self.game.finished(): self.slotInputChanged() QWidget.show(self) def penalty(self): """penalty button clicked""" dlg = PenaltyDialog(self.game) dlg.exec_() def slotLastTile(self): """called when the last tile changes""" newLastTile = self.computeLastTile() if not newLastTile: return if self.prevLastTile and self.prevLastTile.isExposed != newLastTile.isExposed: # state of last tile (concealed/exposed) changed: # for all checked boxes check if they still are applicable winner = self.game.winner if winner: for box in winner.manualRuleBoxes: if box.isChecked(): box.setChecked(False) if winner.hand.manualRuleMayApply(box.rule): box.setChecked(True) self.prevLastTile = newLastTile self.fillLastMeldCombo() self.slotInputChanged() def computeLastTile(self): """returns the currently selected last tile""" idx = self.cbLastTile.currentIndex() if idx >= 0: return self.cbLastTile.itemData(idx) def clickedPlayerIdx(self, checkbox): """the player whose box has been clicked""" for idx in range(4): if checkbox == self.wonBoxes[idx]: return idx assert False def wonChanged(self): """if a new winner has been defined, uncheck any previous winner""" newWinner = None if self.sender() != self.draw: clicked = self.clickedPlayerIdx(self.sender()) if self.wonBoxes[clicked].isChecked(): newWinner = self.game.players[clicked] else: newWinner = None self.game.winner = newWinner for idx in range(4): if newWinner != self.game.players[idx]: self.wonBoxes[idx].setChecked(False) if newWinner: self.draw.setChecked(False) self.fillLastTileCombo() self.slotInputChanged() def updateManualRules(self): """enable/disable them""" # if an exclusive rule has been activated, deactivate it for # all other players ruleBox = self.sender() if isinstance( ruleBox, RuleBox) and ruleBox.isChecked() and ruleBox.rule.exclusive(): for idx, player in enumerate(self.game.players): if ruleBox.parentWidget() != self.details[idx]: for pBox in player.manualRuleBoxes: if pBox.rule.name == ruleBox.rule.name: pBox.setChecked(False) try: newState = bool(self.game.winner.handBoard.uiTiles) except AttributeError: newState = False self.lblLastTile.setEnabled(newState) self.cbLastTile.setEnabled(newState) self.lblLastMeld.setEnabled(newState) self.cbLastMeld.setEnabled(newState) if self.game: for player in self.game.players: player.refreshManualRules(self.sender()) def clear(self): """prepare for next hand""" if self.game: for idx, player in enumerate(self.game.players): self.spValues[idx].clear() self.spValues[idx].setValue(0) self.wonBoxes[idx].setChecked(False) player.payment = 0 player.invalidateHand() for box in self.wonBoxes: box.setVisible(False) self.draw.setChecked(False) self.updateManualRules() if self.game is None: self.hide() else: self.refreshWindLabels() self.computeScores() self.spValues[0].setFocus() self.spValues[0].selectAll() def refreshWindLabels(self): """update their wind and prevailing""" for idx, player in enumerate(self.game.players): self.windLabels[idx].wind = player.wind self.windLabels[idx].roundsFinished = self.game.roundsFinished def computeScores(self): """if tiles have been selected, compute their value""" # pylint: disable=too-many-branches # too many branches if not self.game: return if self.game.finished(): self.hide() return for nameLabel, wonBox, spValue, player in zip(self.nameLabels, self.wonBoxes, self.spValues, self.game.players): with BlockSignals([spValue, wonBox]): # we do not want that change to call computeScores again if player.handBoard and player.handBoard.uiTiles: spValue.setEnabled(False) nameLabel.setBuddy(wonBox) for _ in range(10): prevTotal = player.handTotal player.invalidateHand() wonBox.setVisible(player.hand.won) if not wonBox.isVisibleTo(self) and wonBox.isChecked(): wonBox.setChecked(False) self.game.winner = None elif prevTotal == player.handTotal: break player.refreshManualRules() spValue.setValue(player.handTotal) else: if not spValue.isEnabled(): spValue.clear() spValue.setValue(0) spValue.setEnabled(True) nameLabel.setBuddy(spValue) wonBox.setVisible( player.handTotal >= self.game.ruleset.minMJTotal()) if not wonBox.isVisibleTo(self) and wonBox.isChecked(): wonBox.setChecked(False) if not wonBox.isVisibleTo(self) and player is self.game.winner: self.game.winner = None if Internal.scene.explainView: Internal.scene.explainView.refresh() def __lastMeldContent(self): """prepare content for lastmeld combo""" lastTiles = set() winnerTiles = [] if self.game.winner and self.game.winner.handBoard: winnerTiles = self.game.winner.handBoard.uiTiles pairs = [] for meld in self.game.winner.hand.melds: if len(meld) < 4: pairs.extend(meld) for tile in winnerTiles: if tile.tile in pairs and not tile.isBonus: lastTiles.add(tile.tile) return lastTiles, winnerTiles def __fillLastTileComboWith(self, lastTiles, winnerTiles): """fill last meld combo with prepared content""" self.comboTilePairs = lastTiles idx = self.cbLastTile.currentIndex() if idx < 0: idx = 0 indexedTile = self.cbLastTile.itemData(idx) restoredIdx = None self.cbLastTile.clear() if not winnerTiles: return pmSize = winnerTiles[0].board.tileset.faceSize pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5) self.cbLastTile.setIconSize(pmSize) QPixmapCache.clear() self.__tilePixMaps = [] shownTiles = set() for tile in winnerTiles: if tile.tile in lastTiles and tile.tile not in shownTiles: shownTiles.add(tile.tile) self.cbLastTile.addItem( QIcon(tile.pixmapFromSvg(pmSize, withBorders=False)), '', tile.tile) if indexedTile is tile.tile: restoredIdx = self.cbLastTile.count() - 1 if not restoredIdx and indexedTile: # try again, maybe the tile changed between concealed and exposed indexedTile = indexedTile.exposed for idx in range(self.cbLastTile.count()): if indexedTile is self.cbLastTile.itemData(idx).exposed: restoredIdx = idx break if not restoredIdx: restoredIdx = 0 self.cbLastTile.setCurrentIndex(restoredIdx) self.prevLastTile = self.computeLastTile() def clearLastTileCombo(self): """as the name says""" self.comboTilePairs = None self.cbLastTile.clear() def fillLastTileCombo(self): """fill the drop down list with all possible tiles. If the drop down had content before try to preserve the current index. Even if the tile changed state meanwhile.""" if self.game is None: return lastTiles, winnerTiles = self.__lastMeldContent() if self.comboTilePairs == lastTiles: return with BlockSignals(self.cbLastTile): # we only want to emit the changed signal once self.__fillLastTileComboWith(lastTiles, winnerTiles) self.cbLastTile.currentIndexChanged.emit(0) def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile): """fill last meld combo with prepared content""" winner = self.game.winner faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5 faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5 restoredIdx = None for meld in winnerMelds: pixMap = QPixmap(faceWidth * len(meld), faceHeight) pixMap.fill(Qt.transparent) self.__meldPixMaps.append(pixMap) painter = QPainter(pixMap) for element in meld: painter.drawPixmap( 0, 0, winner.handBoard.tilesByElement(element)[0].pixmapFromSvg( QSize(faceWidth, faceHeight), withBorders=False)) painter.translate(QPointF(faceWidth, 0.0)) self.cbLastMeld.addItem(QIcon(pixMap), '', str(meld)) if indexedMeld == str(meld): restoredIdx = self.cbLastMeld.count() - 1 if not restoredIdx and indexedMeld: # try again, maybe the meld changed between concealed and exposed indexedMeld = indexedMeld.lower() for idx in range(self.cbLastMeld.count()): meldContent = str(self.cbLastMeld.itemData(idx)) if indexedMeld == meldContent.lower(): restoredIdx = idx if lastTile not in meldContent: lastTile = lastTile.swapped assert lastTile in meldContent with BlockSignals(self.cbLastTile ): # we want to continue right here idx = self.cbLastTile.findData(lastTile) self.cbLastTile.setCurrentIndex(idx) break if not restoredIdx: restoredIdx = 0 self.cbLastMeld.setCurrentIndex(restoredIdx) self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight)) def fillLastMeldCombo(self): """fill the drop down list with all possible melds. If the drop down had content before try to preserve the current index. Even if the meld changed state meanwhile.""" with BlockSignals(self.cbLastMeld ): # we only want to emit the changed signal once showCombo = False idx = self.cbLastMeld.currentIndex() if idx < 0: idx = 0 indexedMeld = str(self.cbLastMeld.itemData(idx)) self.cbLastMeld.clear() self.__meldPixMaps = [] if not self.game.winner: return if self.cbLastTile.count() == 0: return lastTile = Internal.scene.computeLastTile() winnerMelds = [ m for m in self.game.winner.hand.melds if len(m) < 4 and lastTile in m ] assert len(winnerMelds), 'lastTile %s missing in %s' % ( lastTile, self.game.winner.hand.melds) if len(winnerMelds) == 1: self.cbLastMeld.addItem(QIcon(), '', str(winnerMelds[0])) self.cbLastMeld.setCurrentIndex(0) return showCombo = True self.__fillLastMeldComboWith(winnerMelds, indexedMeld, lastTile) self.lblLastMeld.setVisible(showCombo) self.cbLastMeld.setVisible(showCombo) self.cbLastMeld.currentIndexChanged.emit(0) def slotInputChanged(self): """some input fields changed: update""" for player in self.game.players: player.invalidateHand() self.updateManualRules() self.computeScores() self.validate() for player in self.game.players: player.showInfo() Internal.mainWindow.updateGUI() def validate(self): """update the status of the OK button""" game = self.game if game: valid = True if game.winner and game.winner.handTotal < game.ruleset.minMJTotal( ): valid = False elif not game.winner and not self.draw.isChecked(): valid = False self.btnSave.setEnabled(valid)