Ejemplo n.º 1
0
    def testFullScreen(self):
        showHideTreeActionInfo = self.application.actionController.getActionInfo(
            ShowHideTreeAction.stringId)
        showHideAttachesActionInfo = self.application.actionController.getActionInfo(
            ShowHideAttachesAction.stringId)
        showHideTagsActionInfo = self.application.actionController.getActionInfo(
            ShowHideTagsAction.stringId)

        self.application.actionController.check(FullScreenAction.stringId,
                                                True)

        if getOS().name == 'windows':
            self.assertTrue(self.mainWindow.IsFullScreen())

        self.assertFalse(self.mainWindow.treePanel.isShown())
        self.assertFalse(self.mainWindow.attachPanel.isShown())
        self.assertFalse(self.mainWindow.tagsCloudPanel.isShown())

        self.assertFalse(showHideTreeActionInfo.menuItem.IsChecked())
        self.assertFalse(showHideAttachesActionInfo.menuItem.IsChecked())
        self.assertFalse(showHideTagsActionInfo.menuItem.IsChecked())

        self.application.actionController.check(FullScreenAction.stringId,
                                                False)

        if getOS().name == 'windows':
            self.assertFalse(self.mainWindow.IsFullScreen())

        self.assertTrue(self.mainWindow.treePanel.isShown())
        self.assertTrue(self.mainWindow.attachPanel.isShown())
        self.assertTrue(self.mainWindow.tagsCloudPanel.isShown())

        self.assertTrue(showHideTreeActionInfo.menuItem.IsChecked())
        self.assertTrue(showHideAttachesActionInfo.menuItem.IsChecked())
        self.assertTrue(showHideTagsActionInfo.menuItem.IsChecked())
Ejemplo n.º 2
0
        def __correctSysPath(self):
            cmd_folder = unicode(os.path.dirname(os.path.abspath(__file__)), getOS().filesEncoding)

            syspath = [unicode(item, getOS().filesEncoding) if type(item) != type(u"") else item for item in sys.path]

            if cmd_folder not in syspath:
                sys.path.insert(0, cmd_folder)
Ejemplo n.º 3
0
    def OnInit(self):
        getOS().migrateConfig()
        self._fullConfigPath = getConfigPath()
        Application.init(self._fullConfigPath)

        try:
            starter = Starter()
            starter.processConsole()
        except StarterExit:
            return True

        redirector = LogRedirector(self.getLogFileName(self._fullConfigPath))
        redirector.init()

        from outwiker.gui.mainwindow import MainWindow

        self.mainWnd = MainWindow(None, -1, "")
        self.SetTopWindow(self.mainWnd)

        Application.mainWindow = self.mainWnd
        Application.actionController = ActionController(
            self.mainWnd, Application.config)

        registerActions(Application)
        self.mainWnd.createGui()

        Application.plugins.load(getPluginsDirList())

        self.bindActivateApp()
        self.Bind(wx.EVT_QUERY_END_SESSION, self._onEndSession)

        starter.processGUI()

        return True
Ejemplo n.º 4
0
    def OnInit (self):
        getOS().migrateConfig()
        self._fullConfigPath = getConfigPath ()
        Application.init(self._fullConfigPath)

        try:
            starter = Starter()
            starter.processConsole()
        except StarterExit:
            return True

        redirector = LogRedirector (self.getLogFileName (self._fullConfigPath))
        redirector.init()

        from outwiker.gui.mainwindow import MainWindow

        self.mainWnd = MainWindow(None, -1, "")
        self.SetTopWindow (self.mainWnd)

        Application.mainWindow = self.mainWnd
        Application.actionController = ActionController (self.mainWnd, Application.config)

        registerActions(Application)
        self.mainWnd.createGui()

        Application.plugins.load (getPluginsDirList())

        self.bindActivateApp()
        self.Bind (wx.EVT_QUERY_END_SESSION, self._onEndSession)

        starter.processGUI()

        return True
Ejemplo n.º 5
0
def openHelp():
    global _
    _ = get_()

    help_dir = _(u'help/en')
    help_path = os.path.join(getPluginPath(), help_dir, u'__content.html')
    getOS().startFile(help_path)
Ejemplo n.º 6
0
 def _updateExample (self):
     try:
         dateStr = unicode (datetime.now().strftime (self.GetValue().encode (getOS().filesEncoding)),
                            getOS().filesEncoding)
         self.exampleText.SetValue (dateStr)
     except ValueError:
         pass
