コード例 #1
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_windowTitleAndTabs_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        tab_with_file = self.window.currentTab

        self.window.createNew('bla')
        processEventsUntilIdle()

        tab_with_unsaved_content = self.window.currentTab

        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertIs(self.window.currentTab, tab_with_unsaved_content)
        self.assertIs(self.window.tabWidget.currentWidget(), tab_with_unsaved_content)
        self.assertEqual(self.window.ind, 1)
        self.assertEqual(self.window.tabWidget.tabText(0), 'existing_file')
        self.assertEqual(self.window.tabWidget.tabText(1), 'New document*')

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertIs(self.window.currentTab, tab_with_file)
        self.assertIs(self.window.tabWidget.currentWidget(), tab_with_file)
コード例 #2
0
ファイル: retext.py プロジェクト: davidfraser/retext
def main():
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	RtTranslator = QTranslator()
	if not RtTranslator.load("retext_"+QLocale.system().name(), "locale"):
		RtTranslator.load("retext_"+QLocale.system().name(), "/usr/share/retext/locale")
	QtTranslator = QTranslator()
	QtTranslator.load("qt_"+QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	if settings.contains('appStyleSheet'):
		stylename = readFromSettings('appStyleSheet', str)
		sheetfile = QFile(stylename)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	fileNames = [QFileInfo(arg).canonicalFilePath() for arg in sys.argv[1:]]
	for fileName in fileNames:
		try:
			fileName = QString.fromUtf8(fileName)
		except:
			# Not needed for Python 3
			pass
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
	sys.exit(app.exec_())
コード例 #3
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndRestructuredtextAsDefaultMarkup(self):
        self.globalSettingsMock.defaultMarkup = 'reStructuredText'
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #4
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndMarkdownAsDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        # markdown is the default markup
        self.check_widgets_enabled_for_markdown(self.window)
コード例 #5
0
    def test_saveWidgetStates(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))
        self.assertFalse(self.window.isWindowModified())

        # check if it's enabled after inserting some text
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))
        self.assertTrue(self.window.isWindowModified())

        # check if it's disabled again after loading a file in a second tab and switching to it
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))
        self.assertFalse(self.window.isWindowModified())

        # check if it's enabled again after switching back
        self.window.switchTab()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))
        self.assertTrue(self.window.isWindowModified())

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))
            self.assertFalse(self.window.isWindowModified())
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))
コード例 #6
0
    def test_saveWidgetStates_autosaveEnabled(self, getOpenFileNamesMock,
                                              getSaveFileNameMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))

        # check if it stays enabled after inserting some text (because autosave
        # can't save without a filename)
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))

            # check if it is still disabled after inserting some text (because
            # autosave will take care of saving now that the filename is known)
            self.window.currentTab.editBox.textCursor().insertText('some text')
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))
コード例 #7
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_markupDependentWidgetStates_afterLoadingRestructuredtextDocument(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #8
0
    def test_windowTitleAndTabs_afterStartWithEmptyTab(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertFalse(self.window.currentTab.fileName)
コード例 #9
0
    def test_markupDependentWidgetStates_afterChangingDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.window.setDefaultMarkup(markups.ReStructuredTextMarkup)

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #10
0
ファイル: test_window.py プロジェクト: varikmp/retext
    def test_markupDependentWidgetStates_afterLoadingMarkdownDocument(
            self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        app.processEvents()

        self.check_widgets_enabled_for_markdown(self.window)
コード例 #11
0
ファイル: test_window.py プロジェクト: jrodri39/retext
    def test_windowTitleAndTabs_afterLoadingFile(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that file is opened in the existing empty tab
        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))
コード例 #12
0
ファイル: retext.py プロジェクト: ahnan4arch/retext
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #13
0
 def test_doesNotTweakSpecialCharacters(self):
     fileName = tempfile.mkstemp(suffix='.mkd')[1]
     content = 'Non-breaking\u00a0space\n\nLine\u2028separator\n'
     with open(fileName, 'w') as tempFile:
         tempFile.write(content)
     window = ReTextWindow()
     window.openFileWrapper(fileName)
     self.assertTrue(window.saveFile())
     with open(fileName) as tempFile:
         self.assertMultiLineEqual(content, tempFile.read())
     os.remove(fileName)
コード例 #14
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_encodingAndReloadWidgetStates(self, getOpenFileNamesMock):
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionReload','actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionReload','actionSetEncoding'))
コード例 #15
0
ファイル: test_window.py プロジェクト: starofrainnight/retext
 def test_doesNotTweakSpecialCharacters(self):
     fileName = tempfile.mkstemp(suffix='.mkd')[1]
     content = 'Non-breaking\u00a0space\n\nLine\u2028separator\n'
     with open(fileName, 'w', encoding='utf-8') as tempFile:
         tempFile.write(content)
     window = ReTextWindow()
     window.openFileWrapper(fileName)
     self.assertTrue(window.saveFile())
     with open(fileName, encoding='utf-8') as tempFile:
         self.assertMultiLineEqual(content, tempFile.read())
     with suppress(PermissionError):
         os.remove(fileName)
コード例 #16
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_markupDependentWidgetStates_afterSavingDocumentAsDifferentMarkup(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()

        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.rst'))

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #17
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_markupDependentWidgetStates_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Just to make sure that sending two actionOpen triggers has had the desired effect
        self.assertIn('.rst', self.window.windowTitle())

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertIn('.md', self.window.windowTitle())
        self.check_widgets_enabled_for_markdown(self.window)
コード例 #18
0
ファイル: test_window.py プロジェクト: varikmp/retext
    def test_encodingAndReloadWidgetStates_alwaysDisabledWhenAutosaveEnabled(
            self, getOpenFileNamesMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        app.processEvents()
        self.check_widgets_disabled(self.window,
                                    ('actionReload', 'actionSetEncoding'))

        self.window.actionOpen.trigger()
        app.processEvents()
        self.check_widgets_disabled(self.window,
                                    ('actionReload', 'actionSetEncoding'))
コード例 #19
0
    def __init__(self, parent=None):
        ReTextWindow.__init__(self, parent)

        # Read notebookList, open the first notebook.
        notebooks = Mikibook.read()
        if len(notebooks) == 0:
            Mikibook.create()
            notebooks = Mikibook.read()

        if len(notebooks) != 0:
            settings = Setting(notebooks)
            # Initialize application and main window.

        self.settings = settings
        self.notePath = settings.notePath

        ################ Setup core components ################
        self.notesTree = MikiTree(self)
        self.notesTree.setObjectName("notesTree")
        initTree(self.notePath, self.notesTree)
        self.notesTree.sortItems(0, Qt.AscendingOrder)

        #self.viewedList = QToolBar(self.tr('Recently Viewed'), self)
        #self.viewedList.setIconSize(QSize(16, 16))
        #self.viewedList.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        #self.viewedListActions = []
        self.noteSplitter = QSplitter(Qt.Horizontal)

        self.dockIndex = QDockWidget("Index")
        self.dockSearch = QDockWidget("Search")
        self.searchEdit = QLineEdit()
        self.searchView = MikiSearch(self)
        self.searchTab = QWidget()
        self.dockToc = QDockWidget("TOC")
        self.tocTree = TocTree()
        self.dockAttachment = QDockWidget("Attachment")
        self.attachmentView = AttachmentView(self)

        #<-- wiki init done

        ################ Setup search engine   ################
        self.whoosh = Whoosh(self.settings.indexdir, self.settings.schema)
        self.whoosh.reindex(wikiPageIterator(self.notesTree))

        self.actions = dict()
        self.setupActions()

        self.setupMainWindow()
コード例 #20
0
    def __init__(self, parent=None):
        ReTextWindow.__init__(self, parent)

        # Read notebookList, open the first notebook.
        notebooks = Mikibook.read()
        if len(notebooks) == 0:
            Mikibook.create()
            notebooks = Mikibook.read()

        if len(notebooks) != 0:
            settings = Setting(notebooks)
            # Initialize application and main window.

        self.settings = settings
        self.notePath = settings.notePath

        ################ Setup core components ################
        self.notesTree = MikiTree(self)
        self.notesTree.setObjectName("notesTree")
        initTree(self.notePath, self.notesTree)
        self.notesTree.sortItems(0, Qt.AscendingOrder)

        #self.viewedList = QToolBar(self.tr('Recently Viewed'), self)
        #self.viewedList.setIconSize(QSize(16, 16))
        #self.viewedList.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        #self.viewedListActions = []
        self.noteSplitter = QSplitter(Qt.Horizontal)

        self.dockIndex = QDockWidget("Index")
        self.dockSearch = QDockWidget("Search")
        self.searchEdit = QLineEdit()
        self.searchView = MikiSearch(self)
        self.searchTab = QWidget()
        self.dockToc = QDockWidget("TOC")
        self.tocTree = TocTree()
        self.dockAttachment = QDockWidget("Attachment")
        self.attachmentView = AttachmentView(self)

        #<-- wiki init done

        ################ Setup search engine   ################
        self.whoosh = Whoosh(self.settings.indexdir, self.settings.schema)
        self.whoosh.reindex(wikiPageIterator(self.notesTree))

        self.actions = dict()
        self.setupActions()

        self.setupMainWindow()
コード例 #21
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_saveWidgetStates_autosaveEnabled(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it stays enabled after inserting some text (because autosave
        # can't save without a filename)
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))

            # check if it is still disabled after inserting some text (because
            # autosave will take care of saving now that the filename is known)
            self.window.currentTab.editBox.textCursor().insertText('some text')
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))
コード例 #22
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndMarkdownAsDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        # markdown is the default markup
        self.check_widgets_enabled_for_markdown(self.window)
コード例 #23
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterLoadingRestructuredtextDocument(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #24
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndRestructuredtextAsDefaultMarkup(self):
        self.globalSettingsMock.defaultMarkup = 'reStructuredText'
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #25
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_saveWidgetStates(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it's enabled after inserting some text
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled again after loading a file in a second tab and switching to it
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it's enabled again after switching back
        self.window.switchTab()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))
コード例 #26
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterChangingDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.window.setDefaultMarkup(markups.ReStructuredTextMarkup)

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #27
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_windowTitleAndTabs_afterStartWithEmptyTab(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertFalse(self.window.currentTab.fileName)
コード例 #28
0
ファイル: retext.py プロジェクト: cnsinger/retext
def main():
    app = QApplication(sys.argv)
    app.setOrganizationName("ReText project")
    app.setApplicationName("ReText")
    RtTranslator = QTranslator()
    if not RtTranslator.load("retext_" + QLocale.system().name(), "locale"):
        RtTranslator.load("retext_" + QLocale.system().name(),
                          "/usr/share/retext/locale")
    QtTranslator = QTranslator()
    QtTranslator.load("qt_" + QLocale.system().name(),
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(RtTranslator)
    app.installTranslator(QtTranslator)
    if settings.contains('appStyleSheet'):
        stylename = readFromSettings('appStyleSheet', str)
        sheetfile = QFile(stylename)
        sheetfile.open(QIODevice.ReadOnly)
        app.setStyleSheet(QTextStream(sheetfile).readAll())
        sheetfile.close()
    window = ReTextWindow()
    window.show()
    fileNames = [QFileInfo(arg).canonicalFilePath() for arg in sys.argv[1:]]
    for fileName in fileNames:
        try:
            fileName = QString.fromUtf8(fileName)
        except:
            # Not needed for Python 3
            pass
        if QFile.exists(fileName):
            window.openFileWrapper(fileName)
    signal.signal(signal.SIGINT, lambda sig, frame: window.close())
    sys.exit(app.exec_())
コード例 #29
0
ファイル: retext.py プロジェクト: liyongming1982/retext
def main():
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if sys.stdin.isatty() else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #30
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_windowTitleAndTabs_afterLoadingFile(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that file is opened in the existing empty tab
        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))
コード例 #31
0
ファイル: test_window.py プロジェクト: visaul/retext
    def test_activeTab_afterLoadingFileThatIsAlreadyOpenInOtherTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        tab_with_file = self.window.currentTab

        self.window.createNew('')
        processEventsUntilIdle()

        # Make sure that the newly created tab is the active one
        self.assertFalse(self.window.currentTab.fileName)

        # Load the same document again
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that we have indeed been switched back to the previous tab
        self.assertIs(self.window.currentTab, tab_with_file)
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))
コード例 #32
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_encodingAndReloadWidgetStates(self, getOpenFileNamesMock):
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionReload','actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionReload','actionSetEncoding'))
コード例 #33
0
def main():
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.trigger()
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if sys.stdin.isatty() else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #34
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterSavingDocumentAsDifferentMarkup(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()

        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.rst'))

        self.check_widgets_enabled_for_restructuredtext(self.window)
コード例 #35
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_markupDependentWidgetStates_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Just to make sure that sending two actionOpen triggers has had the desired effect
        self.assertIn('.rst', self.window.windowTitle())

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertIn('.md', self.window.windowTitle())
        self.check_widgets_enabled_for_markdown(self.window)
コード例 #36
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_activeTab_afterLoadingFileThatIsAlreadyOpenInOtherTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        tab_with_file = self.window.currentTab

        self.window.createNew('')
        processEventsUntilIdle()

        # Make sure that the newly created tab is the active one
        self.assertFalse(self.window.currentTab.fileName)

        # Load the same document again
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that we have indeed been switched back to the previous tab
        self.assertTrue(self.window.currentTab is tab_with_file)
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))
コード例 #37
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
    def test_windowTitleAndTabs_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        tab_with_file = self.window.currentTab

        self.window.createNew('bla')
        processEventsUntilIdle()

        tab_with_unsaved_content = self.window.currentTab

        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab is tab_with_unsaved_content)
        self.assertTrue(self.window.tabWidget.currentWidget() is tab_with_unsaved_content)

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab is tab_with_file)
        self.assertTrue(self.window.tabWidget.currentWidget() is tab_with_file)
