示例#1
1
    def __init__(self, main, channels, default_channel=None):
        super(ChannelAddWidget, self).__init__()
        self.setObjectName("ChannelAddWidget")
        self.main_win = main
        self.channels = channels
        self.default_channel = default_channel
        self.channel = {}
        self.linedit_list = []
        self.game = self.main_win.games[self.main_win.game_index]
        combox_items = os.listdir(Utils.get_full_path('channelsdk'))

        v_layout = QVBoxLayout()
        v_layout.addSpacing(30)
        select_channel_combox = QComboBox()
        select_channel_combox.addItems(combox_items)
        select_channel_combox.activated[str].connect(self.select_channel)
        v_layout.addWidget(select_channel_combox, alignment=Qt.AlignHCenter)
        v_layout.addSpacing(30)

        h_layout1 = QHBoxLayout()
        form_layout1 = QFormLayout()
        form_layout1.setContentsMargins(10, 10, 10, 0)
        game_appid_value = QLabel(self.game['id'])
        form_layout1.addRow("游戏ID:", game_appid_value)
        game_appid_value.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.channel_id_value = QLineEdit()
        self.channel_id_value.setPlaceholderText("必填参数")
        form_layout1.addRow("渠道ID:", self.channel_id_value)
        self.game_name_value = QLineEdit()
        self.game_name_value.setText(self.game['name'])
        form_layout1.addRow("游戏名称:", self.game_name_value)
        self.game_package_value = QLineEdit()
        form_layout1.addRow("游戏包名:", self.game_package_value)
        self.game_vcode_value = QLineEdit()
        form_layout1.addRow("游戏版本号:", self.game_vcode_value)
        self.game_vname_value = QLineEdit()
        form_layout1.addRow("游戏版本名:", self.game_vname_value)
        self.debug_value = QLineEdit("false")
        form_layout1.addRow("打印日志:", self.debug_value)
        h_layout1.addLayout(form_layout1)
        self.form_layout2 = QFormLayout()
        self.form_layout2.setContentsMargins(10, 10, 10, 0)
        h_layout1.addLayout(self.form_layout2)
        v_layout.addLayout(h_layout1)

        h_layout2 = QHBoxLayout()
        back_btn = QPushButton("返 回")
        back_btn.setFixedWidth(100)
        back_btn.clicked.connect(self.back)
        h_layout2.addWidget(back_btn, alignment=Qt.AlignLeft)
        add_btn = QPushButton("添 加")
        add_btn.setFixedWidth(100)
        add_btn.clicked.connect(self.add)
        h_layout2.addWidget(add_btn, alignment=Qt.AlignRight)
        v_layout.addSpacing(50)
        v_layout.addLayout(h_layout2)

        self.setLayout(v_layout)
        # 默认松鼠SDK
        select_channel_combox.setCurrentText("songshu")
        self.select_channel("songshu")
class ConfigWidget(QWidget):
    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # copy of preferences
        self.tmpserials = plugin_prefs['kobo_serials']

        combo_label = QLabel(_('When should Obok try to insert EPUBs into existing calibre entries?'), self)
        layout.addWidget(combo_label)
        self.find_homes = QComboBox()
        self.find_homes.setToolTip(_('<p>Default behavior when duplicates are detected. None of the choices will cause calibre ebooks to be overwritten'))
        layout.addWidget(self.find_homes)
        self.find_homes.addItems([_('Ask'), _('Always'), _('Never')])
        index = self.find_homes.findText(plugin_prefs['finding_homes_for_formats'])
        self.find_homes.setCurrentIndex(index)

        self.serials_button = QtGui.QPushButton(self)
        self.serials_button.setToolTip(_(u"Click to manage Kobo serial numbers for Kobo ebooks"))
        self.serials_button.setText(u"Kobo devices serials")
        self.serials_button.clicked.connect(self.edit_serials)
        layout.addWidget(self.serials_button)


    def edit_serials(self):
        d = ManageKeysDialog(self,u"Kobo device serial numbers",self.tmpserials, AddSerialDialog)
        d.exec_()

    
    def save_settings(self):
        plugin_prefs['finding_homes_for_formats'] = unicode(self.find_homes.currentText())
        plugin_prefs['kobo_serials'] = self.tmpserials
