Ejemplo n.º 1
0
    def generate_image(self, text):
        if isinstance(text, basestring):
            text = text.splitlines(True)

        # Filter out empty lines, not allowed in latex equation blocks
        text = (line for line in text if line and not line.isspace())
        text = ''.join(text)
        #~ print '>>>%s<<<' % text

        # Write to tmp file using the template for the header / footer
        texfile = self.texfile
        texfile.writelines(self.template.process({'equation': text}))
        #~ print '>>>%s<<<' % texfile.read()

        # Call latex
        logfile = File(texfile.path[:-4] + '.log')  # len('.tex') == 4
        try:
            latex = Application(latexcmd)
            latex.run((texfile.basename, ), cwd=texfile.dir)
        except ApplicationError:
            # log should have details of failure
            return None, logfile

        # Call dvipng
        dvifile = File(texfile.path[:-4] + '.dvi')  # len('.tex') == 4
        pngfile = File(texfile.path[:-4] + '.png')  # len('.tex') == 4
        dvipng = Application(dvipngcmd)
        dvipng.run((pngfile, dvifile))  # output, input
        # No try .. except here - should never fail
        # TODO dvipng can start processing before latex finished - can we win speed there ?

        return pngfile, logfile
Ejemplo n.º 2
0
 def check_dependencies(cls):
     xclip_cmd = ('xclip', )
     pandoc_cmd = ('pandoc', )
     has_xclip = Application(xclip_cmd).tryexec()
     has_pandoc = Application(pandoc_cmd).tryexec()
     return (has_xclip and has_pandoc), [('xclip', has_xclip, True),
                                         ('pandoc', has_pandoc, True)]
Ejemplo n.º 3
0
	def get_fallback_emailclient(klass):
		# Don't use mimetype lookup here, this is a fallback
		if os.name == 'nt':
			return StartFile()
		elif os.name == 'darwin':
			app = Application('open')
		else: # linux and friends
			app = Application('xdg-email')

		if app.tryexec():
			return app
		else:
			return WebBrowser()
Ejemplo n.º 4
0
	def get_fallback_filebrowser(klass):
		# Don't use mimetype lookup here, this is a fallback
		# should handle all file types
		if os.name == 'nt':
			return StartFile()
		elif os.name == 'darwin':
			app = Application('open')
		else: # linux and friends
			app = Application('xdg-open')

		if app.tryexec():
			return app
		else:
			return WebBrowser()
Ejemplo n.º 5
0
def get_zim_application(command, *args):
    '''Constructor to get a L{Application} object for zim itself
	Use this object to spawn new instances of zim from inside the zim
	application.

	@param command: the first commandline argument for zim, e.g.
	"C{--gui}", "C{--manual}" or "C{--server}"
	@param args: additional commandline arguments.
	@returns: a L{Application} object for zim itself
	'''
    # TODO: if not standalone, make object call IPC directly rather than
    #       first spawning a process
    assert command is not None

    from zim import ZIM_EXECUTABLE
    from zim.applications import Application
    from zim.ipc import in_child_process

    args = [command] + list(args)
    if not command.startswith('--ipc'):
        if not in_child_process():
            args.append('--standalone', )

        # more detailed logging has lower number, so WARN > INFO > DEBUG
        loglevel = logging.getLogger().getEffectiveLevel()
        if loglevel <= logging.DEBUG:
            args.append('-D', )
        elif loglevel <= logging.INFO:
            args.append('-V', )

    return Application([ZIM_EXECUTABLE] + args)
Ejemplo n.º 6
0
	def generate_image(self, text):
		if isinstance(text, basestring):
			text = text.splitlines(True)

		plotscriptfile = self.plotscriptfile
		pngfile = File(plotscriptfile.path[:-2] + '.png')

		plot_script = "".join(text)

		template_vars = {
			'gnu_r_plot_script': plot_script,
			'png_fname': pngfile.path.replace('\\', '/'),
				# Even on windows, GNU R expects unix path seperator
		}

		# Write to tmp file usign the template for the header / footer
		plotscriptfile.writelines(
			self.template.process(template_vars)
		)
		#print '>>>%s<<<' % plotscriptfile.read()

		# Call GNU R
		try:
			gnu_r = Application(gnu_r_cmd)
			#~ gnu_r.run(args=('-f', plotscriptfile.basename, ), cwd=plotscriptfile.dir)
			gnu_r.run(args=('-f', plotscriptfile.basename, '--vanilla'), cwd=plotscriptfile.dir)
		except:
			return None, None # Sorry, no log
		else:
			return pngfile, None