Ejemplo n.º 7
0
    def testFullScreen(self):
        showHideTreeActionInfo = self.application.actionController.getActionInfo(ShowHideTreeAction.stringId)
        showHideAttachesActionInfo = self.application.actionController.getActionInfo(ShowHideAttachesAction.stringId)
        showHideTagsActionInfo = self.application.actionController.getActionInfo(ShowHideTagsAction.stringId)

        self.application.actionController.check(FullScreenAction.stringId, True)

        if getOS().name == 'windows':
            self.assertTrue(self.mainWindow.IsFullScreen())

        self.assertFalse(self.mainWindow.treePanel.isShown())
        self.assertFalse(self.mainWindow.attachPanel.isShown())
        self.assertFalse(self.mainWindow.tagsCloudPanel.isShown())

        self.assertFalse(showHideTreeActionInfo.menuItem.IsChecked())
        self.assertFalse(showHideAttachesActionInfo.menuItem.IsChecked())
        self.assertFalse(showHideTagsActionInfo.menuItem.IsChecked())

        self.application.actionController.check(FullScreenAction.stringId, False)

        if getOS().name == 'windows':
            self.assertFalse(self.mainWindow.IsFullScreen())

        self.assertTrue(self.mainWindow.treePanel.isShown())
        self.assertTrue(self.mainWindow.attachPanel.isShown())
        self.assertTrue(self.mainWindow.tagsCloudPanel.isShown())

        self.assertTrue(showHideTreeActionInfo.menuItem.IsChecked())
        self.assertTrue(showHideAttachesActionInfo.menuItem.IsChecked())
        self.assertTrue(showHideTagsActionInfo.menuItem.IsChecked())
