def do_response_ok(self): """ Call to insert citation when pressing ok. Will insert the whole bibliography text. """ textbuffer = self.pageview.textview.get_buffer() data = {} link_format = self.preferences['link_format'] bibliography_style = self.preferences['bibliography_style'] if link_format == 'bibliography' and bibliography_style is not None: data['style'] = bibliography_style data['method'] = self.form['search'] data['format'] = link_format data['q'] = self.form['searchtext'] urlvalues = urlencode(data) url = self.zotxturlsearch + urlvalues try: resp = json.loads(urlopen(url).read().decode('utf-8')) if link_format == 'bibliography': for i in resp: key = i['key'] zotlink = (self.linkurl + key) bibtext = i['text'] textbuffer.insert_link_at_cursor(bibtext, href=zotlink) textbuffer.insert_at_cursor("\n") elif link_format == 'betterbibtexkey': for key in resp: zotlink = (self.linkurl + '@' + key) textbuffer.insert_link_at_cursor(key, href=zotlink) textbuffer.insert_at_cursor("\n") elif link_format == 'easykey': for key in resp: try: zokey = self.fetchkey(key) except Exception as error: ErrorDialog( self, 'Could not fetch Zotero key: ' + str(error)).run() continue zotlink = (self.linkurl + zokey) textbuffer.insert_link_at_cursor(key, href=zotlink) textbuffer.insert_at_cursor("\n") elif link_format == 'key': for key in resp: zotlink = (self.linkurl + key) textbuffer.insert_link_at_cursor(key, href=zotlink) textbuffer.insert_at_cursor("\n") else: ErrorDialog(self, 'link format unknown: ' + link_format).run() return False except Exception as error: errorstr = "While executing the request to Zotero, a error happend" + str( error) + "\n" + url ErrorDialog(self, errorstr).run() return False return True
def do_response_ok(self): name = self.form['name'] cmd = self.form['exec'] default = self.form['default'] if not (name and cmd): return False manager = ApplicationManager() application = manager.create(self.mimetype, name, cmd, NoDisplay=default) # Default implies NoDisplay, this to keep the list # more or less clean. if not application.tryexec(): ErrorDialog( self, _('Could not find executable "%s"') % application.cmd[0]).run() # T: Error message for new commands in "open with" dialog application.file.remove() return False if default: manager.set_default_application(self.mimetype, application) self.result = application return True
def start(self): # Start server try: uri = self.notebookcombobox.get_notebook() if uri: notebook, x = build_notebook(NotebookInfo(uri)) if not notebook: return else: return port = int(self.portentry.get_value()) public = self.public_checkbox.get_active() self.httpd = make_server(notebook, port, public, **self.interface_opts) if sys.platform == 'win32': # glib io watch conflicts with socket use on windows.. # idle handler uses a bit to much CPU for my taste, # timeout every 0.5 sec is better self.httpd.timeout = 0.1 # 100 ms self._source_id = glib.timeout_add(500, self.do_serve_on_poll) else: self.httpd.timeout = 3 # if no response after 3 sec, drop it self._source_id = glib.io_add_watch( self.httpd.fileno(), glib.IO_IN | glib.IO_OUT | glib.IO_ERR | glib.IO_HUP | glib.IO_PRI, # any event.. self.do_serve_on_io) logger.info("Serving HTTP on %s port %i...", self.httpd.server_name, self.httpd.server_port) except Exception, error: ErrorDialog(self, error).run() return
def start(self): # Start server try: uri = self.notebookcombobox.get_notebook() if uri: notebook, x = build_notebook(NotebookInfo(uri)) if not notebook: return else: return if not notebook.index.is_uptodate: for info in notebook.index.update_iter(): #logger.info('Indexing %s', info) pass # TODO meaningful info for above message port = int(self.portentry.get_value()) public = self.public_checkbox.get_active() self.httpd = make_server(notebook, port, public, **self.interface_opts) if sys.platform == 'win32': # GObject io watch conflicts with socket use on windows.. # idle handler uses a bit to much CPU for my taste, # timeout every 0.5 sec is better self.httpd.timeout = 0.1 # 100 ms self._source_id = GObject.timeout_add(500, self.do_serve_on_poll) else: self.httpd.timeout = 3 # if no response after 3 sec, drop it self._source_id = GObject.io_add_watch( self.httpd.fileno(), GObject.IO_IN | GObject.IO_OUT | GObject.IO_ERR | GObject.IO_HUP | GObject.IO_PRI, # any event.. self.do_serve_on_io) logger.info("Serving HTTP on %s port %i...", self.httpd.server_name, self.httpd.server_port) except Exception as error: ErrorDialog(self, error).run() return # Update UI self.notebookcombobox.set_sensitive(False) self.portentry.set_sensitive(False) self.public_checkbox.set_sensitive(False) self.open_button.set_sensitive(False) self.start_button.set_sensitive(False) self.stop_button.set_sensitive(True) self.status_label.set_markup('<i>' + _('Server started') + '</i>') # T: Status in web server gui #if self.public_checkbox.get_active(): # url = 'http://%s:%i' % (self.httpd.server_name, self.httpd.server_port) #else: # url = 'http://localhost:%i' % self.httpd.server_port url = 'http://localhost:%i' % self.httpd.server_port if self.link_button: self.link_button.set_uri(url) self.link_button.set_label(url) self.link_button.set_sensitive(True)
def spawn(self, args=None, callback=None, data=None, cwd=None): '''Start the application in the background and return immediately. This is used to start an external in parallel with zim that is not expected to exit immediatly, so we do not want to wait for it - e.g. a webbrowser to show an URL that was clicked. @param args: additional arguments to give to the command as tuple or list @param callback: optional callback can be used to trigger when the application exits. The signature is:: callback(status, data) where 'C{status}' is the exit status of the process. The application object provides a constant 'C{STATUS_OK}' which can be used to test if the application was successful or not. @param data: additional data for the callback @param cwd: the folder to set as working directory for the command @returns: the PID for the new process ''' cwd, argv = self._checkargs(cwd, args) opts = {} flags = GObject.SPAWN_SEARCH_PATH if callback: flags |= GObject.SPAWN_DO_NOT_REAP_CHILD # without this flag child is reaped automatically -> no zombies logger.info('Spawning: %s (cwd: %s)', argv, cwd) if TEST_MODE: TEST_MODE_RUN_CB(argv) return None try: try: pid, stdin, stdout, stderr = \ GObject.spawn_async(argv, flags=flags, **opts) except GObject.GError: if _CAN_CALL_FLATPAK_HOST_COMMAND: pid, stdin, stdout, stderr = \ GObject.spawn_async(_FLATPAK_HOSTCOMMAND_PREFIX + argv, flags=flags, **opts) else: raise except GObject.GError: from zim.gui.widgets import ErrorDialog ErrorDialog(None, _('Failed running: %s') % argv[0]).run() #~ # T: error when application failed to start return None else: logger.debug('Process started with PID: %i', pid) if callback: # child watch does implicit reaping -> no zombies if data is None: GObject.child_watch_add( pid, lambda pid, status: callback(status)) else: GObject.child_watch_add( pid, lambda pid, status, data: callback(status, data), data) return pid
def open_attachments_folder(self): '''Menu action to open the attachment folder for the current page''' dir = self.notebook.get_attachments_dir(self.page) if dir is None: error = _('This page does not have an attachments folder') # T: Error message ErrorDialog(self.widget, error).run() else: open_folder_prompt_create(self.widget, dir)
def check_close_dialog(status): if status != 0: dialog.destroy() ErrorDialog(widget, _('Could not open: %s') % file.basename).run() # T: error when external application fails else: newmtime = file.mtime() if newmtime != oldmtime: dialog.destroy()
def _monitor_thread(thread): if thread.done: if thread.error: error = thread.exc_info[1] logger.error('Error during async commit', exc_info=thread.exc_info) ErrorDialog(None, error, thread.exc_info).run() # XXX None should be window return False # stop signal else: return True # keep handler
def open_document_root(self): '''Menu action to open the document root folder''' # TODO: should be insensitive if document_root is not defined dir = self.notebook.document_root if dir is None: error = _('No document root defined for this notebook') # T: Error message ErrorDialog(self.widget, error).run() else: open_folder_prompt_create(self.widget, dir)
def _search(self): string = self.query_entry.get_text() if self.namespacecheckbox.get_active(): string = 'Section: "%s" ' % self.ui.page.name + string #~ print '!! QUERY: ' + string self._set_state(self.SEARCHING) try: self.results_treeview.search(string) except Exception, error: ErrorDialog(self, error).run()
def do_response(self, widget, id): # Handler for the response signal, dispatches to do_response_ok() # or do_response_cancel() and destroys the dialog if that function # returns True. # Ensure the dialog always closes on delete event, regardless # of any errors or bugs that may occur. if id == gtk.RESPONSE_OK: logger.debug('Dialog response OK') try: destroy = self.do_response_ok() except Exception as error: ErrorDialog(self.ui, error).run() destroy = False else: if not destroy: logger.warning('Dialog input not valid') elif id == gtk.RESPONSE_CANCEL: logger.debug('Dialog response CANCEL') try: destroy = self.do_response_cancel() except Exception as error: ErrorDialog(self.ui, error).run() destroy = False else: if not destroy: logger.warning('Could not cancel dialog') else: destroy = True try: x, y = self.dialog.get_position() self.dialog.uistate['_windowpos'] = (x, y) w, h = self.dialog.get_size() self.dialog.uistate['windowsize'] = (w, h) self.dialog.save_uistate() except: logger.exception('Exception in do_response()') if destroy: self.dialog.destroy() logger.debug('Closed dialog "%s"', self.title[:-6])
def do_response_ok(self) -> bool: try: entry = self.entry self.rpc.addVorgang(entry.number(), self.date, entry.time_total(), entry.details()) buffer = self.textview.get_buffer() # type: TextBuffer buffer.toggle_checkbox_for_cursor_or_selection(CHECKED_BOX, True) return True except Exception as error: ErrorDialog(self, str(error)).run() return False
def callback(status, tmpfile): if status == helper.STATUS_OK: name = time.strftime('screenshot_%Y-%m-%d-%H%M%S.png') imgdir = self.notebook.get_attachments_dir(self.page) imgfile = imgdir.new_file(name) tmpfile.rename(imgfile) pageview = self.app_window.pageview pageview.insert_image(imgfile, interactive=False, force=True) else: ErrorDialog( self.ui, _('Some error occurred while running "%s"') % self.screenshot_command).run()
def callback(status, tmpfile): if status == helper.STATUS_OK: name = time.strftime('screenshot_%Y-%m-%d-%H%M%S.png') dir = self.notebook.get_attachments_dir(self.page) file = dir.new_file(name) tmpfile.rename(file) self.ui.pageview.insert_image( file, interactive=False) # XXX ui == window else: ErrorDialog( self.ui, _('Some error occurred while running "%s"') % COMMAND).run()
def __init__(self, widget, notebook, path): assert path, 'Need a page here' FileDialog.__init__(self, widget, _('Attach File'), multiple=True) # T: Dialog title self.notebook = notebook self.path = path self.add_shortcut(notebook, path) self.load_last_folder() dir = notebook.get_attachments_dir(path) if dir is None: ErrorDialog(_('Page "%s" does not have a folder for attachments') % self.path) # T: Error dialog - %s is the full page name raise Exception('Page "%s" does not have a folder for attachments' % self.path)
def _search(self): string = self.query_entry.get_text() if self.namespacecheckbox.get_active(): string = 'Section: "%s" ' % self.app_window.ui.page.name + string # XXX #~ print '!! QUERY: ' + string self._set_state(self.SEARCHING) try: self.results_treeview.search(string) except Exception as error: ErrorDialog(self, error).run() if not self.results_treeview.cancelled: self._set_state(self.READY) else: self._set_state(self.CANCELLED)
def setup(self): textview = self.pageview.textview lang = self._language or locale.getdefaultlocale()[0] logger.debug('Spellcheck language: %s', lang) try: checker = self._adapter_cls(textview, lang) except: ErrorDialog( self.pageview, ( _('Could not load spell checking'), # T: error message _('This could mean you don\'t have the proper\ndictionaries installed' ) # T: error message explanation )).run() else: textview._gtkspell = checker
def setup(self): textview = self.window.pageview.view lang = self.plugin.preferences['language'] or None try: self.spell = gtkspell.Spell(textview, lang) except: ErrorDialog( self.ui, ( _('Could not load spell checking'), # T: error message _('This could mean you don\'t have the proper\ndictionaries installed' ) # T: error message explanation )).run() self.spell = None else: textview.gtkspell = self.spell # HACK used by hardcoded hook in pageview
def do_response_ok(self): #~ import pprint #~ pprint.pprint(self.uistate) #~ return True options = {} for k in ('format', 'template', 'index_page'): if self.uistate[k] and not self.uistate[k].isspace(): options[k] = self.uistate[k] options['format'] = \ zim.formats.canonical_name(options['format']) if options['template'] == '__file__': options['template'] = self.uistate['template_file'] if self.uistate['document_root_url'] == 'url': options['document_root_url'] = self.uistate['document_root_url'] try: exporter = Exporter(self.ui.notebook, **options) except Exception, error: ErrorDialog(self, error).run() return False
def _run_error_dialog(error): #~ try: from zim.gui.widgets import ErrorDialog ErrorDialog(None, error, do_logging=False).run()
def check_error(status): if status != 0: ErrorDialog(widget, _('Could not open: %s') % uri).run()