Ejemplo n.º 7
0
    def do_response_ok(self):
        tmpfile = TmpFile('insert-screenshot.png')
        selection_mode = False
        delay = 0
        if ScreenshotPicker.has_select_cmd(
                self.screenshot_command) and self.select_radio.get_active():
            selection_mode = True

        if ScreenshotPicker.has_delay_cmd(self.screenshot_command):
            delay = self.time_spin.get_value_as_int()

        options = ScreenshotPicker.get_cmd_options(self.screenshot_command,
                                                   selection_mode, str(delay))
        helper = Application((self.screenshot_command, ) + options)

        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()
                # T: Error message in "insert screenshot" dialog, %s will be replaced by application name

        tmpfile.dir.touch()
        helper.spawn((tmpfile, ), callback, tmpfile)
        return True
Ejemplo n.º 8
0
def _get_lilypond_version():
	try:
		lilypond = Application(lilypondver_cmd)
		output = lilypond.pipe()
		return output[0].split()[2]
	except ApplicationError:
		return '2.14.2'
Ejemplo n.º 9
0
    def generate_image(self, text):

        if isinstance(text, str):
            text = text.splitlines(True)
        text = (line for line in text if line and not line.isspace())
        text = ''.join(text)
        print('[PLUGINS:INSERT LATEX] text written >>>%s<<<' % text)

        # Write to tmp file
        self.texfile.write(text)
        print('[PLUGINS:INSERT LATEX] read from file >>>%s<<<' %
              self.texfile.read())

        # Call latex
        logfile = File(self.texfile.path[:-4] + '.log')  # len('.tex') == 4
        print("[PLUGINS:INSERT LATEX] >>>", self.texfile, logfile)

        try:
            latex = Application(latex_cmd)
            latex.run((self.texfile.basename, ), cwd=self.texfile.dir)
        except ApplicationError:
            print("[PLUGINS:INSERT LATEX] ApplicationError")
            return None, logfile

        png_file = File(self.texfile.path[:-4] + '.png')  # len('.tex') == 4

        return png_file, logfile
Ejemplo n.º 10
0
    def generate_image(self, text):
        plotscriptfile = self.plotscriptfile
        pngfile = File(plotscriptfile.path[:-4] + '.png')

        template_vars = { # they go in the template
         'gnuplot_script': text,
         'png_fname': pngfile.path,
        }
        if self.attachment_folder and self.attachment_folder.exists():
            template_vars['attachment_folder'] = self.attachment_folder.path
        else:
            template_vars['attachment_folder'] = ''

        # Write to tmp file using the template for the header / footer
        lines = []
        self.template.process(lines, template_vars)
        plotscriptfile.writelines(lines)
        #~ print '>>>\n%s<<<' % plotscriptfile.read()

        # Call Gnuplot
        try:
            gnu_gp = Application(gnuplot_cmd)
            gnu_gp.run(args=(plotscriptfile.basename, ),
                       cwd=plotscriptfile.dir)
            # you call it as % gnuplot output.plt

        except ApplicationError:
            return None, None  # Sorry - no log
        else:
            return pngfile, None
Ejemplo n.º 11
0
	def __call__(self, path):
		from zim.applications import Application
		logger.info('Mount: %s', self.dir)
		try:
			Application(self.mount).run()
		except:
			logger.exception('Failed to run: %s', self.mount)
		return path.exists()
Ejemplo n.º 12
0
    def generate_image(self, text):

        (version, text) = self.extract_version(text)
        text = ''.join(text)
        #~ print '>>>%s<<<' % text

        # Write to tmp file using the template for the header / footer
        scorefile = self.scorefile
        lines = []
        self.template.process(
            lines, {
                'score': text,
                'version': version or '',
                'include_header': self.include_header or '',
                'include_footer': self.include_footer or '',
            })
        scorefile.writelines(lines)
        #~ print '>>>%s<<<' % scorefile.read()

        # Call convert-ly to convert document of current version of
        # Lilypond.
        clogfile = File(scorefile.path[:-3] +
                        '-convertly.log')  # len('.ly) == 3
        try:
            convertly = Application(convertly_cmd)
            convertly.run((scorefile.basename, ), cwd=scorefile.dir)
        except ApplicationError:
            clogfile.write('convert-ly failed.\n')
            return None, clogfile

        # Call lilypond to generate image.
        logfile = File(scorefile.path[:-3] + '.log')  # len('.ly') == 3
        try:
            lilypond = Application(lilypond_cmd)
            lilypond.run((
                '-dlog-file=' + logfile.basename[:-4],
                scorefile.basename,
            ),
                         cwd=scorefile.dir)
        except ApplicationError:
            # log should have details of failure
            return None, logfile
        pngfile = File(scorefile.path[:-3] + '.png')  # len('.ly') == 3

        return pngfile, logfile
Ejemplo n.º 13
0
    def testSideBySide(self):
        app = get_side_by_side_app()
        if Application('meld').tryexec():
            self.assertIsNotNone(app)

        if app is None:
            print '\nCould not find an application for side-by-side comparison'
        else:
            self.assertTrue(app.tryexec)