Ejemplo n.º 8
0
 def run(self, params):
     # 0 - папка рядом с запускаемым файлом, затем идут другие папки, если они есть
     pluginsDir = getPluginsDirList()[-1]
     try:
         getOS().startFile(pluginsDir)
     except OSError:
         text = _(u"Can't open folder '{}'".format(pluginsDir))
         MessageBox(text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Ejemplo n.º 9
0
 def run (self, params):
     # 0 - папка рядом с запускаемым файлом, затем идут другие папки, если они есть
     pluginsDir = getPluginsDirList ()[-1]
     try:
         getOS().startFile (pluginsDir)
     except OSError:
         text = _(u"Can't open folder '{}'".format (pluginsDir))
         MessageBox (text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Ejemplo n.º 10
0
 def run (self, params):
     if self._application.selectedPage is not None:
         folder = Attachment (self._application.selectedPage).getAttachPath (create=True)
         try:
             getOS().startFile (folder)
         except OSError:
             text = _(u"Can't open folder '{}'".format (folder))
             MessageBox (text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Ejemplo n.º 11
0
 def run(self, params):
     # 0 - папка рядом с запускаемым файлом,
     # затем идут другие папки, если они есть
     pluginsDir = getPluginsDirList()[-1]
     try:
         getOS().startFile(pluginsDir)
     except OSError:
         text = _(u"Can't open folder '{}'".format(pluginsDir))
         showError(self._application.mainWindow, text)
Ejemplo n.º 12
0
 def run(self, params):
     if self._application.selectedPage is not None:
         folder = Attachment(
             self._application.selectedPage).getAttachPath(create=True)
         try:
             getOS().startFile(folder)
         except OSError:
             text = _(u"Can't open folder '{}'".format(folder))
             showError(self._application.mainWindow, text)
Ejemplo n.º 13
0
 def _updateExample(self):
     try:
         dateStr = unicode(
             datetime.now().strftime(self.GetValue().encode(
                 getOS().filesEncoding)),
             getOS().filesEncoding)
         self.exampleText.SetValue(dateStr)
     except ValueError:
         pass
Ejemplo n.º 14
0
 def run(self, params):
     if self._application.selectedPage is not None:
         folder = Attachment(
             self._application.selectedPage).getAttachPath(create=True)
         try:
             getOS().startFile(folder)
         except OSError:
             text = _(u"Can't open folder '{}'".format(folder))
             showError(self._application.mainWindow, text)
Ejemplo n.º 15
0
    def _correctSysPath (self):
        cmd_folder = unicode (os.path.dirname(os.path.abspath(__file__)),
                              getOS().filesEncoding)
        cmd_folder = os.path.join (cmd_folder, u'libs')

        syspath = [unicode (item, getOS().filesEncoding)
                   if not isinstance (item, unicode)
                   else item for item in sys.path]

        if cmd_folder not in syspath:
            sys.path.insert(0, cmd_folder)
Ejemplo n.º 16
0
        def __correctSysPath (self):
            cmd_folder = os.path.join (unicode (os.path.dirname(os.path.abspath(__file__)),
                                                getOS().filesEncoding),
                                       u"libs")

            syspath = [unicode (item, getOS().filesEncoding)
                       if not isinstance (item, unicode)
                       else item for item in sys.path]

            if cmd_folder not in syspath:
                sys.path.insert(0, cmd_folder)
Ejemplo n.º 17
0
        def __correctSysPath(self):
            cmd_folder = unicode(os.path.dirname(os.path.abspath(__file__)),
                                 getOS().filesEncoding)

            syspath = [
                unicode(item,
                        getOS().filesEncoding)
                if type(item) != type(u"") else item for item in sys.path
            ]

            if cmd_folder not in syspath:
                sys.path.insert(0, cmd_folder)
Ejemplo n.º 18
0
    def run(self, params):
        page = self._application.selectedPage
        assert page is not None

        url = page.source

        if url is not None:
            try:
                getOS().startFile(url)
            except OSError:
                text = _(u"Can't open URL '{}'").format(url)
                MessageBox(text, "Error", wx.ICON_ERROR | wx.OK)
Ejemplo n.º 19
0
    def run (self, params):
        page = self._application.selectedPage
        assert page is not None

        url = page.source

        if url is not None:
            try:
                getOS().startFile (url)
            except OSError:
                text = _(u"Can't open URL '{}'").format (url)
                MessageBox (text, "Error", wx.ICON_ERROR | wx.OK)
Ejemplo n.º 20
0
    def OnInit(self):
        getOS().init()
        getOS().migrateConfig()

        self._fullConfigPath = getConfigPath()
        Application.init(self._fullConfigPath)
        self._locale = wx.Locale(wx.LANGUAGE_DEFAULT)

        try:
            starter = Starter()
            starter.processConsole()
        except StarterExit:
            return True

        if APP_DATA_DEBUG not in Application.sharedData:
            config = GeneralGuiConfig(Application.config)
            Application.sharedData[APP_DATA_DEBUG] = config.debug.value

        level = (logging.DEBUG
                 if Application.sharedData.get(APP_DATA_DEBUG, False)
                 else logging.WARNING)

        redirector = LogRedirector(self.getLogFileName(self._fullConfigPath),
                                   level)
        redirector.init()
        wx.Log.SetLogLevel(0)

        logger = logging.getLogger('outwiker')
        for n, dirname in enumerate(getSpecialDirList(u'')):
            logger.info(u'Special directory [{}]: {}'.format(n, dirname))

        from outwiker.gui.mainwindow import MainWindow

        self.mainWnd = MainWindow(None, -1, "")
        self.SetTopWindow(self.mainWnd)

        Application.mainWindow = self.mainWnd
        Application.actionController = ActionController(self.mainWnd,
                                                        Application.config)

        registerActions(Application)
        self.mainWnd.createGui()

        Application.plugins.load(getPluginsDirList())

        self.bindActivateApp()
        self.Bind(wx.EVT_QUERY_END_SESSION, self._onEndSession)

        starter.processGUI()

        return True
Ejemplo n.º 21
0
    def testInterface (self):
        """
        Тест на то, что в интерфейсе классов outwiker не пропали нужные публичные свойства и методы
        """
        from outwiker.core.pluginbase import Plugin
        from outwiker.core.system import getOS
        from outwiker.core.commands import getCurrentVersion
        from outwiker.core.version import Version, StatusSet
        from outwiker.pages.wiki.wikipanel import WikiPagePanel
        from outwiker.pages.wiki.parser.command import Command

        getOS().filesEncoding
        StatusSet.DEV
        Command.parseParams
Ejemplo n.º 22
0
    def testInterface(self):
        """
        Тест на то, что в интерфейсе классов outwiker не пропали нужные публичные свойства и методы
        """
        from outwiker.core.pluginbase import Plugin
        from outwiker.core.system import getOS
        from outwiker.core.commands import getCurrentVersion
        from outwiker.core.version import Version, StatusSet
        from outwiker.pages.wiki.wikipanel import WikiPagePanel
        from outwiker.pages.wiki.parser.command import Command

        getOS().filesEncoding
        StatusSet.DEV
        Command.parseParams
Ejemplo n.º 23
0
    def initialize(self):
        domain = u"testdebug"
        self.__ID_TREE_POPUP = wx.NewId()
        self.__ID_TRAY_POPUP = wx.NewId()

        langdir = unicode (os.path.join (os.path.dirname (__file__), "locale"), getOS().filesEncoding)
        global _

        try:
            _ = self._init_i18n (domain, langdir)
        except BaseException as e:
            print e

        self.ID_PLUGINSLIST = wx.NewId()
        self.ID_BUTTONSDIALOG = wx.NewId()
        self.ID_START_WATCH_EVENTS = wx.NewId()
        self.ID_STOP_WATCH_EVENTS = wx.NewId()

        self.__menuName = _(u"Debug")

        if self._application.mainWindow is not None:
            self.__createMenu()
            self.__createTestAction()

            self._application.onTreePopupMenu += self.__onTreePopupMenu
            self._application.onTrayPopupMenu += self.__onTrayPopupMenu
            self._application.onPostprocessing += self.__onPostProcessing
            self._application.onPreprocessing += self.__onPreProcessing
            self._application.onHoverLink += self.__onHoverLink
            self._application.onLinkClick += self.__onLinkClick
            self._application.onEditorPopupMenu += self.__onEditorPopupMenu
            self._application.onSpellChecking += self.__onSpellChecking
Ejemplo n.º 24
0
		def _initlocale (self, domain):
			langdir = unicode (os.path.join (os.path.dirname (__file__), "locale"), getOS().filesEncoding)
			global _
			try:
				_ = self._init_i18n (domain, langdir)
			except BaseException, e:
				print e
Ejemplo n.º 25
0
    def __init__(self, parent, *args, **kwds):
        super(BaseHtmlPanel, self).__init__(parent, *args, **kwds)

        # Предыдущее содержимое результирующего HTML, чтобы не переписывать
        # его каждый раз
        self._oldHtmlResult = u""

        # Страница, для которой уже есть сгенерированный HTML
        self._oldPage = None

        # Где хранить параметы текущей страницы страницы (код, просмотр и т.д.)
        self.tabSectionName = u"Misc"
        self.tabParamName = u"PageIndex"

        self.imagesDir = getImagesDir()

        self.notebook = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
        self._codeEditor = self.getTextEditor()(self.notebook)
        self.htmlWindow = getOS().getHtmlRender(self.notebook)

        self.__do_layout()

        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self._onTabChanged,
                  self.notebook)
        self.Bind(self.EVT_SPELL_ON_OFF, handler=self._onSpellOnOff)
Ejemplo n.º 26
0
    def load(self, dirlist):
        """
        Загрузить плагины из указанных директорий.
        Каждый вызов метода load() добавляет плагины в список загруженных
            плагинов, не очищая его.
        dirlist - список директорий, где могут располагаться плагины.
            Каждый плагин расположен в своей поддиректории
        """
        assert dirlist is not None

        for currentDir in dirlist:
            if os.path.exists(currentDir):
                dirPackets = sorted(os.listdir(currentDir))

                # Добавить путь до currentDir в sys.path
                fullpath = os.path.abspath(currentDir)
                # TODO: Разобраться с Unicode в следующей строке.
                # Иногда выскакивает предупреждение:
                # ...\outwiker\core\pluginsloader.py:41: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

                syspath = [unicode(item, getOS().filesEncoding)
                           if type(item) != unicode else item
                           for item in sys.path]

                if fullpath not in syspath:
                    sys.path.insert(0, fullpath)

                # Все поддиректории попытаемся открыть как пакеты
                self.__importModules(currentDir, dirPackets)
Ejemplo n.º 27
0
        def _correctSysPath (self):
            syspath = [unicode (item, getOS().filesEncoding)
                       if not isinstance (item, unicode)
                       else item for item in sys.path]

            if self._pluginPath not in syspath:
                sys.path.insert(0, self._pluginPath)
Ejemplo n.º 28
0
    def getCommandsList(self, urlparams):
        """
        Return list of the ExecInfo. Macros will be replaced in params
        urlparams is dictionary with params from url.
        """
        from externaltools.commandexec.execinfo import ExecInfo

        result = []

        comindex = 1
        comparams = PROTO_COMMAND.format(number=comindex)

        encoding = getOS().filesEncoding

        while comparams in urlparams:
            command = unicode(urlparams[comparams][0], "utf8").encode(encoding)
            params = [
                unicode(param, "utf8").encode(encoding)
                for param in urlparams[comparams][1:]
            ]

            result.append(ExecInfo(command, params))

            comindex += 1
            comparams = PROTO_COMMAND.format(number=comindex)

        return result
Ejemplo n.º 29
0
    def makeImage (self, eqn):
        """
        eqn - выражение, которое нужно отрендерить
        """
        currentOS = getOS()

        temp_path = os.path.join (self.thumb_path, self.tempFname)

        imageName = self.getImageName (eqn)
        image_path = os.path.join (self.thumb_path, imageName)

        if os.path.exists (image_path):
            # Если такой файл уже есть, значит еще раз геренить такую формулу не надо
            return imageName

        with open (temp_path, "w") as fp:
            fp.write (eqn.encode("utf8"))

        # mimeTexPath нужно определить в производных классах
        mimeTexPath = self.mimeTexPath

        args = [mimeTexPath.encode (currentOS.filesEncoding),
                "-f", temp_path.encode (currentOS.filesEncoding),
                "-e", image_path.encode (currentOS.filesEncoding),
                "-s", str (self.fontsize)]

        self.run (args)
        return imageName
Ejemplo n.º 30
0
    def __init__(self, *args, **kwds):
        self.ID_ATTACH = wx.NewId()
        self.ID_REMOVE = wx.NewId()
        self.ID_PASTE = wx.NewId()
        self.ID_EXECUTE = wx.NewId()
        self.ID_OPEN_FOLDER = wx.NewId()
        self.ID_REFRESH = wx.NewId()

        wx.Panel.__init__(self, *args, **kwds)
        self.__toolbar = self.__createToolBar(self, -1)
        self.__attachList = wx.ListCtrl(self, -1, style=wx.LC_LIST | wx.SUNKEN_BORDER)

        self.__set_properties()
        self.__do_layout()

        self.__fileIcons = getOS().fileIcons
        self.__attachList.SetImageList (self.__fileIcons.imageList, wx.IMAGE_LIST_SMALL)

        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.__onBeginDrag, self.__attachList)

        self.Bind(wx.EVT_MENU, self.__onAttach, id=self.ID_ATTACH)
        self.Bind(wx.EVT_MENU, self.__onRemove, id=self.ID_REMOVE)
        self.Bind(wx.EVT_MENU, self.__onPaste, id=self.ID_PASTE)
        self.Bind(wx.EVT_MENU, self.__onExecute, id=self.ID_EXECUTE)
        self.Bind(wx.EVT_MENU, self.__onOpenFolder, id=self.ID_OPEN_FOLDER)
        self.Bind(wx.EVT_MENU, self.__onRefresh, id=self.ID_REFRESH)
        self.Bind (wx.EVT_CLOSE, self.__onClose)

        self.__bindAppEvents()

        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.__onDoubleClick, self.__attachList)
