Beispiel #1
0
    def open_proj(self):
        """Open file."""
        file_names, ok = QFileDialog.getOpenFileNames(
            self,
            "Open Projects",
            self.env,
            SUPPORT_FILE_FORMATS
        )
        if not ok:
            return

        def in_widget(path: str) -> int:
            """Is name in tree widget."""
            for i in range(self.tree_main.topLevelItemCount()):
                if path == self.tree_main.topLevelItem(i).text(1):
                    return i
            return -1

        for file_name in file_names:
            self.env = QFileInfo(file_name).absolutePath()
            index = in_widget(file_name)
            if index == -1:
                root_node = QTreeRoot(QFileInfo(file_name).baseName(), file_name, '')
                self.tree_main.addTopLevelItem(root_node)
                parse(root_node, self.data)
                self.tree_main.setCurrentItem(root_node)
            else:
                self.tree_main.setCurrentItem(self.tree_main.topLevelItem(index))

        self.__add_macros()
Beispiel #2
0
 def __new_proj(self):
     """New file."""
     file_name, suffix_type = QFileDialog.getSaveFileName(
         self, "New Project", self.env, SUPPORT_FILE_FORMATS)
     if not file_name:
         return
     suffix = _str_between(suffix_type, '(', ')').split('*')[-1]
     if QFileInfo(file_name).completeSuffix() != suffix[1:]:
         file_name += suffix
     self.env = QFileInfo(file_name).absolutePath()
     root_node = QTreeRoot(
         QFileInfo(file_name).baseName(), file_name,
         str(self.data.new_num()))
     suffix_text = file_suffix(file_name)
     if suffix_text == 'md':
         root_node.setIcon(0, file_icon("markdown"))
     elif suffix_text == 'py':
         root_node.setIcon(0, file_icon("python"))
     elif suffix_text == 'html':
         root_node.setIcon(0, file_icon("html"))
     elif suffix_text == 'kmol':
         root_node.setIcon(0, file_icon("kmol"))
     else:
         root_node.setIcon(0, file_icon("txt"))
     self.tree_main.addTopLevelItem(root_node)
Beispiel #3
0
 def new_proj(self):
     """New file."""
     filename, _ = QFileDialog.getSaveFileName(
         self,
         "New Project",
         self.env,
         SUPPORT_FILE_FORMATS
     )
     if not filename:
         return
     self.env = QFileInfo(filename).absolutePath()
     root_node = QTreeRoot(
         QFileInfo(filename).baseName(),
         filename,
         str(self.data.new_num())
     )
     suffix_text = file_suffix(filename)
     if suffix_text == 'md':
         root_node.setIcon(0, file_icon("markdown"))
     elif suffix_text == 'html':
         root_node.setIcon(0, file_icon("html"))
     elif suffix_text == 'kmol':
         root_node.setIcon(0, file_icon("kmol"))
     else:
         root_node.setIcon(0, file_icon("txt"))
     self.tree_main.addTopLevelItem(root_node)
Beispiel #4
0
 def outputTo(self, format_name: str, format_choose: List[str]) -> str:
     """Simple to support multiple format."""
     file_name, suffix = QFileDialog.getSaveFileName(
         self, f"Save to {format_name}...",
         self.env + '/' + self.DatabaseWidget.file_name.baseName(),
         ';;'.join(format_choose))
     if file_name:
         suffix = str_between(suffix, '(', ')').split('*')[-1]
         print(f"Format: {suffix}")
         if QFileInfo(file_name).completeSuffix() != suffix[1:]:
             file_name += suffix
         self.setLocate(QFileInfo(file_name).absolutePath())
     return file_name
Beispiel #5
0
def outputTo(self, formatName: str, formatChoose: List[str]) -> str:
    """Simple to support mutiple format."""
    suffix0 = strbetween(formatChoose[0], '(', ')').split('*')[-1]
    file_name, suffix = QFileDialog.getSaveFileName(
        self, "Save to {}...".format(formatName),
        self.env + '/' + self.FileWidget.file_name.baseName() + suffix0,
        ';;'.join(formatChoose))
    if file_name:
        suffix = strbetween(suffix, '(', ')').split('*')[-1]
        print("Format: {}".format(suffix))
        if QFileInfo(file_name).suffix() != suffix[1:]:
            file_name += suffix
        self.setLocate(QFileInfo(file_name).absolutePath())
    return file_name
