Example #1
0
    def __init__(self, boundings):
        super().__init__()
        self.boundings_path = boundings
        
        self.setScene(QGraphicsScene(self))
        self.setRenderHint(QPainter.Antialiasing)
        
        config = ConfigFile()
        self.cache_path = config.readPath('cache', 'cachepath')
        self.cache_path = os.path.join(self.cache_path, 'maps')
        if not os.path.exists(self.cache_path):
            os.makedirs(self.cache_path)
        
        self.calculateNeededTiles(boundings)

        #self.scene_rect = self.scene().itemsBoundingRect()
        
        grid = QGridLayout()
        grid.setRowStretch(0, 10000)
        grid.setColumnStretch(0, 10000)
        self.setLayout(grid)
        
        zoom_in_button = QPushButton()
        zoom_in_button.setIcon(QIcon.fromTheme('zoom-in'))
        zoom_in_button.setMaximumSize(25, 25)
        grid.addWidget(zoom_in_button, 1, 1)
        zoom_in_button.clicked.connect(self.zoomInClicked)
        
        zoom_out_button = QPushButton()
        zoom_out_button.setIcon(QIcon.fromTheme('zoom-out'))
        zoom_out_button.setMaximumSize(25, 25)
        grid.addWidget(zoom_out_button, 2, 1)
        zoom_out_button.clicked.connect(self.zoomOutClicked)
Example #2
0
 def __init__(self, queue, scene):
     super().__init__()
     
     self.queue = queue
     self.scene = scene
     
     config = ConfigFile()
     self.cache_path = config.readPath('cache', 'cachepath')
     self.cache_path = os.path.join(self.cache_path, 'maps')
     if not os.path.exists(self.cache_path):
         os.makedirs(self.cache_path)
Example #3
0
    def applyStylesheet(self):
        config = ConfigFile(None, None)
        path = config.readVar('global', 'stylesheet')
        stylesheet = ''
        try:
            with open(path) as css:
                for line in css:
                    stylesheet += line

            self.display_widget.setStyleSheet(stylesheet)
        except FileNotFoundError:
            pass
Example #4
0
 def __init__(self):
     
     # copy vocables.db to config dir first
     config = ConfigFile(None, None)
     dbpath = config.readPath("vocable", "vocableDBPath")
     if not os.path.exists(dbpath):
         moveToConfigDir = ConfigDir(None, None)
         sourcepath = os.path.join(os.getcwd(), MASTER_DB_PATH)
         os.makedirs(os.path.dirname(dbpath))
         shutil.copyfile(sourcepath, dbpath)
     
     
     self.connection = sqlite3.connect(dbpath)
     self.cursor = self.connection.cursor()
Example #5
0
    def resultInMultimediaTable(self, result):
        self.display_widget.deleteLater()

        max_length = 0
        for line in result.payload:
            if len(line) > max_length:
                max_length = len(line)

        self.display_widget = QTableWidget()
        self.display_widget.setRowCount(len(result.payload))
        self.display_widget.setColumnCount(max_length)

        audio_count = 0
        config = ConfigFile(None, None)
        deckpath = config.readPath("vocable", "deckpath")
        for row, line in enumerate(result.payload):
            deckname = line[0]
            for column, item in enumerate(line):
                if self.isImage(str(item)):
                    pixmap = QPixmap()
                    pixmap.load(path.join(deckpath, deckname, str(item)))
                    pixmap = pixmap.scaled(QSize(60, 30), Qt.KeepAspectRatio)
                    image_widget = QLabel()
                    image_widget.setPixmap(pixmap)
                    self.display_widget.setCellWidget(row, column,
                                                      image_widget)
                elif self.isAudio(str(item)):
                    splitted = item.split(',')
                    if audio_count < len(splitted):
                        audio_count = len(splitted)
                    audio_widget = QAudioItems(path.join(deckpath, deckname),
                                               self.display_widget, 7,
                                               max_length)
                    audio_widget.appendPlayButtonsList(splitted, row)
                else:
                    table_item = QTableWidgetItem(str(item))
                    table_item.setFlags(Qt.ItemIsEnabled)
                    #self.unicode_fonts.applyFontToQWidget(str(item), table_item)
                    self.display_widget.setItem(row, column, table_item)

        self.display_widget.setColumnCount(max_length + audio_count)
        self.display_widget.resizeColumnsToContents()
        self.addDisplayWidget()
Example #6
0
    def __init__(self):
        super().__init__()

        config = ConfigFile(None, None)
        self.defaultDeckPath = config.readPath("vocable", "deckpath")

        while not os.path.exists(self.defaultDeckPath):
            title = "default path for decks needed"
            text = "use " + self.defaultDeckPath + " as path for saving decks?"
            reply = QMessageBox.question(self, title, text, QMessageBox.Yes,
                                         QMessageBox.No)
            if reply == QMessageBox.Yes:
                os.makedirs(self.defaultDeckPath)
            else:
                folder_path = QFileDialog.getExistingDirectory(
                    self, "Please select Folder for Decks",
                    self.defaultDeckPath)

                if folder_path:
                    if not folder_path == self.defaultDeckPath:
                        config.write("vocable", "deckpath", folder_path)
                        self.defaultDeckPath = folder_path