Ejemplo n.º 31
0
    def testNotPortableConfig1(self):
        """
        Проверка правильности определения расположения конфига при хранении его
        в папке профиля
        """
        dirname = ".outwiker_test"
        fname = "outwiker_test.ini"

        programDir = getCurrentDir()
        localPath = os.path.join(programDir, fname)

        # На всякий случай проверим, что файла в локальной папке нет,
        # иначе удалим его
        if os.path.exists(localPath):
            os.remove(localPath)

        homeDir = os.path.join(getOS().settingsDir, dirname)
        homePath = os.path.join(homeDir, fname)

        # Удалим папку в профиле
        if os.path.exists(homeDir):
            shutil.rmtree(homeDir)

        fullpath = getConfigPath(dirname, fname)

        self.assertEqual(homePath, fullpath)
        self.assertTrue(os.path.exists(homeDir))

        # Удалим папку в профиле
        if os.path.exists(homeDir):
            shutil.rmtree(homeDir)
Ejemplo n.º 32
0
    def generateDate(self, page):
        config = GeneralGuiConfig(self.__application.config)
        dateStr = unicode(page.datetime.strftime(config.dateTimeFormat.value),
                          getOS().filesEncoding)
        result = _(u"Last modified date: {0}").format(dateStr)

        return result