Beispiel #6
0
    def __exec_script(self, code: Union[int, str]):
        """Run a script in a new thread."""
        self.__save_current()

        variables = {
            # Qt file operation classes.
            'QStandardPaths': QStandardPaths,
            'QFileInfo': QFileInfo,
            'QDir': QDir,
        }
        node = self.tree_main.currentItem()
        variables['node'] = node
        if node:
            root = _get_root(node)
            variables['root'] = root
            variables['root_path'] = QFileInfo(root.text(1)).absoluteFilePath()
            variables['node_path'] = getpath(node)

        def chdir_tree(path: str):
            if QFileInfo(path).isDir():
                chdir(path)
            elif QFileInfo(path).isFile():
                chdir(QFileInfo(path).absolutePath())

        variables['chdir'] = chdir_tree
        thread = Thread(
            target=exec,
            args=(self.data[code] if type(code) == int else code, variables)
        )
        thread.start()
Beispiel #7
0
 def on_save_atlas_clicked(self):
     """Save function as same as type synthesis widget."""
     count = self.collection_list.count()
     if not count:
         return
     lateral, ok = QInputDialog.getInt(self, "Atlas",
                                       "The number of lateral:", 5, 1, 10)
     if not ok:
         return
     fileName = self.outputTo("Atlas image", Qt_images)
     if not fileName:
         return
     icon_size = self.collection_list.iconSize()
     width = icon_size.width()
     image_main = QImage(
         QSize(lateral * width if count > lateral else count * width,
               ((count // lateral) + bool(count % lateral)) * width),
         self.collection_list.item(0).icon().pixmap(
             icon_size).toImage().format())
     image_main.fill(QColor(Qt.white).rgb())
     painter = QPainter(image_main)
     for row in range(count):
         image = self.collection_list.item(row).icon().pixmap(
             icon_size).toImage()
         painter.drawImage(
             QPointF(row % lateral * width, row // lateral * width), image)
     painter.end()
     pixmap = QPixmap()
     pixmap.convertFromImage(image_main)
     pixmap.save(fileName, format=QFileInfo(fileName).suffix())
     self.saveReplyBox("Atlas", fileName)
Beispiel #8
0
    def dropEvent(self, event):
        """Drop file in to our window."""
        for url in event.mimeData().urls():
            file_name = url.toLocalFile()
            self.env = QFileInfo(file_name).absolutePath()
            index = self.__in_widget(file_name)
            if index == -1:
                root_node = QTreeRoot(
                    QFileInfo(file_name).baseName(), file_name, '')
                self.tree_main.addTopLevelItem(root_node)
                parse(root_node, self.data)
                self.tree_main.setCurrentItem(root_node)
            else:
                self.tree_main.setCurrentIndex(index)

        self.__add_macros()
        event.acceptProposedAction()
Beispiel #9
0
 def saveReplyBox(self, title: str, file_name: str):
     """Show message when successfully saved."""
     size = QFileInfo(file_name).size()
     print("Size: " + (f"{size / 1024 / 1024:.02f} MB" if size / 1024 //
                       1024 else f"{size / 1024:.02f} KB"))
     QMessageBox.information(self, f"Initial Saved: {title}",
                             f"Successfully saved:\n{file_name}")
     print(f"Initial saved: [\"{file_name}\"]")
Beispiel #10
0
 def __export_image(self):
     """Picture save function."""
     file_name = self.outputTo("picture", qt_image_format)
     if not file_name:
         return
     pixmap = self.MainCanvas.grab()
     pixmap.save(file_name, format=QFileInfo(file_name).suffix())
     self.saveReplyBox("Picture", file_name)
Beispiel #11
0
def getpath(node: QTreeWidgetItem) -> str:
    """Get the path of current node."""
    parent = node.parent()
    file_name = node.text(1)
    if parent:
        return QFileInfo(QDir(
            node_getpath(parent)).filePath(file_name)).absoluteFilePath()
    return file_name
Beispiel #12
0
def on_action_Output_to_Picture_triggered(self):
    """Picture save function."""
    file_name = self.outputTo("picture", QTIMAGES)
    if not file_name:
        return
    pixmap = self.MainCanvas.grab()
    pixmap.save(file_name, format=QFileInfo(file_name).suffix())
    self.saveReplyBox("Picture", file_name)
Beispiel #13
0
 def read(self, fileName: str):
     """Load database commit."""
     self.connectDatabase(fileName)
     history_commit = CommitModel.select().order_by(CommitModel.id)
     commit_count = len(history_commit)
     if not commit_count:
         QMessageBox.warning(self, "Warning",
                             "This file is a non-committed database.")
         return
     self.clearFunc()
     self.reset()
     self.history_commit = history_commit
     for commit in self.history_commit:
         self.addCommit(commit)
     print("{} commit(s) was find in database.".format(commit_count))
     self.loadCommit(self.history_commit.order_by(-CommitModel.id).get())
     self.fileName = QFileInfo(fileName)
     self.isSavedFunc()
Beispiel #14
0
def saveReplyBox(self, title: str, file_name: str):
    """Show message when successfully saved."""
    size = QFileInfo(file_name).size()
    print("Size: {}".format("{} MB".format(round(size / 1024 /
                                                 1024, 2)) if size / 1024 //
                            1024 else "{} KB".format(round(size / 1024, 2))))
    QMessageBox.information(self, title,
                            "Successfully converted:\n{}".format(file_name))
    print("Successful saved: [\"{}\"]".format(file_name))
Beispiel #15
0
 def dragEnterEvent(self, event):
     """Drag file in to our window."""
     mimeData = event.mimeData()
     if not mimeData.hasUrls():
         return
     for url in mimeData.urls():
         file_name = url.toLocalFile()
         if QFileInfo(file_name).suffix() in ('pyslvs', 'db'):
             event.acceptProposedAction()
Beispiel #16
0
 def read(self, file_name: str):
     """Load database commit."""
     self.__connect_database(file_name)
     history_commit = CommitModel.select().order_by(CommitModel.id)
     commit_count = len(history_commit)
     if not commit_count:
         QMessageBox.warning(self, "Warning",
                             "This file is a non-committed database.")
         return
     self.__clear_func()
     self.reset()
     self.history_commit = history_commit
     for commit in self.history_commit:
         self.__add_commit(commit)
     print(f"{commit_count} commit(s) was find in database.")
     self.__load_commit(self.history_commit.order_by(-CommitModel.id).get())
     self.file_name = QFileInfo(file_name)
     self.__workbook_saved()
Beispiel #17
0
 def reset(self):
     """Clear all the things that dependent on database."""
     self.history_commit: Optional[CommitModel] = None
     self.file_name = QFileInfo("Untitled")
     self.last_time = datetime.datetime.now()
     self.changed = False
     self.Stack = 0
     self.__command_clear()
     for row in range(self.CommitTable.rowCount()):
         self.CommitTable.removeRow(0)
     self.BranchList.clear()
     self.AuthorList.clear()
     self.FileAuthor.clear()
     self.FileDescription.clear()
     self.branch_current.clear()
     self.commit_search_text.clear()
     self.commit_current_id.setValue(0)
     self.__close_database()
Beispiel #18
0
 def loadExample(self, isImport=False) -> bool:
     """Load example to new workbook."""
     if not self.checkSaved():
         return False
     #load example by expression.
     example_name, ok = QInputDialog.getItem(
         self, "Examples", "Select a example to load:",
         sorted(k for k in example_list), 0, False)
     if not ok:
         return False
     if not isImport:
         self.reset()
         self.clearFunc()
     self.parseFunc(example_list[example_name])
     self.fileName = QFileInfo(example_name)
     self.isSavedFunc()
     print("Example \"{}\" has been loaded.".format(example_name))
     return True
Beispiel #19
0
 def dragEnterEvent(self, event):
     """Drag file in to our window."""
     mime_data = event.mimeData()
     if not mime_data.hasUrls():
         return
     for url in mime_data.urls():
         suffix = QFileInfo(url.toLocalFile()).completeSuffix()
         if suffix in {'nc', 'g'}:
             event.acceptProposedAction()
Beispiel #20
0
def save_file(node: QTreeWidgetItem, data: DataDict) -> Tuple[str, bool]:
    """Recursive to all the contents of nodes."""
    text_data = []
    all_saved = data.is_saved(int(node.text(2)))
    for i in range(node.childCount()):
        doc, saved = save_file(node.child(i), data)
        text_data.append(doc)
        all_saved &= saved
    my_content = data[int(node.text(2))].splitlines()
    for i in range(len(my_content)):
        content_text = my_content[i]
        if content_text.endswith("@others"):
            preffix = content_text[:-len("@others")]
            my_content[i] = '\n\n'.join(preffix + t for t in text_data)
    my_content = '\n'.join(my_content)
    path_text = QFileInfo(node.text(1)).fileName()
    if path_text and not all_saved:
        suffix_text = QFileInfo(path_text).suffix()
        if suffix_text == 'kmol':
            # Save project.
            _write_tree(node.text(1), node, data)
        else:
            # File path.
            file_path = QDir(QFileInfo(node_getpath(node)).absolutePath())
            if not file_path.exists():
                file_path.mkpath('.')
                print("Create Folder: {}".format(file_path.absolutePath()))
            file_name = file_path.filePath(path_text)

            if suffix_text in _SUPPORTED_FILE_SUFFIX:
                # Add end new line.
                if my_content and (my_content[-1] != '\n'):
                    my_content += '\n'
                try:
                    with open(file_name, 'w', encoding='utf-8') as f:
                        f.write(my_content)
                except UnicodeError:
                    print(f"Unicode Error in: {file_name}")
                else:
                    print(f"Saved: {file_name}")
            elif suffix_text:
                print(f"Ignore file: {file_name}")

    return my_content, all_saved
Beispiel #21
0
 def load_from_args(self):
     if not ARGUMENTS.file:
         return
     suffix = QFileInfo(ARGUMENTS.file).suffix()
     if suffix == 'pyslvs':
         self.database_widget.read(ARGUMENTS.file)
     elif suffix == 'slvs':
         self.__read_slvs(ARGUMENTS.file)
     else:
         logger.critical("Unsupported format has been ignore when startup.")
Beispiel #22
0
 def dropEvent(self, event):
     """Drop file in to our window."""
     for url in event.mimeData().urls():
         filename = url.toLocalFile()
         root_node = QTreeRoot(QFileInfo(filename).baseName(), filename, '')
         self.tree_main.addTopLevelItem(root_node)
         parse(root_node, self.data)
         self.tree_main.setCurrentItem(root_node)
     self.__add_macros()
     event.acceptProposedAction()
Beispiel #23
0
 def readFromArgs(self):
     if not ARGUMENTS.file:
         return
     suffix = QFileInfo(ARGUMENTS.file).suffix()
     if suffix == 'pyslvs':
         self.DatabaseWidget.read(ARGUMENTS.file)
     elif suffix == 'slvs':
         self.__read_slvs(ARGUMENTS.file)
     else:
         print("Unsupported format has been ignore when startup.")
Beispiel #24
0
 def inputFrom(self,
               format_name: str,
               format_choose: List[str],
               multiple: bool = False) -> str:
     """Get file name(s)."""
     args = (f"Open {format_name} file{'s' if multiple else ''}...",
             self.env, ';;'.join(format_choose))
     if multiple:
         file_name_s, suffix = QFileDialog.getOpenFileNames(self, *args)
     else:
         file_name_s, suffix = QFileDialog.getOpenFileName(self, *args)
     if file_name_s:
         suffix = str_between(suffix, '(', ')').split('*')[-1]
         print(f"Format: {suffix}")
         if type(file_name_s) == str:
             self.setLocate(QFileInfo(file_name_s).absolutePath())
         else:
             self.setLocate(QFileInfo(file_name_s[0]).absolutePath())
     return file_name_s
Beispiel #25
0
def node_getpath(node: QTreeWidgetItem) -> str:
    """Recursive return the path of the node."""
    path = node.text(1)
    parent = node.parent()
    if parent is None:
        if file_suffix(path) == 'kmol':
            return QFileInfo(path).absolutePath()
        else:
            return path
    return QDir(node_getpath(parent)).filePath(path)
Beispiel #26
0
 def reset(self):
     """Clear all the things that dependent on database."""
     #peewee Quary(CommitModel) type
     self.history_commit = None
     self.Script = ""
     self.fileName = QFileInfo("Untitled")
     self.lastTime = datetime.datetime.now()
     self.changed = False
     self.Stack = 0
     self.CommandStack.clear()
     for row in range(self.CommitTable.rowCount()):
         self.CommitTable.removeRow(0)
     self.BranchList.clear()
     self.AuthorList.clear()
     self.FileAuthor.clear()
     self.FileDescription.clear()
     self.branch_current.clear()
     self.commit_search_text.clear()
     self.commit_current_id.setValue(0)
Beispiel #27
0
    def __open_proj(self, file_names: Optional[Sequence[str]] = None):
        """Open file."""
        if file_names is None:
            file_names, ok = QFileDialog.getOpenFileNames(
                self, "Open Projects", self.env, SUPPORT_FILE_FORMATS)
            if not ok:
                return

        for file_name in file_names:
            self.env = QFileInfo(file_name).absolutePath()
            index = self.__in_widget(file_name)
            if index == -1:
                root_node = QTreeRoot(
                    QFileInfo(file_name).baseName(), file_name, '')
                self.tree_main.addTopLevelItem(root_node)
                self.refresh_proj(root_node)
                self.tree_main.setCurrentItem(root_node)
            else:
                self.tree_main.setCurrentItem(
                    self.tree_main.topLevelItem(index))
Beispiel #28
0
    def __exec_script(self, code: Union[int, str]):
        """Run a script in a new thread."""
        self.__save_current()

        variables: Dict[str, Any] = {
            # Shell functions.
            "is_file": isfile,
            "is_dir": isdir,
            "rm_file": remove,
            "rm_dir": rmdir,
            "run_shell": os_system,
            "run_shell_out":
            lambda *command: check_output(command).decode('utf-8'),

            # Qt file operation classes.
            'QStandardPaths': QStandardPaths,
            'QFileInfo': QFileInfo,
            'QDir': QDir,
        }
        node = self.tree_main.currentItem()
        if node is not None:
            root = _get_root(node)
            variables['root'] = root
            variables['root_file'] = QFileInfo(root.text(1)).absoluteFilePath()
            variables['root_path'] = QFileInfo(
                variables['root_file']).absolutePath()
            variables['node_file'] = getpath(node)
            variables['node_path'] = QFileInfo(
                variables['node_file']).absolutePath()

        def chdir_tree(path: str):
            if QFileInfo(path).isDir():
                chdir(path)
            elif QFileInfo(path).isFile():
                chdir(QFileInfo(path).absolutePath())

        variables['chdir'] = chdir_tree
        thread = Thread(target=exec,
                        args=(self.data[code] if type(code) == int else code,
                              variables))
        thread.start()
Beispiel #29
0
    def __switch_data(self, current: QTreeWidgetItem,
                      previous: QTreeWidgetItem):
        """Switch node function.

        + Auto collapse and expand function.
        + Important: Store the string data.
        """
        if self.auto_expand_option.isChecked():
            self.tree_main.expandItem(current)
        self.tree_main.scrollToItem(current)

        bar: QScrollBar = self.text_editor.verticalScrollBar()
        if previous:
            key = int(previous.text(2))
            self.data[key] = self.text_editor.text()
            self.data.set_pos(key, bar.value())
        if current:
            # Auto highlight.
            path = current.text(1)
            file_name = QFileInfo(path).fileName()
            suffix = QFileInfo(file_name).suffix()
            if current.text(0).startswith('@'):
                self.highlighter_option.setCurrentText("Python")
            else:
                self.highlighter_option.setCurrentText("Markdown")
            if path:
                for name_m, suffix_m in HIGHLIGHTER_SUFFIX.items():
                    if suffix in suffix_m:
                        self.highlighter_option.setCurrentText(name_m)
                        break
                else:
                    for name_m, filename_m in HIGHLIGHTER_FILENAME.items():
                        if file_name in filename_m:
                            self.highlighter_option.setCurrentText(name_m)
                            break
            key = int(current.text(2))
            self.text_editor.setText(self.data[key])
            bar.setValue(self.data.pos(key))

        self.reload_html_viewer()
        self.__action_changed()
Beispiel #30
0
 def set_path(self):
     """Set file directory."""
     node = self.tree_main.currentItem()
     file_name, ok = QFileDialog.getOpenFileName(self, "Open File",
                                                 self.env,
                                                 SUPPORT_FILE_FORMATS)
     if not ok:
         return
     self.env = QFileInfo(file_name).absolutePath()
     project_path = QDir(_get_root(node).text(1))
     project_path.cdUp()
     node.setText(1, project_path.relativeFilePath(file_name))