class GusHardwareOptions(QWidget):
    def __init__(self, parent, name="GusHardwareOptions"):
        QWidget.__init__(self, parent, name)
        numrows = 2
        numcols = 3
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "GusHardwareOptionsLayout")
        self.base_box = ConfigSpinWidget(self, "I/O address", max=1000)
        self.grid.addWidget(self.base_box, 0, 0)
        self.irq1_box = ConfigSpinWidget(self, "IRQ 1", min=3, max=15)
        self.grid.addWidget(self.irq1_box, 0, 1)
        self.irq2_box = ConfigSpinWidget(self, "IRQ 2", min=3, max=15)
        self.grid.addWidget(self.irq2_box, 1, 1)
        self.dma1_box = ConfigSpinWidget(self, "DMA 1")
        self.grid.addWidget(self.dma1_box, 0, 2)
        self.dma2_box = ConfigSpinWidget(self, "DMA 2")
        self.grid.addWidget(self.dma2_box, 1, 2)

    def get_config_options(self):
        opts = {}
        opts["gusbase"] = self.base_box.get_config_option()
        opts["irq1"] = self.irq1_box.get_config_option()
        opts["irq2"] = self.irq2_box.get_config_option()
        opts["dma1"] = self.dma1_box.get_config_option()
        opts["dma2"] = self.dma2_box.get_config_option()

        return opts

    def set_config_options(self, opts):
        self.base_box.set_config_option(opts["gusbase"])
        self.irq1_box.set_config_option(opts["irq1"])
        self.irq2_box.set_config_option(opts["irq2"])
        self.dma1_box.set_config_option(opts["dma1"])
        self.dma2_box.set_config_option(opts["dma2"])
class BaseWorksEntryFrame(QFrame):
    def __init__(self, parent, name='BaseWorksEntryFrame'):
        QFrame.__init__(self, parent, name)
        margin = 0
        space = 1
        self.grid = QGridLayout(self, 6, 1, margin, space)
        
        self.worktype_lbl = QLabel('Work Type', self)
        self.worktype_entry = KLineEdit('website', self)
        self.title_lbl = QLabel('Title', self)
        self.title_entry = KLineEdit('', self)
        self.url_lbl = QLabel('Url', self)
        self.url_entry = KLineEdit('', self)

        row = 0
        for widget in [self.worktype_lbl, self.worktype_entry,
                       self.title_lbl, self.title_entry,
                       self.url_lbl, self.url_entry]:
            self.grid.addWidget(widget, row, 0)
            row += 1
            
    def get_data(self):
        wtype = str(self.worktype_entry.text())
        title = str(self.title_entry.text())
        url = str(self.url_entry.text())
        return dict(title=title, url=url, type=wtype)

    def set_data(self, data):
        self.title_entry.setText(data['title'])
        self.url_entry.setText(data['url'])
        wtype = data['type']
        if wtype is None:
            wtype = 'website'
        self.worktype_entry.setText(wtype)
class IntroPage(BaseConfigWidget):
    def __init__(self, parent, name='IntroPage'):
        BaseConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 1
        margin = 5
        space = 7
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'IntroPageLayout')
        lbl = QLabel(intro, self)
        self.grid.addWidget(lbl, 0, 0)
class SoundBlasterHardwareOptions(QWidget):
    def __init__(self, parent, name="SoundBlasterHardwareOptions"):
        QWidget.__init__(self, parent, name)
        numrows = 2
        numcols = 3
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "SoundBlasterHardwareOptionsLayout")
        self.base_box = ConfigSpinWidget(self, "I/O address", max=1000)
        self.grid.addWidget(self.base_box, 0, 0)
        self.irq_box = ConfigSpinWidget(self, "IRQ", min=3, max=15)
        self.grid.addWidget(self.irq_box, 1, 0)
        self.dma_box = ConfigSpinWidget(self, "DMA")
        self.grid.addWidget(self.dma_box, 0, 2)
        self.hdma_box = ConfigSpinWidget(self, "High DMA")
        self.grid.addWidget(self.hdma_box, 1, 2)

    def get_config_options(self):
        opts = {}
        opts["sbbase"] = self.base_box.get_config_option()
        opts["irq"] = self.irq_box.get_config_option()
        opts["dma"] = self.dma_box.get_config_option()
        opts["hdma"] = self.hdma_box.get_config_option()
        return opts

    def set_config_options(self, opts):
        self.base_box.set_config_option(opts["sbbase"])
        self.irq_box.set_config_option(opts["irq"])
        self.dma_box.set_config_option(opts["dma"])
        self.hdma_box.set_config_option(opts["hdma"])
Exemple #5
0
class LabeledProgress(QWidget):
    def __init__(self, parent, text='', name='LabeledProgress'):
        QWidget.__init__(self, parent, name)
        self.grid = QGridLayout(self, 2, 1, 5, 7)
        self.label = QLabel(self)
        if text:
            self.label.setText(text)
        self.progressbar = SimpleProgress(self)
        self.grid.addWidget(self.label, 0, 0)
        self.grid.addWidget(self.progressbar, 1, 0)

    def setTotalSteps(self, total):
        self.progressbar.setTotalSteps(total)

    def step_progress(self, *args):
        self.progressbar.step_progress(*args)
Exemple #6
0
 def onDockChartViewToggled(self, checked):
   if checked:
     self.chartPopupWindow = QDialog()
     self.chartPopupWindow.setWindowFlags(PythonQt.QtCore.Qt.WindowStaysOnTopHint)
     layout = QGridLayout()
     self.chartPopupWindow.setLayout(layout)
     layout.addWidget(self._multiVolumeIntensityChart.chartView)
     layout.addWidget(self.popupChartButton)
     self.chartPopupWindow.finished.connect(self.dockChartView)
     self.chartPopupWindow.resize(self.chartPopupSize)
     self.chartPopupWindow.move(self.chartPopupPosition)
     self.chartPopupWindow.show()
     self.popupChartButton.setText("Dock chart")
     self._multiVolumeIntensityChart.chartView.show()
   else:
     self.chartPopupWindow.close()
class TestConfigTab(QWidget):
    def __init__(self, parent, name='TestConfigTab'):
        QWidget.__init__(self, parent, name)
        self.grid = QGridLayout(self, 2, 1, 0, 1, 'TestConfigTabLayout')
        self.textbrowser = KTextBrowser(self)
        self.grid.addWidget(self.textbrowser, 0, 0)
        self.button = KPushButton(self)
        self.button.setText('test get_config')
        self.grid.addWidget(self.button, 1, 0)
        
    def set_config(self, cfg):
        tfile = StringIO()
        cfg.write(tfile)
        tfile.seek(0)
        text = tfile.read()
        self.textbrowser.setText(text)
class DosboxPathPage(BaseConfigWidget):
    def __init__(self, parent, name='DosboxPathPage'):
        BaseConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 1
        margin = 5
        space = 7
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'DosboxPathPageLayout')
        lbl = QLabel(dosbox_path_lbl, self)
        lbl.setFrameStyle(lbl.Panel + lbl.Sunken)
        #lbl.setFrameStyle(lbl.Raised)
        self.grid.addWidget(lbl, 0, 0)
        self.dosbox_path_entry = ConfigKURLSelectWidget(self, 'Path to main dosbox area',
                                                        filetype='dir')
        self.grid.addWidget(self.dosbox_path_entry, 1, 0)
class LabeledProgress(QWidget):
    def __init__(self, parent, text='', name='LabeledProgress'):
        QWidget.__init__(self, parent, name)
        self.grid = QGridLayout(self, 2, 1, 5, 7)
        self.label = QLabel(self)
        if text:
            self.label.setText(text)
        self.progressbar = SimpleProgress(self)
        self.grid.addWidget(self.label, 0, 0)
        self.grid.addWidget(self.progressbar, 1, 0)
                  
    def setTotalSteps(self, total):
        self.progressbar.setTotalSteps(total)

    def step_progress(self, *args):
        self.progressbar.step_progress(*args)
class BaseTagDialogFrame(QFrame):
    def __init__(self, parent, name='BaseEntityDataFrame'):
        QFrame.__init__(self, parent, name)
        self.entityid = None
        numrows = 5
        numcols = 1
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'BaseEntityDataLayout')
        self.app = get_application_pointer()

        self.lbl = QLabel('Select the tags', self)
        self.grid.addWidget(self.lbl, 0, 0)

        self.listView = KListView(self)
        self.listView.addColumn('tagname', -1)
        self.listView.clear()
        self.grid.addMultiCellWidget(self.listView, 1, 4, 0, 0)
class ImportGameDialog(BaseDialogWindow):
    def __init__(self, parent, name='ImportGameDialog'):
        BaseDialogWindow.__init__(self, parent, name=name)
        self.frame = QFrame(self)
        margin = 5
        space = 7
        self.grid = QGridLayout(self.frame, 2, 1, margin, space)
        self.url_lbl = QLabel('URL', self.frame)
        self.url_entry = KLineEdit('', self.frame)
        self.grid.addWidget(self.url_lbl, 0, 0)
        self.grid.addWidget(self.url_entry, 1, 0)
        self.setMainWidget(self.frame)
        self.connect(self, SIGNAL('okClicked()'), self.import_game)
        

    def import_game(self):
        url = str(self.url_entry.text())
        print url
        KMessageBox.information(self, "import_game is still not implemented")
class BaseGuestAppearanceFrame(QFrame):
    def __init__(self, parent, name='BaseGuestAppearanceFrame'):
        QFrame.__init__(self, parent, name)
        margin = 0
        space = 1
        self.grid = QGridLayout(self, 4, 1, margin, space)
        self.appearance_lbl = QLabel('Appearance', self)
        self.appearance_url = KLineEdit('', self)
        row = 0
        for widget in [self.appearance_lbl, self.appearance_url]:
            self.grid.addWidget(widget, row, 0)
            row += 1

    def get_data(self):
        url = str(self.appearance_url.text())
        return dict(url=url)

    def set_data(self, data):
        self.appearance_url.setText(data['url'])