示例#3
0
class HashGeneratorTab(QWidget):
    def __init__(self, console):
        super().__init__()
        self.layout = QVBoxLayout(self)

        self.titleText = QLabel("<H1>HashGenerator</H1>\nText Einfügen")
        self.layout.addWidget(self.titleText)

        self.textField = QTextEdit()
        self.layout.addWidget(self.textField)

        self.selectHash = QComboBox()
        self.selectHash.addItems(
            ["SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "MD5"])
        self.selectHash.setCurrentText("SHA512")
        self.layout.addWidget(self.selectHash)

        self.genButton = QPushButton("Generiere Hash")
        self.hashGenerator = HashGenerator()
        self.genButton.clicked.connect(self.generateHash)
        self.layout.addWidget(self.genButton)

        self.output = QTextEdit("Output")
        self.output.setReadOnly(True)
        self.layout.addWidget(self.output)

        self.layout.addStretch(1)

    def generateHash(self):
        text = self.textField.toPlainText()
        hash = self.selectHash.currentText()

        self.output.setText(self.hashGenerator.getHash(text, hash))
示例#4
0
 def make_color_combobox(self, row, dex):
     c = QComboBox(self)
     c.addItem('')
     c.addItems(QColor.colorNames())
     self.table.setCellWidget(row, 1, c)
     if dex >= 0:
         c.setCurrentIndex(dex)
     return c
示例#5
0
class ConfigWidget(QWidget):
    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # copy of preferences
        self.tmpserials = plugin_prefs['kobo_serials']
        self.kobodirectory = plugin_prefs['kobo_directory']

        combo_label = QLabel(
            _('When should Obok try to insert EPUBs into existing calibre entries?'
              ), self)
        layout.addWidget(combo_label)
        self.find_homes = QComboBox()
        self.find_homes.setToolTip(
            _('<p>Default behavior when duplicates are detected. None of the choices will cause calibre ebooks to be overwritten'
              ))
        layout.addWidget(self.find_homes)
        self.find_homes.addItems([_('Ask'), _('Always'), _('Never')])
        index = self.find_homes.findText(
            plugin_prefs['finding_homes_for_formats'])
        self.find_homes.setCurrentIndex(index)

        self.serials_button = QtGui.QPushButton(self)
        self.serials_button.setToolTip(
            _("Click to manage Kobo serial numbers for Kobo ebooks"))
        self.serials_button.setText("Kobo devices serials")
        self.serials_button.clicked.connect(self.edit_serials)
        layout.addWidget(self.serials_button)

        self.kobo_directory_button = QtGui.QPushButton(self)
        self.kobo_directory_button.setToolTip(
            _("Click to specify the Kobo directory"))
        self.kobo_directory_button.setText("Kobo directory")
        self.kobo_directory_button.clicked.connect(self.edit_kobo_directory)
        layout.addWidget(self.kobo_directory_button)

    def edit_serials(self):
        d = ManageKeysDialog(self, "Kobo device serial number",
                             self.tmpserials, AddSerialDialog)
        d.exec_()

    def edit_kobo_directory(self):
        tmpkobodirectory = QFileDialog.getExistingDirectory(
            self, "Select Kobo directory", self.kobodirectory or "/home",
            QFileDialog.Option.ShowDirsOnly)

        if tmpkobodirectory != u"" and tmpkobodirectory is not None:
            self.kobodirectory = tmpkobodirectory

    def save_settings(self):
        plugin_prefs[
            'finding_homes_for_formats'] = self.find_homes.currentText()
        plugin_prefs['kobo_serials'] = self.tmpserials
        plugin_prefs['kobo_directory'] = self.kobodirectory
示例#6
0
class GuiHeader(QWidget):
    def __init__(self, caller, *args, **kwargs):
        QWidget.__init__(self)
        myFont = QFont("Times", italic=True)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        # --- 1) Check Box
        self.centralBox = QGridLayout()
        self.centralBox.setContentsMargins(0, 0, 0, 5)
        # --- 1a) Select & Check RPC
        label1 = QLabel("PIVX server")
        self.centralBox.addWidget(label1, 0, 0)
        self.rpcClientsBox = QComboBox()
        self.rpcClientsBox.setToolTip(
            "Select RPC server.\nLocal must be configured.")
        rpcClients = ["Local Wallet"]
        self.rpcClientsBox.addItems(rpcClients)
        self.centralBox.addWidget(self.rpcClientsBox, 0, 1)
        self.button_checkRpc = QPushButton("Connect")
        self.button_checkRpc.setToolTip("try to connect to RPC server")
        self.button_checkRpc.clicked.connect(caller.onCheckRpc)
        self.centralBox.addWidget(self.button_checkRpc, 0, 2)
        self.rpcLed = QLabel()
        self.rpcLed.setToolTip("status: %s" % caller.rpcStatusMess)
        self.rpcLed.setPixmap(caller.ledGrayH_icon)
        self.centralBox.addWidget(self.rpcLed, 0, 3)
        label2 = QLabel("Last Ping Block:")
        self.centralBox.addWidget(label2, 0, 4)
        self.lastBlockLabel = QLabel()
        self.lastBlockLabel.setFont(myFont)
        self.centralBox.addWidget(self.lastBlockLabel, 0, 5)
        # -- 1b) Select & Check hardware
        label3 = QLabel("HW device")
        self.centralBox.addWidget(label3, 1, 0)
        self.hwDevices = QComboBox()
        self.hwDevices.setToolTip("Select hardware device")
        hwDevices = ["Ledger Nano S"]
        self.hwDevices.addItems(hwDevices)
        self.centralBox.addWidget(self.hwDevices, 1, 1)
        self.button_checkHw = QPushButton("Connect")
        self.button_checkHw.setToolTip("try to connect to Hardware Wallet")
        self.button_checkHw.clicked.connect(caller.onCheckHw)
        self.centralBox.addWidget(self.button_checkHw, 1, 2)
        self.hwLed = QLabel()
        self.hwLed.setToolTip("status: %s" % caller.hwStatusMess)
        self.hwLed.setPixmap(caller.ledGrayH_icon)
        self.centralBox.addWidget(self.hwLed, 1, 3)
        layout.addLayout(self.centralBox)
        layout.addStretch(1)
        # --- 3) logo
        Logo = QLabel()
        Logo_file = os.path.join(caller.imgDir, 'pet4lLogo_horiz.png')
        Logo.setPixmap(
            QPixmap(Logo_file).scaledToHeight(87, Qt.SmoothTransformation))
        layout.addWidget(Logo)
        self.setLayout(layout)
示例#7
0
 def test():
     w = QWidget()
     l = FlowLayout(w)
     la = QLabel('Some text in a label')
     l.addWidget(la)
     c = QCheckBox('A checkboxy widget')
     l.addWidget(c)
     cb = QComboBox()
     cb.addItems(['Item one'])
     l.addWidget(cb)
     return w
示例#8
0
 def test():
     w = QWidget()
     l = FlowLayout(w)
     la = QLabel('Some text in a label')
     l.addWidget(la)
     c = QCheckBox('A checkboxy widget')
     l.addWidget(c)
     cb = QComboBox()
     cb.addItems(['Item one'])
     l.addWidget(cb)
     return w
示例#9
0
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                     index: QModelIndex) -> QWidget:
        combobox = QComboBox(parent)
        li = [str(t) for t in Type]
        combobox.addItems(li)
        combobox.setCurrentIndex(index.model().data(index))

        # There's probably a better way to do this, but since I don't know it, I'll make a new
        # signal for it, so I can get the row for the type. Time is limited, deadline is tomorrow
        combobox.currentIndexChanged.connect(
            lambda x: self.type_changed_signal.emit(x, index))
        return combobox
示例#10
0
class PlayerInfoField(QWidget): #Widget for inputting player info. 
    names = ['Alex', 'Clifford', 'Tyrone', 'Ava', 'Ralph', 'Emily', 'Falcon', 'Giselle', 'Jaeger', 'Sally', 'Quentin', 'Lara']
    
    def __init__(self, parent, index):
        super(PlayerInfoField, self).__init__(parent)
        self.index = index
        
        self.layout = QHBoxLayout()
        
        self.auto_button = Button(self, 'Auto')
        self.auto_button.setFixedWidth(60)
        self.auto_button.clicked.connect(self.generate_name)
        self.layout.addWidget(self.auto_button)
        
        self.name_field = QLineEdit()
        self.name_field.setPalette(QPalette(Qt.white))
        self.name_field.setPlaceholderText('Name')
        self.name_field.setClearButtonEnabled(True)
        self.name_field.setFixedWidth(250)
        self.layout.addWidget(self.name_field)
        
        self.AItoggle = QCheckBox()
        self.AItoggle.setText('Computer')
        self.AItoggle.setFixedWidth(100)
        self.layout.addWidget(self.AItoggle)
        self.AItoggle.stateChanged.connect(self.AIToggled)
        
        self.AIdifficulty = QComboBox()
        self.AIdifficulty.setPalette(QPalette(Qt.white))
        self.AIdifficulty.setFixedWidth(100)
        self.AIdifficulty.addItems(['Braindead', 'Easy', 'Normal', 'Hard', 'HAL-9000'])
        self.AIdifficulty.setCurrentIndex(2)
        self.AIdifficulty.setDisabled(True)
        self.layout.addWidget(self.AIdifficulty)
        
        self.spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.layout.addItem(self.spacer)
        self.layout.setContentsMargins(0, 0, 0, 0)
        
        self.setLayout(self.layout)
        
        
    def generate_name(self):
        self.name_field.setText(PlayerInfoField.names[self.index])
     
    def AIToggled(self):
        if self.AItoggle.checkState() == Qt.Checked:
            self.AIdifficulty.setEnabled(True)
            
        else:
            self.AIdifficulty.setDisabled(True)
示例#11
0
 def ins_button_clicked(self):
     row = self.table.currentRow()
     if row < 0:
         error_dialog(self,
                      _('Select a cell'),
                      _('Select a cell before clicking the button'),
                      show=True)
         return
     self.table.insertRow(row)
     self.table.setItem(row, 0, QTableWidgetItem())
     c = QComboBox(self)
     c.addItem('')
     c.addItems(QColor.colorNames())
     self.table.setCellWidget(row, 1, c)
class HashcrackerTab(QWidget):

    def __init__(self, console):
        super().__init__()

        self.layout = QVBoxLayout(self)

        self.titleText = QLabel("<H1>Hashcracker</H1>\nHash hier einfügen")
        self.layout.addWidget(self.titleText)

        self.hashField = QLineEdit()
        self.layout.addWidget(self.hashField)

        self.hashSelectionLabel = QLabel("Wähle Hashfunktion aus")
        self.layout.addWidget(self.hashSelectionLabel)

        self.selectHash = QComboBox(self)
        self.selectHash.addItems(["SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "MD5"])
        self.selectHash.setCurrentText("SHA-512")
        self.layout.addWidget(self.selectHash)

        self.hboxText = QHBoxLayout()
        self.bruteforceLabel = QLabel("<H2>Bruteforce</H2>")
        self.listLabel = QLabel("<H2>Passwort Liste</H2>")
        self.rtLabel = QLabel("<H2>Ranbowtable Crack</H2>")
        self.hboxText.addWidget(self.bruteforceLabel)
        self.hboxText.addWidget(self.listLabel)
        self.hboxText.addWidget(self.rtLabel)
        self.layout.addLayout(self.hboxText)

        self.hboxAction = QHBoxLayout()
        self.bruteforceCharset = QLineEdit("Charset")
        self.hboxAction.addWidget(self.bruteforceCharset)
        self.listSelect = QPushButton("Wähle Datei aus")
        self.hboxAction.addWidget(self.listSelect)
        self.rtSelect = QPushButton("Wähle Ranbowtable aus")
        self.hboxAction.addWidget(self.rtSelect)
        self.layout.addLayout(self.hboxAction)

        self.hboxCrackButton = QHBoxLayout()
        self.bruteforceCrack = QPushButton("Crack Bruteforce")
        self.hboxCrackButton.addWidget(self.bruteforceCrack)
        self.listCrack = QPushButton("Crack List")
        self.hboxCrackButton.addWidget(self.listCrack)
        self.rainbowCrack = QPushButton("Crack Rainbowtable")
        self.hboxCrackButton.addWidget(self.rainbowCrack)
        self.layout.addLayout(self.hboxCrackButton)

        self.layout.addStretch(1)
示例#13
0
文件: win.py 项目: russionbear/mynew
    def initUI(self):
        self.setFixedSize(800, 600)

        layout = QVBoxLayout()

        layout1 = QHBoxLayout()

        layout1.addWidget(QLabel('地图类型'))
        tmp = QComboBox(self)
        tmp.addItems(self.types)
        tmp.currentTextChanged.connect(self.swap_menu)
        self.typeCom = tmp
        layout1.addWidget(tmp)
        layout1.addStretch(1)

        layout1.addWidget(QLabel('编辑器宽高:'))
        tmp = QSpinBox(self)
        tmp.setMaximum(1960)
        tmp.setMinimum(400)
        tmp.setValue(600)
        tmp.setSingleStep(100)
        layout1.addWidget(tmp)
        tmp = QSpinBox(self)
        tmp.setMaximum(1080)
        tmp.setSingleStep(100)
        tmp.setMinimum(400)
        layout1.addWidget(tmp)

        layout.addLayout(layout1)

        layout1 = QHBoxLayout()
        self.layer1 = []
        tmp = QLabel(self)
        self.layer1.append(tmp)
        self.image = tmp
        self.image.filepath = None
        layout1.addWidget(tmp)
        tmp = QPushButton('选择文件', self)
        tmp.clicked.connect(self.open_file)
        self.layer1.append(tmp)
        layout1.addWidget(tmp)

        layout.addLayout(layout1)

        tmp = QPushButton('开始编辑', self)
        tmp.clicked.connect(self.edit)
        layout.addWidget(tmp)

        self.setLayout(layout)
示例#14
0
class ConfigWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        labelColumnWidths = []

        self.opdsUrlLabel = QLabel('OPDS URL: ')
        self.layout.addWidget(self.opdsUrlLabel, 0, 0)
        labelColumnWidths.append(
            self.layout.itemAtPosition(0, 0).sizeHint().width())

        print(type(prefs.defaults['opds_url']))
        print(type(prefs['opds_url']))
        convertSingleStringOpdsUrlPreferenceToListOfStringsPreference()
        self.opdsUrlEditor = QComboBox(self)
        self.opdsUrlEditor.addItems(prefs['opds_url'])
        self.opdsUrlEditor.setEditable(True)
        self.opdsUrlEditor.setInsertPolicy(QComboBox.InsertAtTop)
        self.layout.addWidget(self.opdsUrlEditor, 0, 1)
        self.opdsUrlLabel.setBuddy(self.opdsUrlEditor)

        self.hideNewsCheckbox = QCheckBox('Hide Newspapers', self)
        self.hideNewsCheckbox.setChecked(prefs['hideNewspapers'])
        self.layout.addWidget(self.hideNewsCheckbox, 1, 0)
        labelColumnWidths.append(
            self.layout.itemAtPosition(1, 0).sizeHint().width())

        self.hideBooksAlreadyInLibraryCheckbox = QCheckBox(
            'Hide books already in library', self)
        self.hideBooksAlreadyInLibraryCheckbox.setChecked(
            prefs['hideBooksAlreadyInLibrary'])
        self.layout.addWidget(self.hideBooksAlreadyInLibraryCheckbox, 2, 0)
        labelColumnWidths.append(
            self.layout.itemAtPosition(2, 0).sizeHint().width())

        labelColumnWidth = max(labelColumnWidths)
        self.layout.setColumnMinimumWidth(1, labelColumnWidth * 2)

    def save_settings(self):
        prefs['hideNewspapers'] = self.hideNewsCheckbox.isChecked()
        prefs[
            'hideBooksAlreadyInLibrary'] = self.hideBooksAlreadyInLibraryCheckbox.isChecked(
            )
        prefs['opds_url'] = saveOpdsUrlCombobox(self.opdsUrlEditor)
示例#15
0
文件: config.py 项目: Moscarda/DRMM
class ConfigWidget(QWidget):
    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)
        
        combo_label = QLabel(_('When should Obok try to insert EPUBs into existing calibre entries?'), self)
        layout.addWidget(combo_label)
        self.find_homes = QComboBox()
        self.find_homes.setToolTip(_('<p>Default behavior when duplicates are detected. None of the choices will cause calibre ebooks to be overwritten'))
        layout.addWidget(self.find_homes)
        self.find_homes.addItems([_('Ask'), _('Always'), _('Never')])
        index = self.find_homes.findText(plugin_prefs['finding_homes_for_formats'])
        self.find_homes.setCurrentIndex(index)
    
    def save_settings(self):
        plugin_prefs['finding_homes_for_formats'] = unicode(self.find_homes.currentText())
class ConfigWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.l = QVBoxLayout()
        self.setLayout(self.l)

        self.cbox1 = QCheckBox("Reformatting")
        self.cbox1.setChecked(prefs["reformat"])
        self.l.addWidget(self.cbox1)

        self.cbox5 = QCheckBox("Paragraph by Ending mark")
        self.cbox5.setChecked(prefs["para_by_mark"])
        self.l.addWidget(self.cbox5)

        self.cbox2 = QCheckBox("Pretty Quote char")
        self.cbox2.setChecked(prefs["pretty_quote"])
        self.l.addWidget(self.cbox2)

        self.cbox3 = QCheckBox("Guess Chapter")
        self.cbox3.setChecked(prefs["guess_chapter"])
        self.l.addWidget(self.cbox3)

        self.cbox4 = QCheckBox("Allow Empty Paragraph")
        self.cbox4.setChecked(prefs["insert_empty_paragraph"])
        self.l.addWidget(self.cbox4)

        cl = QHBoxLayout()
        cl.addWidget(QLabel("Broken Word over lines"))
        self.combo1 = QComboBox()
        wbrk_list = ["None", "Pattern", "Naver"]
        self.combo1.addItems(wbrk_list)
        self.combo1.setCurrentIndex(wbrk_list.index(prefs["correct_word_break"]))
        cl.addWidget(self.combo1)
        self.l.addLayout(cl)

    def save_settings(self):
        prefs["reformat"] = self.cbox1.isChecked()
        prefs["para_by_mark"] = self.cbox5.isChecked()
        prefs["pretty_quote"] = self.cbox2.isChecked()
        prefs["guess_chapter"] = self.cbox3.isChecked()
        prefs["insert_empty_paragraph"] = self.cbox4.isChecked()
        prefs["correct_word_break"] = str(self.combo1.currentText())
示例#17
0
class ConfigWidget(QWidget):
    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        combo_label = QLabel(_("When should Obok try to insert EPUBs into existing calibre entries?"), self)
        layout.addWidget(combo_label)
        self.find_homes = QComboBox()
        self.find_homes.setToolTip(
            _(
                "<p>Default behavior when duplicates are detected. None of the choices will cause calibre ebooks to be overwritten"
            )
        )
        layout.addWidget(self.find_homes)
        self.find_homes.addItems([_("Ask"), _("Always"), _("Never")])
        index = self.find_homes.findText(plugin_prefs["finding_homes_for_formats"])
        self.find_homes.setCurrentIndex(index)

    def save_settings(self):
        plugin_prefs["finding_homes_for_formats"] = unicode(self.find_homes.currentText())
示例#18
0
class ConfigWidget(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        labelColumnWidths = []

        self.opdsUrlLabel = QLabel('OPDS URL: ')
        self.layout.addWidget(self.opdsUrlLabel, 0, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(0, 0).sizeHint().width())

        print type(prefs.defaults['opds_url'])
        print type(prefs['opds_url'])
        convertSingleStringOpdsUrlPreferenceToListOfStringsPreference()
        self.opdsUrlEditor = QComboBox(self)
        self.opdsUrlEditor.addItems(prefs['opds_url'])
        self.opdsUrlEditor.setEditable(True)
        self.opdsUrlEditor.setInsertPolicy(QComboBox.InsertAtTop)
        self.layout.addWidget(self.opdsUrlEditor, 0, 1)
        self.opdsUrlLabel.setBuddy(self.opdsUrlEditor)

        self.hideNewsCheckbox = QCheckBox('Hide Newspapers', self)
        self.hideNewsCheckbox.setChecked(prefs['hideNewspapers'])
        self.layout.addWidget(self.hideNewsCheckbox, 1, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(1, 0).sizeHint().width())

        self.hideBooksAlreadyInLibraryCheckbox = QCheckBox('Hide books already in library', self)
        self.hideBooksAlreadyInLibraryCheckbox.setChecked(prefs['hideBooksAlreadyInLibrary'])
        self.layout.addWidget(self.hideBooksAlreadyInLibraryCheckbox, 2, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(2, 0).sizeHint().width())

        labelColumnWidth = max(labelColumnWidths)
        self.layout.setColumnMinimumWidth(1, labelColumnWidth * 2)

    def save_settings(self):
        prefs['hideNewspapers'] = self.hideNewsCheckbox.isChecked()
        prefs['hideBooksAlreadyInLibrary'] = self.hideBooksAlreadyInLibraryCheckbox.isChecked()
        prefs['opds_url'] = saveOpdsUrlCombobox(self.opdsUrlEditor)
示例#19
0
 def initiate_combo_boxes(self):
     """Sets the horizontal and vertical headers, initiates the comboboxes
         sets the comboboxes to the right values, found in the model."""
     column_count = self.columnCount()
     row_count = self.rowCount()
     self.blockSignals(True)
     global_properrties = GlobalProperties.get_instance()
     for column in range(0,column_count - 1):
         for row in range(0,row_count - 1):
             row_heading = self.horizontalHeaderItem(row).text()
             column_heading = self.verticalHeaderItem(column).text()
             is_connected = global_properrties.mpdj_data.is_connected(row_heading,column_heading)
             new_combo_box = QComboBox()
             new_combo_box.addItems(['0','1'])
             is_connected_str = str(is_connected)
             item_index = new_combo_box.findText(is_connected_str)
             if item_index != -1:
                 new_combo_box.setCurrentIndex(item_index)
             new_combo_box.setProperty('row', row)
             new_combo_box.setProperty('column',column)
             new_combo_box.currentIndexChanged.connect(
                 self.artist_connection_combo_box_changed_indexchanged)
             self.setCellWidget(row,column, new_combo_box)
     self.blockSignals(False)
示例#20
0
class ConversionDialog(Dialog):
    def __init__(self, parent, force_entire_book=False):
        self.prefs = self.prefsPrep()
        self.parent = parent
        self.force_entire_book = force_entire_book
        self.criteria = None
        Dialog.__init__(self, _('Chinese Conversion'),
                        'chinese_conversion_dialog', parent)

    def setup_ui(self):
        self.quote_for_trad_target = _("Update quotes: "",'' -> 「」,『』")
        self.quote_for_simp_target = _("Update quotes: 「」,『』 -> "",''")

        # Create layout for entire dialog
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        #Create a scroll area for the top part of the dialog
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)

        # Create widget for all the contents of the dialog except the OK and Cancel buttons
        self.scrollContentWidget = QWidget(self.scrollArea)
        self.scrollArea.setWidget(self.scrollContentWidget)
        widgetLayout = QVBoxLayout(self.scrollContentWidget)

        # Add scrollArea to dialog
        layout.addWidget(self.scrollArea)

        self.operation_group_box = QGroupBox(_('Conversion Direction'))
        widgetLayout.addWidget(self.operation_group_box)
        operation_group_box_layout = QVBoxLayout()
        self.operation_group_box.setLayout(operation_group_box_layout)

        operation_group = QButtonGroup(self)
        self.no_conversion_button = QRadioButton(_('No Conversion'))
        operation_group.addButton(self.no_conversion_button)
        self.trad_to_simp_button = QRadioButton(_('Traditional to Simplified'))
        operation_group.addButton(self.trad_to_simp_button)
        self.simp_to_trad_button = QRadioButton(_('Simplified to Traditional'))
        operation_group.addButton(self.simp_to_trad_button)
        self.trad_to_trad_button = QRadioButton(
            _('Traditional to Traditional'))
        operation_group.addButton(self.trad_to_trad_button)
        operation_group_box_layout.addWidget(self.no_conversion_button)
        operation_group_box_layout.addWidget(self.trad_to_simp_button)
        operation_group_box_layout.addWidget(self.simp_to_trad_button)
        operation_group_box_layout.addWidget(self.trad_to_trad_button)
        self.no_conversion_button.toggled.connect(self.update_gui)
        self.trad_to_simp_button.toggled.connect(self.update_gui)
        self.simp_to_trad_button.toggled.connect(self.update_gui)
        self.trad_to_trad_button.toggled.connect(self.update_gui)

        self.style_group_box = QGroupBox(_('Language Styles'))
        widgetLayout.addWidget(self.style_group_box)
        style_group_box_layout = QVBoxLayout()
        self.style_group_box.setLayout(style_group_box_layout)

        input_layout = QHBoxLayout()
        style_group_box_layout.addLayout(input_layout)
        self.input_region_label = QLabel(_('Input:'))
        input_layout.addWidget(self.input_region_label)
        self.input_combo = QComboBox()
        input_layout.addWidget(self.input_combo)
        self.input_combo.addItems([_('Mainland'), _('Hong Kong'), _('Taiwan')])
        self.input_combo.setToolTip(_('Select the origin region of the input'))
        self.input_combo.currentIndexChanged.connect(self.update_gui)

        output_layout = QHBoxLayout()
        style_group_box_layout.addLayout(output_layout)
        self.output_region_label = QLabel(_('Output:'))
        output_layout.addWidget(self.output_region_label)
        self.output_combo = QComboBox()
        output_layout.addWidget(self.output_combo)
        self.output_combo.addItems(
            [_('Mainland'), _('Hong Kong'),
             _('Taiwan')])
        self.output_combo.setToolTip(
            _('Select the desired region of the output'))
        self.output_combo.currentIndexChanged.connect(self.update_gui)

        self.use_target_phrases = QCheckBox(
            _('Use output target phrases if possible'))
        self.use_target_phrases.setToolTip(
            _('Check to allow region specific word replacements if available'))
        style_group_box_layout.addWidget(self.use_target_phrases)
        self.use_target_phrases.stateChanged.connect(self.update_gui)

        self.quotation_group_box = QGroupBox(_('Quotation Marks'))
        widgetLayout.addWidget(self.quotation_group_box)
        quotation_group_box_layout = QVBoxLayout()
        self.quotation_group_box.setLayout(quotation_group_box_layout)

        quotation_group = QButtonGroup(self)
        self.quotation_no_conversion_button = QRadioButton(_('No Conversion'))
        quotation_group.addButton(self.quotation_no_conversion_button)
        self.quotation_trad_to_simp_button = QRadioButton(
            self.quote_for_simp_target)
        quotation_group.addButton(self.quotation_trad_to_simp_button)
        self.quotation_simp_to_trad_button = QRadioButton(
            self.quote_for_trad_target)
        quotation_group.addButton(self.quotation_simp_to_trad_button)
        quotation_group_box_layout.addWidget(
            self.quotation_no_conversion_button)
        quotation_group_box_layout.addWidget(
            self.quotation_simp_to_trad_button)
        quotation_group_box_layout.addWidget(
            self.quotation_trad_to_simp_button)
        self.quotation_no_conversion_button.toggled.connect(self.update_gui)
        self.quotation_trad_to_simp_button.toggled.connect(self.update_gui)
        self.quotation_simp_to_trad_button.toggled.connect(self.update_gui)
        self.use_smart_quotes = QCheckBox(
            """Use curved 'Smart" quotes if applicable""")
        self.use_smart_quotes.setToolTip(
            _('Use smart curved half-width quotes rather than straight full-width quotes'
              ))
        quotation_group_box_layout.addWidget(self.use_smart_quotes)
        self.use_smart_quotes.stateChanged.connect(self.update_gui)

        self.other_group_box = QGroupBox(_('Other Changes'))
        widgetLayout.addWidget(self.other_group_box)
        other_group_box_layout = QVBoxLayout()
        self.other_group_box.setLayout(other_group_box_layout)

        text_dir_layout = QHBoxLayout()
        other_group_box_layout.addLayout(text_dir_layout)
        direction_label = QLabel(_('Text Direction:'))
        text_dir_layout.addWidget(direction_label)
        self.text_dir_combo = QComboBox()
        text_dir_layout.addWidget(self.text_dir_combo)
        self.text_dir_combo.addItems(
            [_('No Conversion'),
             _('Horizontal'),
             _('Vertical')])
        self.text_dir_combo.setToolTip(
            _('Select the desired text orientation'))
        self.text_dir_combo.currentIndexChanged.connect(self.update_gui)

        self.optimization_group_box = QGroupBox(
            _('Reader Device Optimization'))
        other_group_box_layout.addWidget(self.optimization_group_box)
        optimization_group_box_layout = QVBoxLayout()
        self.optimization_group_box.setLayout(optimization_group_box_layout)

        punc_group = QButtonGroup(self)
        self.text_dir_punc_none_button = QRadioButton(
            """No presentation optimization""")
        optimization_group_box_layout.addWidget(self.text_dir_punc_none_button)
        self.text_dir_punc_button = QRadioButton(
            """Optimize presentation for Readium reader""")
        self.text_dir_punc_button.setToolTip(
            _('Use vert/horiz punctuation presentation forms for Chrome Readium Epub3 reader'
              ))
        optimization_group_box_layout.addWidget(self.text_dir_punc_button)
        self.text_dir_punc_kindle_button = QRadioButton(
            """Optimize presentation for Kindle reader""")
        self.text_dir_punc_kindle_button.setToolTip(
            _('Use vert/horiz puncuation presentation forms for Kindle reader')
        )
        optimization_group_box_layout.addWidget(
            self.text_dir_punc_kindle_button)
        self.text_dir_punc_none_button.toggled.connect(self.update_gui)
        self.text_dir_punc_button.toggled.connect(self.update_gui)
        self.text_dir_punc_kindle_button.toggled.connect(self.update_gui)

        source_group = QButtonGroup(self)
        self.file_source_button = QRadioButton(_('Selected File Only'))
        self.book_source_button = QRadioButton(_('Entire eBook'))
        source_group.addButton(self.file_source_button)
        source_group.addButton(self.book_source_button)
        self.source_group_box = QGroupBox(_('Source'))
        if not self.force_entire_book:
            widgetLayout.addWidget(self.source_group_box)
            source_group_box_layout = QVBoxLayout()
            self.source_group_box.setLayout(source_group_box_layout)
            source_group_box_layout.addWidget(self.file_source_button)
            source_group_box_layout.addWidget(self.book_source_button)

        layout.addSpacing(10)
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                           | QDialogButtonBox.Cancel)

        self.button_box.accepted.connect(self._ok_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        self.input_combo.setCurrentIndex(self.prefs['input_format'])
        self.output_combo.setCurrentIndex(self.prefs['output_format'])
        self.no_conversion_button.setChecked(self.prefs['no_conversion'])
        self.trad_to_simp_button.setChecked(self.prefs['trad_to_simp'])
        self.simp_to_trad_button.setChecked(self.prefs['simp_to_trad'])
        self.trad_to_trad_button.setChecked(self.prefs['trad_to_trad'])
        if not self.force_entire_book:
            self.file_source_button.setChecked(self.prefs['use_html_file'])
            self.book_source_button.setChecked(self.prefs['use_entire_book'])
        else:
            self.file_source_button.setChecked(False)
            self.book_source_button.setChecked(True)

        self.quotation_no_conversion_button.setChecked(
            self.prefs['quote_no_conversion'])
        self.quotation_trad_to_simp_button.setChecked(
            self.prefs['quote_trad_to_simp'])
        self.quotation_simp_to_trad_button.setChecked(
            self.prefs['quote_simp_to_trad'])

        self.use_smart_quotes.setChecked(self.prefs['use_smart_quotes'])
        self.text_dir_combo.setCurrentIndex(self.prefs['orientation'])
        self.text_dir_punc_none_button.setChecked(
            self.prefs['no_optimization'])
        self.text_dir_punc_button.setChecked(
            self.prefs['readium_optimization'])
        self.text_dir_punc_kindle_button.setChecked(
            self.prefs['kindle_optimization'])
        self.update_gui()

    def update_gui(self):
        if (self.quotation_trad_to_simp_button.isChecked()):
            self.use_smart_quotes.setEnabled(True)
        else:
            self.use_smart_quotes.setEnabled(False)

        if self.text_dir_combo.currentIndex() == 0:
            self.optimization_group_box.setEnabled(False)
            self.text_dir_punc_none_button.setEnabled(False)
            self.text_dir_punc_button.setEnabled(False)
            self.text_dir_punc_kindle_button.setEnabled(False)
        else:
            self.optimization_group_box.setEnabled(True)
            self.text_dir_punc_none_button.setEnabled(True)
            self.text_dir_punc_button.setEnabled(True)
            self.text_dir_punc_kindle_button.setEnabled(True)

        if self.no_conversion_button.isChecked():
            self.input_combo.setEnabled(False)
            self.output_combo.setEnabled(False)
            self.use_target_phrases.setEnabled(False)
            self.output_region_label.setEnabled(False)
            self.input_region_label.setEnabled(False)
            self.style_group_box.setEnabled(False)

        elif self.trad_to_simp_button.isChecked():
            self.input_combo.setEnabled(True)
            #only mainland output locale for simplified output
            self.output_combo.setCurrentIndex(0)
            self.output_combo.setEnabled(False)
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(False)
            self.input_region_label.setEnabled(True)
            self.style_group_box.setEnabled(True)

        elif self.simp_to_trad_button.isChecked():
            #only mainland input locale for simplified input
            self.input_combo.setCurrentIndex(0)
            self.input_combo.setEnabled(False)
            self.output_combo.setEnabled(True)
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(False)
            self.style_group_box.setEnabled(True)

        elif self.trad_to_trad_button.isChecked():
            #Trad->Trad
            #currently only mainland input locale for Trad->Trad
            self.input_combo.setCurrentIndex(0)
            self.input_combo.setEnabled(False)
            self.output_combo.setEnabled(True)
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(False)
            self.style_group_box.setEnabled(True)

        else:
            self.input_combo.setEnabled(True)
            self.output_combo.setEnabled(True)
            self.use_target_phrases.setEnabled(True)
            self.style_group_box.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(True)

    def _ok_clicked(self):
        output_mode = 0
        if self.trad_to_simp_button.isChecked():
            output_mode = 1  #trad -> simp
        if self.simp_to_trad_button.isChecked():
            output_mode = 2  #simp -> trad
        elif self.trad_to_trad_button.isChecked():
            output_mode = 3  #trad -> trad

        quote_mode = 0
        if self.quotation_trad_to_simp_button.isChecked():
            quote_mode = 1  #trad -> simp
        if self.quotation_simp_to_trad_button.isChecked():
            quote_mode = 2  #simp -> trad

        optimization_mode = 0
        if self.text_dir_punc_button.isChecked():
            optimization_mode = 1  #Readium
        if self.text_dir_punc_kindle_button.isChecked():
            optimization_mode = 2  #Kindle

        self.criteria = (self.file_source_button.isChecked(), output_mode,
                         self.input_combo.currentIndex(),
                         self.output_combo.currentIndex(),
                         self.use_target_phrases.isChecked(), quote_mode,
                         self.use_smart_quotes.isChecked(),
                         self.text_dir_combo.currentIndex(), optimization_mode)
        self.savePrefs()
        self.accept()

    def getCriteria(self):
        return self.criteria

    def prefsPrep(self):
        from calibre.utils.config import JSONConfig
        plugin_prefs = JSONConfig(
            'plugins/{0}_ChineseConversion_settings'.format(PLUGIN_SAFE_NAME))
        plugin_prefs.defaults['input_format'] = 0
        plugin_prefs.defaults['output_format'] = 0
        plugin_prefs.defaults['no_conversion'] = True
        plugin_prefs.defaults['trad_to_simp'] = False
        plugin_prefs.defaults['use_html_file'] = True
        plugin_prefs.defaults['simp_to_trad'] = False
        plugin_prefs.defaults['trad_to_trad'] = False
        plugin_prefs.defaults['use_entire_book'] = True
        plugin_prefs.defaults['use_target_phrases'] = True
        plugin_prefs.defaults['quote_no_conversion'] = True
        plugin_prefs.defaults['quote_trad_to_simp'] = False
        plugin_prefs.defaults['quote_simp_to_trad'] = False
        plugin_prefs.defaults['use_smart_quotes'] = False
        plugin_prefs.defaults['orientation'] = 0
        plugin_prefs.defaults['no_optimization'] = True
        plugin_prefs.defaults['readium_optimization'] = False
        plugin_prefs.defaults['kindle_optimization'] = False
        return plugin_prefs

    def savePrefs(self):
        self.prefs['input_format'] = self.input_combo.currentIndex()
        self.prefs['output_format'] = self.output_combo.currentIndex()
        self.prefs['no_conversion'] = self.no_conversion_button.isChecked()
        self.prefs['trad_to_simp'] = self.trad_to_simp_button.isChecked()
        self.prefs['use_html_file'] = self.file_source_button.isChecked()
        self.prefs['simp_to_trad'] = self.simp_to_trad_button.isChecked()
        self.prefs['trad_to_trad'] = self.trad_to_trad_button.isChecked()
        self.prefs['use_entire_book'] = self.book_source_button.isChecked()
        self.prefs['use_target_phrases'] = self.use_target_phrases.isChecked()
        self.prefs[
            'quote_no_conversion'] = self.quotation_no_conversion_button.isChecked(
            )
        self.prefs[
            'quote_trad_to_simp'] = self.quotation_trad_to_simp_button.isChecked(
            )
        self.prefs[
            'quote_simp_to_trad'] = self.quotation_simp_to_trad_button.isChecked(
            )
        self.prefs['use_smart_quotes'] = self.use_smart_quotes.isChecked()
        self.prefs['orientation'] = self.text_dir_combo.currentIndex()
        self.prefs[
            'no_optimization'] = self.text_dir_punc_none_button.isChecked()
        self.prefs[
            'readium_optimization'] = self.text_dir_punc_button.isChecked()
        self.prefs[
            'kindle_optimization'] = self.text_dir_punc_kindle_button.isChecked(
            )
示例#21
0
 def _updateModel(self, what=SkyModel.UpdateAll, origin=None):
     if origin is self or not what & (SkyModel.UpdateTags
                                      | SkyModel.UpdateGroupStyle):
         return
     model = self.model
     self._setting_model = True  # to ignore cellChanged() signals (in valueChanged())
     # _item_cb is a dict (with row,col keys) containing the widgets (CheckBoxes ComboBoxes) per each cell
     self._item_cb = {}
     # lists of "list" and "plot" checkboxes per each grouping (excepting the default grouping); each entry is an (row,col,item) tuple.
     # used as argument to self._showControls()
     self._list_controls = []
     self._plot_controls = []
     # list of selection callbacks (to which signals are connected)
     self._callbacks = []
     # set requisite number of rows,and start filling
     self.table.setRowCount(len(model.groupings))
     for irow, group in enumerate(model.groupings):
         self.table.setItem(irow, 0, QTableWidgetItem(group.name))
         if group is model.selgroup:
             self._irow_selgroup = irow
         # total # source in group: skip for "current"
         if group is not model.curgroup:
             self.table.setItem(irow, 1, QTableWidgetItem(str(group.total)))
         # selection controls: skip for current and selection
         if group not in (model.curgroup, model.selgroup):
             btns = QWidget()
             lo = QHBoxLayout(btns)
             lo.setContentsMargins(0, 0, 0, 0)
             lo.setSpacing(0)
             # make selector buttons (depending on which group we're in)
             if group is model.defgroup:
                 Buttons = (("+", lambda src, grp=group: True,
                             "select all sources"),
                            ("-", lambda src, grp=group: False,
                             "unselect all sources"))
             else:
                 Buttons = (
                     ("=", lambda src, grp=group: grp.func(src),
                      "select only this grouping"),
                     ("+",
                      lambda src, grp=group: src.selected or grp.func(src),
                      "add grouping to selection"),
                     ("-", lambda src, grp=group: src.selected and not grp.
                      func(src), "remove grouping from selection"),
                     ("&&",
                      lambda src, grp=group: src.selected and grp.func(src),
                      "intersect selection with grouping"))
             lo.addStretch(1)
             for label, predicate, tooltip in Buttons:
                 btn = QToolButton(btns)
                 btn.setText(label)
                 btn.setMinimumWidth(24)
                 btn.setMaximumWidth(24)
                 btn.setToolTip(tooltip)
                 lo.addWidget(btn)
                 # add callback
                 btn.clicked.connect(
                     self._currier.curry(self.selectSources, predicate))
             lo.addStretch(1)
             self.table.setCellWidget(irow, 2, btns)
         # "list" checkbox (not for current and selected groupings: these are always listed)
         if group not in (model.curgroup, model.selgroup):
             item = self._makeCheckItem("", group, "show_list")
             self.table.setItem(irow, self.ColList, item)
             item.setToolTip(
                 """<P>If checked, sources in this grouping will be listed in the source table. If un-checked, sources will be
         excluded from the table. If partially checked, then the default list/no list setting of "all sources" will be in effect.
         </P>""")
         # "plot" checkbox (not for the current grouping, since that's always plotted)
         if group is not model.curgroup:
             item = self._makeCheckItem("", group, "show_plot")
             self.table.setItem(irow, self.ColPlot, item)
             item.setToolTip(
                 """<P>If checked, sources in this grouping will be included in the plot. If un-checked, sources will be
         excluded from the plot. If partially checked, then the default plot/no plot setting of "all sources" will be in effect.
         </P>""")
         # custom style control
         # for default, current and selected, this is just a text label
         if group is model.defgroup:
             item = QTableWidgetItem("default:")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the default plot style used for all sources for which a custom grouping style is not selected.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.curgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the plot style used for the highlighted source, if any.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         elif group is model.selgroup:
             item = QTableWidgetItem("")
             item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
             item.setToolTip(
                 """<P>This is the plot style used for the currently selected sources.</P>"""
             )
             self.table.setItem(irow, self.ColApply, item)
         # for the rest, a combobox with custom priorities
         else:
             cb = QComboBox()
             cb.addItems(["default"] +
                         ["custom %d" % p for p in range(1, 10)])
             index = max(0, min(group.style.apply, 9))
             #        dprint(0,group.name,"apply",index)
             cb.setCurrentIndex(index)
             cb.activated[int].connect(
                 self._currier.xcurry(self._valueChanged,
                                      (irow, self.ColApply)))
             self.table.setCellWidget(irow, self.ColApply, cb)
             cb.setToolTip(
                 """<P>This controls whether sources within this group are plotted with a customized
         plot style. Customized styles have numeric priority; if a source belongs to multiple groups, then
         the style with the lowest priority takes precedence.<P>""")
         # attribute comboboxes
         for icol, attr in self.AttrByCol.items():
             # get list of options for this style attribute. If dealing with first grouping (i==0), which is
             # the "all sources" grouping, then remove the "default" option (which is always first in the list)
             options = PlotStyles.StyleAttributeOptions[attr]
             if irow == 0:
                 options = options[1:]
             # make combobox
             cb = QComboBox()
             cb.addItems(list(map(str, options)))
             # the "label" option is also editable
             if attr == "label":
                 cb.setEditable(True)
             try:
                 index = options.index(getattr(group.style, attr))
                 cb.setCurrentIndex(index)
             except ValueError:
                 cb.setEditText(str(getattr(group.style, attr)))
             slot = self._currier.xcurry(self._valueChanged, (irow, icol))
             cb.activated[int].connect(slot)
             cb.editTextChanged['QString'].connect(slot)
             cb.setEnabled(group is model.defgroup or group.style.apply)
             self.table.setCellWidget(irow, icol, cb)
             label = attr
             if irow:
                 cb.setToolTip(
                     """<P>This is the %s used to plot sources in this group, when a "custom" style for the group
       is enabled via the style control.<P>""" % label)
             else:
                 cb.setToolTip(
                     "<P>This is the default %s used for all sources for which a custom style is not specified below.<P>"
                     % label)
     self.table.resizeColumnsToContents()
     # re-enable processing of cellChanged() signals
     self._setting_model = False
示例#22
0
 def __init__(self, image, parent, imgman, name=None, save=False):
     QFrame.__init__(self, parent)
     self.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)
     # init state
     self._border_pen = None
     self._image_label_text = None
     self._subset = None
     self.image = image
     self._imgman = imgman
     self._currier = PersistentCurrier()
     self._control_dialog = None
     # create widgets
     self._lo = lo = QHBoxLayout(self)
     lo.setContentsMargins(0, 0, 0, 0)
     lo.setSpacing(2)
     # raise button
     self._wraise = QToolButton(self)
     lo.addWidget(self._wraise)
     self._wraise.setIcon(pixmaps.raise_up.icon())
     self._wraise.setAutoRaise(True)
     self._can_raise = False
     self._wraise.clicked.connect(self._raiseButtonPressed)
     self._wraise.setToolTip(
         """<P>Click here to raise this image above other images. Hold the button down briefly to
   show a menu of image operations.</P>""")
     # center label
     self._wcenter = QLabel(self)
     self._wcenter.setPixmap(pixmaps.center_image.pm())
     self._wcenter.setToolTip(
         "<P>The plot is currently centered on (the reference pixel %d,%d) of this image.</P>"
         % self.image.referencePixel())
     lo.addWidget(self._wcenter)
     # name/filename label
     self.name = image.name
     self._wlabel = QLabel(self.name, self)
     self._number = 0
     self.setName(self.name)
     self._wlabel.setToolTip(
         "%s %s" %
         (image.filename, "\u00D7".join(map(str,
                                            image.data().shape))))
     lo.addWidget(self._wlabel, 1)
     # if 'save' is specified, create a "save" button
     if save:
         self._wsave = QToolButton(self)
         lo.addWidget(self._wsave)
         self._wsave.setText("save")
         self._wsave.setAutoRaise(True)
         self._save_dir = save if isinstance(save, str) else "."
         self._wsave.clicked.connect(self._saveImage)
         self._wsave.setToolTip(
             """<P>Click here to write this image to a FITS file.</P>""")
     # render control
     self.image.connectRepaint(self.imageSignalRepaint)
     self.image.connectSlice(self.imageSignalSlice)
     self.image.connectRaise(self.imageSignalRaise)
     self.image.connectUnload(self.imageSignalUnload)
     self.image.connectCenter(self.imageSignalCenter)
     dprint(2, "creating RenderControl")
     self._rc = RenderControl(image, self)
     dprint(2, "done")
     # selectors for extra axes
     self._wslicers = []
     curslice = self._rc.currentSlice(
     )  # this may be loaded from config, so not necessarily 0
     for iextra, axisname, labels in self._rc.slicedAxes():
         if axisname.upper() not in ["STOKES", "COMPLEX"]:
             lbl = QLabel("%s:" % axisname, self)
             lo.addWidget(lbl)
         else:
             lbl = None
         slicer = QComboBox(self)
         self._wslicers.append(slicer)
         lo.addWidget(slicer)
         slicer.addItems(labels)
         slicer.setToolTip(
             """<P>Selects current slice along the %s axis.</P>""" %
             axisname)
         slicer.setCurrentIndex(curslice[iextra])
         slicer.activated[int].connect(
             self._currier.curry(self._rc.changeSlice, iextra))
     # min/max display ranges
     lo.addSpacing(5)
     self._wrangelbl = QLabel(self)
     lo.addWidget(self._wrangelbl)
     self._minmaxvalidator = FloatValidator(self)
     self._wmin = QLineEdit(self)
     self._wmax = QLineEdit(self)
     width = self._wmin.fontMetrics().width("1.234567e-05")
     for w in self._wmin, self._wmax:
         lo.addWidget(w, 0)
         w.setValidator(self._minmaxvalidator)
         w.setMaximumWidth(width)
         w.setMinimumWidth(width)
         w.editingFinished.connect(self._changeDisplayRange)
     # full-range button
     self._wfullrange = QToolButton(self)
     lo.addWidget(self._wfullrange, 0)
     self._wfullrange.setIcon(pixmaps.zoom_range.icon())
     self._wfullrange.setAutoRaise(True)
     self._wfullrange.clicked.connect(
         self.renderControl().resetSubsetDisplayRange)
     rangemenu = QMenu(self)
     rangemenu.addAction(pixmaps.full_range.icon(), "Full subset",
                         self.renderControl().resetSubsetDisplayRange)
     for percent in (99.99, 99.9, 99.5, 99, 98, 95):
         rangemenu.addAction(
             "%g%%" % percent,
             self._currier.curry(self._changeDisplayRangeToPercent,
                                 percent))
     self._wfullrange.setPopupMode(QToolButton.DelayedPopup)
     self._wfullrange.setMenu(rangemenu)
     # update widgets from current display range
     self._updateDisplayRange(*self._rc.displayRange())
     # lock button
     self._wlock = QToolButton(self)
     self._wlock.setIcon(pixmaps.unlocked.icon())
     self._wlock.setAutoRaise(True)
     self._wlock.setToolTip(
         """<P>Click to lock or unlock the intensity range. When the intensity range is locked across multiple images, any changes in the intensity
       range of one are propagated to the others. Hold the button down briefly for additional options.</P>"""
     )
     lo.addWidget(self._wlock)
     self._wlock.clicked.connect(self._toggleDisplayRangeLock)
     self.renderControl().displayRangeLocked.connect(
         self._setDisplayRangeLock)
     self.renderControl().dataSubsetChanged.connect(self._dataSubsetChanged)
     lockmenu = QMenu(self)
     lockmenu.addAction(
         pixmaps.locked.icon(), "Lock all to this",
         self._currier.curry(imgman.lockAllDisplayRanges,
                             self.renderControl()))
     lockmenu.addAction(pixmaps.unlocked.icon(), "Unlock all",
                        imgman.unlockAllDisplayRanges)
     self._wlock.setPopupMode(QToolButton.DelayedPopup)
     self._wlock.setMenu(lockmenu)
     self._setDisplayRangeLock(self.renderControl().isDisplayRangeLocked())
     # dialog button
     self._wshowdialog = QToolButton(self)
     lo.addWidget(self._wshowdialog)
     self._wshowdialog.setIcon(pixmaps.colours.icon())
     self._wshowdialog.setAutoRaise(True)
     self._wshowdialog.setToolTip(
         """<P>Click for colourmap and intensity policy options.</P>""")
     self._wshowdialog.clicked.connect(self.showRenderControls)
     tooltip = """<P>You can change the currently displayed intensity range by entering low and high limits here.</P>
         <TABLE>
         <TR><TD><NOBR>Image min:</NOBR></TD><TD>%g</TD><TD>max:</TD><TD>%g</TD></TR>
         </TABLE>""" % self.image.imageMinMax()
     for w in self._wmin, self._wmax, self._wrangelbl:
         w.setToolTip(tooltip)
     # create image operations menu
     self._menu = QMenu(self.name, self)
     self._qa_raise = self._menu.addAction(
         pixmaps.raise_up.icon(), "Raise image",
         self._currier.curry(self.image.signalRaise.emit, None))
     self._qa_center = self._menu.addAction(
         pixmaps.center_image.icon(), "Center plot on image",
         self._currier.curry(self.image.signalCenter.emit, True))
     self._qa_show_rc = self._menu.addAction(pixmaps.colours.icon(),
                                             "Colours && Intensities...",
                                             self.showRenderControls)
     if save:
         self._qa_save = self._menu.addAction("Save image...",
                                              self._saveImage)
     self._menu.addAction("Export image to PNG file...",
                          self._exportImageToPNG)
     self._export_png_dialog = None
     self._menu.addAction(
         "Unload image",
         self._currier.curry(self.image.signalUnload.emit, None))
     self._wraise.setMenu(self._menu)
     self._wraise.setPopupMode(QToolButton.DelayedPopup)
     # connect updates from renderControl and image
     self.image.signalSlice.connect(self._updateImageSlice)
     self._rc.displayRangeChanged.connect(self._updateDisplayRange)
     # default plot depth of image markers
     self._z_markers = None
     # and the markers themselves
     self._image_border = QwtPlotCurve()
     self._image_border.setRenderHint(QwtPlotItem.RenderAntialiased)
     self._image_label = QwtPlotMarker()
     self._image_label.setRenderHint(QwtPlotItem.RenderAntialiased)
     # subset markers
     self._subset_pen = QPen(QColor("Light Blue"))
     self._subset_border = QwtPlotCurve()
     self._subset_border.setRenderHint(QwtPlotItem.RenderAntialiased)
     self._subset_border.setPen(self._subset_pen)
     self._subset_border.setVisible(False)
     self._subset_label = QwtPlotMarker()
     self._subset_label.setRenderHint(QwtPlotItem.RenderAntialiased)
     text = QwtText("subset")
     text.setColor(self._subset_pen.color())
     self._subset_label.setLabel(text)
     self._subset_label.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
     self._subset_label.setVisible(False)
     self._setting_lmrect = False
     self._all_markers = [
         self._image_border, self._image_label, self._subset_border,
         self._subset_label
     ]
     self._exportMaxRes = False
     self._dockable_colour_ctrl = None
class App(QWidget):

    USs = []  # { F# , name , description , Acceptance Criteria }
    USNames = []  # user stories names
    TCs = []  # { TC name , TC description }

    def __init__(self):
        super().__init__()
        self.title = 'NLP project.'
        self.left = 50
        self.top = 50
        self.width = 1500
        self.height = 800
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

        # Create Label
        label = QLabel('Select User Story by name:', self)
        label.move(50, 0)

        # Create Label
        label2 = QLabel('US Description + Acceptance Criteria:', self)
        label2.move(50, 125)

        # Create Label
        label3 = QLabel('Choose Algorithm:', self)
        label3.move(50, 600)

        # Create Label
        label4 = QLabel('Results:', self)
        label4.move(1000, 50)

        # Create textbox user story
        self.textbox = QPlainTextEdit(self)
        self.textbox.move(50, 175)
        self.textbox.resize(500, 300)
        """
        # Create textbox results
        self.textbox3 = QLineEdit(self)
        self.textbox3.move(1000, 75)
        self.textbox3.resize(400,600)
        self.textbox3.setDisabled(True)
        """

        self.tableWidget = QTableWidget()

        #self.tableWidget.resize(400,600)

        # Create textbox tokenize

        self.textbox4 = QLineEdit(self)
        self.textbox4.move(50, 700)
        self.textbox4.resize(280, 40)
        #self.textbox4.setDisabled(True)
        """
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.move(50,400)
        self.scrollArea.resize(280,40)
        self.scrollArea.setWidget(self.textbox4)
        """
        button = QPushButton('Start', self)
        button.move(150, 750)
        button.clicked.connect(self.on_click_start)

        button2 = QPushButton('Tokenize', self)
        button2.move(50, 625)
        button2.clicked.connect(self.on_click_tokenize)

        button3 = QPushButton('Load excel', self)
        button3.move(50, 750)
        button3.clicked.connect(self.on_click_load)

        button4 = QPushButton('Choose US', self)
        button4.move(550, 29)
        button4.clicked.connect(self.on_click_choose_US)

        button5 = QPushButton('Choose AC', self)
        button5.move(550, 149)
        button5.clicked.connect(self.on_click_choose_AC)

        button6 = QPushButton('Clear', self)
        button6.move(250, 750)
        button6.clicked.connect(self.on_click_clear)

        # algorithm combobox
        self.comboBox = QComboBox(self)
        algorithms = ['cosine', 'other']
        self.comboBox.addItems(algorithms)
        self.comboBox.move(150, 625)

        # US combobox
        self.comboBox2 = QComboBox(self)
        self.comboBox2.move(50, 25)
        self.comboBox2.resize(500, 20)
        #action_relect = lambda: self.on_click_reselect_us(self)
        self.comboBox2.currentIndexChanged.connect(self.on_click_reselect_us)

        # AC combobox
        self.comboBox3 = QComboBox(self)
        self.comboBox3.move(50, 150)
        self.comboBox3.resize(500, 20)

        self.show()

    @pyqtSlot()
    def on_click_reselect_us(self):

        self.textbox.clear()
        self.comboBox3.clear()

    @pyqtSlot()
    def on_click_clear(self):

        self.textbox.clear()
        self.textbox3.clear()
        self.textbox4.clear()
        self.comboBox.clear()
        self.comboBox2.clear()
        self.comboBox3.clear()

    @pyqtSlot()
    def on_click_start(self):

        us = self.textbox2.text()
        results = []
        for tc in self.TCs:
            tmp = tc[0] + tc[1]
            results.append({
                'match_sentence': tmp,
                'score': compare_sens(us, tmp)
            })

        i = 0
        self.tableWidget.setSortingEnabled(True)
        self.tableWidget.setRowCount(100)
        self.tableWidget.setColumnCount(2)
        results = sorted(results, key=itemgetter('score'), reverse=True)

        for res in results:
            #self.tableWidget.insertRow(str(res)+str1)
            #self.tableWidget.setItem(i,0, QTableWidgetItem(str(res[1])))
            self.tableWidget.setItem(i, 0, QTableWidgetItem(str(res)))
            i += 1
            #self.textbox3.insert(str(res)+str1
        self.tableWidget.move(1000, 75)
        self.tableWidget.show()

    @pyqtSlot()
    def on_click_choose_US(self):

        # set User Story over textbox so we can edit if needed
        text = self.comboBox2.currentText()
        self.textbox.setPlainText(text)
        self.textbox.show()

        #  fill AC combobox
        descriptions = []
        ACs = []
        tmp = []
        us = self.comboBox2.currentText()

        for a, b, c, d in self.USs:
            if b == us:
                descriptions.append(c)
                ACs.append(d)
                tmp.append(c + d)
        self.comboBox3.addItems(tmp)

    @pyqtSlot()
    def on_click_choose_AC(self):

        # set AC over textbox so we can edit if needed
        text = self.comboBox3.currentText()
        self.textbox.paste()
        self.textbox.show()

    @pyqtSlot()
    def on_click_tokenize(self):

        text = self.textbox.text()
        tok = str(tokenize(text))
        self.textbox4.setText(tok)

    @pyqtSlot()
    def on_click_load(self):

        # Assign spreadsheet filename to `file`
        file = self.openFileNameDialog()

        # Load in the workbook
        wb = load_workbook(file)

        # Get sheet names
        data_sheets_names = wb.sheetnames
        print(wb.sheetnames)

        # Get all the sheet names that hold User stories and Test Cases
        USs_sheets_names = []
        TCs_Sheets_names = []

        for sheet_name in data_sheets_names:
            if sheet_name.find("TCs") != -1:
                TCs_Sheets_names.append(sheet_name)
            if sheet_name.find(" F") != -1:
                USs_sheets_names.append(sheet_name)

        # get NLP data sheets
        for name in USs_sheets_names:
            sheet = wb[name]
            for i in range(2, sheet.max_row + 1):
                self.USs.append(
                    ((sheet.cell(i, 1).value), (sheet.cell(i, 2).value),
                     (sheet.cell(i, 3).value), (sheet.cell(i, 4).value)))
            self.USNames.append((sheet.cell(2, 2).value))

        for name in TCs_Sheets_names:
            sheet = wb[name]
            for i in range(2, sheet.max_row + 1):
                self.TCs.append(
                    (name, (sheet.cell(i, 1).value), (sheet.cell(i, 2).value)))

        #remove doubles
        self.USNames = list(set(self.USNames))
        self.comboBox2.addItems(self.USNames)

        print(self.USNames)

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*);;Excel Files (*.xlsx)",
            options=options)
        if fileName:
            print(fileName)
        return fileName