コード例 #38
0
ファイル: __main__.py プロジェクト: zymzs/retext
def main():
    multiprocessing.set_start_method('spawn')

    if markups.__version_tuple__ < (2, ):
        sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

    # If we're running on Windows without a console, then discard stdout
    # and save stderr to a file to facilitate debugging in case of crashes.
    if sys.executable.endswith('pythonw.exe'):
        sys.stdout = open(devnull, 'w')
        sys.stderr = open('stderr.log', 'w')

    try:
        # See https://github.com/retext-project/retext/issues/399
        # and https://launchpad.net/bugs/941826
        ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
    except OSError:
        pass

    # Needed for Qt WebEngine on Windows
    QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    app.setOrganizationName("ReText project")
    app.setApplicationName("ReText")
    app.setApplicationDisplayName("ReText")
    app.setApplicationVersion(app_version)
    app.setOrganizationDomain('mitya57.me')
    if hasattr(app, 'setDesktopFileName'):  # available since Qt 5.7
        app.setDesktopFileName('me.mitya57.ReText.desktop')
    QNetworkProxyFactory.setUseSystemConfiguration(True)
    initializeDataDirs()
    RtTranslator = QTranslator()
    for path in datadirs:
        if RtTranslator.load('retext_' + globalSettings.uiLanguage,
                             join(path, 'locale')):
            break
    QtTranslator = QTranslator()
    QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(RtTranslator)
    app.installTranslator(QtTranslator)
    print('Using configuration file:', settings.fileName())
    if globalSettings.appStyleSheet:
        sheetfile = QFile(globalSettings.appStyleSheet)
        sheetfile.open(QIODevice.ReadOnly)
        app.setStyleSheet(QTextStream(sheetfile).readAll())
        sheetfile.close()
    window = ReTextWindow()
    window.show()
    # ReText can change directory when loading files, so we
    # need to have a list of canonical names before loading
    fileNames = list(map(canonicalize, sys.argv[1:]))
    previewMode = False
    readStdIn = False
    if globalSettings.openLastFilesOnStartup:
        window.restoreLastOpenedFiles()
    for fileName in fileNames:
        if QFile.exists(fileName):
            window.openFileWrapper(fileName)
            if previewMode:
                window.actionPreview.setChecked(True)
                window.preview(True)
        elif fileName == '--preview':
            previewMode = True
        elif fileName == '-':
            readStdIn = True

    inputData = ''
    if readStdIn and sys.stdin is not None:
        if sys.stdin.isatty():
            print('Reading stdin, press ^D to end...')
        inputData = sys.stdin.read()
    if inputData or not window.tabWidget.count():
        window.createNew(inputData)
    signal.signal(signal.SIGINT, lambda sig, frame: window.close())
    sys.exit(app.exec())
