<commit_before>#!/usr/bin/env python

import os
import sys
from subprocess import call
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebView, QWebPage
from mikidown.config import *
from mikidown.mikitree import *

import markdown

md = markdown.Markdown()

class MikiWindow(QMainWindow):
    def __init__(self, notebookPath=None, parent=None):
        super(MikiWindow, self).__init__(parent)
        self.resize(800,600)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
        
        self.tabWidget = QTabWidget()
        self.viewedList = QToolBar(self.tr('Recently Viewed'), self)
        self.viewedList.setFixedHeight(25)
        self.notesEdit = QTextEdit()
        self.notesView = QWebView()
        self.findBar = QToolBar(self.tr('Find'), self)
        self.findBar.setFixedHeight(30)
        self.noteSplitter = QSplitter(Qt.Horizontal)
        self.noteSplitter.addWidget(self.notesEdit)
        self.noteSplitter.addWidget(self.notesView)
        self.notesEdit.setVisible(False)
        self.notesView.settings().clearMemoryCaches()
        self.notesView.settings().setUserStyleSheetUrl(QUrl.fromLocalFile('notes.css'))
        self.rightSplitter = QSplitter(Qt.Vertical)
        self.rightSplitter.setChildrenCollapsible(False)
        self.rightSplitter.addWidget(self.viewedList)
        self.rightSplitter.addWidget(self.noteSplitter)
        self.rightSplitter.addWidget(self.findBar)
        self.mainSplitter = QSplitter(Qt.Horizontal)
        self.mainSplitter.addWidget(self.tabWidget)
        self.mainSplitter.addWidget(self.rightSplitter)
        self.setCentralWidget(self.mainSplitter)
        self.mainSplitter.setStretchFactor(0, 1)
        self.mainSplitter.setStretchFactor(1, 5)

        self.notesTree = MikiTree()
        self.searchEdit = QLineEdit()
        self.searchEdit.returnPressed.connect(self.searchNote)
        self.searchList = QListWidget()
        self.searchTab = QWidget()
        searchLayout = QVBoxLayout()
        searchLayout.addWidget(self.searchEdit)
        searchLayout.addWidget(self.searchList)
        self.searchTab.setLayout(searchLayout)
        self.tabWidget.addTab(self.notesTree, 'Index')
        self.tabWidget.addTab(self.searchTab, 'Search')
        self.tabWidget.setMinimumWidth(150)
        #self.rightSplitter.setSizes([600,20,600,580])
        self.rightSplitter.setStretchFactor(0, 0)
        
        # actions in menuFile
        self.actionNewPage = self.act(self.tr('&New Page...'), shct=QKeySequence.New, trig=self.notesTree.newPage)
        self.actionNewSubpage = self.act(self.tr('New Sub&page...'), shct=QKeySequence('Ctrl+Shift+N'), trig=self.notesTree.newSubpage)
        self.actionImportPage = self.act(self.tr('&Import Page...'), trig=self.importPage)
        self.actionOpenNotebook = self.act(self.tr('&Open Notebook...'), shct=QKeySequence.Open, trig=self.openNotebook)
        self.actionSave = self.act(self.tr('&Save'), shct=QKeySequence.Save, trig=self.saveCurrentNote)
        self.actionSave.setEnabled(False)
        self.actionSaveAs = self.act(self.tr('Save &As...'), shct=QKeySequence('Ctrl+Shift+S'), trig=self.saveNoteAs)
        self.actionHtml = self.act(self.tr('to &HTML'), trig=self.saveNoteAsHtml)
        self.actionPdf = self.act(self.tr('to &PDF'), trig=self.saveNoteAsPdf)
        self.actionRenamePage = self.act(self.tr('&Rename Page...'), shct=QKeySequence('F2'), trig=self.notesTree.renamePageWrapper)
        self.actionDelPage = self.act(self.tr('&Delete Page'), shct=QKeySequence('Delete'), trig=self.notesTree.delPageWrapper)
        self.actionQuit = self.act(self.tr('&Quit'), shct=QKeySequence.Quit)
        self.connect(self.actionQuit, SIGNAL('triggered()'), self, SLOT('close()'))
        self.actionQuit.setMenuRole(QAction.QuitRole)
        # actions in menuEdit
        self.actionUndo = self.act(self.tr('&Undo'), shct=QKeySequence.Undo, trig=lambda: self.notesEdit.undo())
        self.actionUndo.setEnabled(False)
        self.notesEdit.undoAvailable.connect(self.actionUndo.setEnabled)
        self.actionRedo = self.act(self.tr('&Redo'), shct=QKeySequence.Redo, trig=lambda: self.notesEdit.redo())
        self.actionRedo.setEnabled(False)
        self.notesEdit.redoAvailable.connect(self.actionRedo.setEnabled)
        self.actionFindText = self.act(self.tr('&Find Text'), shct=QKeySequence.Find)
        self.actionFindText.setCheckable(True)
        self.actionFindText.triggered.connect(self.findBar.setVisible)
        self.actionFind = self.act(self.tr('Next'), shct=QKeySequence.FindNext, trig=self.findText)
        self.actionFindPrev = self.act(self.tr('Previous'), shct=QKeySequence.FindPrevious, 
                trig=lambda:self.findText(back=True))
        # actions in menuView
        self.actionEdit = self.act(self.tr('Edit'), shct=QKeySequence('Ctrl+E'), trigbool=self.edit)
        self.actionLiveView = self.act(self.tr('Live Edit'), shct=QKeySequence('Ctrl+R'), trigbool=self.liveView)
        self.actionFlipEditAndView = self.act(self.tr('Flip Edit and View'), trig=self.flipEditAndView)
        self.actionFlipEditAndView.setEnabled(False)
        self.actionLeftAndRight = self.act(self.tr('Split into Left and Right'), trig=self.leftAndRight)
        self.actionUpAndDown = self.act(self.tr('Split into Up and Down'), trig=self.upAndDown)
        #self.actionLeftAndRight.setEnabled(False)
        #self.actionUpAndDown.setEnabled(False)
        # actions in menuHelp
        self.actionReadme = self.act(self.tr('README'), trig=self.readmeHelp)

        self.menuBar = QMenuBar(self)
        self.setMenuBar(self.menuBar)
        self.menuFile = self.menuBar.addMenu(self.tr('&File'))
        self.menuEdit = self.menuBar.addMenu(self.tr('&Edit'))
        self.menuView = self.menuBar.addMenu(self.tr('&View'))
        self.menuHelp = self.menuBar.addMenu(self.tr('&Help'))
        # menuFile
        self.menuFile.addAction(self.actionNewPage)
        self.menuFile.addAction(self.actionNewSubpage)
        self.menuFile.addAction(self.actionImportPage)
        self.menuFile.addAction(self.actionOpenNotebook)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSaveAs)
        self.menuExport = self.menuFile.addMenu(self.tr('&Export'))
        self.menuExport.addAction(self.actionHtml)
        self.menuExport.addAction(self.actionPdf)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionRenamePage)
        self.menuFile.addAction(self.actionDelPage)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        # menuEdit
        self.menuEdit.addAction(self.actionUndo)
        self.menuEdit.addAction(self.actionRedo)
        self.menuEdit.addAction(self.actionFindText)
        # menuView
        self.menuView.addAction(self.actionEdit)
        self.menuView.addAction(self.actionLiveView)
        self.menuView.addAction(self.actionFlipEditAndView)
        self.menuMode = self.menuView.addMenu(self.tr('Mode'))
        self.menuMode.addAction(self.actionLeftAndRight)
        self.menuMode.addAction(self.actionUpAndDown)
        # menuHelp
        self.menuHelp.addAction(self.actionReadme)

        self.toolBar = QToolBar(self.tr('toolbar'), self)
        self.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.toolBar.addAction(self.actionEdit)
        self.toolBar.addAction(self.actionLiveView)
        self.findEdit = QLineEdit(self.findBar)
        self.findEdit.returnPressed.connect(self.findText)
        self.checkBox = QCheckBox(self.tr('Match case'), self.findBar)
        self.findBar.addWidget(self.findEdit)
        self.findBar.addWidget(self.checkBox)
        self.findBar.addAction(self.actionFindPrev)
        self.findBar.addAction(self.actionFind)
        self.findBar.setVisible(False)
        self.findBar.visibilityChanged.connect(self.findBarVisibilityChanged)
        
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)
        self.statusLabel = QLabel(self)
        self.statusBar.addWidget(self.statusLabel, 1)
        
        #self.connect(self.notesTree, SIGNAL('customContextMenuRequested(QPoint)'), self.treeMenu)
        self.notesTree.currentItemChanged.connect(self.currentItemChangedWrapper)
        self.searchList.currentRowChanged.connect(self.listItemChanged)
        self.connect(self.notesEdit, SIGNAL('textChanged()'), self.noteEditted)

        self.notesEdit.document().modificationChanged.connect(self.modificationChanged)
        self.notesView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.notesView.page().linkClicked.connect(self.linkClicked)
        self.notesView.page().linkHovered.connect(self.linkHovered)
        self.notesView.page().mainFrame().contentsSizeChanged.connect(self.contentsSizeChanged)

        self.scrollPosition = QPoint(0, 0)
        self.contentsSize = QSize(0, 0)

        QDir.setCurrent(notebookPath)
        #QSettings.setPath(QSettings.NativeFormat, QSettings.UserScope, notebookPath)
        #self.notebookSettings = QSettings('mikidown', 'notebook')
        self.notebookSettings = QSettings(notebookPath+'/notebook.conf', QSettings.NativeFormat)
        self.initTree(notebookPath, self.notesTree)
        self.updateRecentViewedNotes()
        files = readListFromSettings(self.notebookSettings, 'recentViewedNoteList')
        if len(files) != 0:
            item = self.notesTree.pagePathToItem(files[0])
            self.notesTree.setCurrentItem(item)

    def initTree(self, notePath, parent):
        if not QDir(notePath).exists():
            return
        noteDir = QDir(notePath)
        self.notesList = noteDir.entryInfoList(['*.markdown'],
                               QDir.NoFilter,
                               QDir.Name|QDir.IgnoreCase)
        for note in self.notesList:
            item = QTreeWidgetItem(parent, [note.baseName()])
            path = self.tr(notePath + '/' + note.baseName())
            self.initTree(path, item)
        self.editted = 0

    def openNote(self, noteFullName):
        filename = noteFullName + '.markdown'
        print(filename)
        fh = QFile(filename)
        try:
            if not fh.open(QIODevice.ReadOnly):
                raise IOError(fh.errorString())
        except IOError as e:
            QMessageBox.warning(self, 'Read Error', 
                    'Failed to open %s: %s' % (filename, e))
        finally:
            if fh is not None:
                noteBody = QTextStream(fh).readAll()
                fh.close()
                self.notesEdit.setPlainText(noteBody)
                #self.editted = 0
                #self.actionSave.setEnabled(False)
                self.notesEdit.document().setModified(False)
                self.updateView()
                self.setCurrentFile()
                self.updateRecentViewedNotes()
                self.viewedListActions[-1].setChecked(True)
                self.statusLabel.setText(noteFullName)
                #self.statusBar.showMessage(noteFullName)

    def currentItemChangedWrapper(self, current, previous):
        if current is None:
            return<commit_msg>fix initTree when no notebooks present<commit_after>#!/usr/bin/env python