Ejemplo n.º 33
0
    def getCommandsList (self, urlparams):
        """
        Return list of the ExecInfo. Macros will be replaced in params
        urlparams is dictionary with params from url.
        """
        from externaltools.commandexec.execinfo import ExecInfo

        result = []

        comindex = 1
        comparams = PROTO_COMMAND.format (number = comindex)

        encoding = getOS().filesEncoding

        while comparams in urlparams:
            command = unicode (urlparams[comparams][0], "utf8").encode (encoding)
            params = [unicode (param, "utf8").encode (encoding)
                      for param
                      in urlparams[comparams][1:]]

            result.append (ExecInfo (command, params))

            comindex += 1
            comparams = PROTO_COMMAND.format (number = comindex)

        return result
Ejemplo n.º 34
0
    def renderToFile(self, content, imagePath):
        """
        content - текст, описывающий диаграмму
        imagePath - полный путь до создаваемого файла
        """
        from blockdiag.parser import parse_string
        from blockdiag.drawer import DiagramDraw
        from blockdiag.builder import ScreenNodeBuilder
        from blockdiag.utils.fontmap import FontMap

        font = os.path.join(
            unicode(os.path.dirname(os.path.abspath(__file__)), getOS().filesEncoding), u"fonts", self._fontDefault
        )

        fontmap = FontMap()
        fontmap.set_default_font(font)

        text = u"blockdiag {{ {content} }}".format(content=content)

        tree = parse_string(text)
        diagram = ScreenNodeBuilder.build(tree)

        draw = DiagramDraw("png", diagram, imagePath, fontmap=fontmap, antialias=True)
        draw.draw()
        draw.save()
Ejemplo n.º 35
0
def createNewWiki (parentwnd):
    """
    Создать новую вики
    parentwnd - окно-владелец диалога выбора файла
    """
    dlg = TestedFileDialog (parentwnd, style = wx.FD_SAVE)

    newPageTitle = _(u"First Wiki Page")
    newPageContent = _(u"""!! First Wiki Page

This is the first page. You can use a text formatting: '''bold''', ''italic'', {+underlined text+}, [[http://jenyay.net | link]] and others.""")

    if dlg.ShowModal() == wx.ID_OK:
        try:
            from outwiker.pages.wiki.wikipage import WikiPageFactory

            newwiki = WikiDocument.create (dlg.GetPath ())
            WikiPageFactory().create (newwiki, newPageTitle, [_(u"test")])
            firstPage = newwiki[newPageTitle]
            firstPage.content = newPageContent

            Application.wikiroot = newwiki
            Application.wikiroot.selectedPage = firstPage
        except (IOError, OSError) as e:
            # TODO: проверить под Windows
            MessageBox (_(u"Can't create wiki\n") + unicode (e.filename.encode (getOS().filesEncoding), "utf8"),
                        _(u"Error"), wx.OK | wx.ICON_ERROR)

    dlg.Destroy()
Ejemplo n.º 36
0
    def __init__(self, parent, application):
        super(BaseHtmlPanel, self).__init__(parent, application)

        # Предыдущее содержимое результирующего HTML, чтобы не переписывать
        # его каждый раз
        self._oldHtmlResult = u""

        # Страница, для которой уже есть сгенерированный HTML
        self._oldPage = None

        # Где хранить параметы текущей страницы страницы(код, просмотр и т.д.)
        self.tabSectionName = u"Misc"
        self.tabParamName = u"PageIndex"

        self._statusbar_item = 0

        self.imagesDir = getImagesDir()

        self.notebook = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
        self._codeEditor = self.getTextEditor()(self.notebook)

        self.htmlWindow = getOS().getHtmlRender(self.notebook)

        self.__do_layout()

        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
                  self._onTabChanged,
                  self.notebook)
        self.Bind(self.EVT_SPELL_ON_OFF, handler=self._onSpellOnOff)
        self._application.onPageUpdate += self._onPageUpdate