class ImportGameUrlDialog(BaseDialogWindow):
    def __init__(self, parent, name='ImportGameUrlDialog'):
        BaseDialogWindow.__init__(self, parent, name=name)
        self.frame = QFrame(self)
        margin = 5
        space = 7
        self.grid = QGridLayout(self.frame, 2, 1, margin, space)
        self.url_lbl = QLabel('URL', self.frame)
        self.url_entry = KLineEdit('', self.frame)
        self.grid.addWidget(self.url_lbl, 0, 0)
        self.grid.addWidget(self.url_entry, 1, 0)
        self.setMainWidget(self.frame)
        self.connect(self, SIGNAL('okClicked()'), self.import_game)
        self.handler = AbandonGamesHandler(self.app)

    def _makeinfo(self, base, parser):
        text = 'Title: %s\n' % parser.title
        if parser.smallinfo:
            text += 'Small Information'
            for k,v in parser.smallinfo.items():
                text += '%s: %s\n' % ( k.capitalize(), v)
        #text += str(parser.smallinfo) + '\n'
        dlurl = base + parser.download_link
        text += 'download page: %s\n' % dlurl
        text += 'direct link: %s\n' % parser.real_download_link
        if parser.files:
            text += 'Files:\n'
            text += '======\n'
            for f in parser.files:
                text += '%s%s\n' % (base, f)
        return text
        
    def import_game(self):
        url = str(self.url_entry.text())
        print url
        #KMessageBox.information(self, "import_game is still not implemented")
        
        #self.handler.get_game_data(url)
        self.handler.handle_url(url)
        #self.handler.parser.feed(file('dunetest.html').read())
        win = AbandoniaInfoWindow(self)
        win.show()
class BaseConfigOptionWidget(BaseConfigWidget):
    def __init__(self, parent, labeltext, optclass,
                 name='BaseConfigOptionWidget'):
        BaseConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 2
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'BaseConfigOptionWidgetLayout')
        self.label = QLabel(labeltext, self)
        self.grid.addWidget(self.label, 0, 0)
        self.mainwidget = optclass(self)
        self.grid.addWidget(self.mainwidget, 1, 0)

    def get_config_option(self):
        raise NotImplementedError, 'get_config_option needs to be defined in subclass'

    def set_config_option(self, option):
        raise NotImplementedError, 'set_config_option needs to be defined in subclass'
class BaseGuestPictureFrame(QFrame):
    def __init__(self, parent, name='BaseGuestPictureFrame'):
        QFrame.__init__(self, parent, name)
        margin = 0
        space = 1
        self.grid = QGridLayout(self, 2, 2, margin, space)
        self.picture_lbl = QLabel('Picture', self)
        self.picture_url = KLineEdit('', self)
        self.picture_btn = KPushButton(KStdGuiItem.Open(),
                                       'Browse for picture', self)

        self.grid.addMultiCellWidget(self.picture_lbl, 0, 0, 0, 1)
        self.grid.addWidget(self.picture_url, 0, 1)
        self.grid.addWidget(self.picture_btn, 1, 1)
        
    def get_data(self):
        url = str(self.appearance_url.text())
        return dict(url=url)

    def set_data(self, data):
        self.appearance_url.setText(data['url'])
class BaseGuestWorksFrame(QFrame):
    def __init__(self, parent, name='BaseGuestWorksFrame'):
        QFrame.__init__(self, parent, name)
        self.works_entries = []
        margin = 0
        space = 1
        self.grid = QGridLayout(self, 2, 6, margin, space)
        self.works_lbl = QLabel('Works', self)
        self.grid.addMultiCellWidget(self.works_lbl, 0, 0, 0, 4)
        self.add_works_btn = KPushButton('+', self, 'add_works_button')
        self.add_works_btn.connect(self.add_works_btn,
                                   SIGNAL('clicked()'),
                                   self.add_works_entries)
        self.grid.addWidget(self.add_works_btn, 0, 5)
        
    def add_works_entries(self):
        frame = BaseWorksEntryFrame(self)
        row = len(self.works_entries) + 1
        self.grid.addMultiCellWidget(frame, row, row, 0, -1)
        self.works_entries.append(frame)
        frame.show()
Exemple #17
0
    def __init__(self):

        QWidget.__init__(self)

        self.textBrowser = QTextBrowser(self)
        self.textBrowser.setTextFormat(QTextBrowser.LogText)
        self.lineEdit = QLineEdit(self)
        self.startButton = QPushButton(self.tr("Start"), self)
        self.stopButton = QPushButton(self.tr("Stop"), self)
        self.stopButton.setEnabled(False)

        self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.startCommand)
        self.connect(self.startButton, SIGNAL("clicked()"), self.startCommand)
        self.connect(self.stopButton, SIGNAL("clicked()"), self.stopCommand)
        layout = QGridLayout(self, 2, 3)
        layout.setSpacing(8)
        layout.addMultiCellWidget(self.textBrowser, 0, 0, 0, 2)
        layout.addWidget(self.lineEdit, 1, 0)
        layout.addWidget(self.startButton, 1, 1)
        layout.addWidget(self.stopButton, 1, 2)



        self.process = QProcess()
        self.connect(self.process, SIGNAL("readyReadStdout()"), self.readOutput)
        self.connect(self.process, SIGNAL("readyReadStderr()"), self.readErrors)
        self.connect(self.process, SIGNAL("processExited()"), self.resetButtons)
Exemple #18
0
class EditableRecordFrame(QFrame):
    def __init__(self, parent, fields, text=None, name='EditableRecordFrame'):
        QFrame.__init__(self, parent, name)
        numrows = len(fields) + 2
        numcols = 2
        self.grid = QGridLayout(self, numrows, numcols, 1, -1, name)
        self.fields = fields
        self.entries = {}
        self._setupfields()
        self.grid.setSpacing(7)
        self.grid.setMargin(10)
        self.text_label = QLabel(text, self)
        self.grid.addMultiCellWidget(self.text_label, 0, 0, 0, 1)

    def _setupfields(self):
        numfields = len(self.fields)
        for fnum in range(numfields):
            fname = self.fields[fnum]
            entry = KLineEdit('', self)
            self.entries[fname] = entry
            self.grid.addWidget(entry, fnum + 1, 1)
            label = QLabel(entry, fname, self, fname)
            self.grid.addWidget(label, fnum + 1, 0)
        self.insButton = KPushButton('insert/new', self)
        self.updButton = KPushButton('update', self)
        self.grid.addWidget(self.insButton, numfields, 0)
        self.grid.addWidget(self.updButton, numfields, 1)

    def get_data(self):
        data = {}
        for field in self.entries:
            data[field] = str(self.entries[field].text())
        return data
Exemple #19
0
class EditableRecordFrame(QFrame):
    def __init__(self, parent, fields, text=None, name='EditableRecordFrame'):
        QFrame.__init__(self, parent, name)
        numrows = len(fields) +2
        numcols = 2
        self.grid = QGridLayout(self, numrows, numcols, 1, -1, name)
        self.fields = fields
        self.entries = {}
        self._setupfields()
        self.grid.setSpacing(7)
        self.grid.setMargin(10)
        self.text_label = QLabel(text, self)
        self.grid.addMultiCellWidget(self.text_label, 0, 0, 0, 1)
        
    def _setupfields(self):
        numfields = len(self.fields)
        for fnum in range(numfields):
            fname = self.fields[fnum]
            entry = KLineEdit('', self)
            self.entries[fname] = entry
            self.grid.addWidget(entry, fnum + 1, 1)
            label = QLabel(entry, fname, self, fname)
            self.grid.addWidget(label, fnum + 1, 0)
        self.insButton = KPushButton('insert/new', self)
        self.updButton = KPushButton('update', self)
        self.grid.addWidget(self.insButton, numfields, 0)
        self.grid.addWidget(self.updButton, numfields, 1)

    def get_data(self):
        data = {}
        for field in self.entries:
            data[field] = str(self.entries[field].text())
        return data
class SoundBlasterOPLOptions(QWidget):
    def __init__(self, parent, name="SoundBlasterHardwareOptions"):
        QWidget.__init__(self, parent, name)
        numrows = 2
        numcols = 1
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols, margin, space, "SoundBlasterHardwareOptionsLayout")
        self._default_oplmodes = ["auto", "cms", "opl2", "dualopl2", "opl3"]
        self.oplmode_box = ConfigComboBoxWidget(self, "OPL mode", self._default_oplmodes)
        self.grid.addWidget(self.oplmode_box, 0, 0)
        self.oplrate_box = SampleRateOption(self, "OPL sample rate")
        self.grid.addWidget(self.oplrate_box, 1, 0)

    def get_config_options(self):
        opts = {}
        opts["oplmode"] = self.oplmode_box.get_config_option()
        opts["oplrate"] = self.oplrate_box.get_config_option()
        return opts

    def set_config_options(self, opts):
        self.oplmode_box.set_config_option(opts["oplmode"])
        self.oplrate_box.set_config_option(opts["oplrate"])
Exemple #21
0
class QGridButtonGroup(QButtonGroup):
    """Reimplementación de QButtonGroup que organiza los botones de forma que ocupen lo menos posible
        Actualmente solo añade un QGridLayout de 2 columnas
    """
    def __init__(self, parent):
        QButtonGroup.__init__(self, parent, "SeleccionMultiple")
        self.setGeometry(QRect(110, 80, 170, 121))
        self.setColumnLayout(0, Qt.Vertical)
        self.layout().setSpacing(6)
        self.layout().setMargin(11)
        self.layout = QGridLayout(self.layout(), 2)
        self.__row = 0
        self.__col = 0

    def insert(self, boton):
        """Añade un boton. Redefine la clase base"""
        QButtonGroup.insert(self, boton)
        self.layout.addWidget(boton, self.__row, self.__col)
        if self.__col == 0:
            self.__col = 1
        else:
            self.__row += 1
            self.__col = 0
class WinSizeEntryWidget(QWidget):
    def __init__(self, parent, name='WinSizeEntryWidget'):
        QWidget.__init__(self, parent, name)
        numrows = 2
        numcols = 2
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'WinSizeEntryWidgetLayout')
        self.w_label = QLabel('width', self)
        self.grid.addWidget(self.w_label, 0, 0)
        # should be using KIntSpinBox instead of text entry
        self.w_entry = KLineEdit(self)
        self.grid.addWidget(self.w_entry, 1, 0)
        self.h_label = QLabel('height', self)
        self.grid.addWidget(self.h_label, 0, 1)
        # should be using KIntSpinBox instead of text entry
        self.h_entry = KLineEdit(self)
        self.grid.addWidget(self.h_entry, 1, 1)
class ArchivePathsPage(BaseConfigWidget):
    def __init__(self, parent, name='ArchivePathsPage'):
        BaseConfigWidget.__init__(self, parent, name=name)
        numrows = 2
        numcols = 1
        margin = 5
        space = 7
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'ArchivePathsPageLayout')
        lbl = QLabel(archive_paths_lbl, self)
        lbl.setFrameStyle(lbl.Panel + lbl.Sunken)
        #lbl.setFrameStyle(lbl.Raised)
        self.grid.addWidget(lbl, 0, 0)
        self.installed_entry = ConfigKURLSelectWidget(self, 'Path to "install" archives',
                                                      filetype='dir')
        self.tooltips.add(self.installed_entry,
                          "This is the path to the archives of fresh installs")
        self.grid.addWidget(self.installed_entry, 1, 0)
        self.extras_entry = ConfigKURLSelectWidget(self, 'Path to "extras" archives',
                                                   filetype='dir')
        self.grid.addWidget(self.extras_entry, 2, 0)

    def set_config(self, configobj):
        self.mainconfig = configobj
        # some assignments to help with typing
        fm = 'filemanagement'
        cfg = self.mainconfig
        installed = cfg.get(fm, 'installed_archives_path')
        self.installed_entry.set_config_option(installed)
        extras = cfg.get(fm, 'extras_archives_path')
        self.extras_entry.set_config_option(extras)

    def get_config(self):
        fm = 'filemanagement'
        cfg = self.localconfig
        installed = self.installed_entry.get_config_option()
        cfg.set(fm, 'installed_archives_path', installed)
        extras = self.extras_entry.get_config_option()
        cfg.set(fm, 'extras_archives_path', extras)
        return cfg
