Exemple #1
0
    def __init__(self, parent=None):
        super(ExportPage, self).__init__(parent=None)

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Export"))
        step_label.setFont(label_font)

        out_file_label = QLabel(str("mtz output name:"))

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.check_scale = QCheckBox("Output Scaled Intensities")
        self.check_scale.setChecked(False)
        self.check_scale.stateChanged.connect(self.update_command)

        self.warning_label = QLabel(str(" "))
        self.warning_label.setWordWrap(True)

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(out_file_label)
        main_v_box.addWidget(self.simple_lin)
        main_v_box.addWidget(self.check_scale)
        main_v_box.addStretch()
        main_v_box.addWidget(self.warning_label)
        main_v_box.addStretch()
        self.setLayout(main_v_box)
        self.fist_time = False
        # self.show()

        self.simple_lin.setText("integrated.mtz")
Exemple #2
0
    def __init__(self, parent=None):
        super(ImportPage, self).__init__(parent=None)

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Import"))
        step_label.setFont(label_font)

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.x_spn_bx = QSpinBox()
        self.x_spn_bx.setMaximum(99999)
        self.x_spn_bx.setSpecialValueText(" ")
        self.y_spn_bx = QSpinBox()
        self.y_spn_bx.setMaximum(99999)
        self.y_spn_bx.setSpecialValueText(" ")

        self.x_spn_bx.valueChanged.connect(self.x_beam_changed)
        self.y_spn_bx.valueChanged.connect(self.y_beam_changed)

        self.chk_invert = QCheckBox("Invert rotation axis")
        self.chk_invert.stateChanged.connect(self.inv_rota_changed)

        self.opn_fil_btn = QPushButton(" \n Select file(s) \n ")

        main_path = get_main_path()

        self.opn_fil_btn.setIcon(QIcon(main_path + "/resources/import.png"))
        self.opn_fil_btn.setIconSize(QSize(80, 48))

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(self.opn_fil_btn)
        main_v_box.addWidget(self.simple_lin)
        self.b_cetre_label = QLabel("\n\n Beam centre")
        main_v_box.addWidget(self.b_cetre_label)
        cent_hbox = QHBoxLayout()
        self.x_label = QLabel("    X: ")
        cent_hbox.addWidget(self.x_label)
        cent_hbox.addWidget(self.x_spn_bx)
        self.y_label = QLabel("    Y: ")
        cent_hbox.addWidget(self.y_label)
        cent_hbox.addWidget(self.y_spn_bx)
        #    cent_hbox.addWidget(QLabel(" \n "))
        cent_hbox.addStretch()
        main_v_box.addLayout(cent_hbox)
        main_v_box.addWidget(self.chk_invert)
        main_v_box.addStretch()

        self.opn_fil_btn.clicked.connect(self.open_files)

        self.defa_dir = str(os.getcwd())
        self.setLayout(main_v_box)
        # self.show()
        self.reset_par()
Exemple #3
0
 def __init__(self, parent, nombre, args):
     """Recibe la lista de elementos"""
     ElementoWidgetOpciones.__init__(self)
     QGridButtonGroup.__init__(self, parent)
     self.setTitle(nombre)
     for elemento in args:
         caja = QCheckBox(self)
         caja.setText(elemento)
         self.insert(caja)
         self.diccionario[elemento] = caja
Exemple #4
0
 def isChecked(self):
     if self.isTristate():
         state=QCheckBox.state(self)
         if state == 0:
             return False
         elif state == 2:
             return True
         else:
             return None
     else:
         return QCheckBox.isChecked(self)
Exemple #5
0
 def setChecked(self, value):
     if self.isTristate():
         if value=='J' or value =='j' or value=="1" or value==1:
             QCheckBox.setChecked(self, True)
         elif value is None:
             QCheckBox.setNoChange(self)
         else:
             QCheckBox.setChecked(self, False)
     else:
         if value=='J' or value =='j' or value=="1" or value==1:
             QCheckBox.setChecked(self, True)
         else:
             QCheckBox.setChecked(self, False)