コード例 #39
0
ファイル: retext.py プロジェクト: jrodri39/retext
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()

	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #40
0
def main():
	multiprocessing.set_start_method('spawn')

	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts)
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)

	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)

	parser = QCommandLineParser()
	parser.addHelpOption()
	parser.addVersionOption()
	previewOption = QCommandLineOption('preview',
		QApplication.translate('main', 'Open the files in preview mode'))
	newWindowOption = QCommandLineOption('new-window',
		QApplication.translate('main', 'Create a new window even if there is an existing one'))
	parser.addOption(previewOption)
	parser.addOption(newWindowOption)
	parser.addPositionalArgument('files',
		QApplication.translate('main', 'List of files to open'),
		'[files...]')

	parser.process(app)
	filesToOpen = parser.positionalArguments()

	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.OpenModeFlag.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()

	openInExistingWindow = (globalSettings.openFilesInExistingWindow
		and not parser.isSet(newWindowOption))
	connection = QDBusConnection.sessionBus()
	if connection.isConnected() and openInExistingWindow:
		connection.registerObject('/', window, QDBusConnection.RegisterOption.ExportAllSlots)
		serviceName = 'me.mitya57.ReText'
		if not connection.registerService(serviceName) and filesToOpen:
			print('Opening the file(s) in the existing window of ReText.')
			iface = QDBusInterface(serviceName, '/', '', connection)
			for fileName in filesToOpen:
				iface.call('openFileWrapper', fileName)
			qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
			qWidgetIface.call('raise')
			sys.exit(0)

	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, filesToOpen))
	readStdIn = False

	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if parser.isSet(previewOption):
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #41
0
ファイル: __main__.py プロジェクト: starofrainnight/retext
def main():
	multiprocessing.set_start_method('spawn')

	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	readStdIn = False
	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