Example #7
0
class UnicodeFonts(object):
    
    config = ConfigFile(None, None)
    
    arabic_block = [1536, 1791]
    hebrew_block = [1424, 1535]
    greek_block = [880, 1023]
    ipa_block = [250, 687]
    
    def __init__(self):
        self.arabic_size = int(self.config.readVar("fonts", "arabic_size"))
        self.hebrew_size = int(self.config.readVar("fonts", "hebrew_size"))
        self.greek_size = int(self.config.readVar("fonts", "greek_size"))
        self.ipa_size = int(self.config.readVar("fonts", "ipa_size"))
        
        self.arabic_font = self.config.readVar("fonts", "arabic_font")
        self.hebrew_font = self.config.readVar("fonts", "hebrew_font")
        self.greek_font = self.config.readVar("fonts", "greek_font")
        self.ipa_font = self.config.readVar("fonts", "ipa_font")
        
        scriptpath = os.path.dirname(os.path.abspath(__file__))
        fonts = [
            "./assets/fonts/SILEOT.ttf",
            "./assets/fonts/Scheherazade-Regular.ttf",
            "./assets/fonts/EzraSIL2.51/SILEOT.ttf",
            "./assets/fonts/GalSIL21/GalSILR.ttf",
            "./assets/fonts/DoulosSIL-R.ttf",
        ]
        for font in fonts:
            """
            fontpath = os.getcwd() + '/' + font
            if platform.system() == 'Windows':
                fontpath = fontpath.replace('/', '\\')
            print(fontpath)
            """
            fontpath = font
            
            print("loading Font:", font.split('/')[-1], QFontDatabase.addApplicationFont(fontpath))
            
        #self.printFonts('Ezra')
        
    def isInUnicodeRange(self, start, end, string):
        result = False
        try:
            for char in string.strip():
                if ord(char) > start and ord(char) < end:
                    result = True
        except AttributeError:
            pass
        
        return result
    
    def applyFontAndSizeToQWidget(self, string, widget):
        if self.isInUnicodeRange(self.arabic_block[0], self.arabic_block[1], string):
            font = QFont(self.arabic_font, self.arabic_size, -1, False)
            widget.setFont(font)
        
        elif self.isInUnicodeRange(self.hebrew_block[0], self.hebrew_block[1], string):
            font = QFont(self.hebrew_font, self.hebrew_size, -1, False)
            widget.setFont(font)
        
        elif self.isInUnicodeRange(self.greek_block[0], self.greek_block[1], string):
            self.setFontSize(widget, self.greek_size)
        
        elif self.isInUnicodeRange(self.ipa_block[0], self.ipa_block[1], string):
            pass
    
    def applyFontToQWidget(self, string, widget):
        if self.isInUnicodeRange(self.arabic_block[0], self.arabic_block[1], string):
            widget.setFont(QFont(self.arabic_font))
        elif self.isInUnicodeRange(self.hebrew_block[0], self.hebrew_block[1], string):
            widget.setFont(QFont(self.hebrew_font))
#        elif self.isInUnicodeRange(self.greek_block[0], self.greek_block[1], string):
#            widget.setFont(QFont(self.greek_font))
    
    def setFont(self, font_category, widget):
        if font_category == 'ipa':
            widget.setFont(QFont(self.ipa_font))
            self.setFontSize(widget, self.ipa_size)
    
    def setFontSize(self, widget, size, font_name=None):
        try:
            widget.setFontPointSize(size)
        except AttributeError:
            if font_name:
                font = QFont(font_name, size)
            else:
                font = QFont()
                font.setPointSize(size)
            widget.setFont(font)
    
    def applyFontToQWidgetFiltered(self, string, widget, languages_filter):
        if 'arabic' in languages_filter:
            if self.isInUnicodeRange(self.arabic_block[0], self.arabic_block[1], string):
                widget.setFont(QFont(self.arabic_font))
        if 'hebrew' in languages_filter:
            if self.isInUnicodeRange(self.hebrew_block[0], self.hebrew_block[1], string):
                widget.setFont(QFont(self.hebrew_font))
        if 'greek' in languages_filter:
            if self.isInUnicodeRange(self.greek_block[0], self.greek_block[1], string):
                widget.setFont(QFont(self.greek_font))
    
    def printFonts(self, filter_str):
        result = []
        
        db = QFontDatabase()
        fonts = QFontDatabase.families(db)
        
        for font in fonts:
            print(font, '|', filter_str)
            
            if filter_str == None:
                print("A")
                result.append(str(font))
            
            elif filter_str in font:
                print("B")
                result.append(font)
            
        return result