Exemple #6
0
    def __init__(self, parent=None):
        super(Games, self).__init__(parent)
        self.selectedGame = None
        self.onlyPending = True
        decorateWindow(self, m18nc('kajongg', 'Games'))
        self.setObjectName('Games')
        self.resize(700, 400)
        self.model = GamesModel()
        if Debug.modelTest:
            self.modelTest = ModelTest(self.model, self)

        self.view = MJTableView(self)
        self.view.setModel(self.model)
        self.selection = QItemSelectionModel(self.model, self.view)
        self.view.setSelectionModel(self.selection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.newButton = self.buttonBox.addButton(
            m18nc('start a new game', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.accept)
        self.loadButton = self.buttonBox.addButton(
            m18n("&Load"), QDialogButtonBox.AcceptRole)
        self.loadButton.clicked.connect(self.loadGame)
        self.loadButton.setIcon(KIcon("document-open"))
        self.deleteButton = self.buttonBox.addButton(
            m18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        chkPending = QCheckBox(m18n("Show only pending games"), self)
        chkPending.setChecked(True)
        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(chkPending)
        cmdLayout.addWidget(self.buttonBox)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)
        StateSaver(self)

        self.selection.selectionChanged.connect(self.selectionChanged)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.view.doubleClicked.connect(self.loadGame)
        chkPending.stateChanged.connect(self.pendingOrNot)
Exemple #7
0
    def __init__(self, parent=None):
        super(Games, self).__init__(parent)
        self.selectedGame = None
        self.onlyPending = True
        decorateWindow(self, i18nc('kajongg', 'Games'))
        self.setObjectName('Games')
        self.resize(700, 400)
        self.model = GamesModel()
        if Debug.modelTest:
            self.modelTest = ModelTest(self.model, self)

        self.view = MJTableView(self)
        self.view.setModel(self.model)
        self.selection = QItemSelectionModel(self.model, self.view)
        self.view.setSelectionModel(self.selection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.newButton = self.buttonBox.addButton(
            i18nc('start a new game', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.accept)
        self.loadButton = self.buttonBox.addButton(
            i18n("&Load"), QDialogButtonBox.AcceptRole)
        self.loadButton.clicked.connect(self.loadGame)
        self.loadButton.setIcon(KIcon("document-open"))
        self.deleteButton = self.buttonBox.addButton(
            i18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        chkPending = QCheckBox(i18n("Show only pending games"), self)
        chkPending.setChecked(True)
        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(chkPending)
        cmdLayout.addWidget(self.buttonBox)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)
        StateSaver(self)

        self.selection.selectionChanged.connect(self.selectionChanged)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.view.doubleClicked.connect(self.loadGame)
        chkPending.stateChanged.connect(self.pendingOrNot)
Exemple #8
0
 def __init__(self, parent, nombre):
     ElementoWidgetOpciones.__init__(self)
     QVGroupBox.__init__(self, parent, "ContenedorOpcional")
     ContenedorElementoWidgetOpciones.__init__(self)
     self.nombre = nombre
     self.checkbox = QCheckBox(self, "checkBox1")
     self.checkbox.setText(nombre)
     self.setTitle(nombre)
     self.__conexiones()
Exemple #9
0
  def setupFrameControlFrame(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupFrameControlFrame(self)

    self.frameCopySelector = slicer.qMRMLNodeComboBox()
    self.frameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
    self.frameCopySelector.setMRMLScene(slicer.mrmlScene)
    self.frameCopySelector.addEnabled = 1
    self.frameCopySelector.enabled = 0
    # do not show "children" of vtkMRMLScalarVolumeNode
    self.frameCopySelector.hideChildNodeTypes = ["vtkMRMLDiffusionWeightedVolumeNode",
                                                  "vtkMRMLDiffusionTensorVolumeNode",
                                                  "vtkMRMLVectorVolumeNode"]
    self.extractFrameCopy = False
    self.extractFrameCheckBox = QCheckBox('Enable copying')
    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Current frame copy'))
    hbox.addWidget(self.frameCopySelector)
    hbox.addWidget(self.extractFrameCheckBox)
    self.inputFrameLayout.addRow(hbox)
Exemple #10
0
 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 setupFrameControlFrame(self):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupFrameControlFrame(
            self)

        self.frameCopySelector = slicer.qMRMLNodeComboBox()
        self.frameCopySelector.setSizePolicy(QSizePolicy.Ignored,
                                             QSizePolicy.Preferred)
        self.frameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.frameCopySelector.setMRMLScene(slicer.mrmlScene)
        self.frameCopySelector.addEnabled = 1
        self.frameCopySelector.enabled = 0
        # do not show "children" of vtkMRMLScalarVolumeNode
        self.frameCopySelector.hideChildNodeTypes = [
            "vtkMRMLDiffusionWeightedVolumeNode",
            "vtkMRMLDiffusionTensorVolumeNode", "vtkMRMLVectorVolumeNode"
        ]
        self.extractFrameCopy = False
        self.extractFrameCheckBox = QCheckBox('Enable copying while sliding')
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Current frame copy'))
        hbox.addWidget(self.frameCopySelector)
        hbox.addWidget(self.extractFrameCheckBox)
        self.inputFrameLayout.addRow(hbox)

        self.currentFrameCopySelector = slicer.qMRMLNodeComboBox()
        self.currentFrameCopySelector.setSizePolicy(QSizePolicy.Ignored,
                                                    QSizePolicy.Preferred)
        self.currentFrameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.currentFrameCopySelector.setMRMLScene(slicer.mrmlScene)
        self.currentFrameCopySelector.addEnabled = 0
        self.currentFrameCopySelector.enabled = 0

        self.currentFrameCopyButton = QPushButton('Copy frame')
        self.currentFrameCopyButton.toolTip = 'Copy currently selected frame'

        hbox2 = QHBoxLayout()
        hbox2.addWidget(QLabel('Current frame click-to-copy'))
        hbox2.addWidget(self.currentFrameCopySelector)
        hbox2.addWidget(self.currentFrameCopyButton)
        self.inputFrameLayout.addRow(hbox2)
Exemple #12
0
class EWOGrupoWidgetOpciones(ElementoWidgetOpciones, QVGroupBox, ContenedorElementoWidgetOpciones):
    """Contiene a un conjunto de opciones, todas ellas activables por un QCheckBox"""
    def __init__(self, parent, nombre):
        ElementoWidgetOpciones.__init__(self)
        QVGroupBox.__init__(self, parent, "ContenedorOpcional")
        ContenedorElementoWidgetOpciones.__init__(self)
        self.nombre = nombre
        self.checkbox = QCheckBox(self, "checkBox1")
        self.checkbox.setText(nombre)
        self.setTitle(nombre)
        self.__conexiones()

    def __conexiones(self):
        """Bloque de conexiones"""
        self.connect(self.checkbox, SIGNAL("toggled(bool)"), self.__cambiar_estado)

    def procesar(self, diccionario):
        """Acciones a relizar cuando se nos pasa un diccionario con widgets"""
        ContenedorElementoWidgetOpciones.procesar(self, diccionario)
        self.__cambiar_estado()

    def __cambiar_estado(self):
        """Acciones a realizar cuando se detecta un cambio de estado en el widget"""
        valor = self.checkbox.isChecked()

        for widget in self.lista:
            if valor: 
                widget.activar()
            else: 
                widget.desactivar()

    def opciones(self):
        """Devuelve las opciones seleccionadas"""
        if self.checkbox.isChecked():
            diccionario = {}
            diccionario.update({self.nombre:ContenedorElementoWidgetOpciones.opciones(self)})
            return diccionario
        else:
            return {}
Exemple #13
0
 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()
Exemple #14
0
 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])
Exemple #15
0
 def setupUi(self):
     """layout the window"""
     self.setContentsMargins(0, 0, 0, 0)
     vlayout = QVBoxLayout(self)
     vlayout.setContentsMargins(0, 0, 0, 0)
     sliderLayout = QHBoxLayout()
     self.kcfg_showShadows = QCheckBox(m18n('Show tile shadows'), self)
     self.kcfg_showShadows.setObjectName('kcfg_showShadows')
     self.kcfg_rearrangeMelds = QCheckBox(
         m18n('Rearrange undisclosed tiles to melds'), self)
     self.kcfg_rearrangeMelds.setObjectName('kcfg_rearrangeMelds')
     self.kcfg_showOnlyPossibleActions = QCheckBox(m18n(
         'Show only possible actions'))
     self.kcfg_showOnlyPossibleActions.setObjectName(
         'kcfg_showOnlyPossibleActions')
     self.kcfg_propose = QCheckBox(m18n('Propose what to do'))
     self.kcfg_propose.setObjectName('kcfg_propose')
     self.kcfg_animationSpeed = QSlider(self)
     self.kcfg_animationSpeed.setObjectName('kcfg_animationSpeed')
     self.kcfg_animationSpeed.setOrientation(Qt.Horizontal)
     self.kcfg_animationSpeed.setSingleStep(1)
     lblSpeed = QLabel(m18n('Animation speed:'))
     lblSpeed.setBuddy(self.kcfg_animationSpeed)
     sliderLayout.addWidget(lblSpeed)
     sliderLayout.addWidget(self.kcfg_animationSpeed)
     self.kcfg_useSounds = QCheckBox(m18n('Use sounds if available'), self)
     self.kcfg_useSounds.setObjectName('kcfg_useSounds')
     self.kcfg_uploadVoice = QCheckBox(m18n(
         'Let others hear my voice'), self)
     self.kcfg_uploadVoice.setObjectName('kcfg_uploadVoice')
     pol = QSizePolicy()
     pol.setHorizontalPolicy(QSizePolicy.Expanding)
     pol.setVerticalPolicy(QSizePolicy.Expanding)
     spacerItem = QSpacerItem(
         20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
     vlayout.addWidget(self.kcfg_showShadows)
     vlayout.addWidget(self.kcfg_rearrangeMelds)
     vlayout.addWidget(self.kcfg_showOnlyPossibleActions)
     vlayout.addWidget(self.kcfg_propose)
     vlayout.addWidget(self.kcfg_useSounds)
     vlayout.addWidget(self.kcfg_uploadVoice)
     vlayout.addLayout(sliderLayout)
     vlayout.addItem(spacerItem)
     self.setSizePolicy(pol)
     self.retranslateUi()
  def setupFrameControlFrame(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupFrameControlFrame(self)

    self.frameCopySelector = slicer.qMRMLNodeComboBox()
    self.frameCopySelector.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)
    self.frameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
    self.frameCopySelector.setMRMLScene(slicer.mrmlScene)
    self.frameCopySelector.addEnabled = 1
    self.frameCopySelector.enabled = 0
    # do not show "children" of vtkMRMLScalarVolumeNode
    self.frameCopySelector.hideChildNodeTypes = ["vtkMRMLDiffusionWeightedVolumeNode",
                                                  "vtkMRMLDiffusionTensorVolumeNode",
                                                  "vtkMRMLVectorVolumeNode"]
    self.extractFrameCopy = False
    self.extractFrameCheckBox = QCheckBox('Enable copying while sliding')
    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Current frame copy'))
    hbox.addWidget(self.frameCopySelector)
    hbox.addWidget(self.extractFrameCheckBox)
    self.inputFrameLayout.addRow(hbox)

    self.currentFrameCopySelector = slicer.qMRMLNodeComboBox()
    self.currentFrameCopySelector.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)
    self.currentFrameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
    self.currentFrameCopySelector.setMRMLScene(slicer.mrmlScene)
    self.currentFrameCopySelector.addEnabled = 0
    self.currentFrameCopySelector.enabled = 0

    self.currentFrameCopyButton = QPushButton('Copy frame')
    self.currentFrameCopyButton.toolTip = 'Copy currently selected frame'

    hbox2 = QHBoxLayout()
    hbox2.addWidget(QLabel('Current frame click-to-copy'))
    hbox2.addWidget(self.currentFrameCopySelector)
    hbox2.addWidget(self.currentFrameCopyButton)
    self.inputFrameLayout.addRow(hbox2)
class SoundConfigWidget(BaseDosboxConfigWidget):
    def __init__(self, parent, name="SDLConfigWidget"):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_mpu401_types = ["none", "uart", "intelligent"]
        self._default_midi_devices = ["default", "none", "alsa", "oss", "coreaudio", "win32"]
        self._default_sbtypes = ["none", "sb1", "sb2", "sbpro1", "sbpro2", "sb16"]
        self._default_tandyopts = ["auto", "on", "off"]
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "SDLConfigWidgetLayout")
        for section in ["mixer", "midi", "sblaster", "gus", "speaker"]:
            self.localconfig.add_section(section)

        # mixer group
        self.mixer_groupbox = VerticalGroupBox(self, "Mixer Options")
        self.mixer_groupbox.setColumns(4)
        self.grid.addWidget(self.mixer_groupbox, 0, 0)
        self.nosound_check = QCheckBox(self.mixer_groupbox)
        self.nosound_check.setText("Disable sound")
        self.sample_rate_box = SampleRateOption(self.mixer_groupbox, "Sample rate")
        # magic number for maximum block size
        self.blocksize_box = ConfigSpinWidget(
            self.mixer_groupbox, "Mixer block size", min=0, max=262144, suffix=" bytes"
        )
        # magic number for maximum prebuffer (10 secs)
        self.prebuffer_box = ConfigSpinWidget(self.mixer_groupbox, "Prebuffer", min=0, max=10000, suffix=" msec")

        # midi group
        self.midi_groupbox = VerticalGroupBox(self, "MIDI Options")
        self.midi_groupbox.setColumns(4)
        self.grid.addWidget(self.midi_groupbox, 1, 1)
        self.mpu401_box = ConfigComboBoxWidget(self.midi_groupbox, "mpu401 type", self._default_mpu401_types)
        self.midi_device_box = ConfigComboBoxWidget(self.midi_groupbox, "MIDI device", self._default_midi_devices)
        self.midi_config_box = ConfigLineEditWidget(self.midi_groupbox, "MIDI config")

        # speaker group
        self.speaker_groupbox = VerticalGroupBox(self, "PC Speaker Options")
        self.speaker_groupbox.setColumns(5)
        self.grid.addMultiCellWidget(self.speaker_groupbox, 1, 1, 0, 0)
        self.enable_speaker_check = QCheckBox(self.speaker_groupbox)
        self.enable_speaker_check.setText("Enable PC speaker emulation")
        self.pc_rate_box = SampleRateOption(self.speaker_groupbox, "Sample rate of PC speaker")
        self.enable_tandy_box = ConfigComboBoxWidget(
            self.speaker_groupbox, "Enable Tandy Sound System emulation", self._default_tandyopts
        )
        self.tandy_rate_box = SampleRateOption(self.speaker_groupbox, "Sample rate of Tandy Sound System")
        self.enable_disney_check = QCheckBox(self.speaker_groupbox)
        self.enable_disney_check.setText("Enable Disney Sound Source emulation")

        # sblaster group
        self.sblaster_groupbox = VerticalGroupBox(self, "SoundBlaster Options")
        self.sblaster_groupbox.setColumns(2)
        # self.grid.addWidget(self.sblaster_groupbox, 0, 0)
        self.grid.addMultiCellWidget(self.sblaster_groupbox, 0, 0, 0, 1)
        self.sbtype_box = ConfigComboBoxWidget(self.sblaster_groupbox, "SoundBlaster type", self._default_sbtypes)
        self.sblaster_hwopt_groupbox = VerticalGroupBox(self.sblaster_groupbox, "SoundBlaster Hardware Options")
        self.sblaster_hwopt_groupbox.setColumns(1)
        self.sblaster_hwopt_box = SoundBlasterHardwareOptions(self.sblaster_hwopt_groupbox)

        self.sb_mixer_check = QCheckBox(self.sblaster_groupbox)
        self.sb_mixer_check.setText("SoundBlaster modifies dosbox mixer")
        self.sblaster_oplopt_groupbox = VerticalGroupBox(self.sblaster_groupbox, "SoundBlaster OPL Options")
        self.sblaster_oplopt_groupbox.setColumns(1)
        self.sblaster_oplopt_box = SoundBlasterOPLOptions(self.sblaster_oplopt_groupbox)

        # gus group
        self.gus_groupbox = VerticalGroupBox(self, "Gravis Ultrasound Options")
        self.gus_groupbox.setColumns(5)
        # self.grid.addWidget(self.gus_groupbox, 2, 1)
        self.grid.addMultiCellWidget(self.gus_groupbox, 0, 1, 2, 2)
        self.enable_gus_check = QCheckBox(self.gus_groupbox)
        self.enable_gus_check.setText("Enable Gravis Ultrasound emulation")
        self.gus_hwopt_groupbox = VerticalGroupBox(self.gus_groupbox, "Gravis Ultrasound hardware options")
        self.gus_hwopt_groupbox.setColumns(1)
        self.gus_hwopt_box = GusHardwareOptions(self.gus_hwopt_groupbox)
        self.gus_rate_box = SampleRateOption(self.gus_groupbox)
        self.gus_ultradir_box = ConfigKURLSelectWidget(self.gus_groupbox, "GUS patches directory", filetype="dir")

    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        mixer = "mixer"
        midi = "midi"
        sblaster = "sblaster"
        gus = "gus"
        speaker = "speaker"
        cfg = self.mainconfig
        # set the various config widgets
        # mixer section
        nosound = cfg.getboolean(mixer, "nosound")
        self.nosound_check.setChecked(nosound)
        rate = cfg.getint(mixer, "rate")
        self.sample_rate_box.set_config_option(rate)
        blocksize = cfg.getint(mixer, "blocksize")
        self.blocksize_box.set_config_option(blocksize)
        prebuffer = cfg.getint(mixer, "prebuffer")
        self.prebuffer_box.set_config_option(prebuffer)
        # midi section
        mpu401 = cfg.get(midi, "mpu401")
        self.mpu401_box.set_config_option(mpu401)
        device = cfg.get(midi, "device")
        self.midi_device_box.set_config_option(device)
        midi_config = cfg.get(midi, "config")
        self.midi_config_box.set_config_option(midi_config)
        # sblaster section
        sbtype = cfg.get(sblaster, "sbtype")
        self.sbtype_box.set_config_option(sbtype)
        opts = {}
        for opt in ["sbbase", "irq", "dma", "hdma"]:
            opts[opt] = cfg.getint(sblaster, opt)
        self.sblaster_hwopt_box.set_config_options(opts)
        mixer = cfg.getboolean(sblaster, "mixer")
        self.sb_mixer_check.setChecked(mixer)
        opts = {}
        opts["oplmode"] = cfg.get(sblaster, "oplmode")
        opts["oplrate"] = cfg.getint(sblaster, "oplrate")
        self.sblaster_oplopt_box.set_config_options(opts)

        # gus section
        enable_gus = cfg.getboolean(gus, "gus")
        self.enable_gus_check.setChecked(enable_gus)
        gusrate = cfg.getint(gus, "gusrate")
        self.gus_rate_box.set_config_option(gusrate)
        opts = {}
        for opt in ["gusbase", "irq1", "irq2", "dma1", "dma2"]:
            opts[opt] = cfg.getint(gus, opt)
        self.gus_hwopt_box.set_config_options(opts)
        ultradir = cfg.get(gus, "ultradir")
        self.gus_ultradir_box.set_config_option(ultradir)
        # speaker section
        pcspeaker = cfg.getboolean(speaker, "pcspeaker")
        self.enable_speaker_check.setChecked(pcspeaker)
        pcrate = cfg.getint(speaker, "pcrate")
        self.pc_rate_box.set_config_option(pcrate)
        tandy = cfg.get(speaker, "tandy")
        self.enable_tandy_box.set_config_option(tandy)
        tandyrate = cfg.getint(speaker, "tandyrate")
        self.tandy_rate_box.set_config_option(tandyrate)
        disney = cfg.getboolean(speaker, "disney")
        self.enable_disney_check.setChecked(disney)

    def get_config(self):
        # some assignments to help with typing
        mixer = "mixer"
        midi = "midi"
        sblaster = "sblaster"
        gus = "gus"
        speaker = "speaker"
        cfg = self.localconfig
        # get config values from the various widgets
        # mixer section
        nosound = self._get_bool_for_config(self.nosound_check)
        cfg.set(mixer, "nosound", nosound)
        rate = self.sample_rate_box.get_config_option()
        cfg.set(mixer, "rate", rate)
        blocksize = self.blocksize_box.get_config_option()
        cfg.set(mixer, "blocksize", blocksize)
        prebuffer = self.prebuffer_box.get_config_option()
        cfg.set(mixer, "prebuffer", prebuffer)
        # midi section
        mpu401 = self.mpu401_box.get_config_option()
        cfg.set(midi, "mpu401", mpu401)
        device = self.midi_device_box.get_config_option()
        cfg.set(midi, "device", device)
        midi_config = self.midi_config_box.get_config_option()
        cfg.set(midi, "config", midi_config)
        # sblaster section
        sbtype = self.sbtype_box.get_config_option()
        cfg.set(sblaster, "sbtype", sbtype)
        opts = self.sblaster_hwopt_box.get_config_options()
        for opt, value in opts.items():
            cfg.set(sblaster, opt, value)
        mixer = self._get_bool_for_config(self.sb_mixer_check)
        cfg.set(sblaster, "mixer", mixer)
        opts = self.sblaster_oplopt_box.get_config_options()
        for opt, value in opts.items():
            cfg.set(sblaster, opt, value)
        # gus section
        enable_gus = self._get_bool_for_config(self.enable_gus_check)
        cfg.set(gus, "gus", enable_gus)
        gusrate = self.gus_rate_box.get_config_option()
        cfg.set(gus, "gusrate", gusrate)
        opts = self.gus_hwopt_box.get_config_options()
        for opt, value in opts.items():
            cfg.set(gus, opt, value)
        ultradir = self.gus_ultradir_box.get_config_option()
        cfg.set(gus, "ultradir", ultradir)
        # speaker section
        pcspeaker = self._get_bool_for_config(self.enable_speaker_check)
        cfg.set(speaker, "pcspeaker", pcspeaker)
        pcrate = self.pc_rate_box.get_config_option()
        cfg.set(speaker, "pcrate", pcrate)
        tandy = self.enable_tandy_box.get_config_option()
        cfg.set(speaker, "tandy", tandy)
        tandyrate = self.tandy_rate_box.get_config_option()
        cfg.set(speaker, "tandyrate", tandyrate)
        disney = self._get_bool_for_config(self.enable_disney_check)
        cfg.set(speaker, "disney", disney)
        # done
        return self.localconfig
  def setupPlotSettingsFrame(self):
    self.plotSettingsFrame = ctk.ctkCollapsibleButton()
    self.plotSettingsFrame.text = "Plotting Settings"
    self.plotSettingsFrame.collapsed = 1
    plotSettingsFrameLayout = QFormLayout(self.plotSettingsFrame)
    self.layout.addWidget(self.plotSettingsFrame)

    # label map for probing
    self.labelMapSelector = slicer.qMRMLNodeComboBox()
    self.labelMapSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']
    self.labelMapSelector.toolTip = 'Label map to be probed'
    self.labelMapSelector.setMRMLScene(slicer.mrmlScene)
    self.labelMapSelector.addEnabled = 0
    self.chartButton = QPushButton('Chart')
    self.chartButton.setEnabled(False)

    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Probed label volume'))
    hbox.addWidget(self.labelMapSelector)
    hbox.addWidget(self.chartButton)
    plotSettingsFrameLayout.addRow(hbox)

    self.iCharting = QCheckBox('Interactive charting')
    self.iCharting.setChecked(True)
    plotSettingsFrameLayout.addRow(self.iCharting)

    self.iChartingMode = QButtonGroup()
    self.iChartingIntensity = QRadioButton('Signal intensity')
    self.iChartingIntensityFixedAxes = QRadioButton('Fixed range intensity')
    self.iChartingPercent = QRadioButton('Percentage change')
    self.iChartingIntensity.setChecked(1)
    self.iChartingMode.addButton(self.iChartingIntensity)
    self.iChartingMode.addButton(self.iChartingIntensityFixedAxes)
    self.iChartingMode.addButton(self.iChartingPercent)

    hbox = QHBoxLayout()
    self.plottingModeGroupBox = QGroupBox('Plotting mode:')
    plottingModeLayout = QVBoxLayout()
    self.plottingModeGroupBox.setLayout(plottingModeLayout)
    plottingModeLayout.addWidget(self.iChartingIntensity)
    plottingModeLayout.addWidget(self.iChartingIntensityFixedAxes)
    plottingModeLayout.addWidget(self.iChartingPercent)
    hbox.addWidget(self.plottingModeGroupBox)

    self.showLegendCheckBox = QCheckBox('Display legend')
    self.showLegendCheckBox.setChecked(0)
    self.xLogScaleCheckBox = QCheckBox('Use log scale for X axis')
    self.xLogScaleCheckBox.setChecked(0)
    self.yLogScaleCheckBox = QCheckBox('Use log scale for Y axis')
    self.yLogScaleCheckBox.setChecked(0)

    self.plotGeneralSettingsGroupBox = QGroupBox('General Plot options:')
    plotGeneralSettingsLayout = QVBoxLayout()
    self.plotGeneralSettingsGroupBox.setLayout(plotGeneralSettingsLayout)
    plotGeneralSettingsLayout.addWidget(self.showLegendCheckBox)
    plotGeneralSettingsLayout.addWidget(self.xLogScaleCheckBox)
    plotGeneralSettingsLayout.addWidget(self.yLogScaleCheckBox)
    hbox.addWidget(self.plotGeneralSettingsGroupBox)
    plotSettingsFrameLayout.addRow(hbox)

    self.nFramesBaselineCalculation = QSpinBox()
    self.nFramesBaselineCalculation.minimum = 1
    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Frame count(baseline calculation):'))
    hbox.addWidget(self.nFramesBaselineCalculation)
    plotSettingsFrameLayout.addRow(hbox)
Exemple #19
0
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)
class qSlicerMultiVolumeExplorerModuleWidget(qSlicerMultiVolumeExplorerSimplifiedModuleWidget):

  def __init__(self, parent=None):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.__init__(self, parent)

  def setupAdditionalFrames(self):
    self.setupPlotSettingsFrame()

  def setupInputFrame(self, parent=None):
    self.inputFrame = ctk.ctkCollapsibleButton()
    self.inputFrame.text = "Input"
    self.inputFrame.collapsed = 0
    inputFrameCollapsibleLayout = QFormLayout(self.inputFrame)
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupInputFrame(self, parent=inputFrameCollapsibleLayout)
    self.layout.addWidget(self.inputFrame)

    self.fgMultiVolumeSelector = slicer.qMRMLNodeComboBox()
    self.fgMultiVolumeSelector.nodeTypes = ['vtkMRMLMultiVolumeNode']
    self.fgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
    self.fgMultiVolumeSelector.addEnabled = 0
    self.fgMultiVolumeSelector.noneEnabled = 1
    self.fgMultiVolumeSelector.toolTip = "Secondary multivolume will be used for the secondary \
      plot in interactive charting. As an example, this can be used to overlay the \
      curve obtained by fitting a model to the data"
    self.inputFrameLayout.addRow(QLabel('Input secondary multivolume'), self.fgMultiVolumeSelector)

  def setupFrameControlFrame(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupFrameControlFrame(self)

    self.frameCopySelector = slicer.qMRMLNodeComboBox()
    self.frameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
    self.frameCopySelector.setMRMLScene(slicer.mrmlScene)
    self.frameCopySelector.addEnabled = 1
    self.frameCopySelector.enabled = 0
    # do not show "children" of vtkMRMLScalarVolumeNode
    self.frameCopySelector.hideChildNodeTypes = ["vtkMRMLDiffusionWeightedVolumeNode",
                                                  "vtkMRMLDiffusionTensorVolumeNode",
                                                  "vtkMRMLVectorVolumeNode"]
    self.extractFrameCopy = False
    self.extractFrameCheckBox = QCheckBox('Enable copying')
    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Current frame copy'))
    hbox.addWidget(self.frameCopySelector)
    hbox.addWidget(self.extractFrameCheckBox)
    self.inputFrameLayout.addRow(hbox)

  def setupPlotSettingsFrame(self):
    self.plotSettingsFrame = ctk.ctkCollapsibleButton()
    self.plotSettingsFrame.text = "Plotting Settings"
    self.plotSettingsFrame.collapsed = 1
    plotSettingsFrameLayout = QFormLayout(self.plotSettingsFrame)
    self.layout.addWidget(self.plotSettingsFrame)

    # label map for probing
    self.labelMapSelector = slicer.qMRMLNodeComboBox()
    self.labelMapSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']
    self.labelMapSelector.toolTip = 'Label map to be probed'
    self.labelMapSelector.setMRMLScene(slicer.mrmlScene)
    self.labelMapSelector.addEnabled = 0
    self.chartButton = QPushButton('Chart')
    self.chartButton.setEnabled(False)

    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Probed label volume'))
    hbox.addWidget(self.labelMapSelector)
    hbox.addWidget(self.chartButton)
    plotSettingsFrameLayout.addRow(hbox)

    self.iCharting = QCheckBox('Interactive charting')
    self.iCharting.setChecked(True)
    plotSettingsFrameLayout.addRow(self.iCharting)

    self.iChartingMode = QButtonGroup()
    self.iChartingIntensity = QRadioButton('Signal intensity')
    self.iChartingIntensityFixedAxes = QRadioButton('Fixed range intensity')
    self.iChartingPercent = QRadioButton('Percentage change')
    self.iChartingIntensity.setChecked(1)
    self.iChartingMode.addButton(self.iChartingIntensity)
    self.iChartingMode.addButton(self.iChartingIntensityFixedAxes)
    self.iChartingMode.addButton(self.iChartingPercent)

    hbox = QHBoxLayout()
    self.plottingModeGroupBox = QGroupBox('Plotting mode:')
    plottingModeLayout = QVBoxLayout()
    self.plottingModeGroupBox.setLayout(plottingModeLayout)
    plottingModeLayout.addWidget(self.iChartingIntensity)
    plottingModeLayout.addWidget(self.iChartingIntensityFixedAxes)
    plottingModeLayout.addWidget(self.iChartingPercent)
    hbox.addWidget(self.plottingModeGroupBox)

    self.showLegendCheckBox = QCheckBox('Display legend')
    self.showLegendCheckBox.setChecked(0)
    self.xLogScaleCheckBox = QCheckBox('Use log scale for X axis')
    self.xLogScaleCheckBox.setChecked(0)
    self.yLogScaleCheckBox = QCheckBox('Use log scale for Y axis')
    self.yLogScaleCheckBox.setChecked(0)

    self.plotGeneralSettingsGroupBox = QGroupBox('General Plot options:')
    plotGeneralSettingsLayout = QVBoxLayout()
    self.plotGeneralSettingsGroupBox.setLayout(plotGeneralSettingsLayout)
    plotGeneralSettingsLayout.addWidget(self.showLegendCheckBox)
    plotGeneralSettingsLayout.addWidget(self.xLogScaleCheckBox)
    plotGeneralSettingsLayout.addWidget(self.yLogScaleCheckBox)
    hbox.addWidget(self.plotGeneralSettingsGroupBox)
    plotSettingsFrameLayout.addRow(hbox)

    self.nFramesBaselineCalculation = QSpinBox()
    self.nFramesBaselineCalculation.minimum = 1
    hbox = QHBoxLayout()
    hbox.addWidget(QLabel('Frame count(baseline calculation):'))
    hbox.addWidget(self.nFramesBaselineCalculation)
    plotSettingsFrameLayout.addRow(hbox)

  def setupPlottingFrame(self, parent=None):
    self.plotFrame = ctk.ctkCollapsibleButton()
    self.plotFrame.text = "Plotting"
    self.plotFrame.collapsed = 0
    plotFrameLayout = QGridLayout(self.plotFrame)
    self.layout.addWidget(self.plotFrame)
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupPlottingFrame(self, parent=plotFrameLayout)

  def onDockChartViewToggled(self, checked):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onDockChartViewToggled(self, checked)
    if checked:
      self.layout.removeWidget(self.plotFrame)
      self.plotFrame.hide()

  def dockChartView(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.dockChartView(self)
    self.layout.addWidget(self.plotFrame)
    self.plotFrame.show()

  def setFramesEnabled(self, enabled):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setFramesEnabled(self, enabled)
    self.plotSettingsFrame.setEnabled(enabled)
    self.plotFrame.setEnabled(enabled)
    self.plotFrame.collapsed = 0 if enabled else 1

  def setupConnections(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupConnections(self)
    self.labelMapSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onLabelNodeChanged)
    self.chartButton.connect('clicked()', self.onLabeledChartRequested)
    self.xLogScaleCheckBox.connect('stateChanged(int)', self.onXLogScaleRequested)
    self.yLogScaleCheckBox.connect('stateChanged(int)', self.onYLogScaleRequested)
    self.nFramesBaselineCalculation.valueChanged.connect(self.onFrameCountBaselineCalculationChanged)
    self.iChartingMode.buttonClicked.connect(self.onChartingModeChanged)
    self.showLegendCheckBox.connect('stateChanged(int)', self.onShowLegendChanged)
    self.fgMultiVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onForegroundInputChanged)
    self.extractFrameCheckBox.connect('stateChanged(int)', self.onExtractFrameChanged)
    self.frameCopySelector.connect('mrmlSceneChanged(vtkMRMLScene*)', self.onVFMRMLSceneChanged)

  def onFrameCountBaselineCalculationChanged(self, value):
    self._multiVolumeIntensityChart.nFramesForBaselineCalculation = value

  def onChartingModeChanged(self, button):
    if button is self.iChartingIntensity:
      self._multiVolumeIntensityChart.activateSignalIntensityMode()
    elif button is self.iChartingIntensityFixedAxes:
      self._multiVolumeIntensityChart.activateFixedRangeIntensityMode()
    elif button is self.iChartingPercent:
      self._multiVolumeIntensityChart.activatePercentageChangeMode()

  def onShowLegendChanged(self, checked):
    self._multiVolumeIntensityChart.showLegend = True if checked == 2 else False

  def onXLogScaleRequested(self, checked):
    self._multiVolumeIntensityChart.showXLogScale = True if checked == 2 else False

  def onYLogScaleRequested(self, checked):
    self._multiVolumeIntensityChart.showYLogScale = True if checked == 2 else False

  def onLVMRMLSceneChanged(self, mrmlScene):
    self.labelMapSelector.setMRMLScene(slicer.mrmlScene)

  def onVFMRMLSceneChanged(self, mrmlScene):
    self.frameCopySelector.setMRMLScene(slicer.mrmlScene)

  def onLabelNodeChanged(self):
    labelNode = self.labelMapSelector.currentNode()
    self.chartButton.setEnabled(labelNode is not None and self._bgMultiVolumeNode is not None)

  def onForegroundInputChanged(self):
    logging.info("qSlicerMultiVolumeExplorerModuleWidget:ForegroundInputChanged")
    self._fgMultiVolumeNode = self.fgMultiVolumeSelector.currentNode()
    self._multiVolumeIntensityChart.fgMultiVolumeNode = self.fgMultiVolumeSelector.currentNode()
    self.refreshGUIForNewBackgroundImage()

  def onBackgroundInputChanged(self):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onBackgroundInputChanged(self)

    if self._bgMultiVolumeNode is not None:
      self.frameCopySelector.setCurrentNode(None)
      self.nFramesBaselineCalculation.maximum = self._bgMultiVolumeNode.GetNumberOfFrames()
    self.onLabelNodeChanged()

  '''
  If extract button is checked, will copy the current frame to the
  selected volume node on each event from frame slider
  '''
  def onExtractFrameChanged(self, checked):
    if checked:
      self.extractFrameCopy = True
      self.onSliderChanged(self.frameSlider.value)
    else:
      self.extractFrameCopy = False

  def onSliderChanged(self, frameId):
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onSliderChanged(self, frameId)
    frameId = int(frameId)
    if self.extractFrameCopy:
      frameVolume = self.frameCopySelector.currentNode()
      frameVolumeCopy = Helper.extractFrame(frameVolume, self._bgMultiVolumeNode, frameId)
      if not frameVolume:
        self.frameCopySelector.setCurrentNode(frameVolumeCopy)
      frameName = '%s frame %d' % (self._bgMultiVolumeNode.GetName(), frameId)
      frameVolumeCopy.SetName(frameName)

  def onLabeledChartRequested(self):
    labelNode = self.labelMapSelector.currentNode()
    mvNode = self._bgMultiVolumeNode

    mvLabels = MultiVolumeIntensityChartView.getMultiVolumeLabels(self._bgMultiVolumeNode)

    chartViewNode = LabeledImageChartView(labelNode=labelNode,
                                           multiVolumeNode=mvNode,
                                           multiVolumeLabels=mvLabels,
                                           baselineFrames=self.nFramesBaselineCalculation,
                                           displayPercentageChange=self.iChartingPercent.checked)
    chartViewNode.requestChartCreation()

  def processEvent(self, observee, event):
    if not self.iCharting.checked:
      return
    qSlicerMultiVolumeExplorerSimplifiedModuleWidget.processEvent(self, observee, event)
Exemple #21
0
class ExportPage(QWidget):

    update_command_lst_low_level = Signal(list)

    """
    This stacked widget basically helps the user to export by
    generating an MTZ file, there is no auto-generated GUI
    form Phil parameters in use withing this widget.
    """

    def __init__(self, parent=None):
        super(ExportPage, self).__init__(parent=None)

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Export"))
        step_label.setFont(label_font)

        out_file_label = QLabel(str("mtz output name:"))

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.check_scale = QCheckBox("Output Scaled Intensities")
        self.check_scale.setChecked(False)
        self.check_scale.stateChanged.connect(self.update_command)

        self.warning_label = QLabel(str(" "))
        self.warning_label.setWordWrap(True)

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(out_file_label)
        main_v_box.addWidget(self.simple_lin)
        main_v_box.addWidget(self.check_scale)
        main_v_box.addStretch()
        main_v_box.addWidget(self.warning_label)
        main_v_box.addStretch()
        self.setLayout(main_v_box)
        self.fist_time = False
        # self.show()

        self.simple_lin.setText("integrated.mtz")

    def update_command(self):
        self.command_lst = [["export"]]

        param1_com = str(self.simple_lin.text())
        self.command_lst[0].append("mtz.hklout=" + param1_com)

        if self.check_scale.checkState():
            param2_com = "intensity=scale"
            self.command_lst[0].append(param2_com)

        self.update_command_lst_low_level.emit(self.command_lst[0])
        self.check_repeated_file()

    def check_repeated_file(self):
        param1_com = str(self.simple_lin.text())
        cwd_path = os.path.join(sys_arg.directory, "dui_files")
        mtz_file_path = os.path.join(cwd_path, param1_com)
        if os.path.isfile(mtz_file_path):
            txt_warning = "Warning, file: " + param1_com + " already exists"
            self.warning_label.setText(txt_warning)
            self.warning_label.setStyleSheet("color: rgba(255, 55, 55, 255)")
            """
            self.warning_label.setStyleSheet(
                        "color: rgba(255, 55, 55, 255);" "background-color: yellow;"
                    )
            """
        else:
            self.warning_label.setText(" ")
            self.warning_label.setStyleSheet("color: rgba(0, 155, 255, 255)")

    def gray_me_out(self):
        self.simple_lin.setEnabled(False)
        self.check_scale.setEnabled(False)

        self.fist_time = False

    def activate_me(self, cur_nod=None):
        self.simple_lin.setEnabled(True)
        self.check_scale.setEnabled(True)
        if self.fist_time is False:
            self.fist_time = True
            self.simple_lin.setText("integrated.mtz")
            self.check_scale.setChecked(False)
            my_node = cur_nod
            found_scale = False
            for iters in range(5):
                try:
                    if my_node.ll_command_lst[0][0] == "scale":
                        found_scale = True
                        break

                except AttributeError as at_err:
                    logger.info("found ", at_err, " in for loop, not to worry")

                my_node = my_node.prev_step

            if found_scale is True:
                self.simple_lin.setText("scaled.mtz")
                self.check_scale.setChecked(True)

        self.check_repeated_file()

    def reset_par(self):
        logger.info("command_lst(ExportPage.reset_par) = ", self.command_lst)
        logger.info(" Not supposed to reset export page")
Exemple #22
0
 def __init__(self, rule):
     QCheckBox.__init__(self, i18n(rule.name))
     self.rule = rule
    def __init__(self, parent, name="SDLConfigWidget"):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_machines = ["vga", "cga", "tandy", "pcjr", "hercules"]
        self._default_scalers = [
            "none",
            "normal2x",
            "normal3x",
            "advmame2x",
            "advmame3x",
            "advinterp2x",
            "advinterp3x",
            "tv2x",
            "tv3x",
            "rgb2x",
            "rgb3x",
            "scan2x",
            "scan3x",
        ]
        self._default_cores = ["simple", "normal", "full", "dynamic"]
        for section in ["render", "cpu", "dosbox", "dos", "bios", "serial", "ipx"]:
            self.localconfig.add_section(section)
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "MachineConfigWidgetLayout")

        # render group
        self.render_groupbox = VerticalGroupBox(self, "Render Options")
        self.render_groupbox.setColumns(2)
        self.grid.addWidget(self.render_groupbox, 0, 1)
        self.frameskip_box = ConfigSpinWidget(self.render_groupbox, "Frame skip", suffix=" frames")
        self.tooltips.add(self.frameskip_box, "How many frames to skip.")
        self.aspect_check = QCheckBox(self.render_groupbox)
        self.aspect_check.setText("Aspect correction")
        self.tooltips.add(self.aspect_check, "Try to keep aspect ratio.")
        self.scaler_box = ConfigComboBoxWidget(self.render_groupbox, "Scaler", self._default_scalers)
        self.tooltips.add(self.scaler_box, "Select size and effect of video")
        # cpu group
        # make a big number for cycles that should never be needed
        cyclemax = int(1e6)
        self.cpu_groupbox = VerticalGroupBox(self, "CPU Options")
        self.cpu_groupbox.setColumns(2)
        self.grid.addWidget(self.cpu_groupbox, 0, 0)
        self.core_box = ConfigComboBoxWidget(self.cpu_groupbox, "Core", self._default_cores)
        self.tooltips.add(self.core_box, "Select type of cpu core")
        self.cycles_box = ConfigSpinWidget(self.cpu_groupbox, "Cycles", max=cyclemax, suffix=" cycles")
        tt = "The number of cycles to attempt to perform in a second"
        self.tooltips.add(self.cycles_box, tt)
        self.cycleup_box = ConfigSpinWidget(self.cpu_groupbox, "Cycle up increment", max=cyclemax, suffix=" cycles")
        self.cycledown_box = ConfigSpinWidget(self.cpu_groupbox, "Cycle down increment", max=cyclemax, suffix=" cycles")

        # dosbox group
        self.dosbox_groupbox = VerticalGroupBox(self, "Dosbox Options")
        self.dosbox_groupbox.setColumns(3)
        # row 1, first two columns
        # self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
        self.grid.addWidget(self.dosbox_groupbox, 1, 0)
        self.language_entry = ConfigKURLSelectWidget(self.dosbox_groupbox, "Language file")
        self.memsize_box = ConfigSpinWidget(self.dosbox_groupbox, "Memory size", suffix="MB")
        self.captures_entry = ConfigKURLSelectWidget(self.dosbox_groupbox, "Captures directory", filetype="dir")

        # dos group
        self.dos_groupbox = VerticalGroupBox(self, "Dos Options")
        self.dos_groupbox.setColumns(3)
        self.grid.addWidget(self.dos_groupbox, 1, 1)
        self.xms_check = QCheckBox(self.dos_groupbox)
        self.xms_check.setText("Enable XMS support")
        self.ems_check = QCheckBox(self.dos_groupbox)
        self.ems_check.setText("Enable EMS support")
        self.umb_check = QCheckBox(self.dos_groupbox)
        self.umb_check.setText("Enable UMB support")

        # peripheral options
        self.peripheral_groupbox = VerticalGroupBox(self, "Peripheral Options")
        self.peripheral_groupbox.setColumns(1)
        # self.grid.addWidget(self.peripheral_groupbox, 2, 0)
        self.grid.addMultiCellWidget(self.peripheral_groupbox, 2, 2, 0, 2)
        # peripherals in bios section
        self.bios_groupbox = VerticalGroupBox(self.peripheral_groupbox, "Bios Options")
        self.bios_groupbox.setColumns(1)
        joystick_types = ["none", "2axis", "4axis", "fcs", "ch"]
        self.joysticktype_box = ConfigComboBoxWidget(self.bios_groupbox, "Joystick type", joystick_types)
        # peripherals in serial section
        self.serial_groupbox = VerticalGroupBox(self.peripheral_groupbox, "Serial Options")
        self.serial_groupbox.setColumns(2)
        self.serial_warning_lbl = QLabel("These options are", self.serial_groupbox)
        self.serial_warning_lbl2 = QLabel("not fully suported yet.", self.serial_groupbox)
        self.serial1_box = SerialPortOption(self.serial_groupbox, "Serial 1")
        self.serial2_box = SerialPortOption(self.serial_groupbox, "Serial 2")
        self.serial3_box = SerialPortOption(self.serial_groupbox, "Serial 3")
        self.serial4_box = SerialPortOption(self.serial_groupbox, "Serial 4")

        # ipx options
        self.ipx_groupbox = VerticalGroupBox(self, "IPX Options")
        self.ipx_groupbox.setColumns(1)
        self.grid.addWidget(self.ipx_groupbox, 1, 2)
        self.ipx_check = QCheckBox(self.ipx_groupbox)
        self.ipx_check.setText("Enable ipx over UDP/IP emulation")
class MachineConfigWidget(BaseDosboxConfigWidget):
    def __init__(self, parent, name="SDLConfigWidget"):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_machines = ["vga", "cga", "tandy", "pcjr", "hercules"]
        self._default_scalers = [
            "none",
            "normal2x",
            "normal3x",
            "advmame2x",
            "advmame3x",
            "advinterp2x",
            "advinterp3x",
            "tv2x",
            "tv3x",
            "rgb2x",
            "rgb3x",
            "scan2x",
            "scan3x",
        ]
        self._default_cores = ["simple", "normal", "full", "dynamic"]
        for section in ["render", "cpu", "dosbox", "dos", "bios", "serial", "ipx"]:
            self.localconfig.add_section(section)
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "MachineConfigWidgetLayout")

        # render group
        self.render_groupbox = VerticalGroupBox(self, "Render Options")
        self.render_groupbox.setColumns(2)
        self.grid.addWidget(self.render_groupbox, 0, 1)
        self.frameskip_box = ConfigSpinWidget(self.render_groupbox, "Frame skip", suffix=" frames")
        self.tooltips.add(self.frameskip_box, "How many frames to skip.")
        self.aspect_check = QCheckBox(self.render_groupbox)
        self.aspect_check.setText("Aspect correction")
        self.tooltips.add(self.aspect_check, "Try to keep aspect ratio.")
        self.scaler_box = ConfigComboBoxWidget(self.render_groupbox, "Scaler", self._default_scalers)
        self.tooltips.add(self.scaler_box, "Select size and effect of video")
        # cpu group
        # make a big number for cycles that should never be needed
        cyclemax = int(1e6)
        self.cpu_groupbox = VerticalGroupBox(self, "CPU Options")
        self.cpu_groupbox.setColumns(2)
        self.grid.addWidget(self.cpu_groupbox, 0, 0)
        self.core_box = ConfigComboBoxWidget(self.cpu_groupbox, "Core", self._default_cores)
        self.tooltips.add(self.core_box, "Select type of cpu core")
        self.cycles_box = ConfigSpinWidget(self.cpu_groupbox, "Cycles", max=cyclemax, suffix=" cycles")
        tt = "The number of cycles to attempt to perform in a second"
        self.tooltips.add(self.cycles_box, tt)
        self.cycleup_box = ConfigSpinWidget(self.cpu_groupbox, "Cycle up increment", max=cyclemax, suffix=" cycles")
        self.cycledown_box = ConfigSpinWidget(self.cpu_groupbox, "Cycle down increment", max=cyclemax, suffix=" cycles")

        # dosbox group
        self.dosbox_groupbox = VerticalGroupBox(self, "Dosbox Options")
        self.dosbox_groupbox.setColumns(3)
        # row 1, first two columns
        # self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
        self.grid.addWidget(self.dosbox_groupbox, 1, 0)
        self.language_entry = ConfigKURLSelectWidget(self.dosbox_groupbox, "Language file")
        self.memsize_box = ConfigSpinWidget(self.dosbox_groupbox, "Memory size", suffix="MB")
        self.captures_entry = ConfigKURLSelectWidget(self.dosbox_groupbox, "Captures directory", filetype="dir")

        # dos group
        self.dos_groupbox = VerticalGroupBox(self, "Dos Options")
        self.dos_groupbox.setColumns(3)
        self.grid.addWidget(self.dos_groupbox, 1, 1)
        self.xms_check = QCheckBox(self.dos_groupbox)
        self.xms_check.setText("Enable XMS support")
        self.ems_check = QCheckBox(self.dos_groupbox)
        self.ems_check.setText("Enable EMS support")
        self.umb_check = QCheckBox(self.dos_groupbox)
        self.umb_check.setText("Enable UMB support")

        # peripheral options
        self.peripheral_groupbox = VerticalGroupBox(self, "Peripheral Options")
        self.peripheral_groupbox.setColumns(1)
        # self.grid.addWidget(self.peripheral_groupbox, 2, 0)
        self.grid.addMultiCellWidget(self.peripheral_groupbox, 2, 2, 0, 2)
        # peripherals in bios section
        self.bios_groupbox = VerticalGroupBox(self.peripheral_groupbox, "Bios Options")
        self.bios_groupbox.setColumns(1)
        joystick_types = ["none", "2axis", "4axis", "fcs", "ch"]
        self.joysticktype_box = ConfigComboBoxWidget(self.bios_groupbox, "Joystick type", joystick_types)
        # peripherals in serial section
        self.serial_groupbox = VerticalGroupBox(self.peripheral_groupbox, "Serial Options")
        self.serial_groupbox.setColumns(2)
        self.serial_warning_lbl = QLabel("These options are", self.serial_groupbox)
        self.serial_warning_lbl2 = QLabel("not fully suported yet.", self.serial_groupbox)
        self.serial1_box = SerialPortOption(self.serial_groupbox, "Serial 1")
        self.serial2_box = SerialPortOption(self.serial_groupbox, "Serial 2")
        self.serial3_box = SerialPortOption(self.serial_groupbox, "Serial 3")
        self.serial4_box = SerialPortOption(self.serial_groupbox, "Serial 4")

        # ipx options
        self.ipx_groupbox = VerticalGroupBox(self, "IPX Options")
        self.ipx_groupbox.setColumns(1)
        self.grid.addWidget(self.ipx_groupbox, 1, 2)
        self.ipx_check = QCheckBox(self.ipx_groupbox)
        self.ipx_check.setText("Enable ipx over UDP/IP emulation")

    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        render = "render"
        cpu = "cpu"
        dosbox = "dosbox"
        dos = "dos"
        bios = "bios"
        serial = "serial"
        ipx = "ipx"
        cfg = self.mainconfig
        # set the various config widgets
        # render section
        frameskip = cfg.getint(render, "frameskip")
        self.frameskip_box.set_config_option(frameskip)
        aspect = cfg.getboolean(render, "aspect")
        self.aspect_check.setChecked(aspect)
        scaler = cfg.get(render, "scaler")
        self.scaler_box.set_config_option(scaler)
        # cpu section
        core = cfg.get(cpu, "core")
        self.core_box.set_config_option(core)
        cycles = cfg.getint(cpu, "cycles")
        self.cycles_box.set_config_option(cycles)
        cycleup = cfg.getint(cpu, "cycleup")
        self.cycleup_box.set_config_option(cycleup)
        cycledown = cfg.getint(cpu, "cycledown")
        self.cycledown_box.set_config_option(cycledown)
        # dosbox section
        language = cfg.get(dosbox, "language")
        self.language_entry.set_config_option(language)
        memsize = cfg.getint(dosbox, "memsize")
        self.memsize_box.set_config_option(memsize)
        captures = cfg.get(dosbox, "captures")
        self.captures_entry.set_config_option(captures)
        # dos section
        xms = cfg.getboolean(dos, "xms")
        self.xms_check.setChecked(xms)
        ems = cfg.getboolean(dos, "ems")
        self.ems_check.setChecked(ems)
        umb = cfg.getboolean(dos, "umb")
        self.umb_check.setChecked(umb)
        # bios section
        joysticktype = cfg.get(bios, "joysticktype")
        self.joysticktype_box.set_config_option(joysticktype)
        # serial section
        serial1 = cfg.get(serial, "serial1")
        self.serial1_box.set_config_option(serial1)
        serial2 = cfg.get(serial, "serial2")
        self.serial2_box.set_config_option(serial2)
        serial3 = cfg.get(serial, "serial3")
        self.serial3_box.set_config_option(serial3)
        serial4 = cfg.get(serial, "serial4")
        self.serial4_box.set_config_option(serial4)
        # ipx section
        ipxopt = cfg.getboolean(ipx, ipx)
        self.ipx_check.setChecked(ipxopt)

    def get_config(self):
        # some assignments to help with typing
        render = "render"
        cpu = "cpu"
        dosbox = "dosbox"
        dos = "dos"
        bios = "bios"
        serial = "serial"
        ipx = "ipx"
        cfg = self.localconfig
        # get config values from the various widgets
        # render section
        frameskip = self.frameskip_box.get_config_option()
        cfg.set(render, "frameskip", frameskip)
        aspect = self._get_bool_for_config(self.aspect_check)
        cfg.set(render, "aspect", aspect)
        scaler = self.scaler_box.get_config_option()
        cfg.set(render, "scaler", scaler)
        # cpu section
        core = self.core_box.get_config_option()
        cfg.set(cpu, "core", core)
        cycles = self.cycles_box.get_config_option()
        cfg.set(cpu, "cycles", cycles)
        cycleup = self.cycleup_box.get_config_option()
        cfg.set(cpu, "cycleup", cycleup)
        cycledown = self.cycledown_box.get_config_option()
        cfg.set(cpu, "cycledown", cycledown)
        # dosbox section
        language = self.language_entry.get_config_option()
        cfg.set(dosbox, "language", language)
        memsize = self.memsize_box.get_config_option()
        cfg.set(dosbox, "memsize", memsize)
        captures = self.captures_entry.get_config_option()
        cfg.set(dosbox, "captures", captures)
        # dos section
        xms = self._get_bool_for_config(self.xms_check)
        cfg.set(dos, "xms", xms)
        ems = self._get_bool_for_config(self.ems_check)
        cfg.set(dos, "ems", ems)
        umb = self._get_bool_for_config(self.umb_check)
        cfg.set(dos, "umb", umb)
        # bios section
        joysticktype = self.joysticktype_box.get_config_option()
        cfg.set(bios, "joysticktype", joysticktype)
        # serial section
        serial1 = self.serial1_box.get_config_option()
        cfg.set(serial, "serial1", serial1)
        serial2 = self.serial2_box.get_config_option()
        cfg.set(serial, "serial2", serial2)
        serial3 = self.serial3_box.get_config_option()
        cfg.set(serial, "serial3", serial3)
        serial4 = self.serial4_box.get_config_option()
        cfg.set(serial, "serial4", serial4)
        # ipx section
        ipxopt = self._get_bool_for_config(self.ipx_check)
        cfg.set(ipx, ipx, ipxopt)
        return self.localconfig
 def __init__(self, parent, name='SettingsWidget'):
     BaseConfigWidget.__init__(self, parent, name=name)
     numrows = 2
     numcols = 2
     margin = 7
     space = 10
     self.grid = QGridLayout(self, numrows, numcols,
                             margin, space, 'SettingsWidgetLayout')
     self.myconfig = self.app.myconfig
     for section in ['filemanagement', 'dosbox', 'externalactions', 'mainwindow']:
         self.localconfig.add_section(section)
         
     # filemanagement area
     self.filemanagement_groupbox = VerticalGroupBox(self, 'File Management')
     self.filemanagement_groupbox.setColumns(4)
     #self.grid.addWidget(self.filemanagement_groupbox, 0, 0)
     self.grid.addMultiCellWidget(self.filemanagement_groupbox, 0, 0, 0, 1)
     self.use_rdiff_backup_check = QCheckBox(self.filemanagement_groupbox)
     self.use_rdiff_backup_check.setText('Use rdiff-backup')
     self.use_rsync_check = QCheckBox(self.filemanagement_groupbox)
     self.use_rsync_check.setText('Use rsync')
     self.overwrite_extras_archives_check = QCheckBox(self.filemanagement_groupbox)
     self.overwrite_extras_archives_check.setText('Overwrite extras archives')
     self.archives_groupbox = VerticalGroupBox(self.filemanagement_groupbox,
                                               'Archive Paths')
     self.archives_groupbox.setColumns(2)
     #self.grid.addWidget(self.archives_groupbox, 0, 1)
     self.installed_archives_entry = ConfigKURLSelectWidget(self.archives_groupbox,
                                                            'Path to the "install" archives',
                                                            filetype='dir')
     self.extras_archives_entry = ConfigKURLSelectWidget(self.archives_groupbox,
                                                         'Path to the "extras" archives',
                                                         filetype='dir')
     # dosbox area
     self.dosbox_groupbox = VerticalGroupBox(self, 'Dosbox Options')
     self.dosbox_groupbox.setColumns(3)
     #self.grid.addWidget(self.dosbox_groupbox, 1, 0)
     self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
     self.main_dosbox_path_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                          'Path to dosbox area',
                                                          filetype='dir')
     self.dosbox_binary_entry = ConfigLineEditWidget(self.dosbox_groupbox,
                                                     'Dosbox executable')
     self.cdrive_is_main_check = QCheckBox(self.dosbox_groupbox)
     self.cdrive_is_main_check.setText('C: Drive is main dosbox path')
     # externalactions area
     self.externalactions_groupbox = VerticalGroupBox(self, 'External Actions')
     self.externalactions_groupbox.setColumns(2)
     self.grid.addWidget(self.externalactions_groupbox, 2, 0)
     self.launch_weblinks_entry = ConfigLineEditWidget(self.externalactions_groupbox,
                                                       'Command to handle weblink clicks')
     self.text_editor_entry = ConfigLineEditWidget(self.externalactions_groupbox,
                                                   'Text editor command')
     # mainwindow area
     self.mainwindow_groupbox = VerticalGroupBox(self, 'Main Window Options')
     self.mainwindow_groupbox.setColumns(3)
     self.grid.addWidget(self.mainwindow_groupbox, 2, 1)
     self.mainwindow_size_box = ConfigWinSizeWidget(self.mainwindow_groupbox,
                                                    'Size of main window')
     self.flat_tree_box = ConfigComboBoxWidget(self.mainwindow_groupbox,
                                               'Game list style', ['flat', 'tree'])
     self.name_title_box = ConfigComboBoxWidget(self.mainwindow_groupbox,
                                                'Game list entries', ['name', 'title'])