import os
import sys
from subprocess import call
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebView, QWebPage
from mikidown.config import *
from mikidown.mikitree import *

import markdown

md = markdown.Markdown()

class MikiWindow(QMainWindow):
    def __init__(self, notebookPath=None, parent=None):
        super(MikiWindow, self).__init__(parent)
        self.resize(800,600)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
        
        self.tabWidget = QTabWidget()
        self.viewedList = QToolBar(self.tr('Recently Viewed'), self)
        self.viewedList.setFixedHeight(25)
        self.notesEdit = QTextEdit()
        self.notesView = QWebView()
        self.findBar = QToolBar(self.tr('Find'), self)
        self.findBar.setFixedHeight(30)
        self.noteSplitter = QSplitter(Qt.Horizontal)
        self.noteSplitter.addWidget(self.notesEdit)
        self.noteSplitter.addWidget(self.notesView)
        self.notesEdit.setVisible(False)
        self.notesView.settings().clearMemoryCaches()
        self.notesView.settings().setUserStyleSheetUrl(QUrl.fromLocalFile('notes.css'))
        self.rightSplitter = QSplitter(Qt.Vertical)
        self.rightSplitter.setChildrenCollapsible(False)
        self.rightSplitter.addWidget(self.viewedList)
        self.rightSplitter.addWidget(self.noteSplitter)
        self.rightSplitter.addWidget(self.findBar)
        self.mainSplitter = QSplitter(Qt.Horizontal)
        self.mainSplitter.addWidget(self.tabWidget)
        self.mainSplitter.addWidget(self.rightSplitter)
        self.setCentralWidget(self.mainSplitter)
        self.mainSplitter.setStretchFactor(0, 1)
        self.mainSplitter.setStretchFactor(1, 5)

        self.notesTree = MikiTree()
        self.searchEdit = QLineEdit()
        self.searchEdit.returnPressed.connect(self.searchNote)
        self.searchList = QListWidget()
        self.searchTab = QWidget()
        searchLayout = QVBoxLayout()
        searchLayout.addWidget(self.searchEdit)
        searchLayout.addWidget(self.searchList)
        self.searchTab.setLayout(searchLayout)
        self.tabWidget.addTab(self.notesTree, 'Index')
        self.tabWidget.addTab(self.searchTab, 'Search')
        self.tabWidget.setMinimumWidth(150)
        #self.rightSplitter.setSizes([600,20,600,580])
        self.rightSplitter.setStretchFactor(0, 0)
        
        # actions in menuFile
        self.actionNewPage = self.act(self.tr('&New Page...'), shct=QKeySequence.New, trig=self.notesTree.newPage)
        self.actionNewSubpage = self.act(self.tr('New Sub&page...'), shct=QKeySequence('Ctrl+Shift+N'), trig=self.notesTree.newSubpage)
        self.actionImportPage = self.act(self.tr('&Import Page...'), trig=self.importPage)
        self.actionOpenNotebook = self.act(self.tr('&Open Notebook...'), shct=QKeySequence.Open, trig=self.openNotebook)
        self.actionSave = self.act(self.tr('&Save'), shct=QKeySequence.Save, trig=self.saveCurrentNote)
        self.actionSave.setEnabled(False)
        self.actionSaveAs = self.act(self.tr('Save &As...'), shct=QKeySequence('Ctrl+Shift+S'), trig=self.saveNoteAs)
        self.actionHtml = self.act(self.tr('to &HTML'), trig=self.saveNoteAsHtml)
        self.actionPdf = self.act(self.tr('to &PDF'), trig=self.saveNoteAsPdf)
        self.actionRenamePage = self.act(self.tr('&Rename Page...'), shct=QKeySequence('F2'), trig=self.notesTree.renamePageWrapper)
        self.actionDelPage = self.act(self.tr('&Delete Page'), shct=QKeySequence('Delete'), trig=self.notesTree.delPageWrapper)
        self.actionQuit = self.act(self.tr('&Quit'), shct=QKeySequence.Quit)
        self.connect(self.actionQuit, SIGNAL('triggered()'), self, SLOT('close()'))
        self.actionQuit.setMenuRole(QAction.QuitRole)
        # actions in menuEdit
        self.actionUndo = self.act(self.tr('&Undo'), shct=QKeySequence.Undo, trig=lambda: self.notesEdit.undo())
        self.actionUndo.setEnabled(False)
        self.notesEdit.undoAvailable.connect(self.actionUndo.setEnabled)
        self.actionRedo = self.act(self.tr('&Redo'), shct=QKeySequence.Redo, trig=lambda: self.notesEdit.redo())
        self.actionRedo.setEnabled(False)
        self.notesEdit.redoAvailable.connect(self.actionRedo.setEnabled)
        self.actionFindText = self.act(self.tr('&Find Text'), shct=QKeySequence.Find)
        self.actionFindText.setCheckable(True)
        self.actionFindText.triggered.connect(self.findBar.setVisible)
        self.actionFind = self.act(self.tr('Next'), shct=QKeySequence.FindNext, trig=self.findText)
        self.actionFindPrev = self.act(self.tr('Previous'), shct=QKeySequence.FindPrevious, 
                trig=lambda:self.findText(back=True))
        # actions in menuView
        self.actionEdit = self.act(self.tr('Edit'), shct=QKeySequence('Ctrl+E'), trigbool=self.edit)
        self.actionLiveView = self.act(self.tr('Live Edit'), shct=QKeySequence('Ctrl+R'), trigbool=self.liveView)
        self.actionFlipEditAndView = self.act(self.tr('Flip Edit and View'), trig=self.flipEditAndView)
        self.actionFlipEditAndView.setEnabled(False)
        self.actionLeftAndRight = self.act(self.tr('Split into Left and Right'), trig=self.leftAndRight)
        self.actionUpAndDown = self.act(self.tr('Split into Up and Down'), trig=self.upAndDown)
        #self.actionLeftAndRight.setEnabled(False)
        #self.actionUpAndDown.setEnabled(False)
        # actions in menuHelp
        self.actionReadme = self.act(self.tr('README'), trig=self.readmeHelp)

        self.menuBar = QMenuBar(self)
        self.setMenuBar(self.menuBar)
        self.menuFile = self.menuBar.addMenu(self.tr('&File'))
        self.menuEdit = self.menuBar.addMenu(self.tr('&Edit'))
        self.menuView = self.menuBar.addMenu(self.tr('&View'))
        self.menuHelp = self.menuBar.addMenu(self.tr('&Help'))
        # menuFile
        self.menuFile.addAction(self.actionNewPage)
        self.menuFile.addAction(self.actionNewSubpage)
        self.menuFile.addAction(self.actionImportPage)
        self.menuFile.addAction(self.actionOpenNotebook)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSaveAs)
        self.menuExport = self.menuFile.addMenu(self.tr('&Export'))
        self.menuExport.addAction(self.actionHtml)
        self.menuExport.addAction(self.actionPdf)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionRenamePage)
        self.menuFile.addAction(self.actionDelPage)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        # menuEdit
        self.menuEdit.addAction(self.actionUndo)
        self.menuEdit.addAction(self.actionRedo)
        self.menuEdit.addAction(self.actionFindText)
        # menuView
        self.menuView.addAction(self.actionEdit)
        self.menuView.addAction(self.actionLiveView)
        self.menuView.addAction(self.actionFlipEditAndView)
        self.menuMode = self.menuView.addMenu(self.tr('Mode'))
        self.menuMode.addAction(self.actionLeftAndRight)
        self.menuMode.addAction(self.actionUpAndDown)
        # menuHelp
        self.menuHelp.addAction(self.actionReadme)

        self.toolBar = QToolBar(self.tr('toolbar'), self)
        self.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.toolBar.addAction(self.actionEdit)
        self.toolBar.addAction(self.actionLiveView)
        self.findEdit = QLineEdit(self.findBar)
        self.findEdit.returnPressed.connect(self.findText)
        self.checkBox = QCheckBox(self.tr('Match case'), self.findBar)
        self.findBar.addWidget(self.findEdit)
        self.findBar.addWidget(self.checkBox)
        self.findBar.addAction(self.actionFindPrev)
        self.findBar.addAction(self.actionFind)
        self.findBar.setVisible(False)
        self.findBar.visibilityChanged.connect(self.findBarVisibilityChanged)
        
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)
        self.statusLabel = QLabel(self)
        self.statusBar.addWidget(self.statusLabel, 1)
        
        #self.connect(self.notesTree, SIGNAL('customContextMenuRequested(QPoint)'), self.treeMenu)
        self.notesTree.currentItemChanged.connect(self.currentItemChangedWrapper)
        self.searchList.currentRowChanged.connect(self.listItemChanged)
        self.connect(self.notesEdit, SIGNAL('textChanged()'), self.noteEditted)

        self.notesEdit.document().modificationChanged.connect(self.modificationChanged)
        self.notesView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.notesView.page().linkClicked.connect(self.linkClicked)
        self.notesView.page().linkHovered.connect(self.linkHovered)
        self.notesView.page().mainFrame().contentsSizeChanged.connect(self.contentsSizeChanged)

        self.scrollPosition = QPoint(0, 0)
        self.contentsSize = QSize(0, 0)

        QDir.setCurrent(notebookPath)
        #QSettings.setPath(QSettings.NativeFormat, QSettings.UserScope, notebookPath)
        #self.notebookSettings = QSettings('mikidown', 'notebook')
        self.notebookSettings = QSettings(notebookPath+'/notebook.conf', QSettings.NativeFormat)
        self.initTree(notebookPath, self.notesTree)
        self.updateRecentViewedNotes()
        files = readListFromSettings(self.notebookSettings, 'recentViewedNoteList')
        if len(files) != 0:
            item = self.notesTree.pagePathToItem(files[0])
            self.notesTree.setCurrentItem(item)

    def initTree(self, notePath, parent):
        if not QDir(notePath).exists():
            return
        noteDir = QDir(notePath)
        self.notesList = noteDir.entryInfoList(['*.markdown'],
                               QDir.NoFilter,
                               QDir.Name|QDir.IgnoreCase)
        for note in self.notesList:
            item = QTreeWidgetItem(parent, [note.baseName()])
            path = notePath + '/' + note.baseName()
            self.initTree(path, item)
        self.editted = 0

    def openNote(self, noteFullName):
        filename = noteFullName + '.markdown'
        print(filename)
        fh = QFile(filename)
        try:
            if not fh.open(QIODevice.ReadOnly):
                raise IOError(fh.errorString())
        except IOError as e:
            QMessageBox.warning(self, 'Read Error', 
                    'Failed to open %s: %s' % (filename, e))
        finally:
            if fh is not None:
                noteBody = QTextStream(fh).readAll()
                fh.close()
                self.notesEdit.setPlainText(noteBody)
                #self.editted = 0
                #self.actionSave.setEnabled(False)
                self.notesEdit.document().setModified(False)
                self.updateView()
                self.setCurrentFile()
                self.updateRecentViewedNotes()
                self.viewedListActions[-1].setChecked(True)
                self.statusLabel.setText(noteFullName)
                #self.statusBar.showMessage(noteFullName)

    def currentItemChangedWrapper(self, current, previous):
        if current is None:
            return
{'fraction_non_alphanumeric': 0.12049519781478545, 'fraction_numerical': 0.004053220548065909, 'mean_word_length': 3.0353777777777777, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7017491', 'n_tokens_mistral': 7114, 'n_tokens_neox': 6933, 'n_words': 866}