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
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
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
def _onSwitchCodeHtml (self): assert self._currentpage != None self.Save() status_item = 0 setStatusText (_(u"Page rendered. Please wait…"), status_item) Application.onHtmlRenderingBegin (self._currentpage, self.htmlWindow) try: self.currentHtmlFile = self.generateHtml (self._currentpage) self._showHtmlCode(self.currentHtmlFile) except IOError as e: # TODO: Проверить под Windows MessageBox (_(u"Can't save file %s") % (unicode (e.filename)), _(u"Error"), wx.ICON_ERROR | wx.OK) except OSError as e: MessageBox (_(u"Can't save HTML-file\n\n%s") % (unicode (e)), _(u"Error"), wx.ICON_ERROR | wx.OK) setStatusText (u"", status_item) Application.onHtmlRenderingEnd (self._currentpage, self.htmlWindow) self._enableAllTools () self.htmlCodeWindow.SetFocus() self.htmlCodeWindow.Update()
def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.THICK_FRAME wx.Dialog.__init__(self, *args, **kwds) self.__treeBook = wx.Treebook(self, -1) self.__set_properties() self.__do_layout() # Страницы с настройками self.__generalPage = None self.__editorPage = None self.__spellPage = None self.__htmlRenderPage = None self.__textPrintPage = None self.__pluginsPage = None self.__hotkeysPage = None self.__htmlEditorPage = None self.__iconsetPage = None self.__tagsPage = None self.__attachPage = None self.__createPages() Application.onPreferencesDialogCreate(self) self.__loadAllOptions() self.Center(wx.CENTRE_ON_SCREEN)
def _onLinkClicked(self, href): """ Клик по ссылке """ (url, page, filename, anchor) = self._identifyUri(href) button = ID_MOUSE_LEFT modifier = self.getKeyCode() params = self.getClickParams(self.decodeIDNA(href), button, modifier, url, page, filename, anchor) Application.onLinkClick(self._currentPage, params) if params.process: return if url is not None: self.openUrl(url) elif page is not None and modifier == ID_KEY_CTRL: if anchor is not None: Application.sharedData[APP_DATA_KEY_ANCHOR] = anchor Application.mainWindow.tabsController.openInTab(page, True) elif page is not None: if anchor is not None: Application.sharedData[APP_DATA_KEY_ANCHOR] = anchor self._currentPage.root.selectedPage = page elif filename is not None: try: outwiker.core.system.getOS().startFile(filename) except OSError: text = _(u"Can't execute file '%s'") % filename outwiker.core.commands.showError(Application.mainWindow, text) elif anchor is not None: self.LoadPage(href)
def testTrayMinimize3 (self): self.wnd.taskBarIcon.config.minimizeToTray.value = True self.wnd.taskBarIcon.config.alwaysShowTrayIcon.value = True self.wnd.taskBarIcon.config.startIconized.value = False Application.onPreferencesDialogClose(None) #self._processEvents() self.wnd.Show() self.wnd.Iconize(False) self._processEvents() self.assertTrue (self.wnd.IsShown()) self.assertTrue (self.wnd.taskBarIcon.IsIconInstalled()) self.wnd.Iconize(True) self._processEvents() self.assertTrue (self.wnd.IsShown()) self.assertTrue (self.wnd.taskBarIcon.IsIconInstalled()) self.wnd.taskBarIcon.restoreWindow() #self._processEvents() self.assertTrue (self.wnd.IsShown()) self.assertTrue (self.wnd.taskBarIcon.IsIconInstalled())
def _showHtml (self): """ Подготовить и показать HTML текущей страницы """ assert self._currentpage != None status_item = 0 setStatusText (_(u"Page rendered. Please wait…"), status_item) Application.onHtmlRenderingBegin (self._currentpage, self.htmlWindow) try: self.currentHtmlFile = self.generateHtml (self._currentpage) self.htmlWindow.LoadPage (self.currentHtmlFile) except IOError as e: # TODO: Проверить под Windows MessageBox (_(u"Can't save file %s") % (unicode (e.filename)), _(u"Error"), wx.ICON_ERROR | wx.OK) except OSError as e: MessageBox (_(u"Can't save HTML-file\n\n%s") % (unicode (e)), _(u"Error"), wx.ICON_ERROR | wx.OK) setStatusText (u"", status_item) Application.onHtmlRenderingEnd (self._currentpage, self.htmlWindow)
def __onOk(self, event): try: self.__saveAll() except PreferencesException: pass Application.onPreferencesDialogClose(self) self.EndModal(wx.ID_OK)
def CreatePopupMenu (self): trayMenu = wx.Menu() trayMenu.Append (self.ID_RESTORE, _(u"Restore")) trayMenu.Append (self.ID_EXIT, _(u"Exit")) Application.onTrayPopupMenu (trayMenu, self) return trayMenu
def __onOk (self, event): try: self.__saveAll() except PreferencesException: pass Application.onPreferencesDialogClose(self) self.EndModal (wx.ID_OK)
def _onStyleNeeded(self, event): if (not self._styleSet and datetime.now() - self._lastEdit >= self._DELAY): page = Application.selectedPage text = self._getTextForParse() params = EditorStyleNeededParams(self, text, self._enableSpellChecking) Application.onEditorStyleNeeded(page, params) self._styleSet = True
def __onLinkClicked(self, href, gtk_mouse_button, gtk_key_modifier): """ Клик по ссылке Возвращает False, если обрабатывать ссылку разрешить компоненту, в противном случае - True (если обрабатываем сами) href - ссылка gtk_mouse_button - кнопка мыши, с помощью которой кликнули по ссылке (1 - левая, 2 - средняя, 3 - правая, -1 - не известно) gtk_key_modifier - зажатые клавиши (1 - Shift, 4 - Ctrl) """ source_href = href href = urllib.parse.unquote(href) href = self._decodeIDNA(href) logger.debug('__onLinkClicked. href_src={source_href}; href_process={href}'.format( source_href=source_href, href=href) ) (url, page, filename, anchor) = self.__identifyUri(href) logger.debug('__onLinkClicked. url={url}, page={page}, filename={filename}, anchor={anchor}'.format( url=url, page=page, filename=filename, anchor=anchor)) modifier = self.__gtk2OutWikerKeyCode(gtk_key_modifier) mouse_button = self.__gtk2OutWikerMouseButtonCode(gtk_mouse_button) params = self._getClickParams(source_href, mouse_button, modifier, url, page, filename, anchor) Application.onLinkClick(self._currentPage, params) if params.process: return True if url is not None: self.openUrl(url) elif (page is not None and (mouse_button == ID_MOUSE_MIDDLE or modifier == ID_KEY_CTRL)): Application.mainWindow.tabsController.openInTab(page, True) elif page is not None: if anchor is not None: Application.sharedData[APP_DATA_KEY_ANCHOR] = anchor self._currentPage.root.selectedPage = page elif filename is not None: try: outwiker.core.system.getOS().startFile(filename) except OSError: text = _(u"Can't execute file '%s'") % filename outwiker.core.commands.showError(Application.mainWindow, text) elif anchor is not None: return False return True
def make (self, page, config): """ Создать парсер page - страница, для которой создается парсер, config - экземпляр класса, хранящий настройки """ parser = Parser (page, config) self._addCommands (parser) Application.onWikiParserPrepare (parser) return parser
def _setStatusText(self, link, text): """ Execute onHoverLink event and set status text """ link_decoded = self.decodeIDNA(link) params = HoverLinkParams(link=link_decoded, text=text) Application.onHoverLink(page=self._currentPage, params=params) outwiker.core.commands.setStatusText(params.text, self._status_item)
def setStatusText (self, link, text): """ Execute onHoverLink event and set status text """ link_decoded = self._decodeIDNA (link) params = HoverLinkParams (link = link_decoded, text = text) Application.onHoverLink (page=self._currentPage, params = params) outwiker.core.commands.setStatusText (params.text, self._status_item)
def __pasteLink(self): """ Сгенерировать сообщение о том, что пользователь хочет вставить ссылку на приаттаченные файлы """ files = self.__getSelectedFiles() if len(files) == 0: MessageBox(_(u"You did not select a file to paste"), _(u"Error"), wx.OK | wx.ICON_ERROR) return Application.onAttachmentPaste(files)
def destroyPageView (self): """ Уничтожить текущий контрол """ if self.__pageView != None: Application.onPageViewDestroy (self.__currentPage) self.contentSizer.Detach (self.__pageView) self.__pageView.Close() self.__pageView = None self.__currentPage = None
def reset(): """ Установить словарь фабрик в первоначальное состояние. Используется для тестирования. Это не конструктор. В случае изменения списка фабрик, установленных по умолчанию, нужно изменять этот метод. """ FactorySelector._factories = { factory.getTypeString(): factory for factory in [WikiPageFactory(), HtmlPageFactory(), TextPageFactory(), SearchPageFactory()] } Application.onPageFactoryListChange(newfactory=None)
def testLoad_02 (self): path = u"../test/samplewiki" Application.getEvent ('onTreeUpdate').bind (self.treeUpdate) self.assertFalse(self.isTreeUpdate) WikiDocument.load (path) self.assertFalse (self.isTreeUpdate) self.assertEqual (self.treeUpdateSender, None) self.assertEqual (self.treeUpdateCount, 0) Application.getEvent ('onTreeUpdate').unbind (self.treeUpdate)
def destroyWithoutSave(self): """ Уничтожить панель без сохранения изменений. Нужно для перезагрузки вики """ if self.__pageView is not None: Application.onPageViewDestroy(self.__currentPage) self.contentSizer.Detach(self.__pageView) self.__pageView.CloseWithoutSave() self.__pageView = None self.__currentPage = None
def destroyWithoutSave (self): """ Уничтожить панель без сохранения изменений. Нужно для перезагрузки вики """ if self.__pageView is not None: Application.onPageViewDestroy (self.__currentPage) self.contentSizer.Detach (self.__pageView) self.__pageView.CloseWithoutSave() self.__pageView = None self.__currentPage = None
def destroyPageView(self): """ Уничтожить текущий контрол """ if self.__pageView is not None: assert self.__currentPage is not None Application.onPageViewDestroy(self.__currentPage) self.contentSizer.Detach(self.__pageView) self.__pageView.Close() self.__pageView = None self.__currentPage = None
def openWiki (path, readonly=False): wikiroot = None Application.onStartTreeUpdate(None) def threadFunc (path, readonly): try: return WikiDocument.load (path, readonly) except IOError, error: return error except outwiker.core.exceptions.RootFormatError, error: return error
def __onPaste(self, event): """ Сгенерировать сообщение о том, что пользователь хочет вставить ссылку на приаттаченные файлы """ files = self.__getSelectedFiles () if len (files) == 0: MessageBox (_(u"You did not select a file to paste"), _(u"Error"), wx.OK | wx.ICON_ERROR) return Application.onAttachmentPaste (files)
def testLoad_02(self): path = u"../test/samplewiki" Application.getEvent('onTreeUpdate').bind(self.treeUpdate) self.assertFalse(self.isTreeUpdate) WikiDocument.load(path) self.assertFalse(self.isTreeUpdate) self.assertEqual(self.treeUpdateSender, None) self.assertEqual(self.treeUpdateCount, 0) Application.getEvent('onTreeUpdate').unbind(self.treeUpdate)
def _checkCaretMoving(self): new_start_selection = self.GetSelectionStart() new_end_selection = self.GetSelectionEnd() if (self._oldStartSelection != new_start_selection or self._oldEndSelection != new_end_selection): self._oldStartSelection = new_start_selection self._oldEndSelection = new_end_selection event_params = TextEditorCaretMoveParams(self, new_start_selection, new_end_selection) Application.onTextEditorCaretMove(Application.selectedPage, event_params)
def onKeyDown(self, event: wx.KeyEvent): eventParams = TextEditorKeyDownParams(self, event.GetKeyCode(), event.GetUnicodeKey(), event.ControlDown(), event.ShiftDown(), event.AltDown(), event.CmdDown(), event.MetaDown()) Application.onTextEditorKeyDown(Application.selectedPage, eventParams) if not eventParams.disableOutput: super().onKeyDown(event) self._checkCaretMoving()
def __onContextMenu(self, event): point = self.textCtrl.ScreenToClient(event.GetPosition()) pos_byte = self.textCtrl.PositionFromPoint(point) popupMenu = TextEditorMenu() self._appendSpellMenuItems(popupMenu, pos_byte) Application.onEditorPopupMenu( Application.selectedPage, EditorPopupMenuParams(self, popupMenu, point, pos_byte)) self.textCtrl.PopupMenu(popupMenu) popupMenu.Destroy()
def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.THICK_FRAME wx.Dialog.__init__(self, *args, **kwds) self.__treeBook = wx.Treebook(self, -1) self.__do_layout() Application.onPreferencesDialogCreate (self) self.__expandAllPages() self.__treeBook.SetSelection (0) self.__loadAllOptions() self.__set_properties()
def __onContextMenu (self, event): point = self.textCtrl.ScreenToClient (event.GetPosition()) pos_byte = self.textCtrl.PositionFromPoint(point) popupMenu = self._getMenu () self._appendSpellItems (popupMenu, pos_byte) Application.onEditorPopupMenu ( Application.selectedPage, EditorPopupMenuParams (self, popupMenu, point, pos_byte) ) self.textCtrl.PopupMenu(popupMenu)
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
def __init__(self, *args, **kwds): kwds[ "style"] = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.THICK_FRAME wx.Dialog.__init__(self, *args, **kwds) self.__treeBook = wx.Treebook(self, -1) self.__do_layout() Application.onPreferencesDialogCreate(self) self.__expandAllPages() self.__treeBook.SetSelection(0) self.__loadAllOptions() self.__set_properties()
def __createPageView(self, page): """ Создать панель просмотра для страницы """ if page is not None: factory = FactorySelector.getFactory(page.getTypeString()) self.__pageView = factory.getPageView(self) self.__pageView.page = page assert self.__pageView is not None self.contentSizer.Add(self.__pageView, 1, wx.EXPAND, 0) self.Layout() Application.onPageViewCreate(page)
def phrase (self, phrase): """ Устанавливает искомую фразу """ self._phrase = phrase phraseOption = StringOption (self.params, self.paramsSection, u"phrase", u"") try: phraseOption.value = phrase except ReadonlyException: # Ничего страшного, если поисковая фраза не сохранится pass Application.onPageUpdate (self, change=PAGE_UPDATE_CONTENT)
def __createPageView (self, page): """ Создать панель просмотра для страницы """ if page != None: factory = FactorySelector.getFactory (page.getTypeString()) self.__pageView = factory.getPageView (self) self.__pageView.page = page assert self.__pageView != None self.contentSizer.Add (self.__pageView, 1, wx.EXPAND, 0) self.Layout() Application.onPageViewCreate (page)
def openWiki(path: str, readonly: bool=False) -> Optional[WikiDocument]: def threadFunc(path, readonly): try: return WikiDocument.load(path, readonly) except BaseException as e: return e logger.debug('Opening notes tree from: {}'.format(path)) if not os.path.exists(path): __canNotLoadWikiMessage(path) return preWikiOpenParams = PreWikiOpenParams(path, readonly) Application.onPreWikiOpen(Application.selectedPage, preWikiOpenParams) if preWikiOpenParams.abortOpen: logger.debug('Opening notes tree aborted') return # The path may be changed in event handlers path = preWikiOpenParams.path logger.debug('Notes tree path after onPreWikiOpen: {}'.format(path)) # Если передан путь до файла настроек (а не до папки с вики), # то оставим только папку if not os.path.isdir(path): path = os.path.split(path)[0] runner = LongProcessRunner(threadFunc, Application.mainWindow, _(u"Loading"), _(u"Opening notes tree...")) result = runner.run(os.path.realpath(path), readonly) success = False if isinstance(result, outwiker.core.exceptions.RootFormatError): __rootFormatErrorHandle(path, readonly) elif isinstance(result, Exception): logger.error(result) __canNotLoadWikiMessage(path) else: Application.wikiroot = result success = True postWikiOpenParams = PostWikiOpenParams(path, readonly, success) Application.onPostWikiOpen(Application.selectedPage, postWikiOpenParams) return Application.wikiroot
def openWiki(path: str, readonly: bool = False) -> Optional[WikiDocument]: def threadFunc(path, readonly): try: return WikiDocument.load(path, readonly) except BaseException as e: return e logger.debug('Opening notes tree from: {}'.format(path)) if not os.path.exists(path): __canNotLoadWikiMessage(path) return None preWikiOpenParams = PreWikiOpenParams(path, readonly) Application.onPreWikiOpen(Application.selectedPage, preWikiOpenParams) if preWikiOpenParams.abortOpen: logger.debug('Opening notes tree aborted') return None # The path may be changed in event handlers path = preWikiOpenParams.path logger.debug('Notes tree path after onPreWikiOpen: {}'.format(path)) # Если передан путь до файла настроек (а не до папки с вики), # то оставим только папку if not os.path.isdir(path): path = os.path.split(path)[0] runner = LongProcessRunner(threadFunc, Application.mainWindow, _(u"Loading"), _(u"Opening notes tree...")) result = runner.run(os.path.realpath(path), readonly) success = False if isinstance(result, outwiker.core.exceptions.RootFormatError): __rootFormatErrorHandle(path, readonly) elif isinstance(result, Exception): logger.error(result) __canNotLoadWikiMessage(path) else: Application.wikiroot = result success = True postWikiOpenParams = PostWikiOpenParams(path, readonly, success) Application.onPostWikiOpen(Application.selectedPage, postWikiOpenParams) return Application.wikiroot
def strategy (self, strategy): if strategy == AllTagsSearchStrategy: strategyCode = 1 else: strategyCode = 0 self._strategy = strategy strategyOption = IntegerOption (self.params, self.paramsSection, u"strategy", 0) try: strategyOption.value = strategyCode except ReadonlyException: # Ничего страшного pass Application.onPageUpdate (self, change=PAGE_UPDATE_CONTENT)
def searchTags (self, tags): """ Выбрать теги для поиска """ self._searchTags = tags tags_str = getTagsString (tags) tagsOption = StringOption (self.params, self.paramsSection, u"tags", u"") try: tagsOption.value = tags_str except ReadonlyException: # Ну не сохранятся искомые теги, ничего страшного pass Application.onPageUpdate (self, change=PAGE_UPDATE_CONTENT)
def __onLinkClicked (self, href, gtk_mouse_button, gtk_key_modifier): """ Клик по ссылке Возвращает False, если обрабатывать ссылку разрешить компоненту, в противном случае - True (если обрабатываем сами) href - ссылка gtk_mouse_button - кнопка мыши, с помощью которой кликнули по ссылке (1 - левая, 2 - средняя, 3 - правая, -1 - не известно) gtk_key_modifier - зажатые клавиши (1 - Shift, 4 - Ctrl) """ (url, page, filename, anchor) = self.__identifyUri (href) modifier = self.__gtk2OutWikerKeyCode (gtk_key_modifier) mouse_button = self.__gtk2OutWikerMouseButtonCode (gtk_mouse_button) params = self._getClickParams (self._decodeIDNA (href), mouse_button, modifier, url, page, filename, anchor) Application.onLinkClick (self._currentPage, params) if params.process: return True if url is not None: self.openUrl (url) elif page is not None and (mouse_button == ID_MOUSE_MIDDLE or modifier == ID_KEY_CTRL): Application.mainWindow.tabsController.openInTab (page, True) elif page is not None: Application.anchor = anchor self._currentPage.root.selectedPage = page elif filename is not None: try: outwiker.core.system.getOS().startFile (filename) except OSError: text = _(u"Can't execute file '%s'") % filename outwiker.core.commands.MessageBox (text, _(u"Error"), wx.ICON_ERROR | wx.OK) elif anchor is not None: return False return True
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
def _onLinkClicked(self, href): """ Клик по ссылке Возвращает False, если обрабатывать ссылку разрешить компоненту, в противном случае - True (если обрабатываем сами) href - ссылка """ modifier = self.getKeyCode() mouse_button = ID_MOUSE_LEFT source_href = href href = urllib.parse.unquote(href) href = self.decodeIDNA(href) logger.debug('_onLinkClicked. href_src={source_href}'.format( source_href=source_href)) (url, page, filename, anchor) = self._identifyUri(href) params = self.getClickParams(source_href, mouse_button, modifier, url, page, filename, anchor) Application.onLinkClick(self._currentPage, params) if params.process: return True if page is not None and anchor is not None: Application.sharedData[APP_DATA_KEY_ANCHOR] = anchor if url is not None: self.openUrl(url) elif page is not None and modifier == ID_KEY_CTRL: Application.mainWindow.tabsController.openInTab(page, True) elif page is not None: self._currentPage.root.selectedPage = page elif filename is not None: try: outwiker.core.system.getOS().startFile(filename) except OSError: text = _("Can't execute file '%s'") % filename outwiker.core.commands.showError(Application.mainWindow, text) elif anchor is not None: return False return True
def __onLinkClicked(self, href, gtk_mouse_button, gtk_key_modifier): """ Клик по ссылке Возвращает False, если обрабатывать ссылку разрешить компоненту, в противном случае - True (если обрабатываем сами) href - ссылка gtk_mouse_button - кнопка мыши, с помощью которой кликнули по ссылке (1 - левая, 2 - средняя, 3 - правая, -1 - не известно) gtk_key_modifier - зажатые клавиши (1 - Shift, 4 - Ctrl) """ (url, page, filename, anchor) = self.__identifyUri(href) modifier = self.__gtk2OutWikerKeyCode(gtk_key_modifier) mouse_button = self.__gtk2OutWikerMouseButtonCode(gtk_mouse_button) params = self._getClickParams(self._decodeIDNA(href), mouse_button, modifier, url, page, filename, anchor) Application.onLinkClick(self._currentPage, params) if params.process: return True if url is not None: self.openUrl(url) elif page is not None and (mouse_button == ID_MOUSE_MIDDLE or modifier == ID_KEY_CTRL): Application.mainWindow.tabsController.openInTab(page, True) elif page is not None: Application.anchor = anchor self._currentPage.root.selectedPage = page elif filename is not None: try: outwiker.core.system.getOS().startFile(filename) except OSError: text = _(u"Can't execute file '%s'") % filename outwiker.core.commands.MessageBox(text, _(u"Error"), wx.ICON_ERROR | wx.OK) elif anchor is not None: return False return True
def openWiki (path, readonly=False): if not os.path.exists (path): __canNotLoadWikiMessage (path) return # Если передан путь до файла настроек (а не до папки с вики), # то оставим только папку if not os.path.isdir (path): path = os.path.split (path)[0] def threadFunc (path, readonly): try: return WikiDocument.load (path, readonly) except IOError as error: return error except outwiker.core.exceptions.RootFormatError as error: return error preWikiOpenParams = PreWikiOpenParams(path, readonly) Application.onPreWikiOpen(Application.selectedPage, preWikiOpenParams) runner = LongProcessRunner (threadFunc, Application.mainWindow, _(u"Loading"), _(u"Opening notes tree...")) result = runner.run (os.path.realpath (path), readonly) success = False if isinstance(result, IOError): __canNotLoadWikiMessage(path) elif isinstance(result, outwiker.core.exceptions.RootFormatError): __rootFormatErrorHandle(path, readonly) else: Application.wikiroot = result success = True postWikiOpenParams = PostWikiOpenParams(path, readonly, success) Application.onPostWikiOpen(Application.selectedPage, postWikiOpenParams) return Application.wikiroot
def openWiki(path, readonly=False): if not os.path.exists(path): __canNotLoadWikiMessage(path) return # Если передан путь до файла настроек (а не до папки с вики), # то оставим только папку if not os.path.isdir(path): path = os.path.split(path)[0] def threadFunc(path, readonly): try: return WikiDocument.load(path, readonly) except BaseException as e: return e preWikiOpenParams = PreWikiOpenParams(path, readonly) Application.onPreWikiOpen(Application.selectedPage, preWikiOpenParams) runner = LongProcessRunner(threadFunc, Application.mainWindow, _(u"Loading"), _(u"Opening notes tree...")) result = runner.run(os.path.realpath(path), readonly) success = False if isinstance(result, outwiker.core.exceptions.RootFormatError): __rootFormatErrorHandle(path, readonly) elif isinstance(result, Exception): logger.error(result) __canNotLoadWikiMessage(path) else: Application.wikiroot = result success = True postWikiOpenParams = PostWikiOpenParams(path, readonly, success) Application.onPostWikiOpen(Application.selectedPage, postWikiOpenParams) return Application.wikiroot
# pparser.run() cProfile.run('pparser.run()', profile_fname) stats = pstats.Stats(profile_fname) stats.strip_dirs().sort_stats('time').print_stats(30) def outwikerProfile(): global outwiker outwiker = OutWiker(0) profile_fname = "../profiles/outwiker.profile" cProfile.run('outwiker.MainLoop()', profile_fname) stats = pstats.Stats(profile_fname) # stats.strip_dirs().sort_stats('calls').print_stats(30) stats.strip_dirs().sort_stats('time').print_stats(100) if __name__ == "__main__": Application.init("../profiles/testconfig.ini") class testApp(wx.App): def __init__(self, *args, **kwds): wx.App.__init__(self, *args, **kwds) app = testApp(redirect=False) wikiparserProfile() # outwikerProfile ()
import wxversion try: wxversion.select(WX_VERSION) except wxversion.VersionError: if os.name == "nt": pass else: raise import wx if __name__ == '__main__': from outwiker.core.application import Application Application.init("../test/testconfig.ini") app = wx.App(redirect=False) def emptyFunc(): pass app.bindActivateApp = emptyFunc app.unbindActivateApp = emptyFunc loop = wx.EventLoop() wx.EventLoop.SetActive(loop) wx.Log.SetLogLevel(0) import unittest from test.plugins.sessions.test_loading import SessionsLoadingTest
def __onCancel(self, event): Application.onPreferencesDialogClose(self) self.EndModal(wx.ID_CANCEL)
def _onActivate(self, event): Application.onForceSave()
def __init__(self, parent): style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER super(PrefDialog, self).__init__(parent, style=style) self.__treeBook = wx.Treebook(self, -1) self.__do_layout() Application.onPreferencesDialogCreate(self)