class qSlicerMultiVolumeExplorerModuleWidget(
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget):
    def __init__(self, parent=None):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.__init__(self, parent)

    def setupAdditionalFrames(self):
        self.setupPlotSettingsFrame()

    def setupInputFrame(self, parent=None):
        self.inputFrame = ctk.ctkCollapsibleButton()
        self.inputFrame.text = "Input"
        self.inputFrame.collapsed = 0
        inputFrameCollapsibleLayout = QFormLayout(self.inputFrame)
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupInputFrame(
            self, parent=inputFrameCollapsibleLayout)
        self.layout.addWidget(self.inputFrame)

        self.fgMultiVolumeSelector = slicer.qMRMLNodeComboBox()
        self.fgMultiVolumeSelector.nodeTypes = ['vtkMRMLMultiVolumeNode']
        self.fgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
        self.fgMultiVolumeSelector.addEnabled = 0
        self.fgMultiVolumeSelector.noneEnabled = 1
        self.fgMultiVolumeSelector.toolTip = "Secondary multivolume will be used for the secondary \
      plot in interactive charting. As an example, this can be used to overlay the \
      curve obtained by fitting a model to the data"

        self.inputFrameLayout.addRow(QLabel('Input secondary multivolume'),
                                     self.fgMultiVolumeSelector)

    def setupFrameControlFrame(self):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupFrameControlFrame(
            self)

        self.frameCopySelector = slicer.qMRMLNodeComboBox()
        self.frameCopySelector.setSizePolicy(QSizePolicy.Ignored,
                                             QSizePolicy.Preferred)
        self.frameCopySelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.frameCopySelector.setMRMLScene(slicer.mrmlScene)
        self.frameCopySelector.addEnabled = 1
        self.frameCopySelector.enabled = 0
        # do not show "children" of vtkMRMLScalarVolumeNode
        self.frameCopySelector.hideChildNodeTypes = [
            "vtkMRMLDiffusionWeightedVolumeNode",
            "vtkMRMLDiffusionTensorVolumeNode", "vtkMRMLVectorVolumeNode"
        ]
        self.extractFrameCopy = False
        self.extractFrameCheckBox = QCheckBox('Enable copying')
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Current frame copy'))
        hbox.addWidget(self.frameCopySelector)
        hbox.addWidget(self.extractFrameCheckBox)
        self.inputFrameLayout.addRow(hbox)

    def setupPlotSettingsFrame(self):
        self.plotSettingsFrame = ctk.ctkCollapsibleButton()
        self.plotSettingsFrame.text = "Plotting Settings"
        self.plotSettingsFrame.collapsed = 1
        plotSettingsFrameLayout = QFormLayout(self.plotSettingsFrame)
        self.layout.addWidget(self.plotSettingsFrame)

        # label map for probing
        self.labelMapSelector = slicer.qMRMLNodeComboBox()
        self.labelMapSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']
        self.labelMapSelector.toolTip = 'Label map to be probed'
        self.labelMapSelector.setMRMLScene(slicer.mrmlScene)
        self.labelMapSelector.addEnabled = 0
        self.chartButton = QPushButton('Chart')
        self.chartButton.setEnabled(False)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Probed label volume'))
        hbox.addWidget(self.labelMapSelector)
        hbox.addWidget(self.chartButton)
        plotSettingsFrameLayout.addRow(hbox)

        self.iCharting = QCheckBox('Interactive charting')
        self.iCharting.setChecked(True)
        plotSettingsFrameLayout.addRow(self.iCharting)

        self.iChartingMode = QButtonGroup()
        self.iChartingIntensity = QRadioButton('Signal intensity')
        self.iChartingIntensityFixedAxes = QRadioButton(
            'Fixed range intensity')
        self.iChartingPercent = QRadioButton('Percentage change')
        self.iChartingIntensity.setChecked(1)
        self.iChartingMode.addButton(self.iChartingIntensity)
        self.iChartingMode.addButton(self.iChartingIntensityFixedAxes)
        self.iChartingMode.addButton(self.iChartingPercent)

        hbox = QHBoxLayout()
        self.plottingModeGroupBox = QGroupBox('Plotting mode:')
        plottingModeLayout = QVBoxLayout()
        self.plottingModeGroupBox.setLayout(plottingModeLayout)
        plottingModeLayout.addWidget(self.iChartingIntensity)
        plottingModeLayout.addWidget(self.iChartingIntensityFixedAxes)
        plottingModeLayout.addWidget(self.iChartingPercent)
        hbox.addWidget(self.plottingModeGroupBox)

        self.showLegendCheckBox = QCheckBox('Display legend')
        self.showLegendCheckBox.setChecked(0)
        self.xLogScaleCheckBox = QCheckBox('Use log scale for X axis')
        self.xLogScaleCheckBox.setChecked(0)
        self.yLogScaleCheckBox = QCheckBox('Use log scale for Y axis')
        self.yLogScaleCheckBox.setChecked(0)

        self.plotGeneralSettingsGroupBox = QGroupBox('General Plot options:')
        plotGeneralSettingsLayout = QVBoxLayout()
        self.plotGeneralSettingsGroupBox.setLayout(plotGeneralSettingsLayout)
        plotGeneralSettingsLayout.addWidget(self.showLegendCheckBox)
        plotGeneralSettingsLayout.addWidget(self.xLogScaleCheckBox)
        plotGeneralSettingsLayout.addWidget(self.yLogScaleCheckBox)
        hbox.addWidget(self.plotGeneralSettingsGroupBox)
        plotSettingsFrameLayout.addRow(hbox)

        self.nFramesBaselineCalculation = QSpinBox()
        self.nFramesBaselineCalculation.minimum = 1
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Frame count(baseline calculation):'))
        hbox.addWidget(self.nFramesBaselineCalculation)
        plotSettingsFrameLayout.addRow(hbox)

    def setupPlottingFrame(self, parent=None):
        self.plotFrame = ctk.ctkCollapsibleButton()
        self.plotFrame.text = "Plotting"
        self.plotFrame.collapsed = 0
        plotFrameLayout = QGridLayout(self.plotFrame)
        self.layout.addWidget(self.plotFrame)
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupPlottingFrame(
            self, parent=plotFrameLayout)

    def onDockChartViewToggled(self, checked):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onDockChartViewToggled(
            self, checked)
        if checked:
            self.layout.removeWidget(self.plotFrame)
            self.plotFrame.hide()

    def dockChartView(self):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.dockChartView(self)
        self.layout.addWidget(self.plotFrame)
        self.plotFrame.show()

    def setFramesEnabled(self, enabled):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setFramesEnabled(
            self, enabled)
        self.plotSettingsFrame.setEnabled(enabled)
        self.plotFrame.setEnabled(enabled)
        self.plotFrame.collapsed = 0 if enabled else 1

    def setupConnections(self):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.setupConnections(self)
        self.labelMapSelector.connect('currentNodeChanged(vtkMRMLNode*)',
                                      self.onLabelNodeChanged)
        self.chartButton.connect('clicked()', self.onLabeledChartRequested)
        self.xLogScaleCheckBox.connect('stateChanged(int)',
                                       self.onXLogScaleRequested)
        self.yLogScaleCheckBox.connect('stateChanged(int)',
                                       self.onYLogScaleRequested)
        self.nFramesBaselineCalculation.valueChanged.connect(
            self.onFrameCountBaselineCalculationChanged)
        self.iChartingMode.buttonClicked.connect(self.onChartingModeChanged)
        self.showLegendCheckBox.connect('stateChanged(int)',
                                        self.onShowLegendChanged)
        self.fgMultiVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)',
                                           self.onForegroundInputChanged)
        self.extractFrameCheckBox.connect('stateChanged(int)',
                                          self.onExtractFrameChanged)
        self.frameCopySelector.connect('mrmlSceneChanged(vtkMRMLScene*)',
                                       self.onVFMRMLSceneChanged)

    def onFrameCountBaselineCalculationChanged(self, value):
        self._multiVolumeIntensityChart.nFramesForBaselineCalculation = value

    def onChartingModeChanged(self, button):
        if button is self.iChartingIntensity:
            self._multiVolumeIntensityChart.activateSignalIntensityMode()
        elif button is self.iChartingIntensityFixedAxes:
            self._multiVolumeIntensityChart.activateFixedRangeIntensityMode()
        elif button is self.iChartingPercent:
            self._multiVolumeIntensityChart.activatePercentageChangeMode()

    def onShowLegendChanged(self, checked):
        self._multiVolumeIntensityChart.showLegend = True if checked == 2 else False

    def onXLogScaleRequested(self, checked):
        self._multiVolumeIntensityChart.showXLogScale = True if checked == 2 else False

    def onYLogScaleRequested(self, checked):
        self._multiVolumeIntensityChart.showYLogScale = True if checked == 2 else False

    def onLVMRMLSceneChanged(self, mrmlScene):
        self.labelMapSelector.setMRMLScene(slicer.mrmlScene)

    def onVFMRMLSceneChanged(self, mrmlScene):
        self.frameCopySelector.setMRMLScene(slicer.mrmlScene)

    def onLabelNodeChanged(self):
        labelNode = self.labelMapSelector.currentNode()
        self.chartButton.setEnabled(labelNode is not None
                                    and self._bgMultiVolumeNode is not None)

    def onForegroundInputChanged(self):
        logging.info(
            "qSlicerMultiVolumeExplorerModuleWidget:ForegroundInputChanged")
        self._fgMultiVolumeNode = self.fgMultiVolumeSelector.currentNode()
        self._multiVolumeIntensityChart.fgMultiVolumeNode = self.fgMultiVolumeSelector.currentNode(
        )
        self.refreshGUIForNewBackgroundImage()

    def onBackgroundInputChanged(self):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onBackgroundInputChanged(
            self)

        if self._bgMultiVolumeNode is not None:
            self.frameCopySelector.setCurrentNode(None)
            self.nFramesBaselineCalculation.maximum = self._bgMultiVolumeNode.GetNumberOfFrames(
            )
        self.onLabelNodeChanged()

    '''
  If extract button is checked, will copy the current frame to the
  selected volume node on each event from frame slider
  '''

    def onExtractFrameChanged(self, checked):
        if checked:
            self.extractFrameCopy = True
            self.onSliderChanged(self.frameSlider.value)
        else:
            self.extractFrameCopy = False

    def onSliderChanged(self, frameId):
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.onSliderChanged(
            self, frameId)
        frameId = int(frameId)
        if self.extractFrameCopy:
            frameVolume = self.frameCopySelector.currentNode()
            frameVolumeCopy = Helper.extractFrame(frameVolume,
                                                  self._bgMultiVolumeNode,
                                                  frameId)
            if not frameVolume:
                self.frameCopySelector.setCurrentNode(frameVolumeCopy)
            frameName = '%s frame %d' % (self._bgMultiVolumeNode.GetName(),
                                         frameId)
            frameVolumeCopy.SetName(frameName)

    def onLabeledChartRequested(self):
        labelNode = self.labelMapSelector.currentNode()
        mvNode = self._bgMultiVolumeNode

        mvLabels = MultiVolumeIntensityChartView.getMultiVolumeLabels(
            self._bgMultiVolumeNode)

        chartViewNode = LabeledImageChartView(
            labelNode=labelNode,
            multiVolumeNode=mvNode,
            multiVolumeLabels=mvLabels,
            baselineFrames=self.nFramesBaselineCalculation,
            displayPercentageChange=self.iChartingPercent.checked)
        chartViewNode.requestChartCreation()

    def processEvent(self, observee, event):
        if not self.iCharting.checked:
            return
        qSlicerMultiVolumeExplorerSimplifiedModuleWidget.processEvent(
            self, observee, event)
    def __init__(self, parent, name='SDLConfigWidget'):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_machines = ['vga', 'cga', 'tandy', 'pcjr', 'hercules']
        self._default_scalers = ['none', 'normal2x', 'normal3x', 'advmame2x', 'advmame3x',
                                 'advinterp2x', 'advinterp3x', 'tv2x', 'tv3x',
                                 'rgb2x', 'rgb3x', 'scan2x', 'scan3x']
        self._default_cores = ['simple', 'normal', 'full', 'dynamic', 'auto']
        for section in ['render', 'cpu', 'dosbox', 'dos', 'bios', 'serial', 'ipx']:
            self.localconfig.add_section(section)
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'MachineConfigWidgetLayout')

        # render group
        self.render_groupbox = VerticalGroupBox(self, 'Render Options')
        self.render_groupbox.setColumns(2)
        self.grid.addWidget(self.render_groupbox, 0, 1)
        self.frameskip_box = ConfigSpinWidget(self.render_groupbox,
                                              'Frame skip', suffix=' frames')
        self.tooltips.add(self.frameskip_box, 'How many frames to skip.')
        self.aspect_check = QCheckBox(self.render_groupbox)
        self.aspect_check.setText('Aspect correction')
        self.tooltips.add(self.aspect_check, 'Try to keep aspect ratio.')
        self.scaler_box = ConfigComboBoxWidget(self.render_groupbox,
                                               'Scaler', self._default_scalers)
        self.tooltips.add(self.scaler_box, 'Select size and effect of video')
        # cpu group
        # make a big number for cycles that should never be needed
        cyclemax = int(1e6)
        self.cpu_groupbox = VerticalGroupBox(self, 'CPU Options')
        self.cpu_groupbox.setColumns(2)
        self.grid.addWidget(self.cpu_groupbox, 0, 0)
        self.core_box = ConfigComboBoxWidget(self.cpu_groupbox,
                                             'Core', self._default_cores)
        self.tooltips.add(self.core_box, 'Select type of cpu core')
        self.cycles_box = ConfigSpinWidget(self.cpu_groupbox,
                                           'Cycles', max=cyclemax, suffix=' cycles')
        tt = 'The number of cycles to attempt to perform in a second'
        self.tooltips.add(self.cycles_box, tt)
        self.cycleup_box = ConfigSpinWidget(self.cpu_groupbox,
                                            'Cycle up increment', max=cyclemax,
                                            suffix=' cycles')
        self.cycledown_box = ConfigSpinWidget(self.cpu_groupbox,
                                              'Cycle down increment', max=cyclemax,
                                              suffix=' cycles')
        
        # dosbox group
        self.dosbox_groupbox = VerticalGroupBox(self, 'Dosbox Options')
        self.dosbox_groupbox.setColumns(3)
        # row 1, first two columns
        #self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
        self.grid.addWidget(self.dosbox_groupbox, 1, 0)
        self.language_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                     'Language file')
        self.memsize_box = ConfigSpinWidget(self.dosbox_groupbox,
                                            'Memory size', suffix='MB')
        self.captures_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                     'Captures directory', filetype='dir')
            
        # dos group
        self.dos_groupbox = VerticalGroupBox(self, 'Dos Options')
        self.dos_groupbox.setColumns(3)
        self.grid.addWidget(self.dos_groupbox, 1, 1)
        self.xms_check = QCheckBox(self.dos_groupbox)
        self.xms_check.setText('Enable XMS support')
        self.ems_check = QCheckBox(self.dos_groupbox)
        self.ems_check.setText('Enable EMS support')
        self.umb_check = QCheckBox(self.dos_groupbox)
        self.umb_check.setText('Enable UMB support')

        # peripheral options
        self.peripheral_groupbox = VerticalGroupBox(self, 'Peripheral Options')
        self.peripheral_groupbox.setColumns(1)
        #self.grid.addWidget(self.peripheral_groupbox, 2, 0)
        self.grid.addMultiCellWidget(self.peripheral_groupbox, 2, 2, 0, 2)
        # peripherals in bios section
        self.bios_groupbox = VerticalGroupBox(self.peripheral_groupbox, 'Bios Options')
        self.bios_groupbox.setColumns(1)
        joystick_types = ['none', '2axis', '4axis', 'fcs', 'ch']
        self.joysticktype_box = ConfigComboBoxWidget(self.bios_groupbox,
                                                     'Joystick type', joystick_types)
        # peripherals in serial section
        self.serial_groupbox = VerticalGroupBox(self.peripheral_groupbox, 'Serial Options')
        self.serial_groupbox.setColumns(2)
        self.serial_warning_lbl = QLabel('These options are',
                                         self.serial_groupbox)
        self.serial_warning_lbl2 = QLabel('not fully suported yet.', self.serial_groupbox)
        self.serial1_box = SerialPortOption(self.serial_groupbox, 'Serial 1')
        self.serial2_box = SerialPortOption(self.serial_groupbox, 'Serial 2')
        self.serial3_box = SerialPortOption(self.serial_groupbox, 'Serial 3')
        self.serial4_box = SerialPortOption(self.serial_groupbox, 'Serial 4')

        # ipx options
        self.ipx_groupbox = VerticalGroupBox(self, 'IPX Options')
        self.ipx_groupbox.setColumns(1)
        self.grid.addWidget(self.ipx_groupbox, 1, 2)
        self.ipx_check = QCheckBox(self.ipx_groupbox)
        self.ipx_check.setText('Enable ipx over UDP/IP emulation')