Ejemplo n.º 37
0
    def generateDate (self, page):
        config = GeneralGuiConfig (self.__application.config)
        dateStr = unicode (page.datetime.strftime (config.dateTimeFormat.value),
                           getOS().filesEncoding)
        result = _(u"Last modified date: {0}").format (dateStr)

        return result
Ejemplo n.º 38
0
    def __init__(self, parent, application):
        super().__init__(parent, application)

        # Предыдущее содержимое результирующего HTML, чтобы не переписывать
        # его каждый раз
        self._oldHtmlResult = u""

        # Страница, для которой уже есть сгенерированный HTML
        self._oldPage = None

        # Где хранить параметы текущей страницы страницы (код, просмотр и т.д.)
        self.tabParamName = u"PageIndex"

        self._statusbar_item = 0

        self.imagesDir = getImagesDir()

        self.notebook = wx.aui.AuiNotebook(self, style=wx.aui.AUI_NB_BOTTOM)
        self._codeEditor = self.getTextEditor()(self.notebook)

        self.htmlWindow = getOS().getHtmlRender(self.notebook)

        self.__do_layout()

        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self._onTabChanged,
                  self.notebook)
        self.Bind(self.EVT_SPELL_ON_OFF, handler=self._onSpellOnOff)
        self._application.onPageUpdate += self._onPageUpdate
Ejemplo n.º 39
0
    def makeImage(self, eqn):
        """
        eqn - выражение, которое нужно отрендерить
        """
        currentOS = getOS()

        temp_path = os.path.join(self.thumb_path, self.tempFname)

        imageName = self.getImageName(eqn)
        image_path = os.path.join(self.thumb_path, imageName)

        if os.path.exists(image_path):
            # Если такой файл уже есть, значит еще раз геренить такую формулу не надо
            return imageName

        with open(temp_path, "w") as fp:
            fp.write(eqn.encode("utf8"))

        # mimeTexPath нужно определить в производных классах
        mimeTexPath = self.mimeTexPath

        args = [
            mimeTexPath.encode(currentOS.filesEncoding), "-f",
            temp_path.encode(currentOS.filesEncoding), "-e",
            image_path.encode(currentOS.filesEncoding), "-s",
            str(self.fontsize)
        ]

        self.run(args)
        return imageName
Ejemplo n.º 40
0
    def renderToFile(self, content, imagePath):
        """
        content - текст, описывающий диаграмму
        imagePath - полный путь до создаваемого файла
        """
        from blockdiag.parser import parse_string
        from blockdiag.drawer import DiagramDraw
        from blockdiag.builder import ScreenNodeBuilder
        from blockdiag.utils.fontmap import FontMap

        font = os.path.join(
            unicode(os.path.dirname(os.path.abspath(__file__)),
                    getOS().filesEncoding), u"fonts", self._fontDefault)

        fontmap = FontMap()
        fontmap.set_default_font(font)

        text = u"blockdiag {{ {content} }}".format(content=content)

        tree = parse_string(text)
        diagram = ScreenNodeBuilder.build(tree)

        draw = DiagramDraw("png",
                           diagram,
                           imagePath,
                           fontmap=fontmap,
                           antialias=True)
        draw.draw()
        draw.save()
Ejemplo n.º 41
0
def createNewWiki(parentwnd):
    """
    Создать новую вики
    parentwnd - окно-владелец диалога выбора файла
    """
    dlg = TestedFileDialog(parentwnd, style=wx.FD_SAVE)

    newPageTitle = _(u"First Wiki Page")
    newPageContent = _(u"""!! First Wiki Page

This is the first page. You can use a text formatting: '''bold''', ''italic'', {+underlined text+}, [[http://jenyay.net | link]] and others."""
                       )

    if dlg.ShowModal() == wx.ID_OK:
        try:
            from outwiker.pages.wiki.wikipage import WikiPageFactory

            newwiki = WikiDocument.create(dlg.GetPath())
            WikiPageFactory().create(newwiki, newPageTitle, [_(u"test")])
            firstPage = newwiki[newPageTitle]
            firstPage.content = newPageContent

            Application.wikiroot = newwiki
            Application.wikiroot.selectedPage = firstPage
        except (IOError, OSError) as e:
            # TODO: проверить под Windows
            MessageBox(
                _(u"Can't create wiki\n") +
                unicode(e.filename.encode(getOS().filesEncoding), "utf8"),
                _(u"Error"), wx.OK | wx.ICON_ERROR)

    dlg.Destroy()
Ejemplo n.º 42
0
    def __executeFile(self):
        if self._application.selectedPage is not None:
            files = self.__getSelectedFiles()

            if len(files) == 0:
                showError(self._application.mainWindow,
                          _(u"You did not select a file to execute"))
                return

            for file in files:
                fullpath = os.path.join(Attachment(self._application.selectedPage).getAttachPath(), file)
                try:
                    getOS().startFile(fullpath)
                except OSError:
                    text = _(u"Can't execute file '%s'") % file
                    showError(self._application.mainWindow, text)
Ejemplo n.º 43
0
 def getImagePath(self, imageName):
     """Return path to images directory."""
     selfdir = os.path.dirname(__file__)
     parentdir = os.path.dirname(selfdir)
     imagedir = unicode(os.path.join(parentdir, "images"), getOS().filesEncoding)
     fname = os.path.join(imagedir, imageName)
     return fname