Exemple #24
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 #25
0
    def __init__(self, repositoryManager):
        """ Constructor. """

        # Init GUI
        AdminWindow.__init__(self)

        # set icon in window-title:
        self.setIcon(QPixmap.fromMimeSource("DF_Logo_24x24.png"))
        iconSet = QIconSet(QPixmap.fromMimeSource("dataType16.png"))
        self.dataNavigator.setTabIconSet(self.dataTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("relationType16.png"))
        self.dataNavigator.setTabIconSet(self.relationTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("dataStore16.png"))
        self.dataNavigator.setTabIconSet(self.dataStores, iconSet)

        logger_handler.installGuiLoggingHandler(self.__logger, self.logList)

        self.myStatusBar = self.statusBar()
        self.statusLabel1 = QLabel("DataFinder", self.myStatusBar)
        self.statusLabel2 = QLabel("OK", self.myStatusBar)

        self.myStatusBar.addWidget(self.statusLabel1, 80)
        self.myStatusBar.addWidget(self.statusLabel2, 20)

        self.statusLabel1.show()
        self.statusLabel2.show()
        self.myStatusBar.show()

        # prepare "About"-dialog:
        self.dfAboutDialog = about_dialog.AboutDialog()
        self.dfAboutDialog.setPixmap(
            QPixmap.fromMimeSource("about_datafinder_admin.png"))

        # Login-dialog:
        self.dfLoginDialog = login_dialog.LoginDialog(
            repositoryManager.preferences, parent=self, showurl=True)

        # IconView:
        propertyPanelLayout = QGridLayout(self.propertyPanel, 1, 1, 2, 6,
                                          "propertyPanelLayout")

        self.iconView = canvas_view.CanvasView(self.propertyPanel, self,
                                               "iconView", 0)
        propertyPanelLayout.addWidget(self.iconView, 0, 0)

        self.iconViewCanvas = self.iconView.canvas()

        self.connect(self.dfLoginDialog.okPushButton,
                     PYSIGNAL("updateWebdavServerView"),
                     self.updateWebdavServerSlot)
        self.connect(self.dataTypeBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"),
                     self.__addDataTypeIconSlot)
        self.connect(self.relationTypeBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"),
                     self.__addRelationTypeIconSlot)
        self.connect(self.dataStoreBrowser, SIGNAL("clicked(QListViewItem*)"),
                     self.iconView.updateCanvasView)
        self.connect(self.dataStoreBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"), self.editSlot)

        # Init model
        self._repositoryManager = repositoryManager
        self.repositoryConfiguration = None
        self._preferences = self._repositoryManager.preferences
        self._lastUploadDirectory = os.path.expanduser("~")

        self._dataTypes = list()
        self._relationTypes = list()
        self._dataStores = list()

        self.__setConnectionState(False)
Exemple #26
0
 def setupUi(self):
     """create all other widgets
     we could make the scene view the central widget but I did
     not figure out how to correctly draw the background with
     QGraphicsView/QGraphicsScene.
     QGraphicsView.drawBackground always wants a pixmap
     for a huge rect like 4000x3000 where my screen only has
     1920x1200"""
     # pylint: disable=too-many-statements
     self.setObjectName("MainWindow")
     centralWidget = QWidget()
     self.centralView = FittingView()
     layout = QGridLayout(centralWidget)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(self.centralView)
     self.setCentralWidget(centralWidget)
     self.centralView.setFocusPolicy(Qt.StrongFocus)
     self.background = None  # just for pylint
     self.windTileset = Tileset(Internal.Preferences.windTilesetName)
     self.adjustMainView()
     self.actionScoreGame = self.kajonggAction("scoreGame", "draw-freehand",
                                               self.scoringScene, Qt.Key_C)
     self.actionPlayGame = self.kajonggAction("play", "arrow-right",
                                              self.playGame, Qt.Key_N)
     self.actionAbortGame = self.kajonggAction("abort", "dialog-close",
                                               self.abortAction, Qt.Key_W)
     self.actionAbortGame.setEnabled(False)
     self.actionQuit = self.kajonggAction("quit", "application-exit",
                                          self.close, Qt.Key_Q)
     self.actionPlayers = self.kajonggAction("players", "im-user",
                                             self.slotPlayers)
     self.actionRulesets = self.kajonggAction("rulesets",
                                              "games-kajongg-law",
                                              self.slotRulesets)
     self.actionChat = self._kajonggToggleAction("chat",
                                                 "call-start",
                                                 shortcut=Qt.Key_H,
                                                 actionData=ChatWindow)
     self.actionChat.setEnabled(False)
     self.actionAngle = self.kajonggAction("angle", "object-rotate-left",
                                           self.changeAngle, Qt.Key_G)
     self.actionAngle.setEnabled(False)
     self.actionScoreTable = self._kajonggToggleAction(
         "scoreTable",
         "format-list-ordered",
         Qt.Key_T,
         actionData=ScoreTable)
     self.actionScoreTable.setEnabled(False)
     self.actionExplain = self._kajonggToggleAction(
         "explain",
         "applications-education",
         Qt.Key_E,
         actionData=ExplainView)
     self.actionExplain.setEnabled(False)
     self.actionFullscreen = self._kajonggToggleAction("fullscreen",
                                                       "view-fullscreen",
                                                       shortcut=Qt.Key_F +
                                                       Qt.ShiftModifier)
     self.actionFullscreen.toggled.connect(self.fullScreen)
     self.actionAutoPlay = self.kajonggAction("demoMode",
                                              "arrow-right-double", None,
                                              Qt.Key_D)
     self.actionAutoPlay.setCheckable(True)
     self.actionAutoPlay.setEnabled(True)
     self.actionAutoPlay.toggled.connect(self._toggleDemoMode)
     self.actionAutoPlay.setChecked(Internal.autoPlay)
     QMetaObject.connectSlotsByName(self)
class BaseGuestDataFrame(QFrame):
    def __init__(self, parent, name='BaseGuestDataFrame'):
        QFrame.__init__(self, parent, name)
        self.guestid = None
        numrows = 2
        numcols = 2
        margin = 0
        space = 1
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'BaseGuestDataLayout')
        self.app = get_application_pointer()


        self.fname_lbl = QLabel('First Name', self)
        self.fname_entry = KLineEdit('', self)

        self.grid.addWidget(self.fname_lbl, 0, 0)
        self.grid.addWidget(self.fname_entry, 1, 0)

        self.lname_lbl = QLabel('Last Name', self)
        self.lname_entry = KLineEdit('', self)

        self.grid.addWidget(self.lname_lbl, 0, 1)
        self.grid.addWidget(self.lname_entry, 1, 1)

        self.title_lbl = QLabel('Title', self)
        self.title_entry = KLineEdit('', self)

        self.grid.addMultiCellWidget(self.title_lbl, 2, 2, 0, 1)
        self.grid.addMultiCellWidget(self.title_entry, 3, 3, 0, 1)

        self.desc_lbl = QLabel('Description', self)
        self.desc_entry = KTextEdit(self, 'description_entry')

        self.grid.addMultiCellWidget(self.desc_lbl, 4, 4, 0, 1)
        self.grid.addMultiCellWidget(self.desc_entry, 5, 7, 0, 1)

        #self.works_frame = BaseGuestWorksFrame(self)
        #self.grid.addMultiCellWidget(self.works_frame, 8, 8, 0, 1)
        
        
    def get_guest_data(self):
        fname = str(self.fname_entry.text())
        lname = str(self.lname_entry.text())
        title = str(self.title_entry.text())
        desc = str(self.desc_entry.text())
        # take the newlines out for now
        # until the sqlgen is fixed to work with sqlite
        desc = desc.replace('\n', ' ')
        data = dict(firstname=fname, lastname=lname,
                    description=desc, title=title)
        if self.guestid is not None:
            data['guestid'] = self.guestid
        return data

    def set_guest_data(self, data):
        self.guestid = data['guestid']
        self.fname_entry.setText(data['firstname'])
        self.lname_entry.setText(data['lastname'])
        if data['title']:
            self.title_entry.setText(data['title'])
        if data['description']:
            desc = data['description']
            desc = self.app.guests.unescape_text(desc)
            self.desc_entry.setText(desc)
