def Save(self): """ Сохранить текущую страницу """ if self.__saveProcessing: return if self.__pageView is not None: if not pageExists(Application.selectedPage.root): # Нет папки с деревом self.__saveProcessing = True MessageBox( _(u"Can't save page. Wiki folder not exists. Wiki will be closed." ), _("Error"), wx.OK | wx.ICON_ERROR) self.__saveProcessing = False Application.wikiroot = None return if not pageExists(Application.selectedPage): # Похоже, страница удалена вручную, перезагрузим вики self.__saveProcessing = True MessageBox( _(u"Can't save page. Page folder not exists. Wiki will be reloaded." ), _("Error"), wx.OK | wx.ICON_ERROR) self.__saveProcessing = False self.__reloadWiki() return self.__pageView.Save()
def editPage (parentWnd, currentPage): """ Вызвать диалог для редактирования страницы parentWnd - родительское окно currentPage - страница для редактирования """ if currentPage.readonly: raise outwiker.core.exceptions.ReadonlyException if not pageExists (currentPage): MessageBox (_(u'Page "%s" not found') % currentPage.display_title, _(u"Error"), wx.OK | wx.ICON_ERROR) return with EditPageDialog (parentWnd, currentPage) as dlg: if dlg.ShowModal() == wx.ID_OK: try: currentPage.display_title = dlg.pageTitle except EnvironmentError as e: MessageBox (_(u"Can't rename page\n") + unicode (e), _(u"Error"), wx.ICON_ERROR | wx.OK) if not dlg.setPageProperties (currentPage): return None
def generateHtml (self, page): resultFileName = self.getHtmlPath() cache = self._getCacher (page, self._application) # Проверим, можно ли прочитать уже готовый HTML if (cache.canReadFromCache() and os.path.exists (resultFileName)) or page.readonly: try: return readTextFile (resultFileName) except IOError: MessageBox (_(u"Can't read file {}".format (resultFileName)), _(u"Error"), wx.ICON_ERROR | wx.OK) return u"" style = Style() stylepath = style.getPageStyle (page) generator = self._getHtmlGenerator (page) try: html = generator.makeHtml(stylepath) cache.saveHash() except IOError: MessageBox (_(u"Can't create HTML file"), _(u"Error"), wx.ICON_ERROR | wx.OK) return html
def __onEndLabelEdit(self, event): if event.IsEditCancelled(): return event.Veto() oldGroupName = self._groups.GetItemData(event.GetItem()) newGroupName = event.GetLabel().strip() assert oldGroupName is not None collection = self.__getIconsCollection() try: collection.renameGroup(oldGroupName, newGroupName) except(IOError, SystemError): MessageBox( _(u"Can't rename directory for icons group"), _(u"Error"), wx.OK | wx.ICON_ERROR) return except DuplicateGroupError: MessageBox( _(u'Group with name "{}" exists already').format(newGroupName), _(u"Error"), wx.OK | wx.ICON_ERROR) return except ValueError: MessageBox( _(u'Invalid group name "{}"').format(newGroupName), _(u"Error"), wx.OK | wx.ICON_ERROR) return self.__updateGroups() self.__selectGroupItem(newGroupName)
def _onRename(self, event): name = self._actionsList.GetStringSelection() if len(name) == 0: return with wx.TextEntryDialog(self, _(u"Enter new session name"), _(u"Rename session"), name) as dlg: if dlg.ShowModal() == wx.ID_OK: newname = dlg.GetValue().strip() if len(newname) == 0: MessageBox( _(u'Session name is empty').format(newname), _(u"Invalid session name"), wx.ICON_ERROR | wx.OK) return # Проверим, что не ввели имя сессии, совпадающее с существующей # сессией (кроме случая, что не изменили имя) if (newname != name and newname in self._storage.getSessions()): MessageBox( _(u'Session "{}" already exists').format(newname), _(u"Invalid session name"), wx.ICON_ERROR | wx.OK) return self._storage.rename(name, newname) self._updateSessionsList() self._guicreator.updateMenu()
def _savePageContent(self, page): """ Сохранение содержимого страницы """ if (page is None or page.isRemoved or page.readonly): return try: self._getCursorPositionOption( page).value = self.GetCursorPosition() except IOError as e: MessageBox( _(u"Can't save file %s") % (unicode(e.filename)), _(u"Error"), wx.ICON_ERROR | wx.OK) return if self.__stringsAreEqual(page.content, self.GetContentFromGui()): return try: page.content = self.GetContentFromGui() except IOError as e: # TODO: Проверить под Windows MessageBox( _(u"Can't save file %s") % (unicode(e.filename)), _(u"Error"), wx.ICON_ERROR | wx.OK)
def install_plugin(self, name): """ Install plugin by name. :return: True if plugin was installed, otherwise False """ getAppInfo = self.vl.getAppInfoFromUrl getDownlodUrl = self.vl.getDownlodUrl plugin_info = self._installerPlugins.get(name, None) if plugin_info: appInfo = getAppInfo(plugin_info["url"]) if not appInfo or not appInfo.versionsList: MessageBox( _(u"The plugin description can't be downloaded. Please install plugin manually" ), u"UpdateNotifier") return False api_required_version = appInfo.requirements.api_version if pv.checkVersionAny(outwiker.__api_version__, api_required_version) != 0: MessageBox( _(u"The plugin required newer version of OutWiker. Please update OutWiker" ), u"UpdateNotifier") return False # get link to latest version url = getDownlodUrl(appInfo) if not url: MessageBox( _(u"The download link was not found in plugin description. Please install plugin manually" ), u"UpdateNotifier") return False # getPluginsDirList[0] - папка рядом с запускаемым файлом, затем идут другие папки, # если они есть pluginPath = self.__deletedPlugins.get( name, os.path.join(getPluginsDirList()[-1], name.lower())) logger.info('install_plugin: {url} {path}'.format(url=url, path=pluginPath)) rez = UpdatePlugin().update(url, pluginPath) if rez: self._application.plugins.load([os.path.dirname(pluginPath)]) self._updateDialog() else: MessageBox( _(u"Plugin was NOT Installed. Please update plugin manually" ), u"UpdateNotifier") return rez
def __onOk(self, event): name = self.sessionName if len(name.strip()) == 0: MessageBox(_(u"The session name must not be empty"), _(u"Error"), wx.ICON_ERROR | wx.OK) return if (name in self._names and MessageBox( _(u'Session with name "{}" exists. Overwrite?').format(name), _(u"Overwrite session?"), wx.ICON_QUESTION | wx.YES | wx.NO) != wx.YES): return event.Skip()
def __onOk(self, _event): from outwiker.core.commands import MessageBox if self.oldTagName is None: MessageBox(_(u"Select tag for rename"), _(u"Error"), wx.ICON_ERROR | wx.OK) return if len(self.newTagName) == 0: MessageBox(_(u"Enter new tag name"), _(u"Error"), wx.ICON_ERROR | wx.OK) return self.EndModal(wx.ID_OK)
def onLinkClick(self, page, params): """ Event handler for clicking on link """ if params.link is None: return urlparams = self._getParams(params.link) if not urlparams: return params.process = True commands = self.getCommandsList(urlparams) config = ExternalToolsConfig(self._application.config) if len(commands) > 1: message = _( u'Run applications by ExternalTools plugin?\nIt may be unsafe.' ) else: message = _( u'Run application by ExternalTools plugin?\nIt may be unsafe.') if (config.execWarning and MessageBox(message, _(u'ExternalTools'), wx.YES_NO | wx.ICON_QUESTION | wx.NO_DEFAULT) != wx.YES): return for command in commands: self._execute(command.command, command.params)
def createPageWithDialog(parentwnd, parentpage): """ Показать диалог настроек и создать страницу """ assert parentpage is not None if parentpage.readonly: raise outwiker.core.exceptions.ReadonlyException page = None with CreatePageDialog(parentwnd, parentpage, Application) as dlg: if dlg.ShowModal() == wx.ID_OK: factory = dlg.selectedFactory alias = dlg.pageTitle siblings = [child_page.title for child_page in parentpage.children] title = getAlternativeTitle(alias, siblings) try: page = factory.create(parentpage, title, []) if title != alias: page.alias = alias except EnvironmentError: MessageBox(_(u"Can't create page"), "Error", wx.ICON_ERROR | wx.OK) return None assert page is not None if not dlg.setPageProperties(page): return None page.root.selectedPage = page return page
def _onOk(self, event): self.resetLog() url = self._dialog.url if len(url) == 0: MessageBox(_('Enter link for downloading'), _(u"Error"), wx.ICON_ERROR | wx.OK) self._dialog.urlText.SetFocus() return if os.path.isfile(url): url = url.replace('\\', '/') if not url.startswith('/'): url = '/' + url url = 'file://' + url if self._thread is None: self._removeDownloadDir() self._downloadDir = mkdtemp(prefix='webpage_tmp_') self._runEvent.set() self._thread = DownloadThread(self._dialog, self._runEvent, self._downloadDir, url) self._thread.start()
def _openGlobalSearch(self): if self._application.wikiroot is not None: try: GlobalSearch.create(self._application.wikiroot) except IOError: MessageBox(_(u"Can't create page"), _(u"Error"), wx.ICON_ERROR | wx.OK)
def __onOk(self, event): if len(self.name.strip()) == 0: MessageBox(_(u"Name of a node can't be empty"), u"Name of a node is empty", wx.ICON_ERROR | wx.OK) return event.Skip()
def setPageProperties(self, page): """ Return True if success and False otherwise """ if self.icon is None: return True icon = os.path.abspath(self.icon) if page.icon is not None and icon == os.path.abspath(page.icon): return True self._recentIconsList.add(icon) # If icon not exists, page may be renamed. Don't will to change icon if os.path.exists(icon): try: page.icon = icon except EnvironmentError as e: MessageBox( _(u"Can't set page icon\n") + str(e), _(u"Error"), wx.ICON_ERROR | wx.OK) return False return True
def _onAddGroup(self, event): ''' Add group button click ''' selectedItem = self._getSelectedItemData() assert selectedItem is not None rootdir = selectedItem.path if not os.path.isdir(rootdir): rootdir = os.path.dirname(rootdir) # Find unique directory for snippets newpath = findUniquePath(rootdir, _(defines.NEW_DIR_NAME)) try: os.mkdir(newpath) snippets_tree = self._loadSnippetsTree() self._fillSnippetsTree(snippets_tree, newpath) newitem = self.snippetsTree.GetSelection() self.snippetsTree.EditLabel(newitem) self._updateMenu() self._scrollToSelectedItem() except EnvironmentError: MessageBox( _(u"Can't create directory\n{}").format(newpath), _(u"Error"), wx.ICON_ERROR | wx.OK)
def OnDropFiles(self, x, y, files): correctedFiles = self.correctFileNames(files) flags_mask = wx.TREE_HITTEST_ONITEMICON | wx.TREE_HITTEST_ONITEMLABEL item, flags = self.targetWindow.HitTest((x, y)) if flags & flags_mask: page = self._notesTree.getPageByItemId(item) if page is not None: file_names = [os.path.basename(fname) for fname in correctedFiles] text = _("Attach files to the note '{title}'?\n\n{files}").format( title=page.display_title, files='\n'.join(file_names) ) if MessageBox(text, _("Attach files to the note?"), wx.YES_NO | wx.ICON_QUESTION) == wx.YES: attachFiles(self._application.mainWindow, page, correctedFiles) return True return False
def setPageProperties(self, page): """ Return True if success and False otherwise """ icon_filename = (os.path.abspath(self.icon) if self.icon is not None else None) if ((page.icon is not None and icon_filename == os.path.abspath(page.icon)) or (page.icon is None and icon_filename is None)): # Icon was not changed return True if icon_filename is not None: self._recentIconsList.add(icon_filename) # If icon_filename not exists, page may be renamed. Don't will to change icon if icon_filename is None or os.path.exists(icon_filename): try: page.icon = icon_filename except EnvironmentError as e: MessageBox(_(u"Can't set page icon\n") + str(e), _(u"Error"), wx.ICON_ERROR | wx.OK) return False return True
def _updateHtmlWindow(self): """ Подготовить и показать HTML текущей страницы """ assert self._currentpage is not None setStatusText(_(u"Page loading. Please wait…"), self._statusbar_item) try: path = self._currentpage.getHtmlPath() if not os.path.exists(path): self._updatePage() html = readTextFile(path) if (self._oldPage != self._currentpage or self._oldHtmlResult != html): self.htmlWindow.LoadPage(path) self._oldHtmlResult = html self._oldPage = self._currentpage except EnvironmentError as e: logger.error(str(e)) MessageBox( _(u'Page loading error: {}').format(self._currentpage.title), _(u'Error'), wx.ICON_ERROR | wx.OK) setStatusText(u"", self._statusbar_item)
def __onHotkeyEdit(self, event): newActionStrId = self.__getSelectedStrid() if newActionStrId is None: return newhotkey = event.hotkey oldActionStrId = self.__findConflict(newhotkey) if oldActionStrId is not None: newAction = self._application.actionController.getTitle( newActionStrId) oldAction = self._application.actionController.getTitle( oldActionStrId) text = _( u'{hotkey} hotkey assigned for "{old}".\nAssign this hotkey for "{new}"?' ).format(hotkey=newhotkey, old=oldAction, new=newAction) if (MessageBox(text, _(u'Hotkeys conflict'), wx.ICON_QUESTION | wx.YES | wx.NO) == wx.YES): self.__hotkeys[oldActionStrId] = None else: self.__hotkeyCtrl.SetValue(self.__hotkeys[newActionStrId]) return self.__hotkeys[newActionStrId] = newhotkey
def _saveParams(self): """ Сохранить параметры в конфиг """ self._updateRealSize() try: if not self.IsIconized(): self.mainWindowConfig.fullscreen.value = self.IsFullScreen() self.__panesController.savePanesParams() if self._realSize: (width, height) = self._realSize self.mainWindowConfig.width.value = width self.mainWindowConfig.height.value = height if self._realPosition: (xpos, ypos) = self._realPosition self.mainWindowConfig.xPos.value = xpos self.mainWindowConfig.yPos.value = ypos self.mainWindowConfig.maximized.value = self._realMaximized except Exception as e: MessageBox( _(u"Can't save config\n%s") % (str(e)), _(u"Error"), wx.ICON_ERROR | wx.OK)
def createPageWithDialog (parentwnd, parentpage): """ Показать диалог настроек и создать страницу """ if parentpage.readonly: raise outwiker.core.exceptions.ReadonlyException page = None with CreatePageDialog (parentwnd, parentpage) as dlg: if dlg.ShowModal() == wx.ID_OK: factory = dlg.selectedFactory title = dlg.pageTitle try: page = factory.create (parentpage, title, []) except EnvironmentError: MessageBox (_(u"Can't create page"), "Error", wx.ICON_ERROR | wx.OK) return None assert page is not None if not dlg.setPageProperties (page): return None page.root.selectedPage = page return page
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)
def __onRemove(self, event): if Application.selectedPage is not None: files = self.__getSelectedFiles() if len(files) == 0: MessageBox(_(u"You did not select a file to remove"), _(u"Error"), wx.OK | wx.ICON_ERROR) return if MessageBox(_(u"Remove selected files?"), _(u"Remove files?"), wx.YES_NO | wx.ICON_QUESTION) == wx.YES: try: Attachment(Application.selectedPage).removeAttach(files) except IOError as e: MessageBox(unicode(e), _(u"Error"), wx.ICON_ERROR | wx.OK) self.updateAttachments()
def __onOk(self, event): result = u'' if self.uidValidator is None else self.uidValidator( self.uid) if len(result) == 0: self.EndModal(wx.ID_OK) else: MessageBox(result, _(u"Error"), wx.ICON_ERROR | wx.OK)
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)
def __onOkPressed(self, event): if len(self.path) == 0: MessageBox(_("Please, select folder for export"), _("Error"), wx.OK | wx.ICON_ERROR) self._setFocusDefault() return self._onOk()
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)
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)
def _showSnippet(self, info): try: text = readTextFile(info.path).rstrip() self._dialog.snippetEditor.SetText(text) except EnvironmentError: MessageBox( _(u"Can't read the snippet\n{}").format(info.path), _(u"Error"), wx.ICON_ERROR | wx.OK)