Ejemplo n.º 44
0
def testPageTitle(title):
    """
    Возвращает True, если можно создавать страницу с таким заголовком
    """
    tester = getOS().pageTitleTester

    try:
        tester.test(title)

    except PageTitleError as error:
        MessageBox(str(error),
                   _(u"Invalid page title"),
                   wx.OK | wx.ICON_ERROR)
        return False

    except PageTitleWarning as warning:
        text = _(u"{0}\nContinue?").format(str(warning))

        if (MessageBox(text,
                       _(u"The page title"),
                       wx.YES_NO | wx.ICON_QUESTION) == wx.YES):
            return True
        else:
            return False

    return True
Ejemplo n.º 45
0
def getImagePath (imageName):
    """
    Получить полный путь до картинки
    """
    imagedir = unicode (os.path.join (os.path.dirname (__file__), "images"), getOS().filesEncoding)
    fname = os.path.join (imagedir, imageName)
    return fname
Ejemplo n.º 46
0
def testPageTitle(title):
    """
    Возвращает True, если можно создавать страницу с таким заголовком
    """
    tester = getOS().pageTitleTester

    try:
        tester.test(title)

    except PageTitleError as error:
        MessageBox(str(error),
                   _(u"Invalid page title"),
                   wx.OK | wx.ICON_ERROR)
        return False

    except PageTitleWarning as warning:
        text = _(u"{0}\nContinue?").format(str(warning))

        if (MessageBox(text,
                       _(u"The page title"),
                       wx.YES_NO | wx.ICON_QUESTION) == wx.YES):
            return True
        else:
            return False

    return True
Ejemplo n.º 47
0
    def testNotPortableConfig1(self):
        """
        Проверка правильности определения расположения конфига при хранении его
        в папке профиля
        """
        dirname = ".outwiker_test"
        fname = "outwiker_test.ini"

        programDir = getCurrentDir()
        localPath = os.path.join(programDir, fname)

        # На всякий случай проверим, что файла в локальной папке нет,
        # иначе удалим его
        if os.path.exists(localPath):
            os.remove(localPath)

        homeDir = os.path.join(getOS().settingsDir, dirname)
        homePath = os.path.join(homeDir, fname)

        # Удалим папку в профиле
        if os.path.exists(homeDir):
            shutil.rmtree(homeDir)

        fullpath = getConfigPath(dirname, fname)

        self.assertEqual(homePath, fullpath)
        self.assertTrue(os.path.exists(homeDir))

        # Удалим папку в профиле
        if os.path.exists(homeDir):
            shutil.rmtree(homeDir)
Ejemplo n.º 48
0
    def load(self, dirlist):
        """
        Загрузить плагины из указанных директорий.
        Каждый вызов метода load() добавляет плагины в список загруженных
            плагинов, не очищая его.
        dirlist - список директорий, где могут располагаться плагины.
            Каждый плагин расположен в своей поддиректории
        """
        assert dirlist is not None

        for currentDir in dirlist:
            if os.path.exists(currentDir):
                dirPackets = sorted(os.listdir(currentDir))

                # Добавить путь до currentDir в sys.path
                fullpath = os.path.abspath(currentDir)
                # TODO: Разобраться с Unicode в следующей строке.
                # Иногда выскакивает предупреждение:
                # ...\outwiker\core\pluginsloader.py:41:
                # UnicodeWarning: Unicode equal comparison failed to convert
                # both arguments to Unicode - interpreting them as
                # being unequal

                syspath = [
                    unicode(item,
                            getOS().filesEncoding)
                    if type(item) != unicode else item for item in sys.path
                ]

                if fullpath not in syspath:
                    sys.path.insert(0, fullpath)

                # Все поддиректории попытаемся открыть как пакеты
                self.__importModules(currentDir, dirPackets)
Ejemplo n.º 49
0
    def OnInit(self):
        self._fullConfigPath = getConfigPath ()
        Application.init(self._fullConfigPath)

        # Если программа запускается в виде exe-шника, то перенаправить вывод ошибок в лог
        exepath = unicode (sys.argv[0], getOS().filesEncoding)
        if exepath.endswith (u".exe"):
            # Закоментировать следующую строку, если не надо выводить strout/strerr в лог-файл
            self.RedirectStdio (self.getLogFileName (self._fullConfigPath))
            pass

        from outwiker.gui.mainwindow import MainWindow
        
        wx.InitAllImageHandlers()
        self.mainWnd = MainWindow(None, -1, "")
        self.SetTopWindow (self.mainWnd)

        Application.mainWindow = self.mainWnd
        Application.actionController = ActionController (self.mainWnd, Application.config)

        registerActions(Application)
        self.mainWnd.createGui()

        Application.plugins.load (getPluginsDirList())

        self.bindActivateApp()
        self.Bind (wx.EVT_QUERY_END_SESSION, self._onEndSession)

        starter = Starter()
        starter.process()
        
        return True