class MachineConfigWidget(BaseDosboxConfigWidget):
    def __init__(self, parent, name='SDLConfigWidget'):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_machines = ['vga', 'cga', 'tandy', 'pcjr', 'hercules']
        self._default_scalers = ['none', 'normal2x', 'normal3x', 'advmame2x', 'advmame3x',
                                 'advinterp2x', 'advinterp3x', 'tv2x', 'tv3x',
                                 'rgb2x', 'rgb3x', 'scan2x', 'scan3x']
        self._default_cores = ['simple', 'normal', 'full', 'dynamic', 'auto']
        for section in ['render', 'cpu', 'dosbox', 'dos', 'bios', 'serial', 'ipx']:
            self.localconfig.add_section(section)
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'MachineConfigWidgetLayout')

        # render group
        self.render_groupbox = VerticalGroupBox(self, 'Render Options')
        self.render_groupbox.setColumns(2)
        self.grid.addWidget(self.render_groupbox, 0, 1)
        self.frameskip_box = ConfigSpinWidget(self.render_groupbox,
                                              'Frame skip', suffix=' frames')
        self.tooltips.add(self.frameskip_box, 'How many frames to skip.')
        self.aspect_check = QCheckBox(self.render_groupbox)
        self.aspect_check.setText('Aspect correction')
        self.tooltips.add(self.aspect_check, 'Try to keep aspect ratio.')
        self.scaler_box = ConfigComboBoxWidget(self.render_groupbox,
                                               'Scaler', self._default_scalers)
        self.tooltips.add(self.scaler_box, 'Select size and effect of video')
        # cpu group
        # make a big number for cycles that should never be needed
        cyclemax = int(1e6)
        self.cpu_groupbox = VerticalGroupBox(self, 'CPU Options')
        self.cpu_groupbox.setColumns(2)
        self.grid.addWidget(self.cpu_groupbox, 0, 0)
        self.core_box = ConfigComboBoxWidget(self.cpu_groupbox,
                                             'Core', self._default_cores)
        self.tooltips.add(self.core_box, 'Select type of cpu core')
        self.cycles_box = ConfigSpinWidget(self.cpu_groupbox,
                                           'Cycles', max=cyclemax, suffix=' cycles')
        tt = 'The number of cycles to attempt to perform in a second'
        self.tooltips.add(self.cycles_box, tt)
        self.cycleup_box = ConfigSpinWidget(self.cpu_groupbox,
                                            'Cycle up increment', max=cyclemax,
                                            suffix=' cycles')
        self.cycledown_box = ConfigSpinWidget(self.cpu_groupbox,
                                              'Cycle down increment', max=cyclemax,
                                              suffix=' cycles')
        
        # dosbox group
        self.dosbox_groupbox = VerticalGroupBox(self, 'Dosbox Options')
        self.dosbox_groupbox.setColumns(3)
        # row 1, first two columns
        #self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
        self.grid.addWidget(self.dosbox_groupbox, 1, 0)
        self.language_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                     'Language file')
        self.memsize_box = ConfigSpinWidget(self.dosbox_groupbox,
                                            'Memory size', suffix='MB')
        self.captures_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                     'Captures directory', filetype='dir')
            
        # dos group
        self.dos_groupbox = VerticalGroupBox(self, 'Dos Options')
        self.dos_groupbox.setColumns(3)
        self.grid.addWidget(self.dos_groupbox, 1, 1)
        self.xms_check = QCheckBox(self.dos_groupbox)
        self.xms_check.setText('Enable XMS support')
        self.ems_check = QCheckBox(self.dos_groupbox)
        self.ems_check.setText('Enable EMS support')
        self.umb_check = QCheckBox(self.dos_groupbox)
        self.umb_check.setText('Enable UMB support')

        # peripheral options
        self.peripheral_groupbox = VerticalGroupBox(self, 'Peripheral Options')
        self.peripheral_groupbox.setColumns(1)
        #self.grid.addWidget(self.peripheral_groupbox, 2, 0)
        self.grid.addMultiCellWidget(self.peripheral_groupbox, 2, 2, 0, 2)
        # peripherals in bios section
        self.bios_groupbox = VerticalGroupBox(self.peripheral_groupbox, 'Bios Options')
        self.bios_groupbox.setColumns(1)
        joystick_types = ['none', '2axis', '4axis', 'fcs', 'ch']
        self.joysticktype_box = ConfigComboBoxWidget(self.bios_groupbox,
                                                     'Joystick type', joystick_types)
        # peripherals in serial section
        self.serial_groupbox = VerticalGroupBox(self.peripheral_groupbox, 'Serial Options')
        self.serial_groupbox.setColumns(2)
        self.serial_warning_lbl = QLabel('These options are',
                                         self.serial_groupbox)
        self.serial_warning_lbl2 = QLabel('not fully suported yet.', self.serial_groupbox)
        self.serial1_box = SerialPortOption(self.serial_groupbox, 'Serial 1')
        self.serial2_box = SerialPortOption(self.serial_groupbox, 'Serial 2')
        self.serial3_box = SerialPortOption(self.serial_groupbox, 'Serial 3')
        self.serial4_box = SerialPortOption(self.serial_groupbox, 'Serial 4')

        # ipx options
        self.ipx_groupbox = VerticalGroupBox(self, 'IPX Options')
        self.ipx_groupbox.setColumns(1)
        self.grid.addWidget(self.ipx_groupbox, 1, 2)
        self.ipx_check = QCheckBox(self.ipx_groupbox)
        self.ipx_check.setText('Enable ipx over UDP/IP emulation')
        
    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        render = 'render'
        cpu = 'cpu'
        dosbox = 'dosbox'
        dos = 'dos'
        bios = 'bios'
        serial = 'serial'
        ipx = 'ipx'
        cfg = self.mainconfig
        # set the various config widgets
        # render section
        frameskip = cfg.getint(render, 'frameskip')
        self.frameskip_box.set_config_option(frameskip)
        aspect = cfg.getboolean(render, 'aspect')
        self.aspect_check.setChecked(aspect)
        scaler = cfg.get(render, 'scaler')
        self.scaler_box.set_config_option(scaler)
        # cpu section
        core = cfg.get(cpu, 'core')
        self.core_box.set_config_option(core)
        cycles = cfg.getint(cpu, 'cycles')
        self.cycles_box.set_config_option(cycles)
        cycleup = cfg.getint(cpu, 'cycleup')
        self.cycleup_box.set_config_option(cycleup)
        cycledown = cfg.getint(cpu, 'cycledown')
        self.cycledown_box.set_config_option(cycledown)
        # dosbox section
        language = cfg.get(dosbox, 'language')
        self.language_entry.set_config_option(language)
        memsize = cfg.getint(dosbox, 'memsize')
        self.memsize_box.set_config_option(memsize)
        captures = cfg.get(dosbox, 'captures')
        self.captures_entry.set_config_option(captures)
        # dos section
        xms = cfg.getboolean(dos, 'xms')
        self.xms_check.setChecked(xms)
        ems = cfg.getboolean(dos, 'ems')
        self.ems_check.setChecked(ems)
        umb = cfg.getboolean(dos, 'umb')
        self.umb_check.setChecked(umb)
        # bios section
        joysticktype = cfg.get(bios, 'joysticktype')
        self.joysticktype_box.set_config_option(joysticktype)
        # serial section
        serial1 = cfg.get(serial, 'serial1')
        self.serial1_box.set_config_option(serial1)
        serial2 = cfg.get(serial, 'serial2')
        self.serial2_box.set_config_option(serial2)
        serial3 = cfg.get(serial, 'serial3')
        self.serial3_box.set_config_option(serial3)
        serial4 = cfg.get(serial, 'serial4')
        self.serial4_box.set_config_option(serial4)
        # ipx section
        ipxopt = cfg.getboolean(ipx, ipx)
        self.ipx_check.setChecked(ipxopt)

    def get_config(self):
        # some assignments to help with typing
        render = 'render'
        cpu = 'cpu'
        dosbox = 'dosbox'
        dos = 'dos'
        bios = 'bios'
        serial = 'serial'
        ipx = 'ipx'
        cfg = self.localconfig
        # get config values from the various widgets
        # render section
        frameskip = self.frameskip_box.get_config_option()
        cfg.set(render, 'frameskip', frameskip)
        aspect = self._get_bool_for_config(self.aspect_check)
        cfg.set(render, 'aspect', aspect)
        scaler = self.scaler_box.get_config_option()
        cfg.set(render, 'scaler', scaler)
        # cpu section
        core = self.core_box.get_config_option()
        cfg.set(cpu, 'core', core)
        cycles = self.cycles_box.get_config_option()
        cfg.set(cpu, 'cycles', cycles)
        cycleup = self.cycleup_box.get_config_option()
        cfg.set(cpu, 'cycleup', cycleup)
        cycledown = self.cycledown_box.get_config_option()
        cfg.set(cpu, 'cycledown', cycledown)
        # dosbox section
        language = self.language_entry.get_config_option()
        cfg.set(dosbox, 'language', language)
        memsize = self.memsize_box.get_config_option()
        cfg.set(dosbox, 'memsize', memsize)
        captures = self.captures_entry.get_config_option()
        cfg.set(dosbox, 'captures', captures)
        # dos section
        xms = self._get_bool_for_config(self.xms_check)
        cfg.set(dos, 'xms', xms)
        ems = self._get_bool_for_config(self.ems_check)
        cfg.set(dos, 'ems', ems)
        umb = self._get_bool_for_config(self.umb_check)
        cfg.set(dos, 'umb', umb)
        # bios section
        joysticktype = self.joysticktype_box.get_config_option()
        cfg.set(bios, 'joysticktype', joysticktype)
        # serial section
        serial1 = self.serial1_box.get_config_option()
        cfg.set(serial, 'serial1', serial1)
        serial2 = self.serial2_box.get_config_option()
        cfg.set(serial, 'serial2', serial2)
        serial3 = self.serial3_box.get_config_option()
        cfg.set(serial, 'serial3', serial3)
        serial4 = self.serial4_box.get_config_option()
        cfg.set(serial, 'serial4', serial4)
        # ipx section
        ipxopt = self._get_bool_for_config(self.ipx_check)
        cfg.set(ipx, ipx, ipxopt)
        return self.localconfig
    def __init__(self, parent, name="SDLConfigWidget"):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 3
        margin = 10
        space = 7
        self._default_mpu401_types = ["none", "uart", "intelligent"]
        self._default_midi_devices = ["default", "none", "alsa", "oss", "coreaudio", "win32"]
        self._default_sbtypes = ["none", "sb1", "sb2", "sbpro1", "sbpro2", "sb16"]
        self._default_tandyopts = ["auto", "on", "off"]
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "SDLConfigWidgetLayout")
        for section in ["mixer", "midi", "sblaster", "gus", "speaker"]:
            self.localconfig.add_section(section)

        # mixer group
        self.mixer_groupbox = VerticalGroupBox(self, "Mixer Options")
        self.mixer_groupbox.setColumns(4)
        self.grid.addWidget(self.mixer_groupbox, 0, 0)
        self.nosound_check = QCheckBox(self.mixer_groupbox)
        self.nosound_check.setText("Disable sound")
        self.sample_rate_box = SampleRateOption(self.mixer_groupbox, "Sample rate")
        # magic number for maximum block size
        self.blocksize_box = ConfigSpinWidget(
            self.mixer_groupbox, "Mixer block size", min=0, max=262144, suffix=" bytes"
        )
        # magic number for maximum prebuffer (10 secs)
        self.prebuffer_box = ConfigSpinWidget(self.mixer_groupbox, "Prebuffer", min=0, max=10000, suffix=" msec")

        # midi group
        self.midi_groupbox = VerticalGroupBox(self, "MIDI Options")
        self.midi_groupbox.setColumns(4)
        self.grid.addWidget(self.midi_groupbox, 1, 1)
        self.mpu401_box = ConfigComboBoxWidget(self.midi_groupbox, "mpu401 type", self._default_mpu401_types)
        self.midi_device_box = ConfigComboBoxWidget(self.midi_groupbox, "MIDI device", self._default_midi_devices)
        self.midi_config_box = ConfigLineEditWidget(self.midi_groupbox, "MIDI config")

        # speaker group
        self.speaker_groupbox = VerticalGroupBox(self, "PC Speaker Options")
        self.speaker_groupbox.setColumns(5)
        self.grid.addMultiCellWidget(self.speaker_groupbox, 1, 1, 0, 0)
        self.enable_speaker_check = QCheckBox(self.speaker_groupbox)
        self.enable_speaker_check.setText("Enable PC speaker emulation")
        self.pc_rate_box = SampleRateOption(self.speaker_groupbox, "Sample rate of PC speaker")
        self.enable_tandy_box = ConfigComboBoxWidget(
            self.speaker_groupbox, "Enable Tandy Sound System emulation", self._default_tandyopts
        )
        self.tandy_rate_box = SampleRateOption(self.speaker_groupbox, "Sample rate of Tandy Sound System")
        self.enable_disney_check = QCheckBox(self.speaker_groupbox)
        self.enable_disney_check.setText("Enable Disney Sound Source emulation")

        # sblaster group
        self.sblaster_groupbox = VerticalGroupBox(self, "SoundBlaster Options")
        self.sblaster_groupbox.setColumns(2)
        # self.grid.addWidget(self.sblaster_groupbox, 0, 0)
        self.grid.addMultiCellWidget(self.sblaster_groupbox, 0, 0, 0, 1)
        self.sbtype_box = ConfigComboBoxWidget(self.sblaster_groupbox, "SoundBlaster type", self._default_sbtypes)
        self.sblaster_hwopt_groupbox = VerticalGroupBox(self.sblaster_groupbox, "SoundBlaster Hardware Options")
        self.sblaster_hwopt_groupbox.setColumns(1)
        self.sblaster_hwopt_box = SoundBlasterHardwareOptions(self.sblaster_hwopt_groupbox)

        self.sb_mixer_check = QCheckBox(self.sblaster_groupbox)
        self.sb_mixer_check.setText("SoundBlaster modifies dosbox mixer")
        self.sblaster_oplopt_groupbox = VerticalGroupBox(self.sblaster_groupbox, "SoundBlaster OPL Options")
        self.sblaster_oplopt_groupbox.setColumns(1)
        self.sblaster_oplopt_box = SoundBlasterOPLOptions(self.sblaster_oplopt_groupbox)

        # gus group
        self.gus_groupbox = VerticalGroupBox(self, "Gravis Ultrasound Options")
        self.gus_groupbox.setColumns(5)
        # self.grid.addWidget(self.gus_groupbox, 2, 1)
        self.grid.addMultiCellWidget(self.gus_groupbox, 0, 1, 2, 2)
        self.enable_gus_check = QCheckBox(self.gus_groupbox)
        self.enable_gus_check.setText("Enable Gravis Ultrasound emulation")
        self.gus_hwopt_groupbox = VerticalGroupBox(self.gus_groupbox, "Gravis Ultrasound hardware options")
        self.gus_hwopt_groupbox.setColumns(1)
        self.gus_hwopt_box = GusHardwareOptions(self.gus_hwopt_groupbox)
        self.gus_rate_box = SampleRateOption(self.gus_groupbox)
        self.gus_ultradir_box = ConfigKURLSelectWidget(self.gus_groupbox, "GUS patches directory", filetype="dir")