示例#24
0
class Config(QDialog):
    '''
    Configuration dialog for single book conversion. If accepted, has the
    following important attributes

    output_format - Output format (without a leading .)
    input_format  - Input format (without a leading .)
    opf_path - Path to OPF file with user specified metadata
    cover_path - Path to user specified cover (can be None)
    recommendations - A pickled list of 3 tuples in the same format as the
    recommendations member of the Input/Output plugins.
    '''
    def __init__(self,
                 parent,
                 db,
                 book_id,
                 preferred_input_format=None,
                 preferred_output_format=None):
        QDialog.__init__(self, parent)
        self.setupUi()
        self.opt_individual_saved_settings.setVisible(False)
        self.db, self.book_id = db, book_id

        self.setup_input_output_formats(self.db, self.book_id,
                                        preferred_input_format,
                                        preferred_output_format)
        self.setup_pipeline()

        self.input_formats.currentIndexChanged[native_string_type].connect(
            self.setup_pipeline)
        self.output_formats.currentIndexChanged[native_string_type].connect(
            self.setup_pipeline)
        self.groups.setSpacing(5)
        self.groups.activated[(QModelIndex)].connect(self.show_pane)
        self.groups.clicked[(QModelIndex)].connect(self.show_pane)
        self.groups.entered[(QModelIndex)].connect(self.show_group_help)
        rb = self.buttonBox.button(self.buttonBox.RestoreDefaults)
        rb.setText(_('Restore &defaults'))
        rb.clicked.connect(self.restore_defaults)
        self.groups.setMouseTracking(True)
        geom = gprefs.get('convert_single_dialog_geom', None)
        if geom:
            self.restoreGeometry(geom)
        else:
            self.resize(self.sizeHint())

    def setupUi(self):
        self.setObjectName("Dialog")
        self.resize(1024, 700)
        self.setWindowIcon(QIcon(I('convert.png')))
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.input_label = QLabel(self)
        self.input_label.setObjectName("input_label")
        self.horizontalLayout.addWidget(self.input_label)
        self.input_formats = QComboBox(self)
        self.input_formats.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.input_formats.setMinimumContentsLength(5)
        self.input_formats.setObjectName("input_formats")
        self.horizontalLayout.addWidget(self.input_formats)
        self.opt_individual_saved_settings = QCheckBox(self)
        self.opt_individual_saved_settings.setObjectName(
            "opt_individual_saved_settings")
        self.horizontalLayout.addWidget(self.opt_individual_saved_settings)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.label_2 = QLabel(self)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.output_formats = QComboBox(self)
        self.output_formats.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.output_formats.setMinimumContentsLength(5)
        self.output_formats.setObjectName("output_formats")
        self.horizontalLayout.addWidget(self.output_formats)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2)
        self.groups = QListView(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groups.sizePolicy().hasHeightForWidth())
        self.groups.setSizePolicy(sizePolicy)
        self.groups.setTabKeyNavigation(True)
        self.groups.setIconSize(QSize(48, 48))
        self.groups.setWordWrap(True)
        self.groups.setObjectName("groups")
        self.gridLayout.addWidget(self.groups, 1, 0, 3, 1)
        self.scrollArea = QScrollArea(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(4)
        sizePolicy.setVerticalStretch(10)
        sizePolicy.setHeightForWidth(
            self.scrollArea.sizePolicy().hasHeightForWidth())
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setLineWidth(0)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 810, 494))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.verticalLayout_3 = QVBoxLayout(self.scrollAreaWidgetContents)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.stack = QStackedWidget(self.scrollAreaWidgetContents)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.stack.sizePolicy().hasHeightForWidth())
        self.stack.setSizePolicy(sizePolicy)
        self.stack.setObjectName("stack")
        self.page = QWidget()
        self.page.setObjectName("page")
        self.stack.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName("page_2")
        self.stack.addWidget(self.page_2)
        self.verticalLayout_3.addWidget(self.stack)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok
                                          | QDialogButtonBox.RestoreDefaults)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1)
        self.help = QTextEdit(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.help.sizePolicy().hasHeightForWidth())
        self.help.setSizePolicy(sizePolicy)
        self.help.setMaximumHeight(80)
        self.help.setObjectName("help")
        self.gridLayout.addWidget(self.help, 2, 1, 1, 1)
        self.input_label.setBuddy(self.input_formats)
        self.label_2.setBuddy(self.output_formats)
        self.input_label.setText(_("&Input format:"))
        self.opt_individual_saved_settings.setText(
            _("Use &saved conversion settings for individual books"))
        self.label_2.setText(_("&Output format:"))

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def sizeHint(self):
        desktop = QCoreApplication.instance().desktop()
        geom = desktop.availableGeometry(self)
        nh, nw = max(300, geom.height() - 100), max(400, geom.width() - 70)
        return QSize(nw, nh)

    def restore_defaults(self):
        delete_specifics(self.db, self.book_id)
        self.setup_pipeline()

    @property
    def input_format(self):
        return unicode_type(self.input_formats.currentText()).lower()

    @property
    def output_format(self):
        return unicode_type(self.output_formats.currentText()).lower()

    @property
    def manually_fine_tune_toc(self):
        for i in range(self.stack.count()):
            w = self.stack.widget(i)
            if hasattr(w, 'manually_fine_tune_toc'):
                return w.manually_fine_tune_toc.isChecked()

    def setup_pipeline(self, *args):
        oidx = self.groups.currentIndex().row()
        input_format = self.input_format
        output_format = self.output_format
        self.plumber = create_dummy_plumber(input_format, output_format)

        def widget_factory(cls):
            return cls(self.stack, self.plumber.get_option_by_name,
                       self.plumber.get_option_help, self.db, self.book_id)

        self.mw = widget_factory(MetadataWidget)
        self.setWindowTitle(
            _('Convert') + ' ' + unicode_type(self.mw.title.text()))
        lf = widget_factory(LookAndFeelWidget)
        hw = widget_factory(HeuristicsWidget)
        sr = widget_factory(SearchAndReplaceWidget)
        ps = widget_factory(PageSetupWidget)
        sd = widget_factory(StructureDetectionWidget)
        toc = widget_factory(TOCWidget)
        from calibre.gui2.actions.toc_edit import SUPPORTED
        toc.manually_fine_tune_toc.setVisible(
            output_format.upper() in SUPPORTED)
        debug = widget_factory(DebugWidget)

        output_widget = self.plumber.output_plugin.gui_configuration_widget(
            self.stack, self.plumber.get_option_by_name,
            self.plumber.get_option_help, self.db, self.book_id)
        input_widget = self.plumber.input_plugin.gui_configuration_widget(
            self.stack, self.plumber.get_option_by_name,
            self.plumber.get_option_help, self.db, self.book_id)
        while True:
            c = self.stack.currentWidget()
            if not c:
                break
            self.stack.removeWidget(c)

        widgets = [self.mw, lf, hw, ps, sd, toc, sr]
        if input_widget is not None:
            widgets.append(input_widget)
        if output_widget is not None:
            widgets.append(output_widget)
        widgets.append(debug)
        for w in widgets:
            self.stack.addWidget(w)
            w.set_help_signal.connect(self.help.setPlainText)

        self._groups_model = GroupModel(widgets)
        self.groups.setModel(self._groups_model)

        idx = oidx if -1 < oidx < self._groups_model.rowCount() else 0
        self.groups.setCurrentIndex(self._groups_model.index(idx))
        self.stack.setCurrentIndex(idx)
        try:
            shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True)
        except:
            pass

    def setup_input_output_formats(self, db, book_id, preferred_input_format,
                                   preferred_output_format):
        if preferred_output_format:
            preferred_output_format = preferred_output_format.upper()
        output_formats = get_output_formats(preferred_output_format)
        input_format, input_formats = get_input_format_for_book(
            db, book_id, preferred_input_format)
        preferred_output_format = preferred_output_format if \
            preferred_output_format in output_formats else \
            sort_formats_by_preference(output_formats,
                    [prefs['output_format']])[0]
        self.input_formats.addItems(
            (unicode_type(x.upper()) for x in input_formats))
        self.output_formats.addItems(
            (unicode_type(x.upper()) for x in output_formats))
        self.input_formats.setCurrentIndex(input_formats.index(input_format))
        self.output_formats.setCurrentIndex(
            output_formats.index(preferred_output_format))

    def show_pane(self, index):
        self.stack.setCurrentIndex(index.row())

    def accept(self):
        recs = GuiRecommendations()
        for w in self._groups_model.widgets:
            if not w.pre_commit_check():
                return
            x = w.commit(save_defaults=False)
            recs.update(x)
        self.opf_file, self.cover_file = self.mw.opf_file, self.mw.cover_file
        self._recommendations = recs
        if self.db is not None:
            recs['gui_preferred_input_format'] = self.input_format
            save_specifics(self.db, self.book_id, recs)
        self.break_cycles()
        QDialog.accept(self)

    def reject(self):
        self.break_cycles()
        QDialog.reject(self)

    def done(self, r):
        if self.isVisible():
            gprefs['convert_single_dialog_geom'] = \
                bytearray(self.saveGeometry())
        return QDialog.done(self, r)

    def break_cycles(self):
        for i in range(self.stack.count()):
            w = self.stack.widget(i)
            w.break_cycles()

    @property
    def recommendations(self):
        recs = [(k, v, OptionRecommendation.HIGH)
                for k, v in self._recommendations.items()]
        return recs

    def show_group_help(self, index):
        widget = self._groups_model.widgets[index.row()]
        self.help.setPlainText(widget.HELP)