Exemple #28
0
 def __init__(self, game):
     """selection for this player, tiles are the still available tiles"""
     QDialog.__init__(self, None)
     decorateWindow(self, i18n("Penalty"))
     self.game = game
     grid = QGridLayout(self)
     lblOffense = QLabel(i18n('Offense:'))
     crimes = list([
         x for x in game.ruleset.penaltyRules
         if not ('absolute' in x.options and game.winner)
     ])
     self.cbCrime = ListComboBox(crimes)
     lblOffense.setBuddy(self.cbCrime)
     grid.addWidget(lblOffense, 0, 0)
     grid.addWidget(self.cbCrime, 0, 1, 1, 4)
     lblPenalty = QLabel(i18n('Total Penalty'))
     self.spPenalty = PenaltyBox(2)
     self.spPenalty.setRange(0, 9999)
     lblPenalty.setBuddy(self.spPenalty)
     self.lblUnits = QLabel(i18n('points'))
     grid.addWidget(lblPenalty, 1, 0)
     grid.addWidget(self.spPenalty, 1, 1)
     grid.addWidget(self.lblUnits, 1, 2)
     self.payers = []
     self.payees = []
     # a penalty can never involve the winner, neither as payer nor as payee
     for idx in range(3):
         self.payers.append(ListComboBox(game.losers()))
         self.payees.append(ListComboBox(game.losers()))
     for idx, payer in enumerate(self.payers):
         grid.addWidget(payer, 3 + idx, 0)
         payer.lblPayment = QLabel()
         grid.addWidget(payer.lblPayment, 3 + idx, 1)
     for idx, payee in enumerate(self.payees):
         grid.addWidget(payee, 3 + idx, 3)
         payee.lblPayment = QLabel()
         grid.addWidget(payee.lblPayment, 3 + idx, 4)
     grid.addWidget(QLabel(''), 6, 0)
     grid.setRowStretch(6, 10)
     for player in self.payers + self.payees:
         player.currentIndexChanged.connect(self.playerChanged)
     self.spPenalty.valueChanged.connect(self.penaltyChanged)
     self.cbCrime.currentIndexChanged.connect(self.crimeChanged)
     buttonBox = KDialogButtonBox(self)
     grid.addWidget(buttonBox, 7, 0, 1, 5)
     buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
     buttonBox.rejected.connect(self.reject)
     self.btnExecute = buttonBox.addButton(i18n("&Execute"),
                                           QDialogButtonBox.AcceptRole)
     self.btnExecute.clicked.connect(self.accept)
     self.crimeChanged()
     StateSaver(self)
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 #30
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()
class BaseGameDataFrame(QFrame):
    def __init__(self, parent, name='BaseGameDataFrame'):
        QFrame.__init__(self, parent, name)
        # there will be more than two rows, but we'll start with two
        numrows = 2
        # there should onlty be two columns
        numcols = 2
        margin = 0
        space = 1
        # add a grid layout to the frame
        self.grid = QGridLayout(self, numrows, numcols,
                                margin, space, 'BaseGameDataLayout')
        # make a couple of lists to point to the weblink entries
        # order is important in these lists
        self.weblink_site_entries = []
        self.weblink_url_entries = []
        # I may use dict[site] = (site_entry, url_entry)
        # I haven't decided yet.  It could always be formed by zipping the 2 lists above.
        self.weblink_dict = {}
        # setup app pointer
        self.app = KApplication.kApplication()
        self.myconfig = self.app.myconfig
        # setup dialog pointers
        self.select_launch_command_dlg = None
        # Setup widgets
        # setup name widgets
        self.name_lbl = QLabel('<b>Name</b>', self)
        self.name_entry = KLineEdit('', self)
        # add name widgets to grid
        self.grid.addWidget(self.name_lbl, 0, 0)
        self.grid.addWidget(self.name_entry, 1, 0)
        # setup fullname widgets
        self.fullname_lbl = QLabel('<b>Full name</b>', self)
        self.fullname_entry = KLineEdit('', self)
        # add fullname widgets
        self.grid.addWidget(self.fullname_lbl, 2, 0)
        self.grid.addWidget(self.fullname_entry, 3, 0)
        # setup description widgets
        self.desc_lbl = QLabel('<b>Description</b>', self)
        self.desc_entry = KTextEdit(self, 'description_entry')
        # set plain text format for description entry
        # we do this in case there are html tags in the entry
        self.desc_entry.setTextFormat(self.PlainText)
        # add description widgets
        self.grid.addWidget(self.desc_lbl, 4, 0)
        #self.addWidget(self.desc_entry, 5, 0)
        # add the description as a multirow entity
        # default from 5 to 15
        # this allows for weblinks to be added
        # (about 5)
        # without the dialog looking ugly
        # going to 15 won't force there to be that many rows
        # until more enough widgets are added
        self.grid.addMultiCellWidget(self.desc_entry, 5, 15, 0, 0)
        # setup launch command widgets
        self.launch_lbl = QLabel('<b>Launch command</b>', self)
        self.launch_entry = KLineEdit('', self)
        self.launch_dlg_button = KPushButton('...', self, 'launch_dlg_button')
        self.launch_dlg_button.connect(self.launch_dlg_button, SIGNAL('clicked()'),
                                       self.select_launch_command)
        # add launch command widgets
        self.grid.addWidget(self.launch_lbl, 0, 1)
        self.grid.addWidget(self.launch_entry, 1, 1)
        self.grid.addWidget(self.launch_dlg_button, 1, 2)
        # setup dosboxpath widgets
        self.dosboxpath_lbl = QLabel('<b>dosbox path</b>', self)
        self.dosboxpath_entry = KLineEdit('', self)
        # add dosboxpath widgets
        self.grid.addWidget(self.dosboxpath_lbl, 2, 1)
        self.grid.addWidget(self.dosboxpath_entry, 3, 1)
        # setup main weblink widgets
        self.weblinks_lbl = QLabel('<b>weblinks</b>', self)
        self.weblinks_btn = KPushButton('+', self, 'add_weblink_button')
        self.weblinks_btn.connect(self.weblinks_btn, SIGNAL('clicked()'),
                                  self.add_weblink_entries)
        # add main weblink widgets
        self.grid.addWidget(self.weblinks_lbl, 4, 1)
        self.grid.addWidget(self.weblinks_btn, 4, 2)
        
    def select_launch_command(self):
        if self.select_launch_command_dlg is None:
            file_filter = "*.exe *.bat *.com|Dos Executables\n*|All Files"
            dlg = KFileDialog(self.fullpath, file_filter,  self, 'select_launch_command_dlg', True)
            dlg.connect(dlg, SIGNAL('okClicked()'), self.launch_command_selected)
            dlg.connect(dlg, SIGNAL('cancelClicked()'), self.destroy_select_launch_command_dlg)
            dlg.connect(dlg, SIGNAL('closeClicked()'), self.destroy_select_launch_command_dlg)
            dlg.show()
            self.select_launch_command_dlg = dlg
        else:
            # we shouldn't need this with a modal dialog
            KMessageBox.error(self, opendlg_errormsg)

    def destroy_select_launch_command_dlg(self):
        self.select_launch_command_dlg = None

    def launch_command_selected(self):
        dlg = self.select_launch_command_dlg
        url = dlg.selectedURL()
        fullpath = str(url.path())
        launch_command = os.path.basename(fullpath)
        self.launch_entry.setText(launch_command)
        self.select_launch_command_dlg = None

    def add_weblink_entries(self, site='', url=''):
        #we start at row #5 column 1 for lbl column 2 for entry
        num_entries = len(self.weblink_url_entries)
        # we need to add 1 on lbl_num because the entries can be appended
        # until instantiated
        lbl_num = num_entries + 1
        site_lbl = QLabel('<b>site %d</b>' % lbl_num, self)
        site_entry = KLineEdit(site, self)
        self.weblink_site_entries.append(site_entry)
        url_lbl = QLabel('<b>url %d</b>' % lbl_num, self)
        url_entry = KLineEdit(url, self)
        self.weblink_url_entries.append(url_entry)
        if len(self.weblink_site_entries) != len(self.weblink_url_entries):
            KMessageBox.error(self, 'entries mismatch, something really bad happened.')
            import sys
            sys.exit(1)
        # we need a little math here to figure out the rows
        # for the widgets
        # num_entries should now be 1 greater than above
        num_entries = len(self.weblink_url_entries)
        site_row = 2*num_entries + 3
        url_row = 2*num_entries + 4
        # add weblink widgets to the grid
        top = self.grid.AlignTop
        self.grid.addWidget(site_entry, site_row, 1)
        self.grid.addWidget(site_lbl, site_row, 2)
        self.grid.addWidget(url_entry, url_row, 1)
        self.grid.addWidget(url_lbl, url_row, 2)
        # we have to call .show() explicitly on the widgets
        # as the rest of the widgets are already visible
        # when show was called on the dialog
        # show() automatically calls show() on all children
        for widget in [site_lbl, site_entry, url_lbl, url_entry]:
            widget.show()
