Example #1
0
class Editor(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        self.current_dir = os.getcwd()
        self.current_file = None
        
        self.init_ui()
    
    def init_ui(self):
        self.text_edit = QTextEdit(self)
        self.setCentralWidget(self.text_edit)
        
        font = QFont("Menlo", 12)
        # TODO: Create a layout and change the line spacing
        #spacing = QFontMetrics(font).lineSpacing()
        self.text_edit.setFont(font)
        self.highlighter = Highlighter(self.text_edit.document(), DEFAULT_RULES, DEFAULT_STYLE)
        #print("Highlighter doc: {}".format(self.text_edit.document()))
        
        menu_bar = self.menuBar()
        m_file = menu_bar.addMenu("File")
        
        i_open = QAction("Open", self)
        i_open.setShortcut('Ctrl+O')
        i_open.triggered.connect(self.on_open)
        
        m_file.addAction(i_open)
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle("tea")
    
    def on_open(self):
        file_path, other = QFileDialog.getOpenFileName(self, "Open File", self.current_dir)
        #print([a for a in dir(QFileDialog) if not a.startswith("_")])
        print("File name: {}, Other: {}".format(file_path, other))
        if file_path:
            dirname = os.path.basename(os.path.dirname(file_path))
            filename = os.path.basename(file_path)
            self.setWindowTitle("{} - {}".format(filename, dirname))
            with open(file_path) as f:
                text = f.read()
                #formatted = markup_python(text)
                #formatted = "<font color=red size=24>{}</font>".format(text)
                self.text_edit.setText(text)
Example #2
0
def embed_readme_images(readme_path):
    """
    QTextEdit used to auto detect raw / html / markdown,
    and do the conversion to html.
    """
    readme_dir = os.path.dirname(readme_path)

    dada = None
    with open(readme_path) as f:
        dada = f.read()
    # strip old embeded dada
    dada = re.sub(r'source=\"data:image.*\"', "", dada)

    editor = QTextEdit()
    editor.setText(dada)
    editor.document().setMetaInformation(QTextDocument.DocumentUrl, readme_dir)
    html = editor.toHtml()

    image_elements = list()
    root = ElementTree.fromstring(html)
    for element in root.iter():
        for sub in element[:]:
            if sub.tag == "head":
                element.remove(sub)
        element.attrib.pop("style", None)
        if element.tag == "img":
            image_elements.append(element)

    width_scalar = calculate_width_scalar(readme_dir, image_elements, 577.0)

    for img in image_elements:
        rel_src_path = img.attrib.get("src", "")
        if rel_src_path.startswith("data:image"):
            print(
                "Embeded src. skipping! (readme_path={readme_path!r})".format(
                    **locals()))
            return
        if rel_src_path:
            src_path = os.path.abspath(os.path.join(readme_dir, rel_src_path))
            if not os.path.isfile(src_path):
                print(
                    "image file missing! (readme_dir={readme_dir!r}, src_path={src_path!r})"
                    .format(**locals()))
            else:
                rel_src_path = os.path.relpath(src_path, readme_dir)
                rel_src_path = "./" + rel_src_path.replace("\\", "/")
                # attribute order must be correct !!!
                # ElementTree in python<3.8 uses sort(dict.items())
                # sooo... lets make sure that there is alphaphetical dummy prefix...
                new_attributes = [
                    ("001_DEL_XML_SUCKS_src", rel_src_path),
                    ("002_DEL_XML_SUCKS_source",
                     embeded_image_scale_to_width(src_path,
                                                  width_scalar=width_scalar))
                ]
                new_attributes.extend((k, v)
                                      for k, v in sorted(img.attrib.items())
                                      if k not in {"src", "source"})
                img.attrib.clear()
                img.attrib.update(new_attributes)

    html = ElementTree.tostring(root).decode()
    html = re.sub(r"\d{3}_DEL_XML_SUCKS_", "", html)
    with open(readme_path, "wb") as f:
        f.write(html.encode("utf-8"))