Ejemplo n.º 14
0
	def __call__(self, path):
		if path.path == self.dir.path or path.ischild(self.dir) \
		and not self.dir.exists() \
		and self.mount:
			from zim.applications import Application
			Application(self.mount).run()
			return path.exists()
		else:
			return False
    def generate_image(self, text):

        # Filter out empty lines, not allowed in latex equation blocks
        if isinstance(text, str):
            text = text.splitlines(True)
        text = (line for line in text if line and not line.isspace())
        text = ''.join(text)
        #~ print('>>>%s<<<' % text)

        # Write to tmp file using the template for the header / footer
        lines = []
        self.template.process(
            lines, {
                'equation': text,
                'font_size': self.preferences['font_size'],
                'dark_mode': self.preferences['dark_mode']
            })
        self.texfile.writelines(lines)
        #~ print('>>>%s<<<' % self.texfile.read())

        # Call latex
        logfile = File(self.texfile.path[:-4] + '.log')  # len('.tex') == 4
        #~ print(">>>", self.texfile, logfile)
        try:
            latex = Application('%s -no-shell-escape -halt-on-error' %
                                (latexcmd))
            latex.run((self.texfile.basename, ), cwd=self.texfile.dir)
        except ApplicationError:
            # log should have details of failure
            return None, logfile

        # Call dvipng
        dvifile = File(self.texfile.path[:-4] + '.dvi')  # len('.tex') == 4
        pngfile = File(self.texfile.path[:-4] + '.png')  # len('.tex') == 4
        dvipng = Application('%s -q -bg Transparent -T tight -D %s -o' %
                             (dvipngcmd, self.preferences['output_dpi']))
        dvipng.run((pngfile, dvifile))  # output, input
        # No try .. except here - should never fail
        # TODO dvipng can start processing before latex finished - can we win speed there ?

        return pngfile, logfile
Ejemplo n.º 16
0
    def generate_image(self, text):
        # Write to tmp file
        self.dotfile.write(text)

        # Call GraphViz
        try:
            dot = Application(dotcmd)
            dot.run((self.dotfile, '-o', self.pngfile))
        except ApplicationError:
            return None, None  # Sorry, no log
        else:
            return self.pngfile, None
Ejemplo n.º 17
0
 def check_dependencies(cls):
     cmds = []
     is_ok = False
     if len(SUPPORTED_COMMANDS):
         for cmd in SUPPORTED_COMMANDS:
             has_tool = Application(cmd).tryexec()
             if has_tool:
                 is_ok = True
                 cmds.append((cmd, True, False))
             else:
                 cmds.append((cmd, False, False))
     return is_ok, cmds
Ejemplo n.º 18
0
    def generate_image(self, text):
        # Write to tmp file
        self.diagfile.write(text)

        # Call seqdiag
        try:
            diag = Application(diagcmd)
            diag.run((self.pngfile, self.diagfile))
        except ApplicationError:
            return None, None  # Sorry, no log
        else:
            return self.pngfile, None
Ejemplo n.º 19
0
    def generate_image(self, text):
        if isinstance(text, basestring):
            text = text.splitlines(True)

        # Write to tmp file
        self.diagfile.writelines(text)

        # Call seqdiag
        try:
            diag = Application(diagcmd)
            diag.run((self.pngfile, self.diagfile))
        except ApplicationError:
            return None, None  # Sorry, no log
        else:
            return self.pngfile, None
Ejemplo n.º 20
0
    def generate_image(self, text):
        if isinstance(text, basestring):
            text = text.splitlines(True)

        # Write to tmp file
        self.dotfile.writelines(text)

        # Call GraphViz
        try:
            dot = Application(dotcmd)
            dot.run((self.dotfile, '-o', self.pngfile))
        except ApplicationError:
            return None, None  # Sorry, no log
        else:
            return self.pngfile, None
Ejemplo n.º 21
0
    def _spawn_standalone(self, args):
        from zim import ZIM_EXECUTABLE
        from zim.applications import Application

        args = list(args)
        if not '--standalone' in args:
            args.append('--standalone')

        # more detailed logging has lower number, so WARN > INFO > DEBUG
        loglevel = logging.getLogger().getEffectiveLevel()
        if loglevel <= logging.DEBUG:
            args.append('-D', )
        elif loglevel <= logging.INFO:
            args.append('-V', )

        Application([ZIM_EXECUTABLE] + args).spawn()