Ejemplo n.º 50
0
    def OnInit(self):
        getOS().init()
        getOS().migrateConfig()

        self._fullConfigPath = getConfigPath()
        Application.init(self._fullConfigPath)
        self._locale = wx.Locale(wx.LANGUAGE_DEFAULT)

        try:
            starter = Starter()
            starter.processConsole()
        except StarterExit:
            return True

        if APP_DATA_DEBUG not in Application.sharedData:
            config = GeneralGuiConfig(Application.config)
            Application.sharedData[APP_DATA_DEBUG] = config.debug.value

        level = (logging.INFO
                 if Application.sharedData.get(APP_DATA_DEBUG, False)
                 else logging.WARNING)

        redirector = LogRedirector(self.getLogFileName(self._fullConfigPath),
                                   level)
        redirector.init()
        wx.Log.SetLogLevel(0)

        from outwiker.gui.mainwindow import MainWindow

        self.mainWnd = MainWindow(None, -1, "")
        self.SetTopWindow(self.mainWnd)

        Application.mainWindow = self.mainWnd
        Application.actionController = ActionController(self.mainWnd,
                                                        Application.config)

        registerActions(Application)
        self.mainWnd.createGui()

        Application.plugins.load(getPluginsDirList())

        self.bindActivateApp()
        self.Bind(wx.EVT_QUERY_END_SESSION, self._onEndSession)

        starter.processGUI()

        return True
Ejemplo n.º 51
0
    def _initPackage(cls, packagename, modulename):
        """
        Инициализировать пакет с рендерами узлов
        packagename - например, "blockdiag.noderenderer", а modulename - "circle"
        """
        packageFullName = ".".join([packagename, modulename])

        # Импортируем модуль, чтобы узнать полное имя файла до него
        try:
            rootmodule = __import__(packageFullName, fromlist=[modulename])
        except (ImportError, ValueError):
            return

        if rootmodule is None:
            return

        path = unicode(os.path.dirname(os.path.abspath(rootmodule.__file__)),
                       getOS().filesEncoding)

        extension = ".py"

        # Перебираем все модули внутри пакета
        for fname in os.listdir(path):
            fullpath = os.path.join(path, fname)

            # Все папки пытаемся открыть как вложенный пакет
            if os.path.isdir(fullpath):
                DiagramRender._initPackage(packageFullName,
                                           fname.encode(getOS().filesEncoding))
            else:
                # Проверим, что файл может быть модулем
                if fname.endswith(extension) and fname != "__init__.py":
                    nestedmodulename = fname[:-len(extension)]
                    # Попытаться импортировать функцию setup из модуля
                    try:
                        currentmodulename = packageFullName + "." + nestedmodulename
                        module = __import__(currentmodulename,
                                            fromlist=["setup"])
                    except ImportError:
                        continue

                    try:
                        module.setup(module)
                    except AttributeError:
                        continue

                    cls._addShape(packageFullName + "." + nestedmodulename)
Ejemplo n.º 52
0
    def __executeFile(self):
        if Application.selectedPage is not None:
            files = self.__getSelectedFiles()

            if len(files) == 0:
                MessageBox(_(u"You did not select a file to execute"),
                           _(u"Error"), wx.OK | wx.ICON_ERROR)
                return

            for file in files:
                fullpath = os.path.join(
                    Attachment(Application.selectedPage).getAttachPath(), file)
                try:
                    getOS().startFile(fullpath)
                except OSError:
                    text = _(u"Can't execute file '%s'") % file
                    MessageBox(text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Ejemplo n.º 53
0
        def _initlocale (self, domain):
            langdir = unicode (os.path.join (os.path.dirname (__file__), "locale"), getOS().filesEncoding)
            global _

            try:
                _ = self._init_i18n (domain, langdir)
            except BaseException, e:
                print e
Ejemplo n.º 54
0
    def __executeTools(self, command, fname):
        encoding = getOS().filesEncoding

        try:
            subprocess.call([command.encode(encoding), fname.encode(encoding)])
        except OSError:
            MessageBox(_(u"Can't execute tools"), _(u"Error"),
                       wx.OK | wx.ICON_ERROR)
Ejemplo n.º 55
0
 def _getKaTeXPath(self):
     """
     Get path to KaTeX library
     """
     katexpath = unicode(
         os.path.join(os.path.dirname(__file__), "tools", "katex"),
         getOS().filesEncoding)
     return katexpath
Ejemplo n.º 56
0
    def __executeFile (self):
        if Application.selectedPage is not None:
            files = self.__getSelectedFiles()

            if len (files) == 0:
                MessageBox (_(u"You did not select a file to execute"),
                            _(u"Error"),
                            wx.OK | wx.ICON_ERROR)
                return

            for file in files:
                fullpath = os.path.join (Attachment (Application.selectedPage).getAttachPath(), file)
                try:
                    getOS().startFile (fullpath)
                except OSError:
                    text = _(u"Can't execute file '%s'") % file
                    MessageBox (text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Ejemplo n.º 57
0
        def _correctSysPath(self):
            syspath = [unicode(item, getOS().filesEncoding)
                       if not isinstance(item, unicode)
                       else item for item in sys.path]

            libspath = os.path.join(self._pluginPath, u'libs')
            if libspath not in syspath:
                sys.path.insert(0, libspath)