Exemple #32
0
class ClientDialog(QDialog):

    """a simple popup dialog for asking the player what he wants to do"""

    def __init__(self, client, parent=None):
        QDialog.__init__(self, parent)
        decorateWindow(self, i18n('Choose'))
        self.setObjectName('ClientDialog')
        self.client = client
        self.layout = QGridLayout(self)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimumHeight(25)
        self.timer = QTimer()
        if not client.game.autoPlay:
            self.timer.timeout.connect(self.timeout)
        self.deferred = None
        self.buttons = []
        self.setWindowFlags(Qt.SubWindow | Qt.WindowStaysOnTopHint)
        self.setModal(False)
        self.btnHeight = 0
        self.answered = False
        self.move = None
        self.sorry = None

    def keyPressEvent(self, event):
        """ESC selects default answer"""
        if not self.client.game or self.client.game.autoPlay:
            return
        if event.key() in [Qt.Key_Escape, Qt.Key_Space]:
            self.selectButton()
            event.accept()
        else:
            for btn in self.buttons:
                if str(event.text()).upper() == btn.message.shortcut:
                    self.selectButton(btn)
                    event.accept()
                    return
            QDialog.keyPressEvent(self, event)

    def __declareButton(self, message):
        """define a button"""
        maySay = self.client.game.myself.sayable[message]
        if Internal.Preferences.showOnlyPossibleActions and not maySay:
            return
        btn = DlgButton(message, self)
        btn.setAutoDefault(True)
        btn.clicked.connect(self.selectedAnswer)
        self.buttons.append(btn)

    def focusTileChanged(self):
        """update icon and tooltip for the discard button"""
        if not self.client.game:
            return
        for button in self.buttons:
            button.setMeaning(self.client.game.myself.handBoard.focusTile)
        for uiTile in self.client.game.myself.handBoard.lowerHalfTiles():
            txt = []
            for button in self.buttons:
                _, _, tileTxt = button.message.toolTip(button, uiTile.tile)
                if tileTxt:
                    txt.append(tileTxt)
            uiTile.setToolTip('<br><br>'.join(txt))
        if self.client.game.activePlayer == self.client.game.myself:
            Internal.scene.handSelectorChanged(
                self.client.game.myself.handBoard)

    def checkTiles(self):
        """does the logical state match the displayed tiles?"""
        for player in self.client.game.players:
            player.handBoard.checkTiles()

    def messages(self):
        """a list of all messages returned by the declared buttons"""
        return list(x.message for x in self.buttons)

    def proposeAction(self):
        """either intelligently or first button by default. May also
        focus a proposed tile depending on the action."""
        result = self.buttons[0]
        game = self.client.game
        if game.autoPlay or Internal.Preferences.propose:
            answer, parameter = game.myself.intelligence.selectAnswer(
                self.messages())
            result = [x for x in self.buttons if x.message == answer][0]
            result.setFocus()
            if answer in [Message.Discard, Message.OriginalCall]:
                for uiTile in game.myself.handBoard.uiTiles:
                    if uiTile.tile is parameter:
                        game.myself.handBoard.focusTile = uiTile
        return result

    def askHuman(self, move, answers, deferred):
        """make buttons specified by answers visible. The first answer is default.
        The default button only appears with blue border when this dialog has
        focus but we always want it to be recognizable. Hence setBackgroundRole."""
        self.move = move
        self.deferred = deferred
        for answer in answers:
            self.__declareButton(answer)
        self.focusTileChanged()
        self.show()
        self.checkTiles()
        game = self.client.game
        myTurn = game.activePlayer == game.myself
        prefButton = self.proposeAction()
        if game.autoPlay:
            self.selectButton(prefButton)
            return
        prefButton.setFocus()

        self.progressBar.setVisible(not myTurn)
        if not myTurn:
            msecs = 50
            self.progressBar.setMinimum(0)
            self.progressBar.setMaximum(
                game.ruleset.claimTimeout * 1000 // msecs)
            self.progressBar.reset()
            self.timer.start(msecs)

    def placeInField(self):
        """place the dialog at bottom or to the right depending on space."""
        mainWindow = Internal.scene.mainWindow
        cwi = mainWindow.centralWidget()
        view = mainWindow.centralView
        geometry = self.geometry()
        if not self.btnHeight:
            self.btnHeight = self.buttons[0].height()
        vertical = view.width() > view.height() * 1.2
        if vertical:
            height = (len(self.buttons) + 1) * self.btnHeight * 1.2
            width = (cwi.width() - cwi.height()) // 2
            geometry.setX(cwi.width() - width)
            geometry.setY(min(cwi.height() // 3, cwi.height() - height))
        else:
            handBoard = self.client.game.myself.handBoard
            if not handBoard:
                # we are in the progress of logging out
                return
            hbLeftTop = view.mapFromScene(
                handBoard.mapToScene(handBoard.rect().topLeft()))
            hbRightBottom = view.mapFromScene(
                handBoard.mapToScene(handBoard.rect().bottomRight()))
            width = hbRightBottom.x() - hbLeftTop.x()
            height = self.btnHeight
            geometry.setY(cwi.height() - height)
            geometry.setX(hbLeftTop.x())
        for idx, btn in enumerate(self.buttons + [self.progressBar]):
            self.layout.addWidget(
                btn,
                idx +
                1 if vertical else 0,
                idx +
                1 if not vertical else 0)
        idx = len(self.buttons) + 2
        spacer = QSpacerItem(
            20,
            20,
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)
        self.layout.addItem(
            spacer,
            idx if vertical else 0,
            idx if not vertical else 0)

        geometry.setWidth(width)
        geometry.setHeight(height)
        self.setGeometry(geometry)

    def showEvent(self, dummyEvent):
        """try to place the dialog such that it does not cover interesting information"""
        self.placeInField()

    def timeout(self):
        """the progressboard wants an update"""
        pBar = self.progressBar
        if isAlive(pBar):
            pBar.setValue(pBar.value() + 1)
            pBar.setVisible(True)
            if pBar.value() == pBar.maximum():
                # timeout: we always return the original default answer, not
                # the one with focus
                self.selectButton()
                pBar.setVisible(False)

    def selectButton(self, button=None):
        """select default answer. button may also be of type Message."""
        if self.answered:
            # sometimes we get this event twice
            return
        if button is None:
            button = self.focusWidget()
        if isinstance(button, Message):
            assert any(x.message == button for x in self.buttons)
            answer = button
        else:
            answer = button.message
        if not self.client.game.myself.sayable[answer]:
            self.proposeAction().setFocus() # go back to default action
            self.sorry = Sorry(i18n('You cannot say %1', answer.i18nName))
            return
        self.timer.stop()
        self.answered = True
        if self.sorry:
            self.sorry.cancel()
        self.sorry = None
        Internal.scene.clientDialog = None
        self.deferred.callback(answer)

    def selectedAnswer(self, dummyChecked):
        """the user clicked one of the buttons"""
        game = self.client.game
        if game and not game.autoPlay:
            self.selectButton(self.sender())
Exemple #33
0
class InstallerWidget(QWidget):
    def __init__(self, parent, umlmachines, name='InstallerWidget'):
        QWidget.__init__(self, parent, name)
        self.resize(600, 600)
        self.app = get_application_pointer()
        self.conn = self.app.conn
        self.umlmachines = umlmachines
        self.machine = self.umlmachines.current
        self.current_machine_process = 'start'
        self.current_profile = None
        self.current_trait = None
        self.traitlist = []
        self.curenv = CurrentEnvironment(self.conn, self.machine)
        self.curenv['current_profile'] = 'None'
        self.curenv['current_trait'] = 'None'
        self.curenv['current_machine_process'] = self.current_machine_process
        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL('timeout()'), self.update_progress)
        self.timer.startTimer(1000)
        self.grid = QGridLayout(self, 4, 1, 5, 7)
        self.main_label = QLabel(self)
        self.main_label.setText(self._msg())
        self.grid.addWidget(self.main_label, 0, 0)
        self.profile_progress_lbl = QLabel(self)
        self.grid.addWidget(self.profile_progress_lbl, 1, 0)
        self.profile_progress = KProgress(self)
        self.grid.addWidget(self.profile_progress, 2, 0)
        self.logview = LogBrowser(self, '/tmp/uml-installer.log')
        self.grid.addWidget(self.logview, 3, 0)
        #self.console_view = StdOutBrowser(self)
        #self.console_view = KTextBrowser(self)
        #self.grid.addWidget(self.console_view, 4, 0)
        self.console_text = ''

    def _msg(self):
        return 'Installing uml machine %s - %s' % (
            self.machine, self.current_machine_process)

    def update_console_text(self):
        if self.umlmachines.run_process is not None:
            stdout = self.umlmachines.run_process.stdout
            stdoutfd = stdout.fileno()
            ready = select.select([stdoutfd], [], [])
            while stdoutfd in ready[0]:
                line = stdout.readline()
                if line:
                    self.console_text += line
                ready = select.select([stdoutfd], [], [])
            stdout = self.umlmachines.run_process.stdout
            line = stdout.readline()
            if line:
                self.console_text += line
            self.console_view.setText(self.console_text)

    def update_progress(self):
        #self.update_console_text()
        process = self.curenv['current_machine_process']
        #print 'update_progress', process
        if process != self.current_machine_process:
            self.current_machine_process = process
            self.main_label.setText(self._msg())
        if self.current_profile is None:
            profile = self.curenv['current_profile']
            if profile != 'None':
                self.current_profile = profile
                print 'profile set to', profile
                traitlist = self.curenv['traitlist']
                tl = [t.strip() for t in traitlist.split(',')]
                self.traitlist = tl
                self.profile_progress.setTotalSteps(len(self.traitlist))
        else:
            trait = self.curenv['current_trait']
            if trait != 'None':
                trait_process = self.curenv['current_trait_process']
                profile = self.current_profile
                msg = 'Installing profile %s, trait %s, process %s' % (
                    profile, trait, trait_process)
                self.profile_progress_lbl.setText(msg)
                self.profile_progress.setProgress(
                    self.traitlist.index(trait) + 1)
                self.app.processEvents()
    def setupPanel(self, parentWidget):
        logging.debug('ProstateTRUSNavUltrasound.setupPanel')

        self.connectorNode = self.guideletParent.connectorNode
        self.connectorNodeConnected = False

        collapsibleButton = ctkCollapsibleButton()
        collapsibleButton.setProperty('collapsedHeight', 20)
        setButtonStyle(collapsibleButton, 2.0)
        collapsibleButton.text = "Ultrasound"
        parentWidget.addWidget(collapsibleButton)

        ultrasoundLayout = QFormLayout(collapsibleButton)
        ultrasoundLayout.setContentsMargins(12, 4, 4, 4)
        ultrasoundLayout.setSpacing(4)

        self.connectDisconnectButton = QPushButton("Connect")
        self.connectDisconnectButton.setToolTip(
            "If clicked, connection OpenIGTLink")

        hbox = QHBoxLayout()
        hbox.addWidget(self.connectDisconnectButton)
        ultrasoundLayout.addRow(hbox)

        self.setupIcons()

        self.captureIDSelector = QComboBox()
        self.captureIDSelector.setToolTip("Pick capture device ID")
        self.captureIDSelector.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Expanding)

        self.volumeReconstructorIDSelector = QComboBox()
        self.volumeReconstructorIDSelector.setToolTip(
            "Pick volume reconstructor device ID")
        self.volumeReconstructorIDSelector.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.startStopRecordingButton = QPushButton("  Start Recording")
        self.startStopRecordingButton.setCheckable(True)
        self.startStopRecordingButton.setIcon(self.recordIcon)
        self.startStopRecordingButton.setEnabled(False)
        self.startStopRecordingButton.setToolTip("If clicked, start recording")
        self.startStopRecordingButton.setSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)

        recordParametersControlsLayout = QGridLayout()

        self.filenameLabel = self.createLabel("Filename:", visible=False)
        recordParametersControlsLayout.addWidget(self.filenameLabel, 1, 0)

        # Offline Reconstruction
        self.offlineReconstructButton = QPushButton("  Offline Reconstruction")
        self.offlineReconstructButton.setCheckable(True)
        self.offlineReconstructButton.setIcon(self.recordIcon)
        self.offlineReconstructButton.setEnabled(False)
        self.offlineReconstructButton.setToolTip(
            "If clicked, reconstruct recorded volume")
        self.offlineReconstructButton.setSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)

        self.offlineVolumeToReconstructSelector = QComboBox()
        self.offlineVolumeToReconstructSelector.setEditable(True)
        self.offlineVolumeToReconstructSelector.setToolTip(
            "Pick/set volume to reconstruct")
        self.offlineVolumeToReconstructSelector.visible = False

        hbox = QHBoxLayout()
        hbox.addWidget(self.startStopRecordingButton)
        hbox.addWidget(self.offlineReconstructButton)
        ultrasoundLayout.addRow(hbox)

        # Scout scan (record and low resolution reconstruction) and live reconstruction
        # Scout scan part

        self.startStopScoutScanButton = QPushButton(
            "  Scout scan\n  Start recording")
        self.startStopScoutScanButton.setCheckable(True)
        self.startStopScoutScanButton.setIcon(self.recordIcon)
        self.startStopScoutScanButton.setToolTip("If clicked, start recording")
        self.startStopScoutScanButton.setEnabled(False)
        self.startStopScoutScanButton.setSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)

        self.startStopLiveReconstructionButton = QPushButton(
            "  Start live reconstruction")
        self.startStopLiveReconstructionButton.setCheckable(True)
        self.startStopLiveReconstructionButton.setIcon(self.recordIcon)
        self.startStopLiveReconstructionButton.setToolTip(
            "If clicked, start live reconstruction")
        self.startStopLiveReconstructionButton.setEnabled(False)
        self.startStopLiveReconstructionButton.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.displayRoiButton = QToolButton()
        self.displayRoiButton.setCheckable(True)
        self.displayRoiButton.setIcon(self.visibleOffIcon)
        self.displayRoiButton.setToolTip("If clicked, display ROI")

        hbox = QHBoxLayout()
        hbox.addWidget(self.startStopScoutScanButton)
        hbox.addWidget(self.startStopLiveReconstructionButton)
        # hbox.addWidget(self.displayRoiButton)
        ultrasoundLayout.addRow(hbox)

        self.snapshotTimer = QTimer()
        self.snapshotTimer.setSingleShot(True)

        self.onParameterSetSelected()

        return collapsibleButton
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
Exemple #36
0
 def __init__(self, game):
     """selection for this player, tiles are the still available tiles"""
     QDialog.__init__(self, None)
     decorateWindow(self, m18n("Penalty"))
     self.game = game
     grid = QGridLayout(self)
     lblOffense = QLabel(m18n("Offense:"))
     crimes = list([x for x in game.ruleset.penaltyRules if not ("absolute" in x.options and game.winner)])
     self.cbCrime = ListComboBox(crimes)
     lblOffense.setBuddy(self.cbCrime)
     grid.addWidget(lblOffense, 0, 0)
     grid.addWidget(self.cbCrime, 0, 1, 1, 4)
     lblPenalty = QLabel(m18n("Total Penalty"))
     self.spPenalty = PenaltyBox(2)
     self.spPenalty.setRange(0, 9999)
     lblPenalty.setBuddy(self.spPenalty)
     self.lblUnits = QLabel(m18n("points"))
     grid.addWidget(lblPenalty, 1, 0)
     grid.addWidget(self.spPenalty, 1, 1)
     grid.addWidget(self.lblUnits, 1, 2)
     self.payers = []
     self.payees = []
     # a penalty can never involve the winner, neither as payer nor as payee
     for idx in range(3):
         self.payers.append(ListComboBox(game.losers()))
         self.payees.append(ListComboBox(game.losers()))
     for idx, payer in enumerate(self.payers):
         grid.addWidget(payer, 3 + idx, 0)
         payer.lblPayment = QLabel()
         grid.addWidget(payer.lblPayment, 3 + idx, 1)
     for idx, payee in enumerate(self.payees):
         grid.addWidget(payee, 3 + idx, 3)
         payee.lblPayment = QLabel()
         grid.addWidget(payee.lblPayment, 3 + idx, 4)
     grid.addWidget(QLabel(""), 6, 0)
     grid.setRowStretch(6, 10)
     for player in self.payers + self.payees:
         player.currentIndexChanged.connect(self.playerChanged)
     self.spPenalty.valueChanged.connect(self.penaltyChanged)
     self.cbCrime.currentIndexChanged.connect(self.crimeChanged)
     buttonBox = KDialogButtonBox(self)
     grid.addWidget(buttonBox, 7, 0, 1, 5)
     buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
     buttonBox.rejected.connect(self.reject)
     if not usingKDE:
         self.btnExecute = buttonBox.addButton(m18n("&Execute"), QDialogButtonBox.AcceptRole)
         self.btnExecute.clicked.connect(self.accept)
     else:
         self.btnExecute = buttonBox.addButton(m18n("&Execute"), QDialogButtonBox.AcceptRole, self, SLOT("accept()"))
     self.crimeChanged()
     StateSaver(self)