示例#25
0
 def __add_address(self, gb_l):
     wgts = {}
     gb_l.addWidget(QLabel(tr('Почтовый индекс')))
     w = QLineEdit()
     gb_l.addWidget(w, 0, 1, 1, 1)
     wgts['Postal_Code'] = w
     gb_l.addWidget(QLabel(tr('Регион')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Region'] = w
     gb_l.addWidget(QLabel(tr('Район')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['District'] = w
     gb_l.addWidget(QLabel(tr('Муниципальное образование')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['City'] = w
     gb_l.addWidget(QLabel(tr('Городской район')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Urban_District'] = w
     gb_l.addWidget(QLabel(tr('Сельсовет')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Soviet_Village'] = w
     gb_l.addWidget(
         QLabel(tr('Населенный пункт <em style="color: red">*</em>')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Locality'] = w
     cb = QComboBox()
     cb.addItems(('Вариант 1', 'Вариант 2'))
     gb_l.addWidget(cb)
     st = QStackedWidget()
     p1 = QWidget()
     l = QGridLayout()
     l.setSpacing(3)
     l.addWidget(QLabel(tr('Улица <em style="color: red">*</em>')))
     w = QLineEdit()
     l.addWidget(w, 0, 1, 1, 1)
     wgts["Street"] = w
     l.addWidget(QLabel(tr('Дом <em style="color: red">*</em>')))
     w = QLineEdit()
     l.addWidget(w)
     wgts["House"] = w
     p1.setLayout(l)
     st.addWidget(p1)
     p2 = QWidget()
     l = QGridLayout()
     l.setSpacing(3)
     l.addWidget(QLabel(tr('Ориентир')))
     w = QLineEdit()
     l.addWidget(w, 0, 1, 1, 1)
     wgts["Reference_point"] = w
     p2.setLayout(l)
     st.addWidget(p2)
     gb_l.addWidget(st, 9, 0, 1, 2)
     cb.activated.connect(st.setCurrentIndex)
     gb_l.addWidget(QLabel(tr('Корпус')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Housing'] = w
     gb_l.addWidget(QLabel(tr('Строение')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Building'] = w
     gb_l.addWidget(QLabel(tr('Квартира')))
     w = QLineEdit()
     gb_l.addWidget(w)
     wgts['Apartment'] = w
     return wgts
示例#26
0
class OpdsDialog(QDialog):
    def __init__(self, gui, icon, do_user_config):
        QDialog.__init__(self, gui)
        self.gui = gui
        self.do_user_config = do_user_config

        self.db = gui.current_db.new_api

        # The model for the book list
        self.model = OpdsBooksModel(None, self.dummy_books(), self.db)
        self.searchproxymodel = QSortFilterProxyModel(self)
        self.searchproxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.searchproxymodel.setFilterKeyColumn(-1)
        self.searchproxymodel.setSourceModel(self.model)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.setWindowTitle("OPDS Client")
        self.setWindowIcon(icon)

        labelColumnWidths = []

        self.opdsUrlLabel = QLabel("OPDS URL: ")
        self.layout.addWidget(self.opdsUrlLabel, 0, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(0, 0).sizeHint().width())

        config.convertSingleStringOpdsUrlPreferenceToListOfStringsPreference()
        self.opdsUrlEditor = QComboBox(self)
        self.opdsUrlEditor.activated.connect(self.opdsUrlEditorActivated)
        self.opdsUrlEditor.addItems(prefs["opds_url"])
        self.opdsUrlEditor.setEditable(True)
        self.opdsUrlEditor.setInsertPolicy(QComboBox.InsertAtTop)
        self.layout.addWidget(self.opdsUrlEditor, 0, 1, 1, 3)
        self.opdsUrlLabel.setBuddy(self.opdsUrlEditor)

        buttonColumnNumber = 7
        buttonColumnWidths = []
        self.about_button = QPushButton("About", self)
        self.about_button.setAutoDefault(False)
        self.about_button.clicked.connect(self.about)
        self.layout.addWidget(self.about_button, 0, buttonColumnNumber)
        buttonColumnWidths.append(
            self.layout.itemAtPosition(0, buttonColumnNumber).sizeHint().width()
        )

        # Initially download the catalogs found in the root catalog of the URL
        # selected at startup.  Fail quietly on failing to open the URL
        catalogsTuple = self.model.downloadOpdsRootCatalog(
            self.gui, self.opdsUrlEditor.currentText(), False
        )
        print(catalogsTuple)
        firstCatalogTitle = catalogsTuple[0]
        self.currentOpdsCatalogs = catalogsTuple[1]  # A dictionary of title->feedURL

        self.opdsCatalogSelectorLabel = QLabel("OPDS Catalog:")
        self.layout.addWidget(self.opdsCatalogSelectorLabel, 1, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(1, 0).sizeHint().width())

        self.opdsCatalogSelector = QComboBox(self)
        self.opdsCatalogSelector.setEditable(False)
        self.opdsCatalogSelectorModel = QStringListModel(self.currentOpdsCatalogs.keys())
        self.opdsCatalogSelector.setModel(self.opdsCatalogSelectorModel)
        self.opdsCatalogSelector.setCurrentText(firstCatalogTitle)
        self.layout.addWidget(self.opdsCatalogSelector, 1, 1, 1, 3)

        self.download_opds_button = QPushButton("Download OPDS", self)
        self.download_opds_button.setAutoDefault(False)
        self.download_opds_button.clicked.connect(self.download_opds)
        self.layout.addWidget(self.download_opds_button, 1, buttonColumnNumber)
        buttonColumnWidths.append(
            self.layout.itemAtPosition(1, buttonColumnNumber).sizeHint().width()
        )

        # Search GUI
        self.searchEditor = QLineEdit(self)
        self.searchEditor.returnPressed.connect(self.searchBookList)
        self.layout.addWidget(self.searchEditor, 2, buttonColumnNumber - 2, 1, 2)

        self.searchButton = QPushButton("Search", self)
        self.searchButton.setAutoDefault(False)
        self.searchButton.clicked.connect(self.searchBookList)
        self.layout.addWidget(self.searchButton, 2, buttonColumnNumber)
        buttonColumnWidths.append(
            self.layout.itemAtPosition(2, buttonColumnNumber).sizeHint().width()
        )

        # The main book list
        self.library_view = QTableView(self)
        self.library_view.setAlternatingRowColors(True)
        self.library_view.setModel(self.searchproxymodel)
        self.library_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.library_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.resizeAllLibraryViewLinesToHeaderHeight()
        self.library_view.resizeColumnsToContents()
        self.layout.addWidget(self.library_view, 3, 0, 3, buttonColumnNumber + 1)

        self.hideNewsCheckbox = QCheckBox("Hide Newspapers", self)
        self.hideNewsCheckbox.clicked.connect(self.setHideNewspapers)
        self.hideNewsCheckbox.setChecked(prefs["hideNewspapers"])
        self.layout.addWidget(self.hideNewsCheckbox, 6, 0, 1, 3)

        self.hideBooksAlreadyInLibraryCheckbox = QCheckBox("Hide books already in library", self)
        self.hideBooksAlreadyInLibraryCheckbox.clicked.connect(self.setHideBooksAlreadyInLibrary)
        self.hideBooksAlreadyInLibraryCheckbox.setChecked(prefs["hideBooksAlreadyInLibrary"])
        self.layout.addWidget(self.hideBooksAlreadyInLibraryCheckbox, 7, 0, 1, 3)

        # Let the checkbox initial state control the filtering
        self.model.setFilterBooksThatAreNewspapers(self.hideNewsCheckbox.isChecked())
        self.model.setFilterBooksThatAreAlreadyInLibrary(
            self.hideBooksAlreadyInLibraryCheckbox.isChecked()
        )

        self.downloadButton = QPushButton("Download selected books", self)
        self.downloadButton.setAutoDefault(False)
        self.downloadButton.clicked.connect(self.downloadSelectedBooks)
        self.layout.addWidget(self.downloadButton, 6, buttonColumnNumber)
        buttonColumnWidths.append(
            self.layout.itemAtPosition(6, buttonColumnNumber).sizeHint().width()
        )

        self.fixTimestampButton = QPushButton("Fix timestamps of selection", self)
        self.fixTimestampButton.setAutoDefault(False)
        self.fixTimestampButton.clicked.connect(self.fixBookTimestamps)
        self.layout.addWidget(self.fixTimestampButton, 7, buttonColumnNumber)
        buttonColumnWidths.append(
            self.layout.itemAtPosition(7, buttonColumnNumber).sizeHint().width()
        )

        # Make all columns of the grid layout the same width as the button column
        buttonColumnWidth = max(buttonColumnWidths)
        for columnNumber in range(0, buttonColumnNumber):
            self.layout.setColumnMinimumWidth(columnNumber, buttonColumnWidth)

        # Make sure the first column isn't wider than the labels it holds
        labelColumnWidth = max(labelColumnWidths)
        self.layout.setColumnMinimumWidth(0, labelColumnWidth)

        self.resize(self.sizeHint())

    def opdsUrlEditorActivated(self, text):
        prefs["opds_url"] = config.saveOpdsUrlCombobox(self.opdsUrlEditor)
        catalogsTuple = self.model.downloadOpdsRootCatalog(
            self.gui, self.opdsUrlEditor.currentText(), True
        )
        firstCatalogTitle = catalogsTuple[0]
        self.currentOpdsCatalogs = catalogsTuple[1]  # A dictionary of title->feedURL
        self.opdsCatalogSelectorModel.setStringList(self.currentOpdsCatalogs.keys())
        self.opdsCatalogSelector.setCurrentText(firstCatalogTitle)

    def setHideNewspapers(self, checked):
        prefs["hideNewspapers"] = checked
        self.model.setFilterBooksThatAreNewspapers(checked)
        self.resizeAllLibraryViewLinesToHeaderHeight()

    def setHideBooksAlreadyInLibrary(self, checked):
        prefs["hideBooksAlreadyInLibrary"] = checked
        self.model.setFilterBooksThatAreAlreadyInLibrary(checked)
        self.resizeAllLibraryViewLinesToHeaderHeight()

    def searchBookList(self):
        searchString = self.searchEditor.text()
        print("starting book list search for: %s" % searchString)
        self.searchproxymodel.setFilterFixedString(searchString)

    def about(self):
        text = get_resources("about.txt")
        QMessageBox.about(self, "About the OPDS Client plugin", text.decode("utf-8"))

    def download_opds(self):
        opdsCatalogUrl = self.currentOpdsCatalogs.get(self.opdsCatalogSelector.currentText(), None)
        if opdsCatalogUrl is None:
            # Just give up quietly
            return
        self.model.downloadOpdsCatalog(self.gui, opdsCatalogUrl)
        if self.model.isCalibreOpdsServer():
            self.model.downloadMetadataUsingCalibreRestApi(self.opdsUrlEditor.currentText())
        self.library_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.resizeAllLibraryViewLinesToHeaderHeight()
        self.resize(self.sizeHint())

    def config(self):
        self.do_user_config(parent=self)

    def downloadSelectedBooks(self):
        selectionmodel = self.library_view.selectionModel()
        if selectionmodel.hasSelection():
            rows = selectionmodel.selectedRows()
            for row in reversed(rows):
                book = row.data(Qt.UserRole)
                self.downloadBook(book)

    def downloadBook(self, book):
        if len(book.links) > 0:
            self.gui.download_ebook(book.links[0])

    def fixBookTimestamps(self):
        selectionmodel = self.library_view.selectionModel()
        if selectionmodel.hasSelection():
            rows = selectionmodel.selectedRows()
            for row in reversed(rows):
                book = row.data(Qt.UserRole)
                self.fixBookTimestamp(book)

    def fixBookTimestamp(self, book):
        bookTimestamp = book.timestamp
        identicalBookIds = self.findIdenticalBooksForBooksWithMultipleAuthors(book)
        bookIdToValMap = {}
        for identicalBookId in identicalBookIds:
            bookIdToValMap[identicalBookId] = bookTimestamp
        if len(bookIdToValMap) < 1:
            print("Failed to set timestamp of book: %s" % book)
        self.db.set_field("timestamp", bookIdToValMap)

    def findIdenticalBooksForBooksWithMultipleAuthors(self, book):
        authorsList = book.authors
        if len(authorsList) < 2:
            return self.db.find_identical_books(book)
        # Try matching the authors one by one
        identicalBookIds = set()
        for author in authorsList:
            singleAuthorBook = Metadata(book.title, [author])
            singleAuthorIdenticalBookIds = self.db.find_identical_books(singleAuthorBook)
            identicalBookIds = identicalBookIds.union(singleAuthorIdenticalBookIds)
        return identicalBookIds

    def dummy_books(self):
        dummy_author = " " * 40
        dummy_title = " " * 60
        books_list = []
        for line in range(1, 10):
            book = DynamicBook()
            book.author = dummy_author
            book.title = dummy_title
            book.updated = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
            book.id = ""
            books_list.append(book)
        return books_list

    def resizeAllLibraryViewLinesToHeaderHeight(self):
        rowHeight = self.library_view.horizontalHeader().height()
        for rowNumber in range(0, self.library_view.model().rowCount()):
            self.library_view.setRowHeight(rowNumber, rowHeight)
示例#27
0
class OpdsDialog(QDialog):

    def __init__(self, gui, icon, do_user_config):
        QDialog.__init__(self, gui)
        self.gui = gui
        self.do_user_config = do_user_config

        self.db = gui.current_db.new_api

        # The model for the book list
        self.model = OpdsBooksModel(None, self.dummy_books(), self.db)
        self.searchproxymodel = QSortFilterProxyModel(self)
        self.searchproxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.searchproxymodel.setFilterKeyColumn(-1)
        self.searchproxymodel.setSourceModel(self.model)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.setWindowTitle('OPDS Client')
        self.setWindowIcon(icon)

        labelColumnWidths = []

        self.opdsUrlLabel = QLabel('OPDS URL: ')
        self.layout.addWidget(self.opdsUrlLabel, 0, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(0, 0).sizeHint().width())

        config.convertSingleStringOpdsUrlPreferenceToListOfStringsPreference()
        self.opdsUrlEditor = QComboBox(self)
        self.opdsUrlEditor.activated.connect(self.opdsUrlEditorActivated)
        self.opdsUrlEditor.addItems(prefs['opds_url'])
        self.opdsUrlEditor.setEditable(True)
        self.opdsUrlEditor.setInsertPolicy(QComboBox.InsertAtTop)
        self.layout.addWidget(self.opdsUrlEditor, 0, 1, 1, 3)
        self.opdsUrlLabel.setBuddy(self.opdsUrlEditor)

        buttonColumnNumber = 7
        buttonColumnWidths = []
        self.about_button = QPushButton('About', self)
        self.about_button.setAutoDefault(False)
        self.about_button.clicked.connect(self.about)
        self.layout.addWidget(self.about_button, 0, buttonColumnNumber)
        buttonColumnWidths.append(self.layout.itemAtPosition(0, buttonColumnNumber).sizeHint().width()) 

        # Initially download the catalogs found in the root catalog of the URL
        # selected at startup.  Fail quietly on failing to open the URL
        catalogsTuple = self.model.downloadOpdsRootCatalog(self.gui, self.opdsUrlEditor.currentText(), False)
        print catalogsTuple
        firstCatalogTitle = catalogsTuple[0]
        self.currentOpdsCatalogs = catalogsTuple[1] # A dictionary of title->feedURL

        self.opdsCatalogSelectorLabel = QLabel('OPDS Catalog:')
        self.layout.addWidget(self.opdsCatalogSelectorLabel, 1, 0)
        labelColumnWidths.append(self.layout.itemAtPosition(1, 0).sizeHint().width())

        self.opdsCatalogSelector = QComboBox(self)
        self.opdsCatalogSelector.setEditable(False)
        self.opdsCatalogSelectorModel = QStringListModel(self.currentOpdsCatalogs.keys())
        self.opdsCatalogSelector.setModel(self.opdsCatalogSelectorModel)
        self.opdsCatalogSelector.setCurrentText(firstCatalogTitle)
        self.layout.addWidget(self.opdsCatalogSelector, 1, 1, 1, 3)

        self.download_opds_button = QPushButton('Download OPDS', self)
        self.download_opds_button.setAutoDefault(False)
        self.download_opds_button.clicked.connect(self.download_opds)
        self.layout.addWidget(self.download_opds_button, 1, buttonColumnNumber)
        buttonColumnWidths.append(self.layout.itemAtPosition(1, buttonColumnNumber).sizeHint().width()) 

        # Search GUI
        self.searchEditor = QLineEdit(self)
        self.searchEditor.returnPressed.connect(self.searchBookList)
        self.layout.addWidget(self.searchEditor, 2, buttonColumnNumber - 2, 1, 2)

        self.searchButton = QPushButton('Search', self)
        self.searchButton.setAutoDefault(False)
        self.searchButton.clicked.connect(self.searchBookList)
        self.layout.addWidget(self.searchButton, 2, buttonColumnNumber)
        buttonColumnWidths.append(self.layout.itemAtPosition(2, buttonColumnNumber).sizeHint().width())

        # The main book list
        self.library_view = QTableView(self)
        self.library_view.setAlternatingRowColors(True)
        self.library_view.setModel(self.searchproxymodel)
        self.library_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.library_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.resizeAllLibraryViewLinesToHeaderHeight()
        self.library_view.resizeColumnsToContents()
        self.layout.addWidget(self.library_view, 3, 0, 3, buttonColumnNumber + 1)

        self.hideNewsCheckbox = QCheckBox('Hide Newspapers', self)
        self.hideNewsCheckbox.clicked.connect(self.setHideNewspapers)
        self.hideNewsCheckbox.setChecked(prefs['hideNewspapers'])
        self.layout.addWidget(self.hideNewsCheckbox, 6, 0, 1, 3)

        self.hideBooksAlreadyInLibraryCheckbox = QCheckBox('Hide books already in library', self)
        self.hideBooksAlreadyInLibraryCheckbox.clicked.connect(self.setHideBooksAlreadyInLibrary)
        self.hideBooksAlreadyInLibraryCheckbox.setChecked(prefs['hideBooksAlreadyInLibrary'])
        self.layout.addWidget(self.hideBooksAlreadyInLibraryCheckbox, 7, 0, 1, 3)

        # Let the checkbox initial state control the filtering
        self.model.setFilterBooksThatAreNewspapers(self.hideNewsCheckbox.isChecked())
        self.model.setFilterBooksThatAreAlreadyInLibrary(self.hideBooksAlreadyInLibraryCheckbox.isChecked())

        self.downloadButton = QPushButton('Download selected books', self)
        self.downloadButton.setAutoDefault(False)
        self.downloadButton.clicked.connect(self.downloadSelectedBooks)
        self.layout.addWidget(self.downloadButton, 6, buttonColumnNumber)
        buttonColumnWidths.append(self.layout.itemAtPosition(6, buttonColumnNumber).sizeHint().width()) 

        self.fixTimestampButton = QPushButton('Fix timestamps of selection', self)
        self.fixTimestampButton.setAutoDefault(False)
        self.fixTimestampButton.clicked.connect(self.fixBookTimestamps)
        self.layout.addWidget(self.fixTimestampButton, 7, buttonColumnNumber)
        buttonColumnWidths.append(self.layout.itemAtPosition(7, buttonColumnNumber).sizeHint().width()) 

        # Make all columns of the grid layout the same width as the button column
        buttonColumnWidth = max(buttonColumnWidths)
        for columnNumber in range(0, buttonColumnNumber):
            self.layout.setColumnMinimumWidth(columnNumber, buttonColumnWidth)

        # Make sure the first column isn't wider than the labels it holds
        labelColumnWidth = max(labelColumnWidths)
        self.layout.setColumnMinimumWidth(0, labelColumnWidth)

        self.resize(self.sizeHint())

    def opdsUrlEditorActivated(self, text):
        prefs['opds_url'] = config.saveOpdsUrlCombobox(self.opdsUrlEditor)
        catalogsTuple = self.model.downloadOpdsRootCatalog(self.gui, self.opdsUrlEditor.currentText(), True)
        firstCatalogTitle = catalogsTuple[0]
        self.currentOpdsCatalogs = catalogsTuple[1] # A dictionary of title->feedURL
        self.opdsCatalogSelectorModel.setStringList(self.currentOpdsCatalogs.keys())
        self.opdsCatalogSelector.setCurrentText(firstCatalogTitle)

    def setHideNewspapers(self, checked):
        prefs['hideNewspapers'] = checked
        self.model.setFilterBooksThatAreNewspapers(checked)
        self.resizeAllLibraryViewLinesToHeaderHeight()

    def setHideBooksAlreadyInLibrary(self, checked):
        prefs['hideBooksAlreadyInLibrary'] = checked
        self.model.setFilterBooksThatAreAlreadyInLibrary(checked)
        self.resizeAllLibraryViewLinesToHeaderHeight()

    def searchBookList(self):
        searchString = self.searchEditor.text()
        print "starting book list search for: %s" % searchString
        self.searchproxymodel.setFilterFixedString(searchString)

    def about(self):
        text = get_resources('about.txt')
        QMessageBox.about(self, 'About the OPDS Client plugin', text.decode('utf-8'))

    def download_opds(self):
        opdsCatalogUrl = self.currentOpdsCatalogs.get(self.opdsCatalogSelector.currentText(), None)
        if opdsCatalogUrl is None:
            # Just give up quietly
            return
        self.model.downloadOpdsCatalog(self.gui, opdsCatalogUrl)
        if self.model.isCalibreOpdsServer():
            self.model.downloadMetadataUsingCalibreRestApi(self.opdsUrlEditor.currentText())
        self.library_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.library_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.resizeAllLibraryViewLinesToHeaderHeight()
        self.resize(self.sizeHint())

    def config(self):
        self.do_user_config(parent=self)

    def downloadSelectedBooks(self):
        selectionmodel = self.library_view.selectionModel()
        if selectionmodel.hasSelection():
            rows = selectionmodel.selectedRows()
            for row in reversed(rows):
                book = row.data(Qt.UserRole)
                self.downloadBook(book)

    def downloadBook(self, book):
        if len(book.links) > 0:
            self.gui.download_ebook(book.links[0])

    def fixBookTimestamps(self):
        selectionmodel = self.library_view.selectionModel()
        if selectionmodel.hasSelection():
            rows = selectionmodel.selectedRows()
            for row in reversed(rows):
                book = row.data(Qt.UserRole)
                self.fixBookTimestamp(book)

    def fixBookTimestamp(self, book):
        bookTimestamp = book.timestamp
        identicalBookIds = self.findIdenticalBooksForBooksWithMultipleAuthors(book)
        bookIdToValMap = {}
        for identicalBookId in identicalBookIds:
            bookIdToValMap[identicalBookId] = bookTimestamp
        if len(bookIdToValMap) < 1:
            print "Failed to set timestamp of book: %s" % book
        self.db.set_field('timestamp', bookIdToValMap)

    def findIdenticalBooksForBooksWithMultipleAuthors(self, book):
        authorsList = book.authors
        if len(authorsList) < 2:
            return self.db.find_identical_books(book)
        # Try matching the authors one by one
        identicalBookIds = set()
        for author in authorsList:
            singleAuthorBook = Metadata(book.title, [author])
            singleAuthorIdenticalBookIds = self.db.find_identical_books(singleAuthorBook)
            identicalBookIds = identicalBookIds.union(singleAuthorIdenticalBookIds)
        return identicalBookIds

    def dummy_books(self):
        dummy_author = ' ' * 40
        dummy_title = ' ' * 60
        books_list = []
        for line in range (1, 10):
            book = DynamicBook()
            book.author = dummy_author
            book.title = dummy_title
            book.updated = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+00:00')
            book.id = ''
            books_list.append(book)
        return books_list

    def resizeAllLibraryViewLinesToHeaderHeight(self):
        rowHeight = self.library_view.horizontalHeader().height()
        for rowNumber in range (0, self.library_view.model().rowCount()):
            self.library_view.setRowHeight(rowNumber, rowHeight)
示例#28
0
class Ui(QApplication):
    def __init__(self):
        super().__init__(argv)
        self.w = QMainWindow()
        self.w.setMinimumWidth(300)
        self.w.setMinimumHeight(300)
        # self.w.setWindowTitle(tr("Отправка запросов на ВС АУГО"))
        self.cw = QScrollArea()
        # self.__create_ui()
        self.__showed = False
        self.__wgts = {}
        self.cb = QComboBox()
        self.individuals = []
        self.entities = []
        self.documents = []
        self.doc_files = []
        self.__setupUi(self.w)
        self.w.showMaximized()

    def report_error(self, msg=None):
        if not msg:
            etype, value, tb = exc_info()
            trace = ''.join(format_exception(etype, value, tb))
            delim_len = 40
            msg = ("*" * delim_len + "\n%s\n" + "*" * delim_len) % trace
            error(msg)
        mb = QMessageBox(QMessageBox.Critical, tr('Ошибка'),
                         str(exc_info()[1]))
        mb.setDetailedText(msg)
        mb.exec()

    def __create_ui(self):
        self.l = QGridLayout()
        self.t = QTableWidget(0, 3)
        self.t.setHorizontalHeaderLabels(
            ('№ дела (обращения)', 'Дата приёма', 'Дата отправки в СМЭВ'))
        self.t.resizeColumnsToContents()
        self.l.addWidget(self.t, 0, 0, 1, 2)
        w = QWidget()
        hl = QHBoxLayout(w)
        hl.setDirection(QHBoxLayout.LeftToRight)
        hl.addWidget(QWidget())
        ok_b = QPushButton(tr('Добавить запрос'))
        ok_b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        ok_b.clicked.connect(self.__show_form)
        hl.addWidget(ok_b)
        w.setLayout(hl)
        self.l.addWidget(w, 1, 0, 1, 2)
        w = QWidget()
        w.setLayout(self.l)
        self.cw.setWidget(w)
        # self.cw.setLayout(self.l)
        # self.w.setCentralWidget(self.cw)
        w = QWidget()
        l = QVBoxLayout()
        l.addWidget(self.cw)
        w.setLayout(l)
        self.w.setCentralWidget(w)

    def __setupUi(self, mainWindow):
        mainWindow.setObjectName("MainWindow")
        self.centralwidget = QWidget(mainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout.setObjectName("gridLayout")
        self.__show_form()
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.horizontalLayout.addWidget(self.scrollArea)
        mainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(mainWindow)
        self.menubar.setObjectName("menubar")
        self.menu = QMenu(self.menubar)
        self.menu.setObjectName("menu")
        mainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(mainWindow)
        self.statusbar.setObjectName("statusbar")
        mainWindow.setStatusBar(self.statusbar)
        self.action_1 = QAction(mainWindow)
        self.action_1.setObjectName("action")
        self.action_1.triggered.connect(self.send)
        self.action = QAction(mainWindow)
        self.action.setObjectName("action")
        self.action.triggered.connect(self.on_action_triggered)
        self.action_2 = QAction(mainWindow)
        self.action_2.setObjectName("action_2")
        self.action_3 = QAction(mainWindow)
        self.action_3.setObjectName("action_3")
        self.action_3.triggered.connect(self.get_response)
        self.menu.addAction(self.action)
        self.menubar.addAction(self.action_1)
        self.menubar.addAction(self.action_2)
        self.menubar.addAction(self.action_3)
        self.menubar.addAction(self.menu.menuAction())

        self.__retranslateUi(mainWindow)
        QMetaObject.connectSlotsByName(mainWindow)

    @pyqtSlot(bool)
    def get_response(self):
        try:
            from dmsic import Integration
            i = Integration(self)
            res = i.get_response()[0]
            if res:
                QMessageBox.information(self.w, tr("Получен ответ"), str(res))
        except:
            self.report_error()

    @pyqtSlot(bool)
    def send(self):
        try:
            from dmsic import Integration
            i = Integration(self)
            declar = {}
            for k, v in self.__wgts.items():
                if k in ('object_address', 'AppliedDocument', 'legal_entity',
                         'person'):
                    a = {}
                    for key, val in v.items():
                        if val.metaObject().className() == 'QDateEdit':
                            a[key] = datetime.strptime(val.text(), '%d.%m.%Y')
                        else:
                            a[key] = val.text()
                    declar[k] = a
                else:
                    if v.metaObject().className() == 'QDateEdit':
                        declar[k] = datetime.strptime(v.text(), '%d.%m.%Y')
                    else:
                        declar[k] = v.text()
            a = declar[
                'AppliedDocument'] if 'AppliedDocument' in declar else []
            for v in self.documents:
                d = {}
                for key, val in v.items():
                    if val.metaObject().className() == 'QDateEdit':
                        d[key] = datetime.strptime(val.text(), '%d.%m.%Y')
                    else:
                        d[key] = val.text()
                if not self.doc_files:
                    raise Exception('Добавте файл документа')
                d['file_name'] = self.doc_files[self.documents.index(v)]
                a.append(d)
            declar['AppliedDocument'] = a
            a = declar['person'] if 'person' in declar else []
            for v in self.individuals:
                ind = {}
                for key, val in v.items():
                    if key in ('address', 'fact_address'):
                        adr = {}
                        for k, vl in val.items():
                            adr[k] = vl.text()
                        ind[key] = adr
                    else:
                        if val.metaObject().className() == 'QDateEdit':
                            ind[key] = datetime.strptime(
                                val.text(), '%d.%m.%Y')
                        else:
                            ind[key] = val.text()
                a.append(ind)
            declar['person'] = a
            a = declar['legal_entity'] if 'legal_entity' in declar else []
            for v in self.entities:
                ent = {}
                for key, val in v.items():
                    if key == 'address':
                        adr = {}
                        for k, vl in val.items():
                            adr[k] = vl.text()
                        ent[key] = adr
                    else:
                        if val.metaObject().className() == 'QDateEdit':
                            ent[key] = datetime.strptime(
                                val.text(), '%d.%m.%Y')
                        else:
                            ent[key] = val.text()
                a.append(ent)
            declar['legal_entity'] = a
            i.send(declar)
            mb = QMessageBox(self.w)
            mb.information(self.w, tr('Готово'), tr('Запрос отправлен'))
        except:
            self.report_error()

    @pyqtSlot(bool)
    def on_action_triggered(self):
        a = Ui_Dialog()
        d = QDialog()
        a.setupUi(d)
        d.exec()

    def __retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("MainWindow", "Отправка запросов на ВС АУГО"))
        # self.pushButton.setText(_translate("MainWindow", "Добавить"))
        self.menu.setTitle(_translate("MainWindow", "Справка"))
        self.action_1.setText(_translate("MainWindow", "Отправить"))
        self.action_2.setText(_translate("MainWindow", "Настройка"))
        self.action.setText(_translate("MainWindow", "О программе"))
        self.action_3.setText(_translate("MainWindow", "Получить ответ"))

    @pyqtSlot(bool)
    def __show_form(self):
        if self.__showed:
            return

        self.gridLayout.addWidget(
            QLabel(tr('№ дела (обращения) <em style="color: red">*</em>')))
        w = QLineEdit()
        self.gridLayout.addWidget(w)
        w.setFocus()
        self.__wgts['declar_number'] = w
        self.gridLayout.addWidget(
            QLabel(
                tr('Услуга (код или номер, или наименование)<em style="color: red">*</em>'
                   )))
        w = QLineEdit()
        self.gridLayout.addWidget(w)
        self.__wgts['service'] = w
        self.gridLayout.addWidget(
            QLabel(
                tr('Дата регистрации запроса <em style="color: red">*</em>')))
        de = QDateEdit(QDate().currentDate())
        de.setCalendarPopup(True)
        self.gridLayout.addWidget(de)
        self.__wgts['register_date'] = de
        self.gridLayout.addWidget(
            QLabel(
                tr('Плановый срок предоставления услуги <em style="color: red">*</em>'
                   )))
        de = QDateEdit()
        self.__wgts['register_date'].dateChanged.connect(de.setMinimumDate)
        de.setCalendarPopup(True)
        de.setMinimumDate(self.__wgts['register_date'].date())
        self.gridLayout.addWidget(de)
        self.__wgts['end_date'] = de

        gb = QGroupBox(tr('Место нахождения объекта услуги'))
        gb_l = QGridLayout()
        self.__wgts['object_address'] = self.__add_address(gb_l)
        gb.setLayout(gb_l)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)

        doc = {}
        gb = QGroupBox(tr('Приложенный документ *'))
        gb_l = QGridLayout()
        gb_l.addWidget(
            QLabel(tr('Наименование документа <em style="color: red">*</em>')))
        w = QLineEdit()
        w.setMaxLength(1024)
        gb_l.addWidget(w, 0, 1, 1, 1)
        doc['title'] = w
        gb_l.addWidget(
            QLabel(tr('Номер документа <em style="color: red">*</em>')))
        w = QLineEdit()
        w.setMaxLength(50)
        gb_l.addWidget(w)
        doc['number'] = w
        gb_l.addWidget(
            QLabel(tr('Дата документа <em style="color: red">*</em>')))
        w = QDateEdit()
        w.setCalendarPopup(True)
        gb_l.addWidget(w)
        doc['date'] = w
        gb_l.addWidget(
            QLabel(
                tr('Прямая ссылка на файл. Поддерживаются только пртоколы '
                   'HTTP, FTP <em style="color: red">*</em>')))
        w = QLineEdit()
        gb_l.addWidget(w)
        doc['url'] = w
        gb.setLayout(gb_l)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)
        self.documents.append(doc)

        gb = QGroupBox(tr('Заявители *'))
        self.dec_layout = QGridLayout()
        self.cb = QComboBox()
        self.cb.addItems(('Физическое лицо',
                          'Юридическое лицо/Индивидуальный предприниматель'))
        self.dec_layout.addWidget(self.cb)
        b = QPushButton(tr('Добавить'))
        b.clicked.connect(self.add_declarant)
        self.dec_layout.addWidget(b, 0, 1, 1, 1)
        gb.setLayout(self.dec_layout)
        self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2)

        b = QPushButton(tr('Добавить файл документа'))
        b.clicked.connect(self.__add_doc_file)
        self.gridLayout.addWidget(b)
        self.file_label = QLabel()
        self.gridLayout.addWidget(self.file_label)
        self.warn_label = QLabel(tr("Не удаляйте файл до отправки запроса"))
        self.warn_label.setStyleSheet('color: red')
        self.warn_label.setVisible(False)
        self.gridLayout.addWidget(self.warn_label,
                                  self.gridLayout.rowCount() + 1, 0, 1, 2)

        self.__showed = True

    @pyqtSlot(bool)
    def __add_doc_file(self):
        file_name = QFileDialog.getOpenFileName(
            caption=tr('Выбурите файл'),
            filter=tr('Файлы pdf (*.pdf);;Все файлы (*.*)'))[0]
        self.file_label.setText(file_name)
        if self.doc_files:
            self.doc_files = []
        self.doc_files.append(file_name)
        self.warn_label.setVisible(True)

    def __add_address(self, gb_l):
        wgts = {}
        gb_l.addWidget(QLabel(tr('Почтовый индекс')))
        w = QLineEdit()
        gb_l.addWidget(w, 0, 1, 1, 1)
        wgts['Postal_Code'] = w
        gb_l.addWidget(QLabel(tr('Регион')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Region'] = w
        gb_l.addWidget(QLabel(tr('Район')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['District'] = w
        gb_l.addWidget(QLabel(tr('Муниципальное образование')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['City'] = w
        gb_l.addWidget(QLabel(tr('Городской район')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Urban_District'] = w
        gb_l.addWidget(QLabel(tr('Сельсовет')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Soviet_Village'] = w
        gb_l.addWidget(
            QLabel(tr('Населенный пункт <em style="color: red">*</em>')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Locality'] = w
        cb = QComboBox()
        cb.addItems(('Вариант 1', 'Вариант 2'))
        gb_l.addWidget(cb)
        st = QStackedWidget()
        p1 = QWidget()
        l = QGridLayout()
        l.setSpacing(3)
        l.addWidget(QLabel(tr('Улица <em style="color: red">*</em>')))
        w = QLineEdit()
        l.addWidget(w, 0, 1, 1, 1)
        wgts["Street"] = w
        l.addWidget(QLabel(tr('Дом <em style="color: red">*</em>')))
        w = QLineEdit()
        l.addWidget(w)
        wgts["House"] = w
        p1.setLayout(l)
        st.addWidget(p1)
        p2 = QWidget()
        l = QGridLayout()
        l.setSpacing(3)
        l.addWidget(QLabel(tr('Ориентир')))
        w = QLineEdit()
        l.addWidget(w, 0, 1, 1, 1)
        wgts["Reference_point"] = w
        p2.setLayout(l)
        st.addWidget(p2)
        gb_l.addWidget(st, 9, 0, 1, 2)
        cb.activated.connect(st.setCurrentIndex)
        gb_l.addWidget(QLabel(tr('Корпус')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Housing'] = w
        gb_l.addWidget(QLabel(tr('Строение')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Building'] = w
        gb_l.addWidget(QLabel(tr('Квартира')))
        w = QLineEdit()
        gb_l.addWidget(w)
        wgts['Apartment'] = w
        return wgts

    @pyqtSlot(bool)
    def add_declarant(self, var=True, gl=None):
        if not gl:
            gl = self.dec_layout
        dc = {}
        gb_l = QGridLayout()
        if self.cb.currentIndex() == 0 or gl != self.dec_layout:
            # Add Individual
            gb = QGroupBox(tr('Физическое лицо *'))
            gb_l.addWidget(QLabel(tr('Фамилия <em style="color: red">*</em>')))
            w = QLineEdit()
            gb_l.addWidget(w, 0, 1, 1, 1)
            dc['surname'] = w
            gb_l.addWidget(QLabel(tr('Имя <em style="color: red">*</em>')))
            w = QLineEdit()
            gb_l.addWidget(w)
            dc['first_name'] = w
            gb_l.addWidget(QLabel(tr('Отчество')))
            w = QLineEdit()
            gb_l.addWidget(w)
            dc['patronymic'] = w

            adr = QGroupBox(tr('Адрес регистрации *'))
            adr_l = QGridLayout()
            dc['address'] = self.__add_address(adr_l)
            adr.setLayout(adr_l)
            gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2)

            gb.setLayout(gb_l)
            gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2)
            self.individuals.append(dc)
        else:
            # Add LegalEntity
            gb = QGroupBox(
                tr('Юридическое лицо/Индивидуальный предприниматель *'))
            gb_l.addWidget(
                QLabel(
                    tr('Краткое наименование ЮЛ <em style="color: red">*</em>')
                ))
            w = QLineEdit()
            gb_l.addWidget(w, 0, 1, 1, 1)
            dc['name'] = w

            adr = QGroupBox(tr('Юридический адрес *'))
            adr_l = QGridLayout()
            dc['address'] = self.__add_address(adr_l)
            adr.setLayout(adr_l)
            gb_l.addWidget(adr, gb_l.rowCount() + 1, 0, 1, 2)

            gb.setLayout(gb_l)
            gl.addWidget(gb, gl.rowCount() + 1, 0, 1, 2)
            self.entities.append(dc)
示例#29
0
class ConfigWidget(QWidget):

    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # --- Directory Options ---
        directory_group_box = QGroupBox(_('Default Unpack Directory:'), self)
        layout.addWidget(directory_group_box)
        directory_group_box_layout = QVBoxLayout()
        directory_group_box.setLayout(directory_group_box_layout)

        # Directory path Textbox
        # Load the textbox with the current preference setting
        self.directory_txtBox = QLineEdit(plugin_prefs['Unpack_Folder'], self)
        self.directory_txtBox.setToolTip(_('<p>Default directory to extract files to'))
        directory_group_box_layout.addWidget(self.directory_txtBox)
        self.directory_txtBox.setReadOnly(True)

        # Folder select button
        directory_button = QPushButton(_('Select/Change Unpack Directory'), self)
        directory_button.setToolTip(_('<p>Select/Change directory to extract files to.'))
        # Connect button to the getDirectory function
        directory_button.clicked.connect(self.getDirectory)
        directory_group_box_layout.addWidget(directory_button)
        self.default_folder_check = QCheckBox(_('Always use the Default Unpack Directory'), self)
        self.default_folder_check.setToolTip(_('<p>When unchecked... you will be prompted to select a destination '+
                                                                                'directory for the extracted content each time you use Mobiunpack.'))
        directory_group_box_layout.addWidget(self.default_folder_check)
        # Load the checkbox with the current preference setting
        self.default_folder_check.setChecked(plugin_prefs['Always_Use_Unpack_Folder'])

        misc_group_box = QGroupBox(_('Default settings:'), self)
        layout.addWidget(misc_group_box)
        misc_group_box_layout = QVBoxLayout()
        misc_group_box.setLayout(misc_group_box_layout)

        self.use_hd_images = QCheckBox(_('Always use HD images if present'), self)
        self.use_hd_images.setToolTip(_('<p>When checked... any HD images present in the kindlebook '+
                                                                                'will be used for creating the ePub.'))
        misc_group_box_layout.addWidget(self.use_hd_images)
        # Load the checkbox with the current preference setting
        self.use_hd_images.setChecked(plugin_prefs['Use_HD_Images'])

        combo_label = QLabel('Select epub version output:', self)
        misc_group_box_layout.addWidget(combo_label)
        self.epub_version_combobox = QComboBox()
        self.epub_version_combobox.setToolTip(_('<p>Select the type of OPF file to create.'))
        misc_group_box_layout.addWidget(self.epub_version_combobox)
        self.epub_version_combobox.addItems(['Auto-detect', 'ePub2', 'ePub3'])
        if plugin_prefs['Epub_Version'] == 'A':
            self.epub_version_combobox.setCurrentIndex(0)
        else:
            self.epub_version_combobox.setCurrentIndex(int(plugin_prefs['Epub_Version'])-1)

    def save_settings(self):
        # Save current dialog sttings back to JSON config file
            plugin_prefs['Unpack_Folder'] = unicode(self.directory_txtBox.displayText())
            plugin_prefs['Always_Use_Unpack_Folder'] = self.default_folder_check.isChecked()
            plugin_prefs['Use_HD_Images'] = self.use_hd_images.isChecked()
            if unicode(self.epub_version_combobox.currentText()) == 'Auto-detect':
                plugin_prefs['Epub_Version'] = 'A'
            else:
                plugin_prefs['Epub_Version'] = unicode(self.epub_version_combobox.currentText())[4:]

    def getDirectory(self):
        c = choose_dir(self, _(PLUGIN_NAME + 'dir_chooser'),
                _('Select Default Directory To Unpack Kindle Book/Mobi To'))
        if c:
            self.directory_txtBox.setReadOnly(False)
            self.directory_txtBox.setText(c)
            self.directory_txtBox.setReadOnly(True)

    def validate(self):
        # This is just to catch the situation where somone might
        # manually enter a non-existent path in the Default path textbox.
        # Shouldn't be possible at this point.
        if not os.path.exists(self.directory_txtBox.text()):
            errmsg = '<p>The path specified for the Default Unpack folder does not exist.</p>' \
                        '<p>Your latest preference changes will <b>NOT</b> be saved!</p>' + \
                        '<p>You should configure again and make sure your settings are correct.'
            error_dialog(None, _(PLUGIN_NAME + ' v' + PLUGIN_VERSION),
                                    _(errmsg), show=True)
            return False
        return True
示例#30
0
class SourceSelectorDialog(QDialog):
    def __init__(self, parent, flags=Qt.WindowFlags()):
        QDialog.__init__(self, parent, flags)
        self.setModal(False)
        self.setWindowTitle("Select sources by...")
        lo = QVBoxLayout(self)
        lo.setContentsMargins(10, 10, 10, 10)
        lo.setSpacing(5)
        # select by
        lo1 = QHBoxLayout()
        lo.addLayout(lo1)
        lo1.setContentsMargins(0, 0, 0, 0)
        #    lab = QLabel("Select:")
        #   lo1.addWidget(lab)
        self.wselby = QComboBox(self)
        lo1.addWidget(self.wselby, 0)
        self.wselby.activated[str].connect(self._setup_selection_by)
        # under/over
        self.wgele = QComboBox(self)
        lo1.addWidget(self.wgele, 0)
        self.wgele.addItems([">", ">=", "<=", "<", "sum<=", "sum>", "=="])
        self.wgele.activated[str].connect(self._select_threshold)
        # threshold value
        self.wthreshold = QLineEdit(self)
        self.wthreshold.editingFinished.connect(self._select_threshold)
        lo1.addWidget(self.wthreshold, 1)
        # min and max label
        self.wminmax = QLabel(self)
        lo.addWidget(self.wminmax)
        # selection slider
        lo1 = QHBoxLayout()
        lo.addLayout(lo1)
        self.wpercent = QSlider(self)
        self.wpercent.setTracking(False)
        self.wpercent.valueChanged[int].connect(self._select_percentile)
        self.wpercent.sliderMoved[int].connect(
            self._select_percentile_threshold)
        self.wpercent.setRange(0, 100)
        self.wpercent.setOrientation(Qt.Horizontal)
        lo1.addWidget(self.wpercent)
        self.wpercent_lbl = QLabel("0%", self)
        self.wpercent_lbl.setMinimumWidth(64)
        lo1.addWidget(self.wpercent_lbl)
        #    # hide button
        #    lo.addSpacing(10)
        #    lo2 = QHBoxLayout()
        #    lo.addLayout(lo2)
        #    lo2.setContentsMargins(0,0,0,0)
        #    hidebtn = QPushButton("Close",self)
        #    hidebtn.setMinimumWidth(128)
        #    QObject.connect(hidebtn,pyqtSignal("clicked()"),self.hide)
        #    lo2.addStretch(1)
        #    lo2.addWidget(hidebtn)
        #    lo2.addStretch(1)
        #    self.setMinimumWidth(384)
        self._in_select_threshold = False
        self._sort_index = None
        self.qerrmsg = QErrorMessage(self)

    def resetModel(self):
        """Resets dialog based on current model."""
        if not self.model:
            return
        # getset of model tags, and remove the non-sorting tags
        alltags = set(self.model.tagnames)
        alltags -= NonSortingTags
        # make list of tags from StandardTags that are present in model
        self.sorttags = [
            tag for tag in StandardTags
            if tag in alltags or tag in TagAccessors
        ]
        # append model tags that were not in StandardTags
        self.sorttags += list(alltags - set(self.sorttags))
        # set selector
        self.wselby.clear()
        self.wselby.addItems(self.sorttags)
        for tag in "Iapp", "I":
            if tag in self.sorttags:
                self.wselby.setCurrentIndex(self.sorttags.index(tag))
                break
        self._setup_selection_by(self.wselby.currentText())

    def _reset_percentile(self):
        self.wthreshold.setText("")
        self.wpercent.setValue(50)
        self.wpercent_lbl.setText("--%")

    def _setup_selection_by(self, tag):
        tag = str(tag)  # may be QString
        # clear threshold value and percentiles
        self._reset_percentile()
        # get min/max values, and sort indices
        # _sort_index will be an array of (value,src,cumsum) tuples, sorted by tag value (high to low),
        # where src is the source, and cumsum is the sum of all values in the list from 0 up to and including the current one
        self._sort_index = []
        minval = maxval = value = None
        for isrc, src in enumerate(self.model.sources):
            try:
                if hasattr(src, tag):
                    # test if item can be cast to float
                    try:
                        float(getattr(src, tag))
                    except:
                        continue
                    else:
                        value = float(getattr(src, tag))

                elif tag in TagAccessors:
                    value = float(TagAccessors[tag](src))
                else:  # not existant for this source (maybe a tag or something??)
                    value = np.nan
            # skip source if failed to access this tag as a float
            except:
                traceback.print_exc()
                continue
            if value is not None:
                self._sort_index.append(
                    [value if not np.isnan(value) else -np.inf, src, 0.])
                minval = min(minval, value if not np.isnan(value) else
                             np.inf) if minval is not None else value
                maxval = max(maxval, value if not np.isnan(value) else
                             -np.inf) if maxval is not None else value
        # add label
        if minval is None:
            self._range = None
            self.wminmax.setText(
                "<font color=red>'%s' is not a numeric attribute</font>" % tag)
            for w in self.wgele, self.wthreshold, self.wpercent, self.wpercent_lbl:
                w.setEnabled(False)
        else:
            self._range = (minval, maxval)
            self.wminmax.setText("min: %g max: %g" % self._range)
            for w in self.wgele, self.wthreshold, self.wpercent, self.wpercent_lbl:
                w.setEnabled(True)
        # sort index by descending values
        self._sort_index.sort(reverse=True, key=operator.itemgetter(0))
        # generate cumulative sums
        cumsum = 0.
        for entry in self._sort_index:
            if not np.isneginf(entry[0]):
                cumsum += entry[0]
            entry[2] = cumsum

    # Maps comparison operators to callables. Used in _select_threshold.
    # Each callable takes two arguments: e is a tuple of (value,src,cumsum) (see _sort_index above), and x is a threshold
    # Second argument is a flag: if False, selection is inverted w.r.t. operator
    Operators = {
        "<": ((lambda e, x: e[0] >= x), False),
        "<=": ((lambda e, x: e[0] > x), False),
        ">": ((lambda e, x: e[0] > x), True),
        ">=": ((lambda e, x: e[0] >= x), True),
        "sum<=": ((lambda e, x: e[2] <= x), True),
        "sum>": ((lambda e, x: e[2] <= x), False),
        "==": ((lambda e, x: np.abs(e[0] - x) < 1.0e-8), True),
    }

    def _select_threshold(self, *dum):
        dprint(1, "select_threshold", dum)
        self._in_select_threshold = True
        busy = BusyIndicator()
        try:
            # get threshold, ignore if not set
            threshold = str(self.wthreshold.text())
            if not threshold:
                self._reset_percentile()
                return
            # try to parse threshold, ignore if invalid
            try:
                threshold = float(threshold)
            except:
                self._reset_percentile()
                return
            # get comparison operator
            op, select = self.Operators[str(self.wgele.currentText())]
            # apply to initial segment (that matches operator)
            for num, entry in enumerate(self._sort_index):
                if not op(entry, threshold):
                    break
                entry[1].selected = select
            else:
                num = len(self._sort_index)
            # apply to remaining segment
            for val, src, cumsum in self._sort_index[num:]:
                src.selected = not select
            # set percentile
            percent = round(float(num * 100) / len(self._sort_index))
            if not select:
                percent = 100 - percent
            self.wpercent.setValue(percent)
            self.wpercent_lbl.setText("%3d%%" % percent)
            # emit signal
            self.model.emitSelection(self)
        finally:
            self._in_select_threshold = False
            busy.reset_cursor()

    def _select_percentile(self, percent):
        self._select_percentile_threshold(percent, do_select=True)

    def _select_percentile_threshold(self, percent, do_select=False):
        # ignore if no sort index set up, or if _select_threshold() is being called
        if self._sort_index is None or self._in_select_threshold:
            return
        dprint(1, "select_precentile_threshold", percent)
        busy = BusyIndicator()
        # number of objects to select
        nsrc = len(self._sort_index)
        nsel = int(math.ceil(nsrc * float(percent) / 100))
        # get comparison operator
        opstr = str(self.wgele.currentText())
        op, select = self.Operators[opstr]
        # select head or tail of list, depending on direction of operator
        if select:
            thr = self._sort_index[min(nsel, nsrc - 1)]
            slc1 = slice(0, nsel)
            slc2 = slice(nsel, None)
        else:
            thr = self._sort_index[-min(nsel + 1, nsrc)]
            slc1 = slice(nsrc - nsel, None)
            slc2 = slice(0, nsrc - nsel)
        if do_select:
            for val, src, cumsum in self._sort_index[slc1]:
                src.selected = True
            for val, src, cumsum in self._sort_index[slc2]:
                src.selected = False
            self.model.emitSelection(self)
        self.wpercent_lbl.setText("%3d%%" % percent)
        self.wthreshold.setText(
            "%g" % (thr[2] if opstr.startswith("sum") else thr[0]))
        busy.reset_cursor()
        return nsel

    def setModel(self, model):
        """Sets the current model. If dialog is visible, applies the changes"""
        self.model = model
        if self.isVisible():
            self.resetModel()
        if not model:
            self.hide()

    def show(self):
        """Shows dialog, resetting the model if it was invisible."""
        if not self.isVisible():
            self.resetModel()
        QDialog.show(self)
示例#31
0
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Biyao'
        self.option = webdriver.ChromeOptions()
        self.option.add_argument('headless')
        self.web = webdriver.Chrome(chrome_options=self.option)
        self.web.get(
            'https://www.supremecommunity.com/season/spring-summer2019/droplists/'
        )
        self.web.find_element_by_id('box-latest').click()
        self.soup = BeautifulSoup(self.web.page_source, 'html5lib')
        self.item_list = ['']
        for items in self.soup.find_all(
                'h2', class_='name item-details item-details-title'):
            self.item = items.text.strip()
            self.item_list.append(self.item)
        self.createWindow()

    def createWindow(self):
        self.status = True
        self.cateStatus = ''
        self.sizes = ''
        self.setWindowTitle(self.title)
        self.item = ''
        self.color = ''

        #Button
        self.button1 = QPushButton('Start Running', self)
        self.button1.clicked.connect(
            lambda: search.run(self, self.cateStatus, self.status, self.sizes,
                               self.color, self.item))
        self.button2 = QPushButton('Purchase', self)
        self.button2.clicked.connect(lambda: search.purchase(self))
        self.button3 = QPushButton('Close', self)
        self.button3.clicked.connect(lambda: self.close())
        self.button4 = QPushButton('Add item', self)

        #Dropdown menu
        Options = ['', 'True', 'False']
        self.TF = QComboBox(self)
        self.TF.addItems(Options)
        self.TF.activated[str].connect(self.changeOption)

        CateOptions = [
            '', 'jackets', 'shirts', 'tops/sweaters', 'sweatshirts', 'pants',
            'shorts', 't-shirts', 'hats', 'bags', 'accessories'
        ]
        self.cateBox = QComboBox(self)
        self.cateBox.addItems(CateOptions)
        self.cateBox.activated[str].connect(self.changeCateOption)

        sizeOption = ['', 'Small', 'Medium', 'Large']
        self.sizeBox = QComboBox(self)
        self.sizeBox.addItems(sizeOption)
        self.sizeBox.activated[str].connect(self.changeSize)

        itemList = self.item_list
        self.itemBox = QComboBox(self)
        self.itemBox.addItems(itemList)
        self.itemBox.activated[str].connect(self.changeitem)

        #Textbox
        self.EnterColor = QLineEdit(self)
        self.EnterColor.textChanged[str].connect(self.changeColor)

        #Label
        self.Name = QLabel('Name: ', self)
        self.Name.setFont(QtGui.QFont('Microsoft YaHei', 9))

        self.Category = QLabel('Category: ', self)
        self.Category.setFont(QtGui.QFont('Microsoft YaHei', 9))

        self.Sizes = QLabel('Size: ', self)
        self.Sizes.setFont(QtGui.QFont('Microsoft YaHei', 9))

        self.color = QLabel('Color(True/False): ', self)
        self.color.setFont(QtGui.QFont('Microsoft YaHei', 9))

        self.whatColor = QLabel('Color: ', self)
        self.whatColor.setFont(QtGui.QFont('Microsoft YaHei', 9))

        #Vbox
        Operation = QVBoxLayout()
        Operation.addWidget(self.button4)
        Operation.addWidget(self.button1)
        Operation.addWidget(self.button2)
        Operation.addWidget(self.button3)
        Structure = QGridLayout()
        Structure.addLayout(Operation, 4, 0)
        Structure.addWidget(self.Name, 0, 0)
        Structure.addWidget(self.itemBox, 0, 1)
        Structure.addWidget(self.Category, 1, 0)
        Structure.addWidget(self.cateBox, 1, 1)
        Structure.addWidget(self.Sizes, 2, 0)
        Structure.addWidget(self.sizeBox, 2, 1)
        Structure.addWidget(self.color, 3, 0)
        Structure.addWidget(self.TF, 3, 1)
        Structure.addWidget(self.whatColor, 3, 2)
        Structure.addWidget(self.EnterColor, 3, 3)

        #Display
        self.setLayout(Structure)
        self.show()

    def changeOption(self, tf):
        if tf == 'True':
            self.status = True
        else:
            self.status = False

    def changeColor(self, color):
        self.color = color

    def changeCateOption(self, option):
        self.cateStatus = option

    def changeSize(self, size):
        self.sizes = size

    def changeitem(self, item):
        self.item = item
示例#32
0
class PunctDialog(Dialog):
    def __init__(self, parent):
        self.prefs = self.prefsPrep()
        self.criteria = None
        self.parent = parent
        self.help_file_name = '{0}_smarten_help.html'.format(PLUGIN_SAFE_NAME)
        Dialog.__init__(self, _('Smarten Punctuation (the sequel)'), 'toolbag_smarter_dialog', parent)

    def setup_ui(self,):
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        help_layout = QHBoxLayout()
        layout.addLayout(help_layout)
        # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked.
        help_label = QLabel('<a href="http://www.foo.com/">Plugin Help</a>', self)
        help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
        help_label.setAlignment(Qt.AlignRight)
        help_label.linkActivated.connect(self.help_link_activated)
        help_layout.addWidget(help_label)

        self.edu_quotes = QCheckBox(_('Smarten Quotation marks'), self)
        layout.addWidget(self.edu_quotes)
        self.edu_quotes.setChecked(self.prefs['edu_quotes'])
        self.edu_quotes.stateChanged.connect(self.quotes_gui_changes)

        exceptions_group_box = QGroupBox('', self)
        layout.addWidget(exceptions_group_box)
        exceptions_group_box_layout = QVBoxLayout()
        exceptions_group_box.setLayout(exceptions_group_box_layout)
        self.use_file = QCheckBox(_('Use custom apostrophe exceptions file'), self)
        exceptions_group_box_layout.addWidget(self.use_file)
        if not self.edu_quotes.isChecked():
            self.use_file.setDisabled(True)
        else:
            self.use_file.setChecked(self.prefs['use_file'])
        self.use_file.stateChanged.connect(self.use_file_gui_changes)

        path_layout = QHBoxLayout()
        exceptions_group_box_layout.addLayout(path_layout)
        self.file_path = QLineEdit('', self)
        if not self.edu_quotes.isChecked() and not self.use_file.isChecked():
            self.file_path.setReadOnly(True)
        else:
            self.file_path.setText(self.prefs['file_path'])
            self.file_path.setReadOnly(True)
        path_layout.addWidget(self.file_path)
        self.file_button = QPushButton('...', self)
        self.file_button.clicked.connect(self.getFile)
        path_layout.addWidget(self.file_button)
        if not self.edu_quotes.isChecked() and not self.use_file.isChecked():
            self.file_button.setDisabled(True)

        combo_layout = QVBoxLayout()
        layout.addLayout(combo_layout)
        label = QLabel(_('(em|en)-dash settings'), self)
        combo_layout.addWidget(label)
        self.dashes_combo = QComboBox()
        combo_layout.addWidget(self.dashes_combo)
        values = [_('Do not educate dashes'), _('-- = emdash (no endash support)'),
                  _('-- = emdash | --- = endash'), _('--- = emdash | -- = endash')]
        self.dashes_combo.addItems(values)
        self.dashes_combo.setCurrentIndex(self.prefs['dashes'])
        # self.dashes_combo.currentIndexChanged.connect(self.update_gui)

        self.ellipses = QCheckBox(_('Smarten ellipses'), self)
        layout.addWidget(self.ellipses)
        self.ellipses.setChecked(self.prefs['ellipses'])

        self.unicode = QCheckBox(_('Educate with unicode characters (instead of entities)'), self)
        layout.addWidget(self.unicode)
        self.unicode.setChecked(self.prefs['unicode'])

        layout.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def getFile(self):
        unique_dlg_name = '{0}plugin:smarter_choose_dialog'.format(PLUGIN_SAFE_NAME)
        caption = _('Select custom apostrophe exceptions file')
        filters = [('Text files', ['txt'])]
        c = choose_files(self, unique_dlg_name, caption, filters, all_files=True)

        if c:
            self.file_path.setReadOnly(False)
            self.file_path.setText(c[0])
            self.file_path.setReadOnly(True)

    def _ok_clicked(self):
        quotes_setting = 'q' if self.edu_quotes.isChecked() else ''
        if self.dashes_combo.currentIndex() == 0:
            dash_setting = ''
        elif self.dashes_combo.currentIndex() == 1:
            dash_setting = 'd'
        elif self.dashes_combo.currentIndex() == 2:
            dash_setting = 'i'
        elif self.dashes_combo.currentIndex() == 3:
            dash_setting = 'D'
        else:
            dash_setting = ''
        ellipses_setting = 'e' if self.ellipses.isChecked() else ''
        smarty_attr = quotes_setting + dash_setting + ellipses_setting
        if smarty_attr == '':
            smarty_attr = '0'

        self.file_path.setReadOnly(False)
        if self.use_file.isChecked() and not len(self.file_path.displayText()):
            self.file_path.setReadOnly(True)
            return error_dialog(self.parent, _('Error'), '<p>' +
                    _('Must select a custom exception file'), det_msg='', show=True)
        if self.use_file.isChecked():
            apos_exception_file = unicode(self.file_path.displayText())
            if not os.path.exists(apos_exception_file):
                apos_exception_file = None
        else:
            apos_exception_file = None
        self.file_path.setReadOnly(True)
        apos_words_list = []
        if apos_exception_file is not None:
            apos_words_list = self.parseExceptionsFile(os.path.normpath(apos_exception_file))
        self.criteria = (smarty_attr, self.unicode.isChecked(), apos_words_list)
        self.savePrefs()
        self.accept()

    def getCriteria(self):
        return self.criteria

    def quotes_gui_changes(self):
        if self.edu_quotes.isChecked():
            self.use_file.setDisabled(False)
            if self.use_file.isChecked():
                self.file_button.setDisabled(False)
        else:
            self.use_file.setChecked(False)
            self.file_path.setReadOnly(False)
            self.file_path.clear()
            self.file_path.setReadOnly(True)
            self.use_file.setDisabled(True)
            self.file_button.setDisabled(True)

    def use_file_gui_changes(self):
        if self.use_file.isChecked():
            self.file_button.setDisabled(False)
        else:
            self.file_path.setReadOnly(False)
            self.file_path.clear()
            self.file_path.setReadOnly(True)
            self.file_button.setDisabled(True)

    def prefsPrep(self):
        from calibre.utils.config import JSONConfig
        plugin_prefs = JSONConfig('plugins/{0}_SmarterPunct_settings'.format(PLUGIN_SAFE_NAME))
        plugin_prefs.defaults['edu_quotes'] = True
        plugin_prefs.defaults['use_file'] = False
        plugin_prefs.defaults['file_path'] = ''
        plugin_prefs.defaults['dashes'] = 1
        plugin_prefs.defaults['ellipses'] = True
        plugin_prefs.defaults['unicode'] = True
        return plugin_prefs

    def savePrefs(self):
        self.prefs['edu_quotes'] = self.edu_quotes.isChecked()
        self.prefs['use_file'] = self.use_file.isChecked()
        self.prefs['file_path'] = unicode(self.file_path.displayText()) if len(self.file_path.displayText()) else ''
        self.prefs['dashes'] = self.dashes_combo.currentIndex()
        self.prefs['ellipses'] = self.ellipses.isChecked()
        self.prefs['unicode'] = self.unicode.isChecked()

    def help_link_activated(self, url):
        def get_help_file_resource():
            # Copy the HTML helpfile to the plugin directory each time the
            # link is clicked in case the helpfile is updated in newer plugins.
            file_path = os.path.join(config_dir, 'plugins', self.help_file_name)
            with open(file_path,'w') as f:
                f.write(load_resource('resources/{}'.format(self.help_file_name)))
            return file_path
        url = 'file:///' + get_help_file_resource()
        open_url(QUrl(url))

    def parseExceptionsFile(self, filename):
        import os, codecs, chardet
        words_list = []
        bytes = min(32, os.path.getsize(filename))
        raw = open(filename, 'rb').read(bytes)
        if raw.startswith(codecs.BOM_UTF8):
            enc = 'utf-8-sig'
        else:
            result = chardet.detect(raw)
            enc = result['encoding']
        try:
            with codecs.open(filename, encoding=enc, mode='r') as fd:
                words_list = [line.rstrip() for line in fd]
            words_list = filter(None, words_list)
            print('Exceptions list:', words_list)
        except:
            pass
        return words_list
示例#33
0
class RemoveDialog(Dialog):
    def __init__(self, parent):
        from calibre_plugins.diaps_toolbag.span_div_config import plugin_prefs as prefs
        self.criteria = None
        self.prefs = prefs
        self.parent = parent
        self.help_file_name = '{0}_span_div_help.html'.format(PLUGIN_SAFE_NAME)
        self.taglist = TAGLIST
        Dialog.__init__(self, _('Edit Spans & Divs'), 'toolbag_spans_divs_dialog', parent)

    def setup_ui(self):
        DELETE_STR = _('Delete')
        MODIFY_STR = _('Modify')
        NO_ATTRIB_STR = _('No attributes ("naked" tag)')
        self.NO_CHANGE_STR = _('No change')

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        help_layout = QHBoxLayout()
        layout.addLayout(help_layout)
        # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked.
        help_label = QLabel('<a href="http://www.foo.com/">Plugin Help</a>', self)
        help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
        help_label.setAlignment(Qt.AlignRight)
        help_label.linkActivated.connect(self.help_link_activated)
        help_layout.addWidget(help_label)

        action_layout = QHBoxLayout()
        layout.addLayout(action_layout)
        label = QLabel(_('Action type:'), self)
        action_layout.addWidget(label)
        self.action_combo = QComboBox()
        action_layout.addWidget(self.action_combo)
        self.action_combo.addItems([DELETE_STR, MODIFY_STR])
        self.action_combo.currentIndexChanged.connect(self.update_gui)

        tag_layout = QHBoxLayout()
        layout.addLayout(tag_layout)
        label = QLabel(_('Tag name:'), self)
        tag_layout.addWidget(label)
        self.tag_combo = QComboBox()
        tag_layout.addWidget(self.tag_combo)
        self.tag_combo.addItems(self.taglist)
        self.tag_combo.currentIndexChanged.connect(self.update_gui)

        attr_layout = QHBoxLayout()
        layout.addLayout(attr_layout)
        label = QLabel(_('Having the attribute:'), self)
        attr_layout.addWidget(label)
        self.attr_combo = QComboBox()
        attr_layout.addWidget(self.attr_combo)
        self.attr_combo.addItems(self.prefs['attrs'])
        self.attr_combo.addItem(NO_ATTRIB_STR)
        self.attr_combo.currentIndexChanged.connect(self.update_gui)

        srch_layout = QHBoxLayout()
        layout.addLayout(srch_layout)
        label = QLabel(_("Whose value is (no quotes):"), self)
        srch_layout.addWidget(label)
        self.srch_txt = QLineEdit('', self)
        srch_layout.addWidget(self.srch_txt)
        self.srch_method = QCheckBox(_('Regex'), self)
        srch_layout.addWidget(self.srch_method)

        newtag_layout = QHBoxLayout()
        layout.addLayout(newtag_layout)
        label = QLabel(_('Change tag to:'), self)
        newtag_layout.addWidget(label)
        self.newtag_combo = QComboBox()
        newtag_layout.addWidget(self.newtag_combo)

        self.newtag_combo.addItem(self.NO_CHANGE_STR)
        self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))])

        if self.action_combo.currentIndex() == 0:
            self.newtag_combo.setDisabled(True)

        newattr_layout = QVBoxLayout()
        layout.addLayout(newattr_layout)
        label = QLabel(_('New attribute string to insert (entire):'), self)
        newattr_layout.addWidget(label)
        self.newattr_txt = QLineEdit('', self)
        newattr_layout.addWidget(self.newattr_txt)
        self.copy_attr = QCheckBox(_('Copy existing attribute string'), self)
        self.copy_attr.stateChanged.connect(self.update_txt_box)
        newattr_layout.addWidget(self.copy_attr)
        if self.action_combo.currentIndex() == 0:
            self.copy_attr.setDisabled(True)
            self.newattr_txt.setDisabled(True)

        layout.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def update_gui(self):
        if self.attr_combo.currentIndex() == self.attr_combo.count()-1:
            self.srch_txt.clear()
            self.srch_txt.setDisabled(True)
            self.srch_method.setChecked(False)
            self.srch_method.setDisabled(True)
        else:
            self.srch_txt.setDisabled(False)
            self.srch_method.setDisabled(False)

        self.newtag_combo.clear()
        self.newtag_combo.addItem(self.NO_CHANGE_STR)
        self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))])

        if self.action_combo.currentIndex() == 0:
            self.newtag_combo.setCurrentIndex(0)
            self.newtag_combo.setDisabled(True)
            self.newattr_txt.clear()
            self.newattr_txt.setDisabled(True)
            self.copy_attr.setChecked(False)
            self.copy_attr.setDisabled(True)
        else:
            self.newtag_combo.setDisabled(False)
            self.newattr_txt.setDisabled(False)
            self.copy_attr.setDisabled(False)

    def update_txt_box(self):
        if self.copy_attr.isChecked():
            self.newattr_txt.clear()
            self.newattr_txt.setDisabled(True)
        else:
            self.newattr_txt.setDisabled(False)

    def _ok_clicked(self):
        if self.action_combo.currentIndex() == 0:
            action = 'delete'
        else:
            action = 'modify'
        if self.attr_combo.currentIndex() == self.attr_combo.count()-1:
            attribute = None
        else:
            attribute = unicode(self.attr_combo.currentText())
        srch_str = unicode(self.srch_txt.displayText())
        if not len(srch_str):
            srch_str = None
        if srch_str is None and attribute is not None:
            return error_dialog(self.parent, _('Error'), '<p>{0}'.format(
                    _('Must enter a value for the attribute selected')), det_msg='', show=True)
        srch_method = 'normal'
        if self.srch_method.isChecked():
            srch_method = 'regex'
        if self.newtag_combo.currentIndex() == 0:
            newtag = None
        else:
            newtag = unicode(self.newtag_combo.currentText())
        if action == 'modify' and newtag is None and self.copy_attr.isChecked():
            return error_dialog(self.parent, _('Error'), '<p>{0}'.format(
                    _('What--exactly--would that achieve?')), det_msg='', show=True)
        new_str = unicode(self.newattr_txt.displayText())
        copy_attr = False
        if self.copy_attr.isChecked():
            copy_attr = True
        if not len(new_str):
            new_str = ''

        self.criteria = (srch_str, srch_method, unicode(self.tag_combo.currentText()), attribute, action, newtag, new_str, copy_attr)
        self.accept()

    def getCriteria(self):
        return self.criteria

    def help_link_activated(self, url):
        def get_help_file_resource():
            # Copy the HTML helpfile to the plugin directory each time the
            # link is clicked in case the helpfile is updated in newer plugins.
            file_path = os.path.join(config_dir, 'plugins', self.help_file_name)
            with open(file_path,'w') as f:
                f.write(load_resource('resources/{}'.format(self.help_file_name)))
            return file_path
        url = 'file:///' + get_help_file_resource()
        open_url(QUrl(url))
示例#34
0
class StartMenu(QWidget):
    
    def __init__(self, parent):
        super(StartMenu, self).__init__(parent)
        
        self.tophbox = QHBoxLayout()
        self.hbox = QHBoxLayout()
        self.vbox = QVBoxLayout()
        
        self.label = QLabel()
        self.label.setPixmap(QPixmap('img/new-game.png'))
        self.label.setScaledContents(True)
        self.label.setFixedSize(600, 200)
        self.tophbox.addWidget(self.label)
        
        self.startbutton = Button(self, 'Start')
        self.startbutton.setEnabled(False)
        self.startbutton.setFixedHeight(100)
        self.tophbox.addWidget(self.startbutton)
        
        self.playeramt_label = QLabel('Number of players:')
        self.playeramt_label.setFixedWidth(125)
        
        self.playeramount = QComboBox()
        self.playeramount.setStyleSheet('color: rgb(0, 0, 0)')
        self.playeramount.setFixedWidth(50)
        self.playeramount.addItems([str(i) for i in range(2, 13)])
        self.playeramount.setCurrentIndex(2)
        self.playeramount.setMaxVisibleItems(11)
        self.playeramount.currentTextChanged.connect(self.form_player_entries)
        
        self.score_label = QLabel('Score limit:')
        self.score_label.setFixedWidth(65)
        
        self.score_limit = QLineEdit()
        self.score_limit.setMaximumWidth(40)
        self.score_limit.setPalette(QPalette(Qt.white))
        self.score_limit.setText('16')
        
        self.mode_label = QLabel('Game Mode:')
        self.mode_label.setFixedWidth(85)
        
        self.mode_select = QComboBox()
        self.mode_select.addItems(['Deal-1', 'Deal-4'])
        self.mode_select.setPalette(QPalette(Qt.white))
        self.mode_select.setFixedWidth(100)
        self.mode_select.currentTextChanged.connect(self.update_playeramount)
            
        self.autofill_button = Button(self, 'Auto Fill')
        self.autofill_button.clicked.connect(self.auto_fill)
        self.clear_button = Button(self, 'Clear All')
        self.clear_button.clicked.connect(self.clear_all)
        
        self.player_entries = QVBoxLayout()
        
        self.spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        
        self.hbox.addWidget(self.playeramt_label)
        self.hbox.addWidget(self.playeramount)
        self.hbox.addWidget(self.score_label)
        self.hbox.addWidget(self.score_limit)
        self.hbox.addWidget(self.mode_label)
        self.hbox.addWidget(self.mode_select)
        self.hbox.addWidget(self.autofill_button)
        self.hbox.addWidget(self.clear_button)
        
        self.vbox.addLayout(self.tophbox)
        self.vbox.addLayout(self.hbox)
        self.vbox.addLayout(self.player_entries)
        self.vbox.addItem(self.spacer)
        
        self.setLayout(self.vbox)
        
        self.form_player_entries() 


    def form_player_entries(self):
        amt = self.playeramount.currentIndex() + 2  #desired amount of player entries
        curr = self.player_entries.count()          #current amount of player entries
        dif = amt - self.player_entries.count()     #difference between desired and current entries
        
        if dif < 0:                                 #if too many entries currently 
            for i in range(curr-1, amt-1, -1):      #remove starting from last entry
                rm = self.player_entries.itemAt(i).widget()
                self.player_entries.removeWidget(rm)
                rm.setParent(None)
                
        
        else:                                       #if too few entries, add until desired amount reached
            for i in range(dif):
                new_entry = PlayerInfoField(self, self.player_entries.count())
                new_entry.name_field.textChanged.connect(self.check_filled)
                self.player_entries.addWidget(new_entry)
         
        self.check_filled()       
    
    
    def check_filled(self): #Enables start button when player fields are correctly filled
        ready = True
        
        for i in range(self.player_entries.count()):
            entry = self.player_entries.itemAt(i).widget()
            if entry.name_field.text() == '':
                ready = False
                break
            
        if ready:
            self.startbutton.setEnabled(True)
        else:
            self.startbutton.setEnabled(False)
            
                
    def auto_fill(self): #Generates fills the rest of the form automatically
        for i in range(self.player_entries.count()):
            entry = self.player_entries.itemAt(i).widget()
            if entry.name_field.text() == '':
                entry.generate_name()
                entry.AItoggle.setChecked(True)
                
    def clear_all(self):
        for i in range(self.player_entries.count()):
            entry = self.player_entries.itemAt(i).widget()
            entry.name_field.clear()
            entry.AItoggle.setChecked(False)
            
    def update_playeramount(self, mode):
        ind = self.playeramount.currentIndex()
        if mode == 'Deal-1': #Limit max players to 12
            self.playeramount.clear()
            self.playeramount.addItems([str(i) for i in range(2, 13)])
            self.playeramount.setCurrentIndex(ind)
            
        if mode == 'Deal-4': #Limit max players to 4
            self.playeramount.clear()
            self.playeramount.addItems([str(i) for i in range(2, 5)])
            self.playeramount.setCurrentIndex(min(2, ind))
            
        self.check_filled()
            
                
    def extract_info_and_init_game(self): #Creates a game object based on the info 
        pointlimit = int(self.score_limit.text())
        dealmode = self.mode_select.currentIndex()
        game = Game(pointlimit, dealmode)
        
        for i in range(self.player_entries.count()):
            entry = self.player_entries.itemAt(i).widget()
            name = entry.name_field.text()
            if entry.AItoggle.isChecked():
                difficulty = entry.AIdifficulty.currentIndex()
                game.add_player(name, difficulty)
            else:
                game.add_player(name, 5)
            
        return game
示例#35
0
class ConversionDialog(Dialog):
    def __init__(self, parent, force_entire_book=False):
        self.prefs = self.prefsPrep()
        self.parent = parent
        self.force_entire_book = force_entire_book
        self.criteria = None
        Dialog.__init__(self, _('Chinese Conversion'), 'chinese_conversion_dialog', parent)

    def setup_ui(self):

        # Create layout for entire dialog
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        #Create a scroll area for the top part of the dialog
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)

        # Create widget for all the contents of the dialog except the OK and Cancel buttons
        self.scrollContentWidget = QWidget(self.scrollArea)
        self.scrollArea.setWidget(self.scrollContentWidget)
        widgetLayout = QVBoxLayout(self.scrollContentWidget)

        # Add scrollArea to dialog
        layout.addWidget(self.scrollArea)

        self.other_group_box = QGroupBox(_('Other Changes'))
        widgetLayout.addWidget(self.other_group_box)
        other_group_box_layout = QVBoxLayout()
        self.other_group_box.setLayout(other_group_box_layout)

        text_dir_layout = QHBoxLayout()
        other_group_box_layout.addLayout(text_dir_layout)
        direction_label = QLabel(_('Text Direction:'))
        text_dir_layout.addWidget(direction_label)
        self.text_dir_combo = QComboBox()
        text_dir_layout.addWidget(self.text_dir_combo)
        self.text_dir_combo.addItems([_('No Conversion'), _('Horizontal'), _('Vertical')])
        self.text_dir_combo.setToolTip(_('Select the desired text orientation'))
        self.text_dir_combo.currentIndexChanged.connect(self.update_gui)


        self.optimization_group_box = QGroupBox(_('Reader Device Optimization'))
        other_group_box_layout.addWidget(self.optimization_group_box)
        optimization_group_box_layout = QVBoxLayout()
        self.optimization_group_box.setLayout(optimization_group_box_layout)
        
        punc_group=QButtonGroup(self)
        self.text_dir_punc_none_button = QRadioButton("""No presentation optimization""")
        optimization_group_box_layout.addWidget(self.text_dir_punc_none_button)
        self.text_dir_punc_button = QRadioButton("""Optimize presentation for Readium reader""")
        self.text_dir_punc_button.setToolTip(_('Use vert/horiz punctuation presentation forms for Chrome Readium Epub3 reader'))
        optimization_group_box_layout.addWidget(self.text_dir_punc_button)
        self.text_dir_punc_kindle_button = QRadioButton("""Optimize presentation for Kindle reader""")
        self.text_dir_punc_kindle_button.setToolTip(_('Use vert/horiz puncuation presentation forms for Kindle reader'))
        optimization_group_box_layout.addWidget(self.text_dir_punc_kindle_button)
        self.text_dir_punc_none_button.toggled.connect(self.update_gui)
        self.text_dir_punc_button.toggled.connect(self.update_gui)
        self.text_dir_punc_kindle_button.toggled.connect(self.update_gui)

        source_group=QButtonGroup(self)
        self.file_source_button = QRadioButton(_('Selected File Only'))
        self.book_source_button = QRadioButton(_('Entire eBook'))
        source_group.addButton(self.file_source_button)
        source_group.addButton(self.book_source_button)
        self.source_group_box = QGroupBox(_('Source'))
        if not self.force_entire_book:
            widgetLayout.addWidget(self.source_group_box)
            source_group_box_layout = QVBoxLayout()
            self.source_group_box.setLayout(source_group_box_layout)
            source_group_box_layout.addWidget(self.file_source_button)
            source_group_box_layout.addWidget(self.book_source_button)

        layout.addSpacing(10)
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        self.button_box.accepted.connect(self._ok_clicked)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)

        if not self.force_entire_book:
            self.file_source_button.setChecked(self.prefs['use_html_file'])
            self.book_source_button.setChecked(self.prefs['use_entire_book'])
        else:
            self.file_source_button.setChecked(False)
            self.book_source_button.setChecked(True)

        self.text_dir_combo.setCurrentIndex(self.prefs['orientation'])
        self.text_dir_punc_none_button.setChecked(self.prefs['no_optimization'])
        self.text_dir_punc_button.setChecked(self.prefs['readium_optimization'])
        self.text_dir_punc_kindle_button.setChecked(self.prefs['kindle_optimization'])
        self.update_gui()

    def update_gui(self):

        if self.text_dir_combo.currentIndex() == 0:
            self.optimization_group_box.setEnabled(False)
            self.text_dir_punc_none_button.setEnabled(False)
            self.text_dir_punc_button.setEnabled(False)
            self.text_dir_punc_kindle_button.setEnabled(False)
        else:
            self.optimization_group_box.setEnabled(True)
            self.text_dir_punc_none_button.setEnabled(True)
            self.text_dir_punc_button.setEnabled(True)
            self.text_dir_punc_kindle_button.setEnabled(True)
            
    def _ok_clicked(self):

        optimization_mode = 0
        if self.text_dir_punc_button.isChecked():
            optimization_mode = 1    #Readium
        if self.text_dir_punc_kindle_button.isChecked():
            optimization_mode = 2    #Kindle
 
        self.criteria = (self.text_dir_combo.currentIndex(), optimization_mode)
        self.savePrefs()
        self.accept()

    def getCriteria(self):
        return self.criteria

    def prefsPrep(self):
        from calibre.utils.config import JSONConfig
        plugin_prefs = JSONConfig('plugins/{0}_ChineseConversion_settings'.format(PLUGIN_SAFE_NAME))
        plugin_prefs.defaults['use_html_file'] = True
        plugin_prefs.defaults['use_entire_book'] = True
        plugin_prefs.defaults['orientation'] = 0
        plugin_prefs.defaults['no_optimization'] = True
        plugin_prefs.defaults['readium_optimization'] = False
        plugin_prefs.defaults['kindle_optimization'] = False
        return plugin_prefs

    def savePrefs(self):
        self.prefs['use_html_file'] = self.file_source_button.isChecked()
        self.prefs['use_entire_book'] = self.book_source_button.isChecked()
        self.prefs['orientation'] = self.text_dir_combo.currentIndex()
        self.prefs['no_optimization'] = self.text_dir_punc_none_button.isChecked()
        self.prefs['readium_optimization'] = self.text_dir_punc_button.isChecked()
        self.prefs['kindle_optimization'] = self.text_dir_punc_kindle_button.isChecked()