Exemple #30
0
 def __init__(self, rule):
     QCheckBox.__init__(self, m18n(rule.name))
     self.rule = rule
class SDLConfigWidget(BaseDosboxConfigWidget):
    def __init__(self, parent, name='SDLConfigWidget'):
        BaseDosboxConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 2
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'SDLConfigWidgetLayout')
        self.myconfig = self.app.myconfig
        res = self.myconfig.get('dosbox_profiles', 'default_resolutions')
        resolutions = [r.strip() for r in res.split(',')]
        self._default_resolutions = ['original'] + resolutions
        self._default_outputs = ['surface', 'overlay', 'opengl', 'openglnb', 'ddraw']
        self._default_priorities = ['lowest', 'lower', 'normal', 'higher', 'highest']
        self.new_stuff()
        self.localconfig.add_section('sdl')
        
    def new_stuff(self):
        # fullscreen group
        self.fullscreen_groupbox = VerticalGroupBox(self, 'Fullscreen Options')
        self.fullscreen_groupbox.setColumns(2)
        self.grid.addWidget(self.fullscreen_groupbox, 0, 0)
        self.fullscreen_check = QCheckBox(self.fullscreen_groupbox)
        self.fullscreen_check.setText('fullscreen')
        self.tooltips.add(self.fullscreen_check, "Run dosbox in fullscreen")
        self.fulldouble_check = QCheckBox(self.fullscreen_groupbox)
        self.fulldouble_check.setText('full&double')
        self.tooltips.add(self.fulldouble_check, "Use double buffering in fullscreen")
        
        # resolution group
        self.resolution_groupbox = VerticalGroupBox(self, 'Resolution Options')
        self.resolution_groupbox.setColumns(4)
        self.grid.addWidget(self.resolution_groupbox, 0, 1)
        self.fullresolution_box = ConfigComboBoxWidget(self.resolution_groupbox,
                                                       'fullscreen resolution', self._default_resolutions)
        self.tooltips.add(self.fullresolution_box, "Resolution when running in fullscreen")

        self.windowresolution_box = ConfigComboBoxWidget(self.resolution_groupbox,
                                                         'windowed resolution', self._default_resolutions)
        self.tooltips.add(self.windowresolution_box, "Resolution when running in a window")
        
        # misc group
        self.misc_groupbox = VerticalGroupBox(self, 'Misc. Options')
        self.misc_groupbox.setColumns(3)
        self.grid.addWidget(self.misc_groupbox, 1, 0)
        self.output_box = ConfigComboBoxWidget(self.misc_groupbox,
                                               'Output', self._default_outputs)
        self.waitonerror_check = QCheckBox(self.misc_groupbox)
        self.waitonerror_check.setText('Wait on error')
        self.tooltips.add(self.waitonerror_check,
                          "Wait before closing window if dosbox has an error")
        
        # mouse group
        self.mouse_groupbox = VerticalGroupBox(self, 'Mouse Options')
        self.mouse_groupbox.setColumns(3)
        self.grid.addWidget(self.mouse_groupbox, 1, 1)
        self.autolock_check = QCheckBox(self.mouse_groupbox)
        self.autolock_check.setText('autolock')
        self.tooltips.add(self.autolock_check,
                          "Clicking in the dosbox window automatically locks mouse")
        self.sensitivity_box = ConfigSpinWidget(self.mouse_groupbox,
                                                'Mouse sensitivity', min=1, max=100,
                                                suffix='%')
        self.tooltips.add(self.sensitivity_box, "How sensitive the mouse is")

        # keyboard group
        self.keyboard_groupbox = VerticalGroupBox(self, 'Keyboard Options')
        self.keyboard_groupbox.setColumns(3)
        # add to row 2, first two columns
        self.grid.addMultiCellWidget(self.keyboard_groupbox, 2, 2, 0, 1)
        self.usescancodes_check = QCheckBox(self.keyboard_groupbox)
        self.usescancodes_check.setText('usescancodes')
        self.tooltips.add(self.usescancodes_check,
                          "Avoid use of symkeys")
        self.mapper_entry = ConfigKURLSelectWidget(self.keyboard_groupbox,
                                                   'mapperfile (File used for key mappings)')
        self.tooltips.add(self.mapper_entry, "File used for key mappings")


        # priority group
        self.priority_groupbox = QGroupBox(self)
        self.priority_groupbox.setTitle('Priority Options')
        self.priority_groupbox.setColumns(2)
        #self.grid.addWidget(self.priority_groupbox, 3, 0)
        # add to row 3 first two columns
        self.grid.addMultiCellWidget(self.priority_groupbox, 3, 3, 0, 1)
        self.focused_box = ConfigComboBoxWidget(self.priority_groupbox,
                                                'focused', self._default_priorities)
        self.tooltips.add(self.focused_box, "Priority level for dosbox when focused")
        self.unfocused_box = ConfigComboBoxWidget(self.priority_groupbox,
                                                  'unfocused', self._default_priorities)
        self.tooltips.add(self.unfocused_box,
                          "Priority level for dosbox when unfocused or minimized")
        
    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        sdl = 'sdl'
        cfg = self.mainconfig
        # set the various config widgets
        fullscreen = cfg.getboolean(sdl, 'fullscreen')
        self.fullscreen_check.setChecked(fullscreen)
        fulldouble = cfg.getboolean(sdl, 'fulldouble')
        self.fulldouble_check.setChecked(fulldouble)
        fullresolution = cfg.get(sdl, 'fullresolution')
        self.fullresolution_box.set_config_option(fullresolution)
        windowresolution = cfg.get(sdl, 'windowresolution')
        self.windowresolution_box.set_config_option(windowresolution)
        output = cfg.get(sdl, 'output')
        self.output_box.set_config_option(output)
        waitonerror = cfg.getboolean(sdl, 'waitonerror')
        self.waitonerror_check.setChecked(waitonerror)
        autolock = cfg.getboolean(sdl, 'autolock')
        self.autolock_check.setChecked(autolock)
        sensitivity = cfg.getint(sdl, 'sensitivity')
        self.sensitivity_box.set_config_option(sensitivity)
        usescancodes = cfg.getboolean(sdl, 'usescancodes')
        self.usescancodes_check.setChecked(usescancodes)
        mapperfile = cfg.get(sdl, 'mapperfile')
        self.mapper_entry.set_config_option(mapperfile)
        priorities = cfg.get(sdl, 'priority')
        focused, unfocused = [p.strip() for p in priorities.split(',')]
        self.focused_box.set_config_option(focused)
        self.unfocused_box.set_config_option(unfocused)

    def get_config(self):
        # some assignments to help with typing
        sdl = 'sdl'
        cfg = self.localconfig
        # get config values from the various widgets
        fullscreen = self._get_bool_for_config(self.fullscreen_check)
        cfg.set(sdl, 'fullscreen', fullscreen)
        fulldouble = self._get_bool_for_config(self.fulldouble_check)
        cfg.set(sdl, 'fulldouble', fulldouble)
        fullresolution = self.fullresolution_box.get_config_option()
        cfg.set(sdl, 'fullresolution', fullresolution)
        windowresolution = self.windowresolution_box.get_config_option()
        cfg.set(sdl, 'windowresolution', windowresolution)
        output = self.output_box.get_config_option()
        cfg.set(sdl, 'output', output)
        waitonerror = self._get_bool_for_config(self.waitonerror_check)
        cfg.set(sdl, 'waitonerror', waitonerror)
        autolock = self._get_bool_for_config(self.autolock_check)
        cfg.set(sdl, 'autolock', autolock)
        sensitivity = self.sensitivity_box.get_config_option()
        cfg.set(sdl, 'sensitivity', sensitivity)
        usescancodes = self._get_bool_for_config(self.usescancodes_check)
        cfg.set(sdl, 'usescancodes', usescancodes)
        mapperfile = self.mapper_entry.get_config_option()
        cfg.set(sdl, 'mapperfile', mapperfile)
        # priorities part
        focused = self.focused_box.get_config_option()
        unfocused = self.unfocused_box.get_config_option()
        priority = ','.join([focused, unfocused])
        cfg.set(sdl, 'priority', priority)
        return self.localconfig