Exemple #37
0
 def setupUi(self):
     """create all other widgets
     we could make the scene view the central widget but I did
     not figure out how to correctly draw the background with
     QGraphicsView/QGraphicsScene.
     QGraphicsView.drawBackground always wants a pixmap
     for a huge rect like 4000x3000 where my screen only has
     1920x1200"""
     # pylint: disable=too-many-statements
     self.setObjectName("MainWindow")
     centralWidget = QWidget()
     self.centralView = FittingView()
     layout = QGridLayout(centralWidget)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(self.centralView)
     self.setCentralWidget(centralWidget)
     self.centralView.setFocusPolicy(Qt.StrongFocus)
     self.background = None  # just for pylint
     self.windTileset = Tileset(Internal.Preferences.windTilesetName)
     self.adjustView()
     self.actionScoreGame = self.kajonggAction(
         "scoreGame",
         "draw-freehand",
         self.scoringScene,
         Qt.Key_C)
     self.actionPlayGame = self.kajonggAction(
         "play",
         "arrow-right",
         self.playingScene,
         Qt.Key_N)
     self.actionAbortGame = self.kajonggAction(
         "abort",
         "dialog-close",
         self.abortAction,
         Qt.Key_W)
     self.actionAbortGame.setEnabled(False)
     self.actionQuit = self.kajonggAction(
         "quit",
         "application-exit",
         self.close,
         Qt.Key_Q)
     self.actionPlayers = self.kajonggAction(
         "players", "im-user", self.slotPlayers)
     self.actionRulesets = self.kajonggAction(
         "rulesets",
         "games-kajongg-law",
         self.slotRulesets)
     self.actionChat = self._kajonggToggleAction("chat", "call-start",
                                                 shortcut=Qt.Key_H, actionData=ChatWindow)
     self.actionChat.setEnabled(False)
     self.actionAngle = self.kajonggAction(
         "angle",
         "object-rotate-left",
         self.changeAngle,
         Qt.Key_G)
     self.actionAngle.setEnabled(False)
     self.actionFullscreen = KToggleFullScreenAction(
         self.actionCollection())
     self.actionFullscreen.setShortcut(Qt.CTRL + Qt.Key_F)
     self.actionFullscreen.setShortcutContext(Qt.ApplicationShortcut)
     self.actionFullscreen.setWindow(self)
     self.actionCollection().addAction("fullscreen", self.actionFullscreen)
     self.actionFullscreen.toggled.connect(self.fullScreen)
     self.actionScoreTable = self._kajonggToggleAction(
         "scoreTable", "format-list-ordered",
         Qt.Key_T, actionData=ScoreTable)
     self.actionScoreTable.setEnabled(False)
     self.actionExplain = self._kajonggToggleAction(
         "explain", "applications-education",
         Qt.Key_E, actionData=ExplainView)
     self.actionExplain.setEnabled(False)
     self.actionAutoPlay = self.kajonggAction(
         "demoMode",
         "arrow-right-double",
         None,
         Qt.Key_D)
     self.actionAutoPlay.setCheckable(True)
     self.actionAutoPlay.setEnabled(True)
     self.actionAutoPlay.toggled.connect(self._toggleDemoMode)
     self.actionAutoPlay.setChecked(Internal.autoPlay)
     QMetaObject.connectSlotsByName(self)
class qSlicerMultiVolumeExplorerSimplifiedModuleWidget:

  def __init__(self, parent=None):
    logging.debug("qSlicerMultiVolumeExplorerSimplifiedModuleWidget:init() called")
    if not parent or not hasattr(parent, "layout"):
      self.parent = slicer.qMRMLWidget()
      self.parent.setLayout(QVBoxLayout())
    else:
      self.parent = parent

    self.layout = self.parent.layout()

    self._bgMultiVolumeNode = None
    self._fgMultiVolumeNode = None

    self.styleObserverTags = []
    self.sliceWidgetsPerStyle = {}

    self.chartPopupWindow = None
    self.chartPopupSize = QSize(600, 300)
    self.chartPopupPosition = QPoint(0,0)

  def hide(self):
    self.widget.hide()

  def show(self):
    self.widget.show()

  def setup(self):
    self.widget = QWidget()
    layout = QGridLayout()
    self.widget.setLayout(layout)
    self.layout.addWidget(self.widget)
    self.widget.show()
    self.layout = layout

    self.setupInputFrame()
    self.setupFrameControlFrame()
    self.setupAdditionalFrames()
    self.setupPlottingFrame()

    self.setFramesEnabled(False)

    self.timer = QTimer()
    self.timer.setInterval(50)

    self.setupConnections()

    # initialize slice observers (from DataProbe.py)
    # keep list of pairs: [observee,tag] so they can be removed easily
    self.styleObserverTags = []
    # keep a map of interactor styles to sliceWidgets so we can easily get sliceLogic
    self.sliceWidgetsPerStyle = {}
    self.refreshObservers()

  def setupInputFrame(self, parent=None):
    if not parent:
      parent = self.layout
    self.bgMultiVolumeSelector = slicer.qMRMLNodeComboBox()
    self.bgMultiVolumeSelector.nodeTypes = ['vtkMRMLMultiVolumeNode']
    self.bgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
    self.bgMultiVolumeSelector.addEnabled = 0
    self._bgMultiVolumeSelectorLabel = QLabel('Input multivolume')
    inputFrameWidget = QWidget()
    self.inputFrameLayout = QFormLayout()
    inputFrameWidget.setLayout(self.inputFrameLayout)
    self.inputFrameLayout.addRow(self._bgMultiVolumeSelectorLabel, self.bgMultiVolumeSelector)
    parent.addWidget(inputFrameWidget)

  def setupFrameControlFrame(self):
    # TODO: initialize the slider based on the contents of the labels array
    self.frameSlider = ctk.ctkSliderWidget()
    self.frameLabel = QLabel('Current frame number')
    self.playButton = QPushButton('Play')
    self.playButton.toolTip = 'Iterate over multivolume frames'
    self.playButton.checkable = True
    frameControlHBox = QHBoxLayout()
    frameControlHBox.addWidget(self.frameLabel)
    frameControlHBox.addWidget(self.frameSlider)
    frameControlHBox.addWidget(self.playButton)
    self.inputFrameLayout.addRow(frameControlHBox)

  def setupAdditionalFrames(self):
    pass

  def setupPlottingFrame(self, parent=None):
    if not parent:
      parent = self.layout
    self.plottingFrameWidget = QWidget()
    self.plottingFrameLayout = QGridLayout()
    self.plottingFrameWidget.setLayout(self.plottingFrameLayout)
    self._multiVolumeIntensityChart = MultiVolumeIntensityChartView()
    self.popupChartButton = QPushButton("Undock chart")
    self.popupChartButton.setCheckable(True)
    self.plottingFrameLayout.addWidget(self._multiVolumeIntensityChart.chartView)
    self.plottingFrameLayout.addWidget(self.popupChartButton)
    parent.addWidget(self.plottingFrameWidget)

  def setupConnections(self):
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)', self.onVCMRMLSceneChanged)
    self.bgMultiVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onBackgroundInputChanged)
    self.playButton.connect('toggled(bool)', self.onPlayButtonToggled)
    self.frameSlider.connect('valueChanged(double)', self.onSliderChanged)
    self.timer.connect('timeout()', self.goToNext)
    self.popupChartButton.connect('toggled(bool)', self.onDockChartViewToggled)

  def onDockChartViewToggled(self, checked):
    if checked:
      self.chartPopupWindow = QDialog()
      self.chartPopupWindow.setWindowFlags(PythonQt.QtCore.Qt.WindowStaysOnTopHint)
      layout = QGridLayout()
      self.chartPopupWindow.setLayout(layout)
      layout.addWidget(self._multiVolumeIntensityChart.chartView)
      layout.addWidget(self.popupChartButton)
      self.chartPopupWindow.finished.connect(self.dockChartView)
      self.chartPopupWindow.resize(self.chartPopupSize)
      self.chartPopupWindow.move(self.chartPopupPosition)
      self.chartPopupWindow.show()
      self.popupChartButton.setText("Dock chart")
      self._multiVolumeIntensityChart.chartView.show()
    else:
      self.chartPopupWindow.close()

  def dockChartView(self):
    self.chartPopupSize = self.chartPopupWindow.size
    self.chartPopupPosition = self.chartPopupWindow.pos
    self.plottingFrameLayout.addWidget(self._multiVolumeIntensityChart.chartView)
    self.plottingFrameLayout.addWidget(self.popupChartButton)
    self.popupChartButton.setText("Undock chart")
    self.popupChartButton.disconnect('toggled(bool)', self.onDockChartViewToggled)
    self.popupChartButton.checked = False
    self.popupChartButton.connect('toggled(bool)', self.onDockChartViewToggled)

  def onSliderChanged(self, frameId):
    if self._bgMultiVolumeNode is None:
      return
    newValue = int(frameId)
    self.setCurrentFrameNumber(newValue)

  def onVCMRMLSceneChanged(self, mrmlScene):
    logging.debug("qSlicerMultiVolumeExplorerSimplifiedModuleWidget:onVCMRMLSceneChanged")
    self.bgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
    self.onBackgroundInputChanged()

  def refreshGUIForNewBackgroundImage(self):
    self._multiVolumeIntensityChart.reset()
    self.setFramesEnabled(True)
    if self._fgMultiVolumeNode and self._bgMultiVolumeNode:
      Helper.SetBgFgVolumes(self._bgMultiVolumeNode.GetID(), self._fgMultiVolumeNode.GetID())
    else:
      Helper.SetBgVolume(self._bgMultiVolumeNode.GetID())
    self.refreshFrameSlider()
    self._multiVolumeIntensityChart.bgMultiVolumeNode = self._bgMultiVolumeNode
    self.refreshObservers()

  def getBackgroundMultiVolumeNode(self):
    return self.bgMultiVolumeSelector.currentNode()

  def onBackgroundInputChanged(self):
    self._bgMultiVolumeNode = self.getBackgroundMultiVolumeNode()

    if self._bgMultiVolumeNode is not None:
      self.refreshGUIForNewBackgroundImage()
    else:
      self.setFramesEnabled(False)

  def onPlayButtonToggled(self, checked):
    if self._bgMultiVolumeNode is None:
      return
    if checked:
      self.timer.start()
      self.playButton.text = 'Stop'
    else:
      self.timer.stop()
      self.playButton.text = 'Play'

  def processEvent(self, observee, event):
    # logging.debug("processing event %s" % event)
    if self._bgMultiVolumeNode is None:
      return

    # TODO: use a timer to delay calculation and compress events
    if event == 'LeaveEvent':
      # reset all the readouts
      # TODO: reset the label text
      return

    if not self.sliceWidgetsPerStyle.has_key(observee):
      return

    interactor = observee.GetInteractor()
    self.createChart(self.sliceWidgetsPerStyle[observee], interactor.GetEventPosition())

  def createChart(self, sliceWidget, position):
    self._multiVolumeIntensityChart.createChart(sliceWidget, position)

  def setCurrentFrameNumber(self, frameNumber):
    mvDisplayNode = self._bgMultiVolumeNode.GetDisplayNode()
    mvDisplayNode.SetFrameComponent(frameNumber)

  def setFramesEnabled(self, enabled):
    pass

  def refreshObservers(self):
    """ When the layout changes, drop the observers from
    all the old widgets and create new observers for the
    newly created widgets"""
    self.removeObservers()
    # get new slice nodes
    layoutManager = slicer.app.layoutManager()
    sliceNodeCount = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceNode')
    for nodeIndex in xrange(sliceNodeCount):
      # find the widget for each node in scene
      sliceNode = slicer.mrmlScene.GetNthNodeByClass(nodeIndex, 'vtkMRMLSliceNode')
      sliceWidget = layoutManager.sliceWidget(sliceNode.GetLayoutName())
      if sliceWidget:
        # add observers and keep track of tags
        style = sliceWidget.sliceView().interactorStyle()
        self.sliceWidgetsPerStyle[style] = sliceWidget
        events = ("MouseMoveEvent", "EnterEvent", "LeaveEvent")
        for event in events:
          tag = style.AddObserver(event, self.processEvent)
          self.styleObserverTags.append([style,tag])

  def removeObservers(self):
    for observee,tag in self.styleObserverTags:
      observee.RemoveObserver(tag)
    self.styleObserverTags = []
    self.sliceWidgetsPerStyle = {}

  def refreshFrameSlider(self):
    self.frameSlider.minimum = 0
    if not self._bgMultiVolumeNode:
      self.frameSlider.maximum = 0
      return
    nFrames = self._bgMultiVolumeNode.GetNumberOfFrames()
    self.frameSlider.maximum = nFrames - 1

  def goToNext(self):
    currentElement = self.frameSlider.value
    currentElement += 1
    if currentElement > self.frameSlider.maximum:
      currentElement = 0
    self.frameSlider.value = currentElement