Ejemplo n.º 22
0
    def make_screenshot(self, selection_mode, delay):
        tmpfile = TmpFile('insert-screenshot.png')
        options = ScreenshotPicker.get_cmd_options(self.screenshot_command,
                                                   selection_mode, str(delay))
        cmd = (self.screenshot_command, ) + options
        helper = Application(cmd)

        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.pageview
                pageview.insert_image(imgfile)
            else:
                ErrorDialog(
                    self.ui,
                    _('Some error occurred while running "%s"') %
                    self.screenshot_command).run()
                # T: Error message in "insert screenshot" dialog, %s will be replaced by application name

        tmpfile.dir.touch()
        helper.spawn((tmpfile, ), callback, tmpfile)
        return True

        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.pageview
                pageview.insert_image(imgfile)
            else:
                ErrorDialog(
                    self.ui,
                    _('Some error occurred while running "%s"') %
                    self.screenshot_command).run()
                # T: Error message in "insert screenshot" dialog, %s will be replaced by application name

        tmpfile.dir.touch()
        helper.spawn((tmpfile, ), callback, tmpfile)
        return True
Ejemplo n.º 23
0
    def generate_image(self, text):
        # Write to tmp file
        self.dotfile.writelines(text)

        # Call PlantUML
        try:
            dot = Application(dotcmd)
            dot.run((self.pngfile, self.dotfile))
        except ApplicationError:
            return None, None  # Sorry, no log
        else:
            if self.pngfile.exists():
                return self.pngfile, None
            else:
                # When supplying a dot file with a syntax error, the dot command
                # doesn't return an error code (so we don't raise
                # ApplicationError), but we still don't have a png file to
                # return, so return None.
                return None, None
Ejemplo n.º 24
0
    def generate_image(self, text):

        plotscriptfile = self.plotscriptfile
        pngfile = File(plotscriptfile.path[:-2] + '.png')

        plot_script = "".join(text)

        plot_width = 480  # default image width (px)
        plot_height = 480  # default image height (px)

        # LOOK for image size in comments of the script
        r = re.search(r"^#\s*WIDTH\s*=\s*([0-9]+)$", plot_script, re.M)
        if r:
            plot_width = int(r.group(1))
        r = re.search(r"^#\s*HEIGHT\s*=\s*([0-9]+)$", plot_script, re.M)
        if r:
            plot_height = int(r.group(1))

        template_vars = {
            'gnu_r_plot_script': plot_script,
            'r_width': plot_width,
            'r_height': plot_height,
            'png_fname': pngfile.path.replace('\\', '/'),
            # Even on windows, GNU R expects unix path seperator
        }

        # Write to tmp file usign the template for the header / footer
        lines = []
        self.template.process(lines, template_vars)
        plotscriptfile.writelines(lines)
        #print '>>>%s<<<' % plotscriptfile.read()

        # Call GNU R
        try:
            gnu_r = Application(gnu_r_cmd)
            #~ gnu_r.run(args=('-f', plotscriptfile.basename, ), cwd=plotscriptfile.dir)
            gnu_r.run(args=('-f', plotscriptfile.basename, '--vanilla'),
                      cwd=plotscriptfile.dir)
        except:
            return None, None  # Sorry, no log
        else:
            return pngfile, None
Ejemplo n.º 25
0
    def do_response_ok(self):
        tmpfile = TmpFile('insert-screenshot.png')
        options = ()

        if COMMAND == 'scrot':
            if self.select_radio.get_active():
                options += ('--select', '--border')
                # Interactively select a window or rectangle with the mouse.
                # When selecting a window, grab wm border too
            else:
                options += ('--multidisp', )
                # For multiple heads, grab shot from each and join them together.

        delay = self.time_spin.get_value_as_int()
        if delay > 0:
            options += ('-d', str(delay))
            # Wait NUM seconds before taking a shot.

        helper = Application((COMMAND, ) + options)

        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()
                # T: Error message in "insert screenshot" dialog, %s will be replaced by application name

        tmpfile.dir.touch()
        helper.spawn((tmpfile, ), callback, tmpfile)
        return True
Ejemplo n.º 26
0
 def check_dependencies(klass):
     has_gnur = Application(gnu_r_cmd).tryexec()
     return has_gnur, [('GNU R', has_gnur, True)]
Ejemplo n.º 27
0
 def check_dependencies(klass):
     has_dotcmd = Application(dotcmd).tryexec()
     return has_dotcmd, [("Ditaa", has_dotcmd, True)]
Ejemplo n.º 28
0
	def check_dependencies(klass):
		has_lilypond = Application(lilypond_cmd).tryexec()
		return has_lilypond, [('GNU Lilypond', has_lilypond, True)]
Ejemplo n.º 29
0
 def build_bin_application_instance(cls):
     return Application(('git', ))
Ejemplo n.º 30
0
 def check_dependencies(klass):
     has_diagcmd = Application(diagcmd).tryexec()
     return has_diagcmd, [("seqdiag", has_diagcmd, True)]