Exemple #32
0
 def setupUi(self):
     """layout the window"""
     self.setContentsMargins(0, 0, 0, 0)
     vlayout = QVBoxLayout(self)
     vlayout.setContentsMargins(0, 0, 0, 0)
     sliderLayout = QHBoxLayout()
     self.kcfg_showShadows = QCheckBox(i18n('Show tile shadows'), self)
     self.kcfg_showShadows.setObjectName('kcfg_showShadows')
     self.kcfg_rearrangeMelds = QCheckBox(
         i18n('Rearrange undisclosed tiles to melds'), self)
     self.kcfg_rearrangeMelds.setObjectName('kcfg_rearrangeMelds')
     self.kcfg_showOnlyPossibleActions = QCheckBox(
         i18n('Show only possible actions'))
     self.kcfg_showOnlyPossibleActions.setObjectName(
         'kcfg_showOnlyPossibleActions')
     self.kcfg_propose = QCheckBox(i18n('Propose what to do'))
     self.kcfg_propose.setObjectName('kcfg_propose')
     self.kcfg_animationSpeed = QSlider(self)
     self.kcfg_animationSpeed.setObjectName('kcfg_animationSpeed')
     self.kcfg_animationSpeed.setOrientation(Qt.Horizontal)
     self.kcfg_animationSpeed.setSingleStep(1)
     lblSpeed = QLabel(i18n('Animation speed:'))
     lblSpeed.setBuddy(self.kcfg_animationSpeed)
     sliderLayout.addWidget(lblSpeed)
     sliderLayout.addWidget(self.kcfg_animationSpeed)
     self.kcfg_useSounds = QCheckBox(i18n('Use sounds if available'), self)
     self.kcfg_useSounds.setObjectName('kcfg_useSounds')
     self.kcfg_uploadVoice = QCheckBox(i18n('Let others hear my voice'),
                                       self)
     self.kcfg_uploadVoice.setObjectName('kcfg_uploadVoice')
     pol = QSizePolicy()
     pol.setHorizontalPolicy(QSizePolicy.Expanding)
     pol.setVerticalPolicy(QSizePolicy.Expanding)
     spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                              QSizePolicy.Expanding)
     vlayout.addWidget(self.kcfg_showShadows)
     vlayout.addWidget(self.kcfg_rearrangeMelds)
     vlayout.addWidget(self.kcfg_showOnlyPossibleActions)
     vlayout.addWidget(self.kcfg_propose)
     vlayout.addWidget(self.kcfg_useSounds)
     vlayout.addWidget(self.kcfg_uploadVoice)
     vlayout.addLayout(sliderLayout)
     vlayout.addItem(spacerItem)
     self.setSizePolicy(pol)
     self.retranslateUi()
Exemple #33
0
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)
    def new_stuff(self):
        # fullscreen group
        self.fullscreen_groupbox = VerticalGroupBox(self, 'Fullscreen Options')
        self.fullscreen_groupbox.setColumns(2)
        self.grid.addWidget(self.fullscreen_groupbox, 0, 0)
        self.fullscreen_check = QCheckBox(self.fullscreen_groupbox)
        self.fullscreen_check.setText('fullscreen')
        self.tooltips.add(self.fullscreen_check, "Run dosbox in fullscreen")
        self.fulldouble_check = QCheckBox(self.fullscreen_groupbox)
        self.fulldouble_check.setText('full&double')
        self.tooltips.add(self.fulldouble_check, "Use double buffering in fullscreen")
        
        # resolution group
        self.resolution_groupbox = VerticalGroupBox(self, 'Resolution Options')
        self.resolution_groupbox.setColumns(4)
        self.grid.addWidget(self.resolution_groupbox, 0, 1)
        self.fullresolution_box = ConfigComboBoxWidget(self.resolution_groupbox,
                                                       'fullscreen resolution', self._default_resolutions)
        self.tooltips.add(self.fullresolution_box, "Resolution when running in fullscreen")

        self.windowresolution_box = ConfigComboBoxWidget(self.resolution_groupbox,
                                                         'windowed resolution', self._default_resolutions)
        self.tooltips.add(self.windowresolution_box, "Resolution when running in a window")
        
        # misc group
        self.misc_groupbox = VerticalGroupBox(self, 'Misc. Options')
        self.misc_groupbox.setColumns(3)
        self.grid.addWidget(self.misc_groupbox, 1, 0)
        self.output_box = ConfigComboBoxWidget(self.misc_groupbox,
                                               'Output', self._default_outputs)
        self.waitonerror_check = QCheckBox(self.misc_groupbox)
        self.waitonerror_check.setText('Wait on error')
        self.tooltips.add(self.waitonerror_check,
                          "Wait before closing window if dosbox has an error")
        
        # mouse group
        self.mouse_groupbox = VerticalGroupBox(self, 'Mouse Options')
        self.mouse_groupbox.setColumns(3)
        self.grid.addWidget(self.mouse_groupbox, 1, 1)
        self.autolock_check = QCheckBox(self.mouse_groupbox)
        self.autolock_check.setText('autolock')
        self.tooltips.add(self.autolock_check,
                          "Clicking in the dosbox window automatically locks mouse")
        self.sensitivity_box = ConfigSpinWidget(self.mouse_groupbox,
                                                'Mouse sensitivity', min=1, max=100,
                                                suffix='%')
        self.tooltips.add(self.sensitivity_box, "How sensitive the mouse is")

        # keyboard group
        self.keyboard_groupbox = VerticalGroupBox(self, 'Keyboard Options')
        self.keyboard_groupbox.setColumns(3)
        # add to row 2, first two columns
        self.grid.addMultiCellWidget(self.keyboard_groupbox, 2, 2, 0, 1)
        self.usescancodes_check = QCheckBox(self.keyboard_groupbox)
        self.usescancodes_check.setText('usescancodes')
        self.tooltips.add(self.usescancodes_check,
                          "Avoid use of symkeys")
        self.mapper_entry = ConfigKURLSelectWidget(self.keyboard_groupbox,
                                                   'mapperfile (File used for key mappings)')
        self.tooltips.add(self.mapper_entry, "File used for key mappings")


        # priority group
        self.priority_groupbox = QGroupBox(self)
        self.priority_groupbox.setTitle('Priority Options')
        self.priority_groupbox.setColumns(2)
        #self.grid.addWidget(self.priority_groupbox, 3, 0)
        # add to row 3 first two columns
        self.grid.addMultiCellWidget(self.priority_groupbox, 3, 3, 0, 1)
        self.focused_box = ConfigComboBoxWidget(self.priority_groupbox,
                                                'focused', self._default_priorities)
        self.tooltips.add(self.focused_box, "Priority level for dosbox when focused")
        self.unfocused_box = ConfigComboBoxWidget(self.priority_groupbox,
                                                  'unfocused', self._default_priorities)
        self.tooltips.add(self.unfocused_box,
                          "Priority level for dosbox when unfocused or minimized")
Exemple #35
0
class ImportPage(QWidget):

    update_command_lst_low_level = Signal(list)

    """
    This stacked widget basically helps the user to browse the input images
    path, there is no auto-generated GUI form Phil parameters in use withing
    this widget.
    """

    def __init__(self, parent=None):
        super(ImportPage, self).__init__(parent=None)

        main_v_box = QVBoxLayout()

        label_font = QFont()
        sys_font_point_size = label_font.pointSize()
        label_font.setPointSize(sys_font_point_size + 2)
        step_label = QLabel(str("Import"))
        step_label.setFont(label_font)

        self.simple_lin = QLineEdit(self)
        self.simple_lin.textChanged.connect(self.update_command)

        self.x_spn_bx = QSpinBox()
        self.x_spn_bx.setMaximum(99999)
        self.x_spn_bx.setSpecialValueText(" ")
        self.y_spn_bx = QSpinBox()
        self.y_spn_bx.setMaximum(99999)
        self.y_spn_bx.setSpecialValueText(" ")

        self.x_spn_bx.valueChanged.connect(self.x_beam_changed)
        self.y_spn_bx.valueChanged.connect(self.y_beam_changed)

        self.chk_invert = QCheckBox("Invert rotation axis")
        self.chk_invert.stateChanged.connect(self.inv_rota_changed)

        self.opn_fil_btn = QPushButton(" \n Select file(s) \n ")

        main_path = get_main_path()

        self.opn_fil_btn.setIcon(QIcon(main_path + "/resources/import.png"))
        self.opn_fil_btn.setIconSize(QSize(80, 48))

        main_v_box.addWidget(step_label)
        main_v_box.addWidget(self.opn_fil_btn)
        main_v_box.addWidget(self.simple_lin)
        self.b_cetre_label = QLabel("\n\n Beam centre")
        main_v_box.addWidget(self.b_cetre_label)
        cent_hbox = QHBoxLayout()
        self.x_label = QLabel("    X: ")
        cent_hbox.addWidget(self.x_label)
        cent_hbox.addWidget(self.x_spn_bx)
        self.y_label = QLabel("    Y: ")
        cent_hbox.addWidget(self.y_label)
        cent_hbox.addWidget(self.y_spn_bx)
        #    cent_hbox.addWidget(QLabel(" \n "))
        cent_hbox.addStretch()
        main_v_box.addLayout(cent_hbox)
        main_v_box.addWidget(self.chk_invert)
        main_v_box.addStretch()

        self.opn_fil_btn.clicked.connect(self.open_files)

        self.defa_dir = str(os.getcwd())
        self.setLayout(main_v_box)
        # self.show()
        self.reset_par()

    def reset_par(self):
        logger.info("reset_par(ImportPage)")
        self.cmd_list = []
        self.simple_lin.setText(" ? ")
        self.x_spn_bx.setValue(0.0)
        self.y_spn_bx.setValue(0.0)
        self.chk_invert.setChecked(False)

        self.x_beam, self.y_beam = 0.0, 0.0
        self.path_file_str = ""
        self.second_half = ""
        self.third_half = ""

    def update_param_w_lst(self, lst_in):
        self.reset_par()
        logger.info("update_param_w_lst(ImportPage) \n lst: \n", lst_in)
        for singl_com in lst_in:
            if singl_com[0:1] == "/":
                self.path_file_str = str(singl_com)
                self.put_str_lin()

            if singl_com[0:12] == "image_range=":
                self.path_file_str += " "
                self.path_file_str += str(singl_com)
                self.put_str_lin()

            if singl_com == "invert_rotation_axis=True":
                self.chk_invert.setChecked(True)

            if singl_com[0:22] == "slow_fast_beam_centre=":
                yb_xb_str = singl_com[22:]
                yb_str, xb_str = yb_xb_str.split(",")
                yb = float(yb_str)
                xb = float(xb_str)
                self.y_spn_bx.setValue(yb)
                self.x_spn_bx.setValue(xb)

    def inv_rota_changed(self):
        if self.chk_invert.checkState():
            self.third_half = "invert_rotation_axis=True"

        else:
            self.third_half = ""

        self.put_str_lin()

    def x_beam_changed(self, value):
        self.x_beam = value
        self.build_second_half()

    def y_beam_changed(self, value):
        self.y_beam = value
        self.build_second_half()

    def build_second_half(self):
        if self.x_beam != 0.0 and self.y_beam != 0.0:
            self.second_half = (
                "slow_fast_beam_centre=" + str(self.y_beam) + "," + str(self.x_beam)
            )

        else:
            self.second_half = ""

        self.put_str_lin()

    def open_files(self):

        lst_file_path = QFileDialog.getOpenFileNames(
            self, "Open File(s)", self.defa_dir, "All Files (*.*)"
        )

        if len(lst_file_path) > 0:
            new_dir, new_command = get_import_run_string(lst_file_path)
            # logger.info("\n new_dir=", new_dir, ">>")
            # logger.info("\n new_command =", new_command, ">>")
            self.path_file_str = new_command
            self.defa_dir = new_dir
            self.put_str_lin()

    def put_str_lin(self):
        # logger.info("self.path_file_str =", self.path_file_str, ">>")
        self.cmd_list = [
            self.path_file_str,
            self.second_half.lstrip(),
            self.third_half.lstrip(),
        ]
        txt_lin = " ".join(self.cmd_list).rstrip()
        while "  " in txt_lin:
            txt_lin = txt_lin.replace("  ", " ")

        self.simple_lin.setText(txt_lin)

    def set_arg_obj(self, sys_arg_in):
        """Pass the system argument object to handle launch arguments."""
        if sys_arg_in.template is not None:
            str_arg = str(sys_arg_in.template)
            self.simple_lin.setText(str_arg)

    def update_command(self):
        self.command_lst = [["import"]]
        param_com = str(self.simple_lin.text())

        cmd_lst = param_com.split(" ")

        for single_com in cmd_lst:
            self.command_lst[0].append(single_com)

        self.update_command_lst_low_level.emit(self.command_lst[0])

    def gray_me_out(self):
        self.simple_lin.setEnabled(False)
        self.opn_fil_btn.setEnabled(False)
        self.x_spn_bx.setEnabled(False)
        self.y_spn_bx.setEnabled(False)
        self.x_label.setEnabled(False)
        self.y_label.setEnabled(False)
        self.b_cetre_label.setEnabled(False)
        self.chk_invert.setEnabled(False)

    def activate_me(self, cur_nod=None):
        self.simple_lin.setEnabled(True)
        self.opn_fil_btn.setEnabled(True)
        self.y_spn_bx.setEnabled(True)
        self.x_spn_bx.setEnabled(True)
        self.x_label.setEnabled(True)
        self.y_label.setEnabled(True)
        self.b_cetre_label.setEnabled(True)
        self.chk_invert.setEnabled(True)
    def setupPlotSettingsFrame(self):
        self.plotSettingsFrame = ctk.ctkCollapsibleButton()
        self.plotSettingsFrame.text = "Plotting Settings"
        self.plotSettingsFrame.collapsed = 1
        plotSettingsFrameLayout = QFormLayout(self.plotSettingsFrame)
        self.layout.addWidget(self.plotSettingsFrame)

        # label map for probing
        self.labelMapSelector = slicer.qMRMLNodeComboBox()
        self.labelMapSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']
        self.labelMapSelector.toolTip = 'Label map to be probed'
        self.labelMapSelector.setMRMLScene(slicer.mrmlScene)
        self.labelMapSelector.addEnabled = 0
        self.chartButton = QPushButton('Chart')
        self.chartButton.setEnabled(False)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Probed label volume'))
        hbox.addWidget(self.labelMapSelector)
        hbox.addWidget(self.chartButton)
        plotSettingsFrameLayout.addRow(hbox)

        self.iCharting = QCheckBox('Interactive charting')
        self.iCharting.setChecked(True)
        plotSettingsFrameLayout.addRow(self.iCharting)

        self.iChartingMode = QButtonGroup()
        self.iChartingIntensity = QRadioButton('Signal intensity')
        self.iChartingIntensityFixedAxes = QRadioButton(
            'Fixed range intensity')
        self.iChartingPercent = QRadioButton('Percentage change')
        self.iChartingIntensity.setChecked(1)
        self.iChartingMode.addButton(self.iChartingIntensity)
        self.iChartingMode.addButton(self.iChartingIntensityFixedAxes)
        self.iChartingMode.addButton(self.iChartingPercent)

        hbox = QHBoxLayout()
        self.plottingModeGroupBox = QGroupBox('Plotting mode:')
        plottingModeLayout = QVBoxLayout()
        self.plottingModeGroupBox.setLayout(plottingModeLayout)
        plottingModeLayout.addWidget(self.iChartingIntensity)
        plottingModeLayout.addWidget(self.iChartingIntensityFixedAxes)
        plottingModeLayout.addWidget(self.iChartingPercent)
        hbox.addWidget(self.plottingModeGroupBox)

        self.showLegendCheckBox = QCheckBox('Display legend')
        self.showLegendCheckBox.setChecked(0)
        self.xLogScaleCheckBox = QCheckBox('Use log scale for X axis')
        self.xLogScaleCheckBox.setChecked(0)
        self.yLogScaleCheckBox = QCheckBox('Use log scale for Y axis')
        self.yLogScaleCheckBox.setChecked(0)

        self.plotGeneralSettingsGroupBox = QGroupBox('General Plot options:')
        plotGeneralSettingsLayout = QVBoxLayout()
        self.plotGeneralSettingsGroupBox.setLayout(plotGeneralSettingsLayout)
        plotGeneralSettingsLayout.addWidget(self.showLegendCheckBox)
        plotGeneralSettingsLayout.addWidget(self.xLogScaleCheckBox)
        plotGeneralSettingsLayout.addWidget(self.yLogScaleCheckBox)
        hbox.addWidget(self.plotGeneralSettingsGroupBox)
        plotSettingsFrameLayout.addRow(hbox)

        self.nFramesBaselineCalculation = QSpinBox()
        self.nFramesBaselineCalculation.minimum = 1
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('Frame count(baseline calculation):'))
        hbox.addWidget(self.nFramesBaselineCalculation)
        plotSettingsFrameLayout.addRow(hbox)
class SettingsWidget(BaseConfigWidget):
    def __init__(self, parent, name='SettingsWidget'):
        BaseConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 2
        margin = 7
        space = 10
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'SettingsWidgetLayout')
        self.myconfig = self.app.myconfig
        for section in ['filemanagement', 'dosbox', 'externalactions', 'mainwindow']:
            self.localconfig.add_section(section)
            
        # filemanagement area
        self.filemanagement_groupbox = VerticalGroupBox(self, 'File Management')
        self.filemanagement_groupbox.setColumns(4)
        #self.grid.addWidget(self.filemanagement_groupbox, 0, 0)
        self.grid.addMultiCellWidget(self.filemanagement_groupbox, 0, 0, 0, 1)
        self.use_rdiff_backup_check = QCheckBox(self.filemanagement_groupbox)
        self.use_rdiff_backup_check.setText('Use rdiff-backup')
        self.use_rsync_check = QCheckBox(self.filemanagement_groupbox)
        self.use_rsync_check.setText('Use rsync')
        self.overwrite_extras_archives_check = QCheckBox(self.filemanagement_groupbox)
        self.overwrite_extras_archives_check.setText('Overwrite extras archives')
        self.archives_groupbox = VerticalGroupBox(self.filemanagement_groupbox,
                                                  'Archive Paths')
        self.archives_groupbox.setColumns(2)
        #self.grid.addWidget(self.archives_groupbox, 0, 1)
        self.installed_archives_entry = ConfigKURLSelectWidget(self.archives_groupbox,
                                                               'Path to the "install" archives',
                                                               filetype='dir')
        self.extras_archives_entry = ConfigKURLSelectWidget(self.archives_groupbox,
                                                            'Path to the "extras" archives',
                                                            filetype='dir')
        # dosbox area
        self.dosbox_groupbox = VerticalGroupBox(self, 'Dosbox Options')
        self.dosbox_groupbox.setColumns(3)
        #self.grid.addWidget(self.dosbox_groupbox, 1, 0)
        self.grid.addMultiCellWidget(self.dosbox_groupbox, 1, 1, 0, 1)
        self.main_dosbox_path_entry = ConfigKURLSelectWidget(self.dosbox_groupbox,
                                                             'Path to dosbox area',
                                                             filetype='dir')
        self.dosbox_binary_entry = ConfigLineEditWidget(self.dosbox_groupbox,
                                                        'Dosbox executable')
        self.cdrive_is_main_check = QCheckBox(self.dosbox_groupbox)
        self.cdrive_is_main_check.setText('C: Drive is main dosbox path')
        # externalactions area
        self.externalactions_groupbox = VerticalGroupBox(self, 'External Actions')
        self.externalactions_groupbox.setColumns(2)
        self.grid.addWidget(self.externalactions_groupbox, 2, 0)
        self.launch_weblinks_entry = ConfigLineEditWidget(self.externalactions_groupbox,
                                                          'Command to handle weblink clicks')
        self.text_editor_entry = ConfigLineEditWidget(self.externalactions_groupbox,
                                                      'Text editor command')
        # mainwindow area
        self.mainwindow_groupbox = VerticalGroupBox(self, 'Main Window Options')
        self.mainwindow_groupbox.setColumns(3)
        self.grid.addWidget(self.mainwindow_groupbox, 2, 1)
        self.mainwindow_size_box = ConfigWinSizeWidget(self.mainwindow_groupbox,
                                                       'Size of main window')
        self.flat_tree_box = ConfigComboBoxWidget(self.mainwindow_groupbox,
                                                  'Game list style', ['flat', 'tree'])
        self.name_title_box = ConfigComboBoxWidget(self.mainwindow_groupbox,
                                                   'Game list entries', ['name', 'title'])

    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        filemanagement = 'filemanagement'
        dosbox = 'dosbox'
        externalactions = 'externalactions'
        mainwindow = 'mainwindow'
        cfg = self.mainconfig
        # set the various config widgets
        # filemanagement section
        use_rdiff_backup = cfg.getboolean(filemanagement, 'use_rdiff_backup')
        self.use_rdiff_backup_check.setChecked(use_rdiff_backup)
        use_rsync = cfg.getboolean(filemanagement, 'use_rsync')
        self.use_rsync_check.setChecked(use_rsync)
        overwrite_extras_archives = cfg.getboolean(filemanagement, 'overwrite_extras_archives')
        self.overwrite_extras_archives_check.setChecked(overwrite_extras_archives)
        installed_archives_path = cfg.get(filemanagement, 'installed_archives_path')
        self.installed_archives_entry.set_config_option(installed_archives_path)
        extras_archives_path = cfg.get(filemanagement, 'extras_archives_path')
        self.extras_archives_entry.set_config_option(extras_archives_path)
        # dosbox section
        dosbox_binary = cfg.get(dosbox, 'dosbox_binary')
        self.dosbox_binary_entry.set_config_option(dosbox_binary)
        main_dosbox_path = cfg.get(dosbox, 'main_dosbox_path')
        self.main_dosbox_path_entry.set_config_option(main_dosbox_path)
        cdrive_is_main = cfg.getboolean(dosbox, 'cdrive_is_main_dosbox_path')
        self.cdrive_is_main_check.setChecked(cdrive_is_main)
        # externalactions section
        launch_weblink = cfg.get(externalactions, 'launch_weblink')
        self.launch_weblinks_entry.set_config_option(launch_weblink)
        text_editor = cfg.get(externalactions, 'text_editor')
        self.text_editor_entry.set_config_option(text_editor)
        # mainwindow section
        mainwindow_size = cfg.get(mainwindow, 'mainwindow_size')
        self.mainwindow_size_box.set_config_option(mainwindow_size)
        flat_tree_view = cfg.get(mainwindow, 'flat_tree_view')
        self.flat_tree_box.set_config_option(flat_tree_view)
        name_title_view = cfg.get(mainwindow, 'name_title_view')
        self.name_title_box.set_config_option(name_title_view)

    def get_config(self):
        # some assignments to help with typing
        filemanagement = 'filemanagement'
        dosbox = 'dosbox'
        externalactions = 'externalactions'
        mainwindow = 'mainwindow'
        cfg = self.localconfig
        # get config values from the various widgets
        # filemanagement section
        use_rdiff_backup = self._get_bool_for_config(self.use_rdiff_backup_check)
        cfg.set(filemanagement, 'use_rdiff_backup', use_rdiff_backup)
        use_rsync = self._get_bool_for_config(self.use_rsync_check)
        cfg.set(filemanagement, 'use_rsync', use_rsync)
        overwrite_extras = self._get_bool_for_config(self.overwrite_extras_archives_check)
        cfg.set(filemanagement, 'overwrite_extras_archives', overwrite_extras)
        installed_archives_path = self.installed_archives_entry.get_config_option()
        cfg.set(filemanagement, 'installed_archives_path', installed_archives_path)
        extras_archives_path = self.extras_archives_entry.get_config_option()
        cfg.set(filemanagement, 'extras_archives_path', extras_archives_path)
        # dosbox section
        dosbox_binary = self.dosbox_binary_entry.get_config_option()
        cfg.set(dosbox, 'dosbox_binary', dosbox_binary)
        main_dosbox_path = self.main_dosbox_path_entry.get_config_option()
        cfg.set(dosbox, 'main_dosbox_path', main_dosbox_path)
        cdrive_is_main = self._get_bool_for_config(self.cdrive_is_main_check)
        cfg.set(dosbox, 'cdrive_is_main_dosbox_path', cdrive_is_main)
        # externalactions section
        launch_weblink = self.launch_weblinks_entry.get_config_option()
        cfg.set(externalactions, 'launch_weblink', launch_weblink)
        text_editor = self.text_editor_entry.get_config_option()
        cfg.set(externalactions, 'text_editor', text_editor)
        # mainwindow section
        mainwindow_size = self.mainwindow_size_box.get_config_option()
        cfg.set(mainwindow, 'mainwindow_size', mainwindow_size)
        flat_tree_view = self.flat_tree_box.get_config_option()
        cfg.set(mainwindow, 'flat_tree_view', flat_tree_view)
        name_title_view = self.name_title_box.get_config_option()
        cfg.set(mainwindow, 'name_title_view', name_title_view)
        return cfg