Example #8
0
class Tambi(QMainWindow):

    tab_widget = None

    meta_key_pressed = False  # Windows-Key or Control-Key on Mac

    config = ConfigFile(None, None)

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

        self.initGUI()
        self.tab_widget = self.initTabs()
        self.addNewCliTab()
        #self.addNewVocableTab()
        #self.addNewMusicWidgetTab()
        #self.addNewSwordModuleManagerTab()

        self.resize(825, 670)
        self.center()

        #self.installEventFilter(self)
        #self.tab_widget.installEventFilter(self)

        QIcon.setThemeSearchPaths(['./assets/icons'])

        #for path in QIcon.themeSearchPaths():
        #    print(path, QIcon.themeName())
        QIcon.setThemeName('oxygen')
        print(QIcon.themeName())

        if len(sys.argv) > 1:
            if sys.argv[1] == "--quickrun":
                command = sys.argv[2]
                #print(command)
                self.addNewCliTabWithCommand(command)

    def center(self):
        geometry = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        center = QApplication.desktop().screenGeometry(screen).center()
        geometry.moveCenter(center)
        self.move(geometry.topLeft())

    """
    def event(self, event):
        if event.type() == QtCore.QEvent.KeyPress:
            print("KEY EVENT ::::")
            if self.meta_key_pressed and event.key() == Qt.Key_Left:
                print("LEFT ::::")
                self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex()-1)
                QMainWindow.event(self, event)
                return True
            elif self.meta_key_pressed and event.key() == Qt.Key_Right:
                print("RIGHT ::::")
                self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex()+1)
                QMainWindow.event(self, event)
                return True
            else:
                return QMainWindow.event(self, event)
        else:
            return QMainWindow.event(self, event)
    
    def eventFilter(self, a, event):
        if event.type() == QtCore.QEvent.KeyPress:
            print("eventFilter: keyPress")
            if self.meta_key_pressed and event.key() == Qt.Key_Left:
                print("LEFT", self.tab_widget.currentIndex())
                self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex()-1)
                return True
            elif self.meta_key_pressed and event.key() == Qt.Key_Right:
                print("RIGHT", self.tab_widget.currentIndex())
                self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex()+1)
                return True
            else:
                return QMainWindow.eventFilter(self, a, event)
        else:
            return QMainWindow.eventFilter(self, a, event)
        #if event.type() == QtCore.QEvent.KeyPress:
            ##print("A")
            #result = self.keyPressEvent(event)
            
            #if result:
                #return True
            #else:
                #return QMainWindow.eventFilter(self, a, event)
        #else:
            ##print("B")
            #return QMainWindow.eventFilter(self, a, event)
    """

    def keyPressEvent(self, event):
        if (event.modifiers() & Qt.ControlModifier):
            if event.key() == Qt.Key_W:
                self.closeTab(self.tab_widget.currentIndex())
        if event.key() == Qt.Key_Meta:
            self.meta_key_pressed = True
        elif self.meta_key_pressed and event.key() == Qt.Key_Up:
            print("prev")
            self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex() - 1)
        elif self.meta_key_pressed and event.key() == Qt.Key_Down:
            print("next")
            self.tab_widget.setCurrentIndex(self.tab_widget.currentIndex() + 1)
        else:
            return QMainWindow.keyPressEvent(self, event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Meta:
            self.meta_key_pressed = False

    def initGUI(self):
        self.setWindowIcon(QIcon('./assets/icons/logo2.png'))

        #self.statusBar().showMessage('Ready')

        #screen_rectangle = QDesktopWidget().availableGeometry()
        #sx, sy = screen_rectangle.getRect()[2], screen_rectangle.getRect()[3]
        #
        #self.resize(sx*0.61, sy*0.61)

        MenuBar(self)

        self.applyStylesheet()

        self.setWindowTitle('tambi')
        self.show()

    def applyStylesheet(self):
        path = self.config.readVar('global', 'stylesheet')
        stylesheet = ''
        try:
            with open(path) as css:
                for line in css:
                    stylesheet += line

            self.setStyleSheet(stylesheet)
        except FileNotFoundError:
            pass

    def initTabs(self):
        tab_widget = QTabWidget()
        tab_widget.setTabsClosable(True)
        tab_widget.setMovable(True)
        tab_widget.tabCloseRequested.connect(self.closeTab)
        self.setCentralWidget(tab_widget)

        return tab_widget

    def closeTab(self, tab_id):
        self.tab_widget.removeTab(tab_id)

    def addNewCliTab(self):
        core = QCoreTab()
        tab = core.cliTab()
        self.tab_widget.addTab(tab, "cli")

        self.activateNewTab()
        tab.set_tab_text.connect(
            partial(self.setTabText, self.tab_widget.currentIndex()))

    def addNewDualCliTab(self):
        tab = QCoreTab().dualCliTab()
        self.tab_widget.addTab(tab, "dual cli")

        self.activateNewTab()
        tab.set_tab_text.connect(
            partial(self.setTabText, self.tab_widget.currentIndex()))

    def setTabText(self, tab_id, text):
        splitted = text.split(" ")
        """
        text = ""
        for i, splinter in enumerate(splitted):
            if i == 0:
                text += splinter[:12] + " "
            else:
                text += splinter[:4] + " "
        """
        self.tab_widget.setTabText(tab_id, text)

    """ to be used internally by the menus """

    def addNewCliTabWithCommand(self, command):
        self.addNewCliTab()
        self.tab_widget.currentWidget().commandEntered(command)

    def addNewVocableTab(self):
        tab = QCoreTab().vocableTab()
        self.tab_widget.addTab(tab, "vocable")

        self.activateNewTab()

    def addNewMusicBeamerWidgetTab(self):
        tab = QCoreTab().musicBeamerTab()
        self.tab_widget.addTab(tab, "music beamer")

        self.activateNewTab()

    def addNewCustomTab(self, custom_widget, tab_name):
        self.tab_widget.addTab(custom_widget, tab_name)

        self.activateNewTab()

    def facepalm(self):
        from QCustomizedWidgets.QBeamerWindow import QBeamerWindow
        self.canvas = QBeamerWindow()
        self.canvas.setImageWithPath('./assets/images/facepalm/facepalm1.jpg')
        self.canvas.routeToScreen()
        self.canvas.showFullScreen()

    def openFile(self):
        home_path = os.path.expanduser('~')
        file_path = QFileDialog.getOpenFileName(self, "Please select File",
                                                home_path)

        print("FILEPATH:", file_path)
        if file_path != ('', ''):
            tab = QCoreTab().editorTab(file_path)
            self.tab_widget.addTab(tab, "editor")

            self.activateNewTab()

    def activateNewTab(self):
        self.tab_widget.setCurrentIndex(self.tab_widget.count() - 1)
Example #9
0
class QSwordGui(QWidget):

    interpreter = Interpreter()
    queue = queue.Queue()

    sword = Sword()

    config = ConfigFile(os.path.join('modules', 'sword'), 'sword.conf')
    history = History("history_sword")

    set_tab_text = pyqtSignal(str)

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

        self.unicode_fonts = UnicodeFonts()
        self.default_bible = self.config.readVar('global', 'default_bible')

        self.grid = QGridLayout()
        self.grid.setContentsMargins(0, 0, 0, 6)
        self.setLayout(self.grid)

        self.text_edit = QTextEditEnhanced()

        self.combo_language = QComboBox()
        self.combo_translation = QComboBox()
        self.combo_book = QComboBox()
        self.combo_chapter = QComboBox()

        self.combo_language.currentTextChanged.connect(self.languageChanged)
        self.combo_translation.currentTextChanged.connect(
            self.translationChanged)
        self.combo_book.currentTextChanged.connect(self.bookChanged)

        self.prev_verse_button = QPushButton("<")
        self.prev_verse_button.setMaximumSize(25, 25)
        self.next_verse_button = QPushButton(">")
        self.next_verse_button.setMaximumSize(25, 25)

        self.prev_verse_button.clicked.connect(self.prevChapter)
        self.next_verse_button.clicked.connect(self.nextChapter)

        self.grid.addWidget(QLabel("Language"), 0, 0)
        self.grid.addWidget(QLabel("Translation"), 0, 1)
        self.grid.addWidget(QLabel("Book"), 0, 2)
        self.grid.addWidget(QLabel("Chapter"), 0, 3)

        self.grid.addWidget(self.combo_language, 1, 0)
        self.grid.addWidget(self.combo_translation, 1, 1)
        self.grid.addWidget(self.combo_book, 1, 2)
        self.grid.addWidget(self.combo_chapter, 1, 3)
        self.grid.addWidget(self.prev_verse_button, 1, 4)
        self.grid.addWidget(self.next_verse_button, 1, 5)

        zoom_in_button = QPushButton(self)
        zoom_in_button.setIcon(QIcon.fromTheme('zoom-in'))
        zoom_in_button.clicked.connect(self.onZoomInClicked)
        zoom_in_button.setMaximumSize(25, 25)

        zoom_out_button = QPushButton(self)
        zoom_out_button.setIcon(QIcon.fromTheme('zoom-out'))
        zoom_out_button.clicked.connect(self.onZoomOutClicked)
        zoom_out_button.setMaximumSize(25, 25)

        zoom_reset_button = QPushButton(self)
        zoom_reset_button.setIcon(QIcon.fromTheme('zoom-original'))
        zoom_reset_button.clicked.connect(self.onZoomResetClicked)
        zoom_reset_button.setMaximumSize(25, 25)

        self.grid.addWidget(zoom_out_button, 1, 6)
        self.grid.addWidget(zoom_reset_button, 1, 7)
        self.grid.addWidget(zoom_in_button, 1, 8)

        self.grid.addWidget(self.text_edit, 2, 0, 1000, 9)

        self.getLanguagesForDropdown()
        self.getBooksForDropdown()

        self.setDefaultBible()
        self.restoreLastBookAndChapter()
        """ this has to be after setting the default values to avoid spamming the history on init and to avoid to much gui-updates on init """
        self.combo_chapter.currentTextChanged.connect(self.chapterChanged)

    def languageChanged(self, language):
        self.getTranslationsForDropdown(language)

    def translationChanged(self, translation):
        self.showText()

    def bookChanged(self, book):
        self.getChaptersForDropdown(book)

    def chapterChanged(self, chapter):
        self.showText()

    def prevChapter(self):
        chapter = self.combo_chapter.currentText()
        self.combo_chapter.setCurrentText(str(int(chapter) - 1))

        self.showText()

    def nextChapter(self):
        chapter = self.combo_chapter.currentText()
        self.combo_chapter.setCurrentText(str(int(chapter) + 1))

        self.showText()

    def getLanguagesForDropdown(self):
        #result = self.interpreter.interpreter('sword.languages', self.queue).payload
        result = self.sword.listLanguages(None, []).payload
        if result is None:
            self.text_edit.clear()
            self.text_edit.setText(
                "no sword modules (=bibles) installed. please install some using the \"Sword->Module Manager\" menu entry."
            )
        else:
            self.combo_language.clear()
            self.combo_language.insertItems(0, result)

    def getTranslationsForDropdown(self, language):
        #result = self.interpreter.interpreter('sword.modules '+language, self.queue).payload
        result = self.sword.listModules(None, [language]).payload

        translations = []
        for translation in result:
            translations.append(translation[0])

        self.combo_translation.clear()
        self.combo_translation.insertItems(0, translations)

    def setDefaultBible(self):
        #sword_modules = self.interpreter.interpreter('sword.modules', self.queue).payload
        sword_modules = self.sword.listModules(None, []).payload

        for module in sword_modules:
            if module[0] == self.default_bible:
                self.combo_language.setCurrentText(module[1])
                self.combo_translation.setCurrentText(self.default_bible)

    def restoreLastBookAndChapter(self):
        last = self.history.historyReadAtIndex(3)
        try:
            translation, book, chapter = last.split(" ")

            self.combo_book.setCurrentText(book)
            self.combo_chapter.setCurrentText(chapter)

            self.showText()
        except ValueError:
            # probably we have an empty history-file
            pass

    def getBooksForDropdown(self):
        #books = self.interpreter.interpreter('sword.books', self.queue).payload
        books = self.sword.books(None, []).payload

        self.combo_book.clear()
        self.combo_book.insertItems(0, books)

    def getChaptersForDropdown(self, book):
        books = self.sword.canons()

        for testament in books:
            for _b in books[testament]:
                if _b[0] == book:
                    chapters = []
                    for i, length in enumerate(_b[3]):
                        chapters.append(str(i + 1))

                    self.combo_chapter.clear()
                    self.combo_chapter.insertItems(0, chapters)
                    break

            # if the inner 'break' was executed, we also want to break the outer loop:
            else:
                continue  # executed if the loop ended normally (no break)
            break  # executed if 'continue' was skipped (break)

    def showText(self):
        current_translation = self.interpreter.interpreter(
            'sword.getModule', self.queue).payload

        translation = self.combo_translation.currentText()
        book = self.combo_book.currentText()
        chapter = self.combo_chapter.currentText()

        if translation:
            self.interpreter.interpreter('sword.setModule ' + translation,
                                         self.queue)
            text = self.interpreter.interpreter(
                'sword.word "' + book + '" ' + chapter, self.queue)
            text = text.toString()
            self.interpreter.interpreter(
                'sword.setModule ' + current_translation, self.queue)

            self.text_edit.clear()
            self.text_edit.setText(text)
            self.text_edit.append("\nEND")
            self.text_edit.setReadOnly(True)

            self.text_edit.setTextInteractionFlags(
                self.text_edit.textInteractionFlags()
                | Qt.TextSelectableByKeyboard)

            self.unicode_fonts.applyFontAndSizeToQWidget(text, self.text_edit)

            if book and chapter:
                self.set_tab_text.emit(translation + ": " + book + " " +
                                       chapter)
                self.history.historyWrite(translation + ": " + book + " " +
                                          chapter)

    def onZoomInClicked(self):
        self.text_edit.zoomIn()

    def onZoomOutClicked(self):
        self.text_edit.zoomOut()

    def onZoomResetClicked(self):
        self.text_edit.zoomReset()
Example #10
0
class Sword(object):

    config = ConfigFile(os.path.join('modules', 'sword'), 'sword.conf')

    def __init__(self):
        self.current_module = self.config.readVar('global', 'default_bible')
        self.canon = self.config.readVar('global', 'default_canon')

    def getCommands(self):
        return {
            "sword.commands": self.commands,
            "sword.history": self.history,
            "sword.books": self.books,
            "sword.aliases": self.booksAliases,
            #"sword.structure": self.structure,
            "sword.canons": self.listCanons,
            "sword.setCanon": self.setCanon,
            "sword.getCanon": self.getCanon,
            "sword.word": self.word,
            "sword": self.word,
            "sword.modules": self.listModules,
            "sword.getModule": self.getCurrentModule,
            "sword.setModule": self.setCurrentModule,
            "sword.languages": self.listLanguages,
        }

    def interpreter(self, command, args, queue):
        commands = self.getCommands()
        return commands.get(command, self.commandNotFound)(command, args)

    def commandNotFound(self, c, a):
        print("not found in SWORD")
        raise CommandNotInThisModule("command not found in module sword")

    def commands(self, none1, none2):
        dic = self.getCommands()

        commands = sorted(dic.items())

        all_commands = []
        for key in commands:
            line = str(key).split(",")[0]
            all_commands.append(str(line[2:-1]))

        result_object = Result()
        result_object.category = "list"
        result_object.payload = all_commands
        return result_object

    def history(self, c, args):
        history = History("history_sword")
        if len(args) < 1:
            result = history.historyReadAll()
        else:
            result = history.historyReadAllWithFilter(args[0])

        result_object = Result()
        result_object.payload = result[::-1]
        result_object.category = "list"
        return result_object

    def listModules(self, c, args):
        modules = SwordModules()
        result = []
        try:
            found_modules = modules.parse_modules()
        except FileNotFoundError:
            category = 'list'
        else:
            for key in found_modules:
                row = []
                row.append(key)

                #for item in found_modules[key]:
                #    row.append(found_modules[key][item])
                row.append(found_modules[key]['lang'])
                row.append(found_modules[key]['about'].replace('\par', "\n"))
                row.append(found_modules[key]['version'])

                if len(args) == 1:
                    category = "itemized"
                    if found_modules[key]['lang'] == args[0]:
                        result.append(row)
                else:
                    category = "table"
                    result.append(row)

        result_object = Result()
        result_object.category = category
        result_object.payload = sorted(result)
        return result_object

    def listLanguages(self, c, a):
        result_object = Result()

        result = []
        modules = SwordModules()
        try:
            found_modules = modules.parse_modules()
        except FileNotFoundError:
            result_object.category = "error"
            result_object.error = "no sword modules could be found!"
        else:
            for main_key in found_modules:
                language = found_modules[main_key]['lang']

                if not language in result:
                    result.append(language)

            result = sorted(result)
            result_object.category = "list"
            result_object.payload = result

        return result_object

    def getCurrentModule(self, c, a):
        result_object = Result()
        result_object.category = "list"
        result_object.payload = self.current_module
        return result_object

    def setCurrentModule(self, c, args):
        self.current_module = args[0]

        result_object = Result()
        result_object.category = "list"
        result_object.payload = 'sword bible-module set to: ' + args[0]
        return result_object

    def listCanons(self, c, a):
        canons = pysword_canons.canons

        result = []
        for key, value in canons.items():
            result.append(key)

        result_object = Result()
        result_object.category = 'list'
        result_object.payload = result
        return result_object

    def getCanon(self, c, a):
        result_object = Result()
        result_object.category = 'list'
        result_object.payload = self.canon
        return result_object

    def setCanon(self, c, args):
        result_object = Result()

        canons = self.listCanons(None, None)
        if len(args) > 0 and args[0] in canons.payload:
            self.canon = args[0]
            result_object.payload = 'canon changed to: ' + args[0]
        else:
            result_object.error = 'no canon specified or canon unknown'

        result_object.category = 'list'
        return result_object

    def books(self, c, args):
        structure = BibleStructure(self.canon)
        books = structure.get_books()
        result = []

        if ((not len(args) == 0) and (args[0] == 'ot')) or (len(args) == 0):
            for book in books['ot']:
                formatted = str(book)[5:][:-1]
                result.append(formatted)
        if ((not len(args) == 0) and (args[0] == 'nt')) or (len(args) == 0):
            for book in books['nt']:
                formatted = str(book)[5:][:-1]
                result.append(formatted)

        result_object = Result()
        result_object.category = "list"
        result_object.payload = result
        return result_object

    def canons(self):
        result = []

        canons = pysword_canons.canons

        books = canons[self.canon]
        return books
        """
        if testament == 'ot':
            for book in books['ot']:
                result.append(book)
        
        if testament == 'nt':
            for book in books['nt']:
                result.append(book)
        
        return result
        """

    def booksAliases(self, c, args):
        result_object = self.books(c, args)

        result = []
        import modules.sword.book_names.books_de as books_de
        for book in result_object.payload:
            for key, value in books_de.books.items():
                if value == book:
                    result.append(key)

        result_object.payload = result
        return result_object

    def word(self, command, args):
        result = None
        result_object = Result()

        modules = SwordModules()
        try:
            found_modules = modules.parse_modules()
        except FileNotFoundError:
            result_object.error = 'no sword modules found on this computer. please install some!'
        else:
            try:
                bible = modules.get_bible_from_module(self.current_module)

                try:
                    book = args[0]

                    import modules.sword.book_names.books_de as books_de
                    if book in books_de.books:
                        book = books_de.books[book]

                    if len(args) == 2:
                        result = bible.get(books=[book],
                                           chapters=[int(args[1])],
                                           clean=True,
                                           join='#|#')

                        splitted = result.split('#|#')
                        result = []
                        for i, line in enumerate(splitted):
                            result.append([i + 1, line.strip()])

                    elif args[2].find('-') > -1:
                        verse_min, verse_max = args[2].split('-')
                        verse_range = range(int(verse_min), int(verse_max) + 1)

                        try:
                            result = bible.get(books=[book],
                                               chapters=[int(args[1])],
                                               verses=verse_range,
                                               clean=True,
                                               join='#|#')
                        except IndexError:
                            result_object.error = 'invalid verse range'
                        else:
                            splitted = result.split('#|#')
                            result = []
                            for i, line in enumerate(splitted):
                                result.append(
                                    [i + int(verse_min),
                                     line.strip()])
                    else:
                        verse_range = int(args[2])

                        result = bible.get(books=[book],
                                           chapters=[int(args[1])],
                                           verses=verse_range,
                                           clean=True,
                                           join='\n')
                except ValueError as e:
                    result_object.error = str(e)
                except KeyError as e:
                    result_object.error = 'book not found in current bible: ' + str(
                        book) + "\n\n" + str(e)
                except IndexError as e:
                    result_object.error = 'invalid input. please have a look at the man-page' + "\n\n" + str(
                        e)
            except KeyError:
                result_object.error = 'current module does not exist: ' + self.current_module
            except ValueError as e:
                result_object.error = str(e)

        result_object.category = "text"
        if result:
            for item in args:
                command += ' ' + str(item)
            if type(result) == list:
                result.insert(0, command)
            elif type(result) == str:
                result = [result]
                result.insert(0, command)
            result_object.payload = result
        return result_object
Example #11
0
File: deck.py Project: nano13/tambi
class Deck(object):

    config = ConfigFile(None, None)
    dbAdapter = DeckDbAdapter()

    def __init__(self):
        pass

    def getCommands(self):
        return {
            "deck.commands": self.commands,
            "deck.toString": self.toString,
            "deck.toTable": self.toTable,
            "deck.count": self.count,
            "deck.chronological": self.chronological,
            "deck.search": self.search,
            "deck.ipaVowels": self.generateIPATable,
            "deck.ipaConsonants": self.generateIPATable,
        }

    def interpreter(self, command, args, queue):
        commands = self.getCommands()
        return commands.get(command, self.commandNotFound)(command, args)

    def commandNotFound(self, c, a):
        raise CommandNotInThisModule("command not found in module vocable")

    def commands(self, none1, none2):
        dic = self.getCommands()

        commands = sorted(dic.items())

        all_commands = []
        for key in commands:
            line = str(key).split(",")[0]
            all_commands.append(str(line[2:-1]))

        result_object = Result()
        result_object.category = "list"
        result_object.payload = all_commands
        return result_object

    def toString(self, c, args):
        result_object = Result()

        try:
            deckname = args[0]
        except IndexError:
            result_object.error = 'please specify the deck by name!'
        else:
            deckpath = self.config.readPath("vocable", "deckpath")
            db_path = os.path.join(deckpath, deckname, 'database.sqlite')
            print(db_path)
            self.dbAdapter.initialize(db_path)
            result, header = self.dbAdapter.summary()

            result_object.category = "text"
            result_object.payload = result
            result_object.header = header

        return result_object

    def toTable(self, c, args):
        result_object = self.toString(c, args)
        result_object.category = "table"
        return result_object

    def count(self, c, args):
        result_object = Result()

        deck_prefix = None
        try:
            deck_prefix = args[0]
        except IndexError:
            """ everything is fine, we just do not have an argument """
            pass

        deckpath = self.config.readPath("vocable", "deckpath")
        root, dirs, path = next(iter(os.walk(deckpath)))
        dirs.sort()

        counter = 0
        for directory in dirs:
            try:
                if directory.startswith(deck_prefix):
                    db_path = os.path.join(root, directory, "database.sqlite")
                    self.dbAdapter.initialize(db_path)
                    result = self.dbAdapter.count()
                    counter += int(result)
            except TypeError:
                db_path = os.path.join(root, directory, "database.sqlite")
                self.dbAdapter.initialize(db_path)
                result = self.dbAdapter.count()
                counter += int(result)

        result_object.category = "string"
        result_object.payload = str(counter)

        return result_object

    def search(self, c, args):
        deckpath = self.config.readPath("vocable", "deckpath")
        root, dirs, path = next(iter(os.walk(deckpath)))
        dirs.sort()

        result_list = []
        result_header = ["deckname"]
        for directory in dirs:
            db_path = os.path.join(root, directory, "database.sqlite")
            self.dbAdapter.initialize(db_path)

            result = self.dbAdapter.search(args[0])

            if result:
                try:
                    result = result[0]
                except KeyError:
                    pass
                else:
                    result_line = []
                    result_line.append(directory)
                    for key in result.keys():
                        result_line.append(result[key])

                        result_header.append(key)

                    result_list.append(result_line)

            self.dbAdapter.closeDB()

        result_object = Result()
        result_object.category = "multimedia_table"
        #result_object.category = "table"
        result_object.payload = result_list
        result_object.header = result_header
        return result_object

    def generateIPATable(self, command, args):
        if command == 'deck.ipaVowels':
            table_type = 'vowels'
        elif command == 'deck.ipaConsonants':
            table_type = 'consonants'
        try:
            deck_prefix = args[0]
        except IndexError:
            """ everything is fine, we just do not have an argument """
            deck_prefix = ''

        deckpath = self.config.readPath("vocable", "deckpath")
        root, dirs, path = next(iter(os.walk(deckpath)))
        dirs.sort()
        """ append all 'phonetical'-characters from all decks to the variable 'result_char_list' and pass it to the ipa-class to generate the table """
        result_char_list = []
        for directory in dirs:
            if directory.startswith(deck_prefix):
                db_path = os.path.join(root, directory, "database.sqlite")
                self.dbAdapter.initialize(db_path)
                result = self.dbAdapter.selectDeckItems()

                for entry in result:
                    phonetical = entry["phonetical"]
                    if phonetical:
                        for char in phonetical:
                            result_char_list.append(char)

        ipa = Ipa()
        result_table, header, header_vertical = ipa._generateIpaTableFromData(
            table_type, result_char_list)

        result_object = Result()
        result_object.category = "table"
        result_object.payload = result_table
        result_object.header = header
        result_object.header_left = header_vertical
        return result_object

    def chronological(self, c, args):
        try:
            deck_prefix = args[0]
        except IndexError:
            deck_prefix = ''

        deckpath = self.config.readPath("vocable", "deckpath")
        root, dirs, path = next(iter(os.walk(deckpath)))

        entries_list = []
        for directory in dirs:
            if directory.startswith(deck_prefix):
                db_path = os.path.join(root, directory, "database.sqlite")
                self.dbAdapter.initialize(db_path)
                result = self.dbAdapter.selectDeckItems()

                for entry in result:
                    print(entry)
                    created = entry["created"]
                    if created:
                        created = datetime.datetime.fromtimestamp(
                            int(created)).strftime('%Y-%m-%d %H:%M:%S')
                    else:
                        created = datetime.datetime.fromtimestamp(0).strftime(
                            '%Y-%m-%d %H:%M:%S')
                    entries_list.append([
                        created, entry["name"], entry["word"],
                        entry["phonetical"], entry["translation"], directory
                    ])
        entries_list.sort()

        header = [
            'date', 'name', 'word', 'phonetical', 'translation', 'deck_name'
        ]

        result_object = Result()
        result_object.category = "table"
        result_object.payload = entries_list
        result_object.header = header
        return result_object
Example #12
0
File: gps.py Project: nano13/tambi
 def __init__(self):
     config = ConfigFile(None, None)
     self.logpath = config.readPath("positioning", "storagepath")
     if not os.path.exists(self.logpath):
         os.makedirs(self.logpath)
Example #13
0
class QDeckAudioListWidget(QTableWidget):

    deckpath = None
    current_deck_rowid = None
    dbAdapter = None

    current_rowid = None

    config = ConfigFile(None, None)

    audioItemsDict = []
    audioPlayer = None
    audioRecorder = None

    STOPPED = 0
    RECORDING = 1
    PLAYING = 2
    status = 0
    row = None

    default_import_path = os.path.expanduser('~')

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

    def setRowID(self, rowid):
        self.current_rowid = rowid

    def initAudioListWidget(self, dbAdapter, deckpath, current_rowid):
        self.audioItemsDict = []

        self.dbAdapter = dbAdapter
        self.deckpath = deckpath
        self.current_rowid = current_rowid

        self.audioPlayer = QMediaPlayer()
        self.audioPlayer.mediaStatusChanged.connect(self.mediaStatusChanged)

        os_name = platform.uname()[0]
        if os_name == "Windows" or os_name == "Darwin":
            self.audioRecorder = QAudioRecorder()
        else:
            from modules.deck.gstAudioRecorder import GstAudioRecorder
            self.audioRecorder = GstAudioRecorder()

        settings = QAudioEncoderSettings()

        audioformat = self.config.readVar('vocable', 'audioformat')
        if audioformat == 'ogg':
            settings.setCodec("audio/vorbis")
            self.audioRecorder.setContainerFormat("ogg")
        elif audioformat == 'mp3':
            settings.setCodec("audio/mpeg")
            self.audioRecorder.setContainerFormat("mp3")
        elif audioformat == 'amr':
            settings.setCodec("audio/amr")
        else:
            settings.setCodec("audio/PCM")
            self.audioRecorder.setContainerFormat("wav")

        self.audioRecorder.setEncodingSettings(settings)

        self.setColumnCount(6)
        self.setHorizontalHeaderLabels(
            ["description", "", "", "", "", "filename"])
        self.setRowCount(0)

        self.itemChanged.connect(self.onItemChanged)

    def getAudioFromDB(self, rowid):
        self.audioItemsDict = self.dbAdapter.audioFilenamesForDeckRowID(rowid)
        self.setRowCount(len(self.audioItemsDict))

        for i, row in enumerate(self.audioItemsDict):
            self.setItem(i, 0, QTableWidgetItem(row["description"]))

        self.updateAudioListWidget()

    def appendNewAudio(self):
        self.audioItemsDict.append({
            "rowid": None,
            "description": "",
            "filename": None
        })
        self.insertRow(self.rowCount())
        self.updateAudioListWidget()

    def updateAudioListWidget(self):
        for i, row in enumerate(range(self.rowCount())):

            button_delete = QPushButton()
            button_delete.setIcon(QIcon.fromTheme('edit-delete'))
            self.setCellWidget(row, DELETE_BUTTON_COLUMN, button_delete)
            button_delete.clicked.connect(
                partial(self.deleteAudioButtonClicked, row))

            button_open_file = QPushButton()
            button_open_file.setIcon(QIcon.fromTheme('document-open'))
            self.setCellWidget(row, OPEN_FILE_BUTTON_COLUMN, button_open_file)
            button_open_file.clicked.connect(
                partial(self.importAudioFileClicked, row))

            button_edit_file = QPushButton()
            #button_edit_file.setIcon(QIcon.fromTheme('audio-x-generic'))
            button_edit_file.setIcon(QIcon('./assets/icons/audacity.jpg'))
            self.setCellWidget(row, EDIT_FILE_BUTTON, button_edit_file)
            button_edit_file.clicked.connect(
                partial(self.editAudioFileClicked, row))

            self.setItem(
                row, FILE_NAME_COLUMN,
                QTableWidgetItem(str(self.audioItemsDict[row]["filename"])))

            if self.status == self.STOPPED:
                if self.audioItemsDict[i]["filename"]:
                    self.insertPlayButton(row)
                else:
                    self.insertRecordButton(row)

            elif self.status == self.PLAYING:
                if i == self.row:
                    self.insertStopPlayButton(row)
                else:
                    if not self.audioItemsDict[i]["filename"]:
                        self.insertRecordButton(row)
                    else:
                        self.insertPlayButton(row)

            elif self.status == self.RECORDING:
                if i == self.row:
                    self.insertStopRecordButton(row)
                else:
                    if self.audioItemsDict[i]["filename"]:
                        self.insertPlayButton(row)
                    else:
                        self.insertRecordButton(row)

            self.resizeColumnsToContents()

    def insertPlayButton(self, row):
        button_play = QPushButton()
        button_play.setIcon(QIcon.fromTheme('media-playback-start'))
        self.setCellWidget(row, PLAY_BUTTON_COLUMN, button_play)
        button_play.clicked.connect(partial(self.playButtonClicked, row))

    def insertStopPlayButton(self, row):
        button_stop = QPushButton()
        button_stop.setIcon(QIcon.fromTheme('media-playback-stop'))
        self.setCellWidget(row, PLAY_BUTTON_COLUMN, button_stop)
        button_stop.clicked.connect(partial(self.stopPlayButtonClicked, row))

    def insertRecordButton(self, row):
        button_record = QPushButton()
        button_record.setIcon(QIcon.fromTheme('media-record'))
        self.setCellWidget(row, RECORD_BUTTON_COLUMN, button_record)
        button_record.clicked.connect(partial(self.recordButtonClicked, row))

    def insertStopRecordButton(self, row):
        button_stop = QPushButton()
        button_stop.setIcon(QIcon.fromTheme('media-playback-stop'))
        self.setCellWidget(row, RECORD_BUTTON_COLUMN, button_stop)
        button_stop.clicked.connect(partial(self.stopRecordButtonClicked, row))

    def deleteAudioButtonClicked(self, row):
        reply = QMessageBox.question(self, 'Delete Audio', "really?",
                                     QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.removeRow(row)

            rowid = self.audioItemsDict[row]["rowid"]
            if rowid:
                self.dbAdapter.deleteAudioItem(rowid)

            filename = self.audioItemsDict[row]["filename"]
            if filename:
                self.dbAdapter.deleteAudioItemByFilename(filename)
                filepath = path.join(self.deckpath, filename)
                if path.exists(filepath):
                    remove(filepath)

            del self.audioItemsDict[row]
            self.updateAudioListWidget()

    def importAudioFileClicked(self, row):
        file_path = QFileDialog.getOpenFileName(self,
                                                'Please select an Audio File',
                                                self.default_import_path)
        self.default_import_path = file_path[0]
        filename = file_path[0].split(os.sep)[::-1][0]
        target_path = os.path.join(self.deckpath, filename)
        #if not os.path.exists(target_path):
        try:
            shutil.copyfile(file_path[0], target_path)
        except FileNotFoundError:
            """ there is simply no file to copy """
            pass
        else:
            self.audioItemsDict[row]["filename"] = filename
            self.status = self.STOPPED
            self.updateAudioListWidget()

            self.saveStateToDB(self.current_rowid)

    def editAudioFileClicked(self, row):
        filename = self.audioItemsDict[row]["filename"]
        target_path = os.path.join(self.deckpath, filename)

        self.process = QProcess()
        self.process.errorOccurred.connect(self.onAudioEditProcessError)
        self.process.stateChanged.connect(self.onAudioStateChangedError)

        os_name = platform.uname()[0]
        if os_name == "Linux":
            open_command = "audacity " + target_path

        elif os_name == "Windows":
            open_command = '"C:\\program files (x86)\\Audacity\\audacity.exe" "' + target_path + '"'

        print(open_command)
        self.process.startDetached(open_command)

    def onAudioEditProcessError(self, error):
        print(error)

    def onAudioStateChangedError(self, state):
        print(state)

    def recordButtonClicked(self, row):
        self.stopPlayButtonClicked(row)
        self.stopRecordButtonClicked(row)

        extension = '.wav'
        audioformat = self.config.readVar('vocable', 'audioformat')
        if audioformat == 'ogg':
            extension = '.ogg'
        elif audioformat == 'mp3':
            extension = '.mp3'
        elif audioformat == 'amr':
            extension = '.amr'
        filename = str(int(time.time())) + self.randomword(5) + extension
        filepath = os.path.join(self.deckpath, filename)
        print(filepath)

        url = QUrl.fromLocalFile(QFileInfo(filepath).absoluteFilePath())
        self.audioRecorder.setOutputLocation(url)
        self.audioRecorder.record()

        self.audioItemsDict[row]["filename"] = filename

        self.status = self.RECORDING
        self.row = row
        self.updateAudioListWidget()

        self.saveStateToDB(self.current_rowid)

    def stopRecordButtonClicked(self, row):
        self.stopPlayButtonClicked(row)
        self.audioRecorder.stop()

        self.status = self.STOPPED
        self.updateAudioListWidget()

    def playButtonClicked(self, row):
        self.stopRecordButtonClicked(row)

        filename = self.audioItemsDict[row]["filename"]
        filepath = path.join(self.deckpath, filename)
        url = QUrl.fromLocalFile(QFileInfo(filepath).absoluteFilePath())
        content = QMediaContent(url)
        self.audioPlayer.setMedia(content)
        self.audioPlayer.play()

        self.status = self.PLAYING
        self.row = row
        self.updateAudioListWidget()

    def stopPlayButtonClicked(self, row):
        self.audioPlayer.stop()

        self.status = self.STOPPED
        self.updateAudioListWidget()

    def stopAllAudio(self):
        row = 1
        self.stopPlayButtonClicked(row)
        self.stopRecordButtonClicked(row)
        self.status = self.STOPPED

    def mediaStatusChanged(self):
        status = self.audioPlayer.mediaStatus()

        if status == 7:
            self.stopAllAudio()

    def onItemChanged(self):

        for i in range(self.rowCount()):
            item = self.item(i, 0)
            if item:
                cell_text = self.item(i, 0).text()
                self.audioItemsDict[i]["description"] = cell_text

    def saveStateToDB(self, deck_rowid):
        self.dbAdapter.saveAudioDict(self.audioItemsDict, deck_rowid)

    def randomword(self, length):
        return ''.join(
            random.choice(string.ascii_lowercase) for i in range(length))