class qSlicerMultiVolumeExplorerSimplifiedModuleWidget:
    def __init__(self, parent=None):
        logging.debug(
            "qSlicerMultiVolumeExplorerSimplifiedModuleWidget:init() called")
        if not parent or not hasattr(parent, "layout"):
            self.parent = slicer.qMRMLWidget()
            self.parent.setLayout(QVBoxLayout())
        else:
            self.parent = parent

        self.layout = self.parent.layout()

        self._bgMultiVolumeNode = None
        self._fgMultiVolumeNode = None

        self.styleObserverTags = []
        self.sliceWidgetsPerStyle = {}

        self.chartPopupWindow = None
        self.chartPopupSize = QSize(600, 300)
        self.chartPopupPosition = QPoint(0, 0)

    def hide(self):
        self.widget.hide()

    def show(self):
        self.widget.show()

    def setup(self):
        self.widget = QWidget()
        layout = QGridLayout()
        self.widget.setLayout(layout)
        self.layout.addWidget(self.widget)
        self.widget.show()
        self.layout = layout

        self.setupInputFrame()
        self.setupFrameControlFrame()
        self.setupAdditionalFrames()
        self.setupPlottingFrame()

        self.setFramesEnabled(False)

        self.timer = QTimer()
        self.timer.setInterval(50)

        self.setupConnections()

        # initialize slice observers (from DataProbe.py)
        # keep list of pairs: [observee,tag] so they can be removed easily
        self.styleObserverTags = []
        # keep a map of interactor styles to sliceWidgets so we can easily get sliceLogic
        self.sliceWidgetsPerStyle = {}
        self.refreshObservers()

    def setupInputFrame(self, parent=None):
        if not parent:
            parent = self.layout
        self.bgMultiVolumeSelector = slicer.qMRMLNodeComboBox()
        self.bgMultiVolumeSelector.nodeTypes = ['vtkMRMLMultiVolumeNode']
        self.bgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
        self.bgMultiVolumeSelector.addEnabled = 0
        self._bgMultiVolumeSelectorLabel = QLabel('Input multivolume')
        inputFrameWidget = QWidget()
        self.inputFrameLayout = QFormLayout()
        inputFrameWidget.setLayout(self.inputFrameLayout)
        self.inputFrameLayout.addRow(self._bgMultiVolumeSelectorLabel,
                                     self.bgMultiVolumeSelector)
        parent.addWidget(inputFrameWidget)

    def setupFrameControlFrame(self):
        # TODO: initialize the slider based on the contents of the labels array
        self.frameSlider = ctk.ctkSliderWidget()
        self.frameSlider.setSizePolicy(QSizePolicy.Ignored,
                                       QSizePolicy.Preferred)
        self.frameLabel = QLabel('Current frame number')
        self.playButton = QPushButton('Play')
        self.playButton.toolTip = 'Iterate over multivolume frames'
        self.playButton.checkable = True
        frameControlHBox = QHBoxLayout()
        frameControlHBox.addWidget(self.frameLabel)
        frameControlHBox.addWidget(self.frameSlider)
        frameControlHBox.addWidget(self.playButton)
        self.inputFrameLayout.addRow(frameControlHBox)

    def setupAdditionalFrames(self):
        pass

    def setupPlottingFrame(self, parent=None):
        if not parent:
            parent = self.layout
        self.plottingFrameWidget = QWidget()
        self.plottingFrameLayout = QGridLayout()
        self.plottingFrameWidget.setLayout(self.plottingFrameLayout)
        self._multiVolumeIntensityChart = MultiVolumeIntensityChartView()
        self.popupChartButton = QPushButton("Undock chart")
        self.popupChartButton.setCheckable(True)
        self.plottingFrameLayout.addWidget(
            self._multiVolumeIntensityChart.chartView)
        self.plottingFrameLayout.addWidget(self.popupChartButton)
        parent.addWidget(self.plottingFrameWidget)

    def setupConnections(self):
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.onVCMRMLSceneChanged)
        self.bgMultiVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)',
                                           self.onBackgroundInputChanged)
        self.playButton.connect('toggled(bool)', self.onPlayButtonToggled)
        self.frameSlider.connect('valueChanged(double)', self.onSliderChanged)
        self.timer.connect('timeout()', self.goToNext)
        self.popupChartButton.connect('toggled(bool)',
                                      self.onDockChartViewToggled)

    def onDockChartViewToggled(self, checked):
        if checked:
            self.chartPopupWindow = QDialog()
            self.chartPopupWindow.setWindowFlags(
                PythonQt.QtCore.Qt.WindowStaysOnTopHint)
            layout = QGridLayout()
            self.chartPopupWindow.setLayout(layout)
            layout.addWidget(self._multiVolumeIntensityChart.chartView)
            layout.addWidget(self.popupChartButton)
            self.chartPopupWindow.finished.connect(self.dockChartView)
            self.chartPopupWindow.resize(self.chartPopupSize)
            self.chartPopupWindow.move(self.chartPopupPosition)
            self.chartPopupWindow.show()
            self.popupChartButton.setText("Dock chart")
            self._multiVolumeIntensityChart.chartView.show()
        else:
            self.chartPopupWindow.close()

    def dockChartView(self):
        self.chartPopupSize = self.chartPopupWindow.size
        self.chartPopupPosition = self.chartPopupWindow.pos
        self.plottingFrameLayout.addWidget(
            self._multiVolumeIntensityChart.chartView)
        self.plottingFrameLayout.addWidget(self.popupChartButton)
        self.popupChartButton.setText("Undock chart")
        self.popupChartButton.disconnect('toggled(bool)',
                                         self.onDockChartViewToggled)
        self.popupChartButton.checked = False
        self.popupChartButton.connect('toggled(bool)',
                                      self.onDockChartViewToggled)

    def onSliderChanged(self, frameId):
        if self._bgMultiVolumeNode is None:
            return
        newValue = int(frameId)
        self.setCurrentFrameNumber(newValue)

    def onVCMRMLSceneChanged(self, mrmlScene):
        logging.debug(
            "qSlicerMultiVolumeExplorerSimplifiedModuleWidget:onVCMRMLSceneChanged"
        )
        self.bgMultiVolumeSelector.setMRMLScene(slicer.mrmlScene)
        self.onBackgroundInputChanged()

    def refreshGUIForNewBackgroundImage(self):
        self._multiVolumeIntensityChart.reset()
        self.setFramesEnabled(True)
        if self._fgMultiVolumeNode and self._bgMultiVolumeNode:
            Helper.SetBgFgVolumes(self._bgMultiVolumeNode.GetID(),
                                  self._fgMultiVolumeNode.GetID())
        else:
            Helper.SetBgVolume(self._bgMultiVolumeNode.GetID())
        self.refreshFrameSlider()
        self._multiVolumeIntensityChart.bgMultiVolumeNode = self._bgMultiVolumeNode
        self.refreshObservers()

    def getBackgroundMultiVolumeNode(self):
        return self.bgMultiVolumeSelector.currentNode()

    def onBackgroundInputChanged(self):
        self._bgMultiVolumeNode = self.getBackgroundMultiVolumeNode()

        if self._bgMultiVolumeNode is not None:
            self.refreshGUIForNewBackgroundImage()
        else:
            self.setFramesEnabled(False)

    def onPlayButtonToggled(self, checked):
        if self._bgMultiVolumeNode is None:
            return
        if checked:
            self.timer.start()
            self.playButton.text = 'Stop'
        else:
            self.timer.stop()
            self.playButton.text = 'Play'

    def processEvent(self, observee, event):
        # logging.debug("processing event %s" % event)
        if self._bgMultiVolumeNode is None:
            return

        # TODO: use a timer to delay calculation and compress events
        if event == 'LeaveEvent':
            # reset all the readouts
            # TODO: reset the label text
            return

        if not self.sliceWidgetsPerStyle.has_key(observee):
            return

        interactor = observee.GetInteractor()
        self.createChart(self.sliceWidgetsPerStyle[observee],
                         interactor.GetEventPosition())

    def createChart(self, sliceWidget, position):
        self._multiVolumeIntensityChart.createChart(sliceWidget, position)

    def setCurrentFrameNumber(self, frameNumber):
        mvDisplayNode = self._bgMultiVolumeNode.GetDisplayNode()
        mvDisplayNode.SetFrameComponent(frameNumber)

    def setFramesEnabled(self, enabled):
        pass

    def refreshObservers(self):
        """ When the layout changes, drop the observers from
    all the old widgets and create new observers for the
    newly created widgets"""
        self.removeObservers()
        # get new slice nodes
        layoutManager = slicer.app.layoutManager()
        sliceNodeCount = slicer.mrmlScene.GetNumberOfNodesByClass(
            'vtkMRMLSliceNode')
        for nodeIndex in xrange(sliceNodeCount):
            # find the widget for each node in scene
            sliceNode = slicer.mrmlScene.GetNthNodeByClass(
                nodeIndex, 'vtkMRMLSliceNode')
            sliceWidget = layoutManager.sliceWidget(sliceNode.GetLayoutName())
            if sliceWidget:
                # add observers and keep track of tags
                style = sliceWidget.sliceView().interactorStyle()
                self.sliceWidgetsPerStyle[style] = sliceWidget
                events = ("MouseMoveEvent", "EnterEvent", "LeaveEvent")
                for event in events:
                    tag = style.AddObserver(event, self.processEvent)
                    self.styleObserverTags.append([style, tag])

    def removeObservers(self):
        for observee, tag in self.styleObserverTags:
            observee.RemoveObserver(tag)
        self.styleObserverTags = []
        self.sliceWidgetsPerStyle = {}

    def refreshFrameSlider(self):
        self.frameSlider.minimum = 0
        if not self._bgMultiVolumeNode:
            self.frameSlider.maximum = 0
            return
        nFrames = self._bgMultiVolumeNode.GetNumberOfFrames()
        self.frameSlider.maximum = nFrames - 1

    def goToNext(self):
        currentElement = self.frameSlider.value
        currentElement += 1
        if currentElement > self.frameSlider.maximum:
            currentElement = 0
        self.frameSlider.value = currentElement