コード例 #42
0
 def saveFileMain(self, dlg):
     ReTextWindow.saveFileMain(self, dlg)
コード例 #43
0
class TestWindow(unittest.TestCase):
    def setUp(self):
        warnings.simplefilter("ignore", Warning)
        self.readListFromSettingsMock = patch(
            'ReText.window.readListFromSettings', return_value=[]).start()
        self.writeListToSettingsMock = patch(
            'ReText.window.writeListToSettings').start()
        self.globalSettingsMock = patch(
            'ReText.window.globalSettings',
            MagicMock(**ReText.configOptions)).start()
        self.fileSystemWatcherMock = patch(
            'ReText.window.QFileSystemWatcher').start()
        ReText.tab.globalSettings = self.globalSettingsMock

    def tearDown(self):
        patch.stopall()

    #
    # Helper functions
    #

    @staticmethod
    def get_ui_enabled_states(window):
        enabled = set([])
        disabled = set([])

        for item in ('actionBold', 'actionCopy', 'actionCut', 'actionItalic',
                     'actionUnderline', 'actionUndo', 'actionRedo',
                     'actionReload', 'actionSave', 'actionSetEncoding',
                     'editBar', 'formattingBox', 'symbolBox'):
            if getattr(window, item).isEnabled():
                enabled.add(item)
            else:
                disabled.add(item)

        return enabled, disabled

    def check_widget_state(self, window, expected_enabled, expected_disabled):
        actually_enabled, actually_disabled = self.get_ui_enabled_states(
            window)

        self.assertEqual(expected_enabled - actually_enabled, set(),
                         'These widgets are unexpectedly disabled')
        self.assertEqual(expected_disabled - actually_disabled, set(),
                         'These widgets are unexpectedly enabled')

    def check_widgets_enabled_for_markdown(self, window):
        self.check_widget_state(
            window,
            set([
                'actionBold', 'actionItalic', 'actionUnderline',
                'formattingBox', 'symbolBox'
            ]), set())

    def check_widgets_enabled_for_restructuredtext(self, window):
        self.check_widget_state(
            window, set(['actionBold', 'actionItalic']),
            set(['actionUnderline', 'formattingBox', 'symbolBox']))

    def check_widgets_enabled(self, window, widgets):
        self.check_widget_state(window, set(widgets), set())

    def check_widgets_disabled(self, window, widgets):
        self.check_widget_state(window, set(), set(widgets))

    #
    # Tests
    #

    def test_windowTitleAndTabs_afterStartWithEmptyTab(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertFalse(self.window.currentTab.fileName)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_windowTitleAndTabs_afterLoadingFile(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that file is opened in the existing empty tab
        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(
            self.window.currentTab.fileName.endswith(
                'tests/testdata/existing_file.md'))
        self.assertFalse(self.window.isWindowModified())

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_windowTitleAndTabs_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        tab_with_file = self.window.currentTab

        self.window.createNew('bla')
        processEventsUntilIdle()

        tab_with_unsaved_content = self.window.currentTab

        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertIs(self.window.currentTab, tab_with_unsaved_content)
        self.assertIs(self.window.tabWidget.currentWidget(),
                      tab_with_unsaved_content)

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertIs(self.window.currentTab, tab_with_file)
        self.assertIs(self.window.tabWidget.currentWidget(), tab_with_file)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_activeTab_afterLoadingFileThatIsAlreadyOpenInOtherTab(
            self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        tab_with_file = self.window.currentTab

        self.window.createNew('')
        processEventsUntilIdle()

        # Make sure that the newly created tab is the active one
        self.assertFalse(self.window.currentTab.fileName)

        # Load the same document again
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that we have indeed been switched back to the previous tab
        self.assertIs(self.window.currentTab, tab_with_file)
        self.assertTrue(
            self.window.currentTab.fileName.endswith(
                'tests/testdata/existing_file.md'))

    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndMarkdownAsDefaultMarkup(
            self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        # markdown is the default markup
        self.check_widgets_enabled_for_markdown(self.window)

    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndRestructuredtextAsDefaultMarkup(
            self):
        self.globalSettingsMock.defaultMarkup = 'reStructuredText'
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)

    def test_markupDependentWidgetStates_afterChangingDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.window.setDefaultMarkup(markups.ReStructuredTextMarkup)

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_markupDependentWidgetStates_afterLoadingMarkdownDocument(
            self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_markdown(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.rst')], None))
    def test_markupDependentWidgetStates_afterLoadingRestructuredtextDocument(
            self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           side_effect=[([os.path.join(path_to_testdata,
                                       'existing_file.md')], None),
                        ([os.path.join(path_to_testdata,
                                       'existing_file.rst')], None)])
    def test_markupDependentWidgetStates_afterSwitchingTab(
            self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Just to make sure that sending two actionOpen triggers has had the desired effect
        self.assertIn('.rst', self.window.windowTitle())

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertIn('.md', self.window.windowTitle())
        self.check_widgets_enabled_for_markdown(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName',
           return_value=(os.path.join(path_to_testdata,
                                      'not_existing_file.rst'), None))
    def test_markupDependentWidgetStates_afterSavingDocumentAsDifferentMarkup(
            self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()

        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.rst'))

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName',
           return_value=(os.path.join(path_to_testdata,
                                      'not_existing_file.md'), None))
    def test_saveWidgetStates(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))
        self.assertFalse(self.window.isWindowModified())

        # check if it's enabled after inserting some text
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))
        self.assertTrue(self.window.isWindowModified())

        # check if it's disabled again after loading a file in a second tab and switching to it
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))
        self.assertFalse(self.window.isWindowModified())

        # check if it's enabled again after switching back
        self.window.switchTab()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))
        self.assertTrue(self.window.isWindowModified())

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))
            self.assertFalse(self.window.isWindowModified())
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName',
           return_value=(os.path.join(path_to_testdata,
                                      'not_existing_file.md'), None))
    def test_saveWidgetStates_autosaveEnabled(self, getOpenFileNamesMock,
                                              getSaveFileNameMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave', ))

        # check if it stays enabled after inserting some text (because autosave
        # can't save without a filename)
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave', ))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))

            # check if it is still disabled after inserting some text (because
            # autosave will take care of saving now that the filename is known)
            self.window.currentTab.editBox.textCursor().insertText('some text')
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave', ))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_encodingAndReloadWidgetStates(self, getOpenFileNamesMock):
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window,
                                    ('actionReload', 'actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window,
                                   ('actionReload', 'actionSetEncoding'))

    @patch('ReText.window.QFileDialog.getOpenFileNames',
           return_value=([os.path.join(path_to_testdata,
                                       'existing_file.md')], None))
    def test_encodingAndReloadWidgetStates_alwaysDisabledWhenAutosaveEnabled(
            self, getOpenFileNamesMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window,
                                    ('actionReload', 'actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window,
                                    ('actionReload', 'actionSetEncoding'))

    def test_doesNotTweakSpecialCharacters(self):
        fileName = tempfile.mkstemp(suffix='.mkd')[1]
        content = 'Non-breaking\u00a0space\n\nLine\u2028separator\n'
        with open(fileName, 'w', encoding='utf-8') as tempFile:
            tempFile.write(content)
        window = ReTextWindow()
        window.openFileWrapper(fileName)
        self.assertTrue(window.saveFile())
        with open(fileName, encoding='utf-8') as tempFile:
            self.assertMultiLineEqual(content, tempFile.read())
        with suppress(PermissionError):
            os.remove(fileName)
コード例 #44
0
ファイル: test_window.py プロジェクト: ahnan4arch/retext
class TestWindow(unittest.TestCase):

    def setUp(self):
        warnings.simplefilter("ignore", Warning)
        self.readListFromSettingsMock = patch('ReText.window.readListFromSettings', return_value=[]).start()
        self.writeListToSettingsMock  = patch('ReText.window.writeListToSettings').start()
        self.writeToSettingsMock      = patch('ReText.window.writeToSettings').start()
        self.globalSettingsMock       = patch('ReText.window.globalSettings', MagicMock(**ReText.configOptions)).start()
        self.fileSystemWatcherMock    = patch('ReText.window.QFileSystemWatcher').start()

    def tearDown(self):
        patch.stopall()


    #
    # Helper functions
    #

    @staticmethod
    def get_ui_enabled_states(window):
        enabled = set([])
        disabled = set([])

        for item in ('actionBold',
                     'actionCopy',
                     'actionCut',
                     'actionItalic',
                     'actionUnderline',
                     'actionUndo',
                     'actionRedo',
                     'actionReload',
                     'actionSave',
                     'actionSetEncoding',
                     'editBar',
                     'formattingBox',
                     'symbolBox'):
            if getattr(window, item).isEnabled():
                enabled.add(item)
            else:
                disabled.add(item)

        return enabled, disabled

    def check_widget_state(self, window, expected_enabled, expected_disabled):
        actually_enabled, actually_disabled = self.get_ui_enabled_states(window)

        self.assertEqual(expected_enabled - actually_enabled, set(), 'These widgets are unexpectedly disabled')
        self.assertEqual(expected_disabled - actually_disabled, set(), 'These widgets are unexpectedly enabled')

    def check_widgets_enabled_for_markdown(self, window):
        self.check_widget_state(window,
                                set(['actionBold', 'actionItalic', 'actionUnderline', 'formattingBox', 'symbolBox']),
                                set())

    def check_widgets_enabled_for_restructuredtext(self, window):
        self.check_widget_state(window,
                                set(['actionBold', 'actionItalic']),
                                set(['actionUnderline', 'formattingBox', 'symbolBox']))

    def check_widgets_enabled(self, window, widgets):
        self.check_widget_state(window,
                                set(widgets),
                                set())

    def check_widgets_disabled(self, window, widgets):
        self.check_widget_state(window,
                                set(),
                                set(widgets))


    #
    # Tests
    #

    def test_windowTitleAndTabs_afterStartWithEmptyTab(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertFalse(self.window.currentTab.fileName)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_windowTitleAndTabs_afterLoadingFile(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that file is opened in the existing empty tab
        self.assertEqual(1, self.window.tabWidget.count())
        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_windowTitleAndTabs_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        tab_with_file = self.window.currentTab

        self.window.createNew('bla')
        processEventsUntilIdle()

        tab_with_unsaved_content = self.window.currentTab

        self.assertEqual('New document[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab is tab_with_unsaved_content)
        self.assertTrue(self.window.tabWidget.currentWidget() is tab_with_unsaved_content)

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertEqual('existing_file.md[*]', self.window.windowTitle())
        self.assertTrue(self.window.currentTab is tab_with_file)
        self.assertTrue(self.window.tabWidget.currentWidget() is tab_with_file)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_activeTab_afterLoadingFileThatIsAlreadyOpenInOtherTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        tab_with_file = self.window.currentTab

        self.window.createNew('')
        processEventsUntilIdle()

        # Make sure that the newly created tab is the active one
        self.assertFalse(self.window.currentTab.fileName)

        # Load the same document again
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Check that we have indeed been switched back to the previous tab
        self.assertTrue(self.window.currentTab is tab_with_file)
        self.assertTrue(self.window.currentTab.fileName.endswith('tests/testdata/existing_file.md'))

    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndMarkdownAsDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        # markdown is the default markup
        self.check_widgets_enabled_for_markdown(self.window)

    def test_markupDependentWidgetStates_afterStartWithEmptyTabAndRestructuredtextAsDefaultMarkup(self):
        self.globalSettingsMock.defaultMarkup = 'reStructuredText'
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)

    def test_markupDependentWidgetStates_afterChangingDefaultMarkup(self):
        self.window = ReTextWindow()
        self.window.createNew('')
        processEventsUntilIdle()

        self.window.setDefaultMarkup(markups.ReStructuredTextMarkup)

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_markupDependentWidgetStates_afterLoadingMarkdownDocument(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_markdown(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.rst')], None))
    def test_markupDependentWidgetStates_afterLoadingRestructuredtextDocument(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames', side_effect=[ ([os.path.join(path_to_testdata, 'existing_file.md')], None),
                                                                       ([os.path.join(path_to_testdata, 'existing_file.rst')], None) ])
    def test_markupDependentWidgetStates_afterSwitchingTab(self, getOpenFileNamesMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        # Just to make sure that sending two actionOpen triggers has had the desired effect
        self.assertIn('.rst', self.window.windowTitle())

        self.window.switchTab()
        processEventsUntilIdle()

        self.assertIn('.md', self.window.windowTitle())
        self.check_widgets_enabled_for_markdown(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName', return_value=(os.path.join(path_to_testdata, 'not_existing_file.rst'), None))
    def test_markupDependentWidgetStates_afterSavingDocumentAsDifferentMarkup(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()
        self.window.createNew('')
        self.window.actionOpen.trigger()
        processEventsUntilIdle()

        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()

        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.rst'))

        self.check_widgets_enabled_for_restructuredtext(self.window)

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName', return_value=(os.path.join(path_to_testdata, 'not_existing_file.md'), None))
    def test_saveWidgetStates(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it's enabled after inserting some text
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled again after loading a file in a second tab and switching to it
        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it's enabled again after switching back
        self.window.switchTab()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    @patch('ReText.window.QFileDialog.getSaveFileName', return_value=(os.path.join(path_to_testdata, 'not_existing_file.md'), None))
    def test_saveWidgetStates_autosaveEnabled(self, getOpenFileNamesMock, getSaveFileNameMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if save is disabled at first
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionSave',))

        # check if it stays enabled after inserting some text (because autosave
        # can't save without a filename)
        self.window.currentTab.editBox.textCursor().insertText('some text')
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionSave',))

        # check if it's disabled after saving
        try:
            self.window.actionSaveAs.trigger()
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))

            # check if it is still disabled after inserting some text (because
            # autosave will take care of saving now that the filename is known)
            self.window.currentTab.editBox.textCursor().insertText('some text')
            processEventsUntilIdle()
            self.check_widgets_disabled(self.window, ('actionSave',))
        finally:
            os.remove(os.path.join(path_to_testdata, 'not_existing_file.md'))

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_encodingAndReloadWidgetStates(self, getOpenFileNamesMock):
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionReload','actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_enabled(self.window, ('actionReload','actionSetEncoding'))

    @patch('ReText.window.QFileDialog.getOpenFileNames', return_value=([os.path.join(path_to_testdata, 'existing_file.md')], None))
    def test_encodingAndReloadWidgetStates_alwaysDisabledWhenAutosaveEnabled(self, getOpenFileNamesMock):
        self.globalSettingsMock.autoSave = True
        self.window = ReTextWindow()

        # check if reload/set encoding is disabled for a tab without filename set
        self.window.createNew('')
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionReload','actionSetEncoding'))

        self.window.actionOpen.trigger()
        processEventsUntilIdle()
        self.check_widgets_disabled(self.window, ('actionReload','actionSetEncoding'))
コード例 #45
0
 def saveFileMain(self, dlg):
     ReTextWindow.saveFileMain(self, dlg)