Example #1
0
    def save(self):
        """Save the file to the current :attr:`path`.

        This calls :meth:`save_as` if :attr:`path` is None, and returns
        False if the user cancels the save as dialog. None is returned
        on errors, and True is returned in all other cases. In other
        words, this returns True if saving succeeded.

        .. seealso:: The :virtevt:`Save` event.
        """
        if self.path is None:
            return self.save_as()

        self.event_generate('<<Save>>')

        encoding = settings.get_section('General')['encoding']
        try:
            with utils.backup_open(self.path, 'w', encoding=encoding) as f:
                for chunk in self.textwidget.iter_chunks():
                    f.write(chunk)
        except (OSError, UnicodeError) as e:
            log.exception("saving '%s' failed", self.path)
            utils.errordialog(
                type(e).__name__, "Saving failed!", traceback.format_exc())
            return None

        self.mark_saved()
        return True
Example #2
0
    def save(self) -> Optional[bool]:
        """Save the file to the current :attr:`path`.

        This calls :meth:`save_as` if :attr:`path` is None, and returns
        False if the user cancels the save as dialog. None is returned
        on errors, and True is returned in all other cases. In other
        words, this returns True if saving succeeded.

        .. seealso:: The :virtevt:`Save` event.
        """
        if self.path is None:
            return self.save_as()

        self.event_generate('<<Save>>')

        encoding = self.settings.get('encoding', str)
        line_ending = self.settings.get('line_ending', settings.LineEnding)

        try:
            with utils.backup_open(self.path,
                                   'w',
                                   encoding=encoding,
                                   newline=line_ending.value) as f:
                f.write(self.textwidget.get('1.0', 'end - 1 char'))
        except (OSError, UnicodeError) as e:
            log.exception("saving '%s' failed", self.path)
            utils.errordialog(
                type(e).__name__, "Saving failed!", traceback.format_exc())
            return None

        self.mark_saved()
        return True
Example #3
0
def pasting_done_callback(paste: Paste, please_wait_window: tkinter.Toplevel,
                          success: bool, result: str) -> None:
    get_main_window().tk.call("tk", "busy", "forget", get_main_window())
    please_wait_window.destroy()

    if success:
        if result.startswith(("http://", "https://")):
            log.info("pasting succeeded")
            dialog = SuccessDialog(url=result)
            dialog.title("Pasting Succeeded")
            dialog.geometry("450x150")
            dialog.transient(get_main_window())
            dialog.wait_window()
        else:
            log.error(f"pastebin returned invalid url: {result!r}")
            messagebox.showerror(
                "Pasting failed",
                f"Instead of a valid URL, {type(paste).name} returned {result!r}."
            )
    elif paste.canceled:
        # Log error with less dramatic log level and don't show in GUI
        log.debug("Pasting failed and was cancelled. Here is the error.",
                  exc_info=True)
    else:
        # result is the traceback as a string
        log.error(f"pasting failed\n{result}")
        utils.errordialog(
            "Pasting Failed",
            ("Check your internet connection and try again.\n\n" +
             "Here's the full error message:"),
            monospace_text=result,
        )
Example #4
0
    def open_files():
        for path in _dialogs.open_files():
            try:
                tab = tabs.FileTab.open_file(_tab_manager, path)
            except (UnicodeError, OSError) as e:
                log.exception("opening '%s' failed", path)
                utils.errordialog(type(e).__name__, "Opening failed!",
                                  traceback.format_exc())
                continue

            _tab_manager.add_tab(tab)
Example #5
0
    def open_files() -> None:
        paths = filedialog.askopenfilenames(**filedialog_kwargs)  # "" or tuple
        for path in map(pathlib.Path, paths):
            try:
                tab = tabs.FileTab.open_file(get_tab_manager(), path)
            except (UnicodeError, OSError) as e:
                log.exception(f"opening '{path}' failed")
                utils.errordialog(
                    type(e).__name__, "Opening failed!",
                    traceback.format_exc())
                continue

            get_tab_manager().add_tab(tab)
Example #6
0
    def done_callback(self, success, result):
        tk_busy_forget()
        self.please_wait_window.destroy()

        if success:
            log.info("pasting succeeded")
            dialog = SuccessDialog(result)
            dialog.title("Pasting Succeeded")
            dialog.geometry('450x150')
            dialog.transient(get_main_window())
            dialog.wait_window()
        else:
            # result is the traceback as a string
            log.error("pasting failed\n%s" % result)
            utils.errordialog(
                "Pasting Failed",
                ("Check your internet connection and try again.\n\n" +
                 "Here's the full error message:"),
                monospace_text=result)
Example #7
0
    def open_files():
        paths = filedialog.askopenfilenames(
            **filetypes.get_filedialog_kwargs())

        # tkinter returns '' if the user cancels, and i'm arfaid that python
        # devs might "fix" a future version to return None
        if not paths:
            return

        for path in paths:
            try:
                tab = tabs.FileTab.open_file(_tab_manager, path)
            except (UnicodeError, OSError) as e:
                log.exception("opening '%s' failed", path)
                utils.errordialog(
                    type(e).__name__, "Opening failed!",
                    traceback.format_exc())
                continue

            _tab_manager.add_tab(tab)
Example #8
0
    def open_files() -> None:
        paths: Sequence[str] = filedialog.askopenfilenames(
            **filedialog_kwargs)  # type: ignore

        # tkinter returns '' if the user cancels, and i'm arfaid that python
        # devs might "fix" a future version to return None
        if not paths:
            return

        for path in map(pathlib.Path, paths):
            try:
                tab = tabs.FileTab.open_file(get_tab_manager(), path)
            except (UnicodeError, OSError) as e:
                log.exception("opening '%s' failed", path)
                utils.errordialog(
                    type(e).__name__, "Opening failed!",
                    traceback.format_exc())
                continue

            get_tab_manager().add_tab(tab)
Example #9
0
def run_autopep8(code: str) -> Optional[str]:
    try:
        import autopep8  # type: ignore
        autopep8 = autopep8  # silence pyflakes warning
    except ImportError:
        # this command is wrong in some cases, but most of the time
        # it's ok
        if platform.system() == 'Windows':
            pip_command = "py -m pip install autopep8"
            terminal = 'command prompt or PowerShell'
        else:
            pip_command = "python3 -m pip install --user autopep8"
            terminal = 'a terminal'

        utils.errordialog(
            "Cannot find autopep8", "Looks like autopep8 is not installed.\n" +
            f"You can install it by running this command on {terminal}:",
            pip_command)
        return None

    # autopep8's main() does some weird signal stuff, so we'll run it in
    # a subprocess just to make sure that the porcupine process is ok
    command = [str(utils.python_executable), '-m', 'autopep8', '-']
    process = subprocess.Popen(command,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    (output, errors) = process.communicate(code.encode('utf-8'))

    if process.returncode != 0:
        utils.errordialog(
            "Running autopep8 failed",
            "autopep8 exited with status code %r." % process.returncode,
            errors.decode('utf-8', errors='replace'))
        return None

    return output.decode('utf-8')