Exemple #40
0
class ClientDialog(QDialog):

    """a simple popup dialog for asking the player what he wants to do"""

    def __init__(self, client, parent=None):
        QDialog.__init__(self, parent)
        decorateWindow(self, m18n('Choose'))
        self.setObjectName('ClientDialog')
        self.client = client
        self.layout = QGridLayout(self)
        self.progressBar = QProgressBar()
        self.timer = QTimer()
        if not client.game.autoPlay:
            self.timer.timeout.connect(self.timeout)
        self.deferred = None
        self.buttons = []
        self.setWindowFlags(Qt.SubWindow | Qt.WindowStaysOnTopHint)
        self.setModal(False)
        self.btnHeight = 0
        self.answered = False
        self.move = None
        self.sorry = None

    def keyPressEvent(self, event):
        """ESC selects default answer"""
        if not self.client.game or self.client.game.autoPlay:
            return
        if event.key() in [Qt.Key_Escape, Qt.Key_Space]:
            self.selectButton()
            event.accept()
        else:
            for btn in self.buttons:
                if str(event.text()).upper() == btn.message.shortcut:
                    self.selectButton(btn)
                    event.accept()
                    return
            QDialog.keyPressEvent(self, event)

    def __declareButton(self, message):
        """define a button"""
        maySay = self.client.game.myself.sayable[message]
        if Internal.Preferences.showOnlyPossibleActions and not maySay:
            return
        btn = DlgButton(message, self)
        btn.setAutoDefault(True)
        btn.clicked.connect(self.selectedAnswer)
        self.buttons.append(btn)

    def focusTileChanged(self):
        """update icon and tooltip for the discard button"""
        if not self.client.game:
            return
        for button in self.buttons:
            button.decorate(self.client.game.myself.handBoard.focusTile)
        for uiTile in self.client.game.myself.handBoard.lowerHalfTiles():
            txt = []
            for button in self.buttons:
                _, _, tileTxt = button.message.toolTip(button, uiTile.tile)
                if tileTxt:
                    txt.append(tileTxt)
            uiTile.setToolTip('<br><br>'.join(txt))
        if self.client.game.activePlayer == self.client.game.myself:
            Internal.scene.handSelectorChanged(
                self.client.game.myself.handBoard)

    def checkTiles(self):
        """does the logical state match the displayed tiles?"""
        for player in self.client.game.players:
            player.handBoard.checkTiles()

    def messages(self):
        """a list of all messages returned by the declared buttons"""
        return list(x.message for x in self.buttons)

    def proposeAction(self):
        """either intelligently or first button by default. May also
        focus a proposed tile depending on the action."""
        result = self.buttons[0]
        game = self.client.game
        if game.autoPlay or Internal.Preferences.propose:
            answer, parameter = game.myself.intelligence.selectAnswer(
                self.messages())
            result = [x for x in self.buttons if x.message == answer][0]
            result.setFocus()
            if answer in [Message.Discard, Message.OriginalCall]:
                for uiTile in game.myself.handBoard.uiTiles:
                    if uiTile.tile is parameter:
                        game.myself.handBoard.focusTile = uiTile
        return result

    def askHuman(self, move, answers, deferred):
        """make buttons specified by answers visible. The first answer is default.
        The default button only appears with blue border when this dialog has
        focus but we always want it to be recognizable. Hence setBackgroundRole."""
        self.move = move
        self.deferred = deferred
        for answer in answers:
            self.__declareButton(answer)
        self.focusTileChanged()
        self.show()
        self.checkTiles()
        game = self.client.game
        myTurn = game.activePlayer == game.myself
        prefButton = self.proposeAction()
        if game.autoPlay:
            self.selectButton(prefButton)
            return
        prefButton.setFocus()

        self.progressBar.setVisible(not myTurn)
        if not myTurn:
            msecs = 50
            self.progressBar.setMinimum(0)
            self.progressBar.setMaximum(
                game.ruleset.claimTimeout * 1000 // msecs)
            self.progressBar.reset()
            self.timer.start(msecs)

    def placeInField(self):
        """place the dialog at bottom or to the right depending on space."""
        mainWindow = Internal.scene.mainWindow
        cwi = mainWindow.centralWidget()
        view = mainWindow.centralView
        geometry = self.geometry()
        if not self.btnHeight:
            self.btnHeight = self.buttons[0].height()
        vertical = view.width() > view.height() * 1.2
        if vertical:
            height = (len(self.buttons) + 1) * self.btnHeight * 1.2
            width = (cwi.width() - cwi.height()) // 2
            geometry.setX(cwi.width() - width)
            geometry.setY(min(cwi.height() // 3, cwi.height() - height))
        else:
            handBoard = self.client.game.myself.handBoard
            if not handBoard:
                # we are in the progress of logging out
                return
            hbLeftTop = view.mapFromScene(
                handBoard.mapToScene(handBoard.rect().topLeft()))
            hbRightBottom = view.mapFromScene(
                handBoard.mapToScene(handBoard.rect().bottomRight()))
            width = hbRightBottom.x() - hbLeftTop.x()
            height = self.btnHeight
            geometry.setY(cwi.height() - height)
            geometry.setX(hbLeftTop.x())
        for idx, btn in enumerate(self.buttons + [self.progressBar]):
            self.layout.addWidget(
                btn,
                idx +
                1 if vertical else 0,
                idx +
                1 if not vertical else 0)
        idx = len(self.buttons) + 2
        spacer = QSpacerItem(
            20,
            20,
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)
        self.layout.addItem(
            spacer,
            idx if vertical else 0,
            idx if not vertical else 0)

        geometry.setWidth(width)
        geometry.setHeight(height)
        self.setGeometry(geometry)

    def showEvent(self, dummyEvent):
        """try to place the dialog such that it does not cover interesting information"""
        self.placeInField()

    def timeout(self):
        """the progressboard wants an update"""
        pBar = self.progressBar
        if isAlive(pBar):
            pBar.setValue(pBar.value() + 1)
            pBar.setVisible(True)
            if pBar.value() == pBar.maximum():
                # timeout: we always return the original default answer, not
                # the one with focus
                self.selectButton()
                pBar.setVisible(False)

    def selectButton(self, button=None):
        """select default answer. button may also be of type Message."""
        if self.answered:
            # sometimes we get this event twice
            return
        if button is None:
            button = self.focusWidget()
        if isinstance(button, Message):
            assert any(x.message == button for x in self.buttons)
            answer = button
        else:
            answer = button.message
        if not self.client.game.myself.sayable[answer]:
            self.proposeAction().setFocus() # go back to default action
            self.sorry = Sorry(m18n('You cannot say %1', answer.i18nName))
            return
        self.timer.stop()
        self.answered = True
        if self.sorry:
            self.sorry.cancel()
        self.sorry = None
        Internal.scene.clientDialog = None
        self.deferred.callback(answer)

    def selectedAnswer(self, dummyChecked):
        """the user clicked one of the buttons"""
        game = self.client.game
        if game and not game.autoPlay:
            self.selectButton(self.sender())