Esempio n. 1
0
    def _do_load_plugin_cb(self, widget):
        self.tw.load_save_folder = self._get_execution_dir()
        file_path, loaddir = get_load_name('.tar.gz', self.tw.load_save_folder)
        if file_path is None:
            return
        try:
            # Copy to tmp file since some systems had trouble
            # with gunzip directly from datastore
            datapath = get_path(None, 'instance')
            if not os.path.exists(datapath):
                os.makedirs(datapath)
            tmpfile = os.path.join(datapath, 'tmpfile.tar.gz')
            subprocess.call(['cp', file_path, tmpfile])
            status = subprocess.call(['gunzip', tmpfile])
            if status == 0:
                tar_fd = tarfile.open(tmpfile[:-3], 'r')
            else:
                tar_fd = tarfile.open(tmpfile, 'r')
        except:
            tar_fd = tarfile.open(file_path, 'r')

        tmp_dir = tempfile.mkdtemp()

        try:
            tar_fd.extractall(tmp_dir)
            load_a_plugin(self, tmp_dir)
            self.restore_cursor()
        except:
            self.restore_cursor()
        finally:
            tar_fd.close()
            # Remove tmpfile.tar
            subprocess.call(['rm',
                             os.path.join(datapath, 'tmpfile.tar')])
Esempio n. 2
0
    def _do_load_plugin_cb(self, widget):
        file_path, loaddir = get_load_name('.tar.gz')
        if file_path is None:
            return
        try:
            # Copy to tmp file since some systems had trouble
            # with gunzip directly from datastore
            datapath = get_path(None, 'instance')
            if not os.path.exists(datapath):
                os.makedirs(datapath)
            tmpfile = os.path.join(datapath, 'tmpfile.tar.gz')
            subprocess.call(['cp', file_path, tmpfile])
            status = subprocess.call(['gunzip', tmpfile])
            if status == 0:
                tar_fd = tarfile.open(tmpfile[:-3], 'r')
            else:
                tar_fd = tarfile.open(tmpfile, 'r')
        except:
            tar_fd = tarfile.open(file_path, 'r')

        tmp_dir = tempfile.mkdtemp()

        try:
            tar_fd.extractall(tmp_dir)
            load_a_plugin(self, tmp_dir)
            self.restore_cursor()
        except:
            self.restore_cursor()
        finally:
            tar_fd.close()
            # Remove tmpfile.tar
            subprocess.call(['rm', os.path.join(datapath, 'tmpfile.tar')])
Esempio n. 3
0
def myblock(tw, title):
    ''' Save heap to journal (Sugar only) '''

    import os.path
    from gettext import gettext as _

    from sugar.activity import activity
    from sugar.datastore import datastore
    from sugar import profile

    from TurtleArt.tautils import get_path, data_to_file

    # Save JSON-encoded heap to temporary file
    heap_file = os.path.join(get_path(activity, 'instance'),
                             str(title) + '.txt')
    data_to_file(tw.lc.heap, heap_file)

    # Create a datastore object
    dsobject = datastore.create()

    # Write any metadata (specifically set the title of the file
    #                     and specify that this is a plain text file).
    dsobject.metadata['title'] = str(title)
    dsobject.metadata['icon-color'] = profile.get_color().to_string()
    dsobject.metadata['mime_type'] = 'text/plain'
    dsobject.set_file_path(heap_file)
    datastore.write(dsobject)
    dsobject.destroy()
Esempio n. 4
0
    def _get_local_settings(self, activity_root):
        """ return an activity-specific Gio.Settings
        """
        # create compiled schema file if missing from activity root
        compiled = os.path.join(activity_root, 'gschemas.compiled')
        if not os.access(compiled, os.R_OK):
            # create schemas directory if missing
            path = os.path.join(get_path(None, 'data'), 'schemas')
            if not os.access(path, os.F_OK):
                os.makedirs(path)

            # create compiled schema file if missing
            compiled = os.path.join(path, 'gschemas.compiled')
            if not os.access(compiled, os.R_OK):
                src = '%s.gschema.xml' % self._GIO_SETTINGS
                lines = open(os.path.join(activity_root, src), 'r').readlines()
                open(os.path.join(path, src), 'w').writelines(lines)
                os.system('glib-compile-schemas %s' % path)
                os.remove(os.path.join(path, src))

            schemas_path = path
        else:
            schemas_path = activity_root

        # create a local Gio.Settings based on the compiled schema
        source = Gio.SettingsSchemaSource.new_from_directory(
            schemas_path, None, True)
        schema = source.lookup(self._GIO_SETTINGS, True)
        _settings = Gio.Settings.new_full(schema, None, None)
        return _settings
Esempio n. 5
0
 def _reskin_turtle(self, payload):
     if len(payload) > 0:
         [nick, [width, height, data]] = data_from_string(payload)
         if nick != self._tw.nick:
             if self._tw.running_sugar:
                 tmp_path = get_path(self._tw.activity, 'instance')
             else:
                 tmp_path = '/tmp'
             file_name = base64_to_image(data, tmp_path)
             pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                 file_name, width, height)
             self._tw.turtles.set_turtle(nick)
             self._tw.turtles.get_active_turtle().set_shapes([pixbuf])
 def _reskin_turtle(self, payload):
     if len(payload) > 0:
         [nick, [width, height, data]] = data_from_string(payload)
         if nick != self._tw.nick:
             if self._tw.running_sugar:
                 tmp_path = get_path(self._tw.activity, 'instance')
             else:
                 tmp_path = '/tmp'
             file_name = base64_to_image(data, tmp_path)
             pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(file_name,
                                                             width, height)
             self._tw.turtles.set_turtle(nick)
             self._tw.turtles.get_active_turtle().set_shapes([pixbuf])
Esempio n. 7
0
 def _draw_pixbuf(self, payload):
     if len(payload) > 0:
         [nick, [a, b, x, y, w, h, width, height, data]] =\
             data_from_string(payload)
         if nick != self._tw.nick:
             if self._tw.running_sugar:
                 tmp_path = get_path(self._tw.activity, 'instance')
             else:
                 tmp_path = '/tmp'
             file_name = base64_to_image(data, tmp_path)
             pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                 file_name, width, height)
             pos = self._tw.turtles.turtle_to_screen_coordinates((x, y))
             self._tw.turtles.get_active_turtle().draw_pixbuf(
                 pixbuf, a, b, pos[0], pos[1], w, h, file_name, False)
 def _draw_pixbuf(self, payload):
     if len(payload) > 0:
         [nick, [a, b, x, y, w, h, width, height, data]] =\
             data_from_string(payload)
         if nick != self._tw.nick:
             if self._tw.running_sugar:
                 tmp_path = get_path(self._tw.activity, 'instance')
             else:
                 tmp_path = '/tmp'
             file_name = base64_to_image(data, tmp_path)
             pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(file_name,
                                                             width, height)
             pos = self._tw.turtles.turtle_to_screen_coordinates((x, y))
             self._tw.turtles.get_active_turtle().draw_pixbuf(
                 pixbuf, a, b, pos[0], pos[1], w, h, file_name, False)
 def _draw_pixbuf(self, payload):
     if len(payload) > 0:
         [nick, [a, b, x, y, w, h, width, height, data]] =\
             data_from_string(payload)
         if nick != self._tw.nick:
             if self._tw.running_sugar:
                 tmp_path = get_path(self._tw.activity, 'instance')
             else:
                 tmp_path = '/tmp'
             file_name = base64_to_image(data, tmp_path)
             pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(file_name,
                                                           width, height)
             x, y = self._tw.canvas.turtle_to_screen_coordinates(x, y)
             self._tw.canvas.draw_pixbuf(pixbuf, a, b, x, y, w, h,
                                         file_name, False)
Esempio n. 10
0
        def __init__(self, tw):
            ''' Set up the stream. We save to a raw .wav file and then
            convert the sound to .ogg for saving. '''
            datapath = get_path(tw.parent, 'instance')
            self.capture_file = os.path.join(datapath, 'output.wav')
            self.save_file = os.path.join(datapath, 'output.ogg')
            self._eos_cb = None

            self._can_limit_framerate = False
            self._recording = False

            self._audio_transcode_handler = None
            self._transcode_id = None

            self._pipeline = gst.Pipeline("Record")
            self._create_audiobin()
            self._pipeline.add(self._audiobin)

            bus = self._pipeline.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_message_handler)
Esempio n. 11
0
        def __init__(self, tw):
            ''' Set up the stream. We save to a raw .wav file and then
            convert the sound to .ogg for saving. '''
            datapath = get_path(tw.parent, 'instance')
            self.capture_file = os.path.join(datapath, 'output.wav')
            self.save_file = os.path.join(datapath, 'output.ogg')
            self._eos_cb = None

            self._can_limit_framerate = False
            self._recording = False

            self._audio_transcode_handler = None
            self._transcode_id = None

            self._pipeline = gst.Pipeline("Record")
            self._create_audiobin()
            self._pipeline.add(self._audiobin)

            bus = self._pipeline.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_message_handler)
    def _get_local_settings(self, activity_root):
        """ return an activity-specific Gio.Settings
        """
        # create schemas directory if missing
        path = os.path.join(get_path(None, 'data'), 'schemas')
        if not os.access(path, os.F_OK):
            os.makedirs(path)

        # create compiled schema file if missing
        compiled = os.path.join(path, 'gschemas.compiled')
        if not os.access(compiled, os.R_OK):
            src = '%s.gschema.xml' % self._GIO_SETTINGS
            lines = open(os.path.join(activity_root, src), 'r').readlines()
            open(os.path.join(path, src), 'w').writelines(lines)
            os.system('glib-compile-schemas %s' % path)
            os.remove(os.path.join(path, src))

        # create a local Gio.Settings based on the compiled schema
        source = Gio.SettingsSchemaSource.new_from_directory(path, None, True)
        schema = source.lookup(self._GIO_SETTINGS, True)
        _settings = Gio.Settings.new_full(schema, None, None)
        return _settings
Esempio n. 13
0
def myblock(tw, sound):
    ''' Plays a sound file '''

    from TurtleArt.tautils import get_path
    import os
    import tempfile

    dirs = [os.path.join(
        os.environ['HOME'],
        'Activities/TamTamMini.activity/common/Resources/Sounds/'),
        os.path.join(
        os.environ['HOME'],
        'Activities/TamTamJam.activity/common/Resources/Sounds/'),
        os.path.join(
        os.environ['HOME'],
        'Activities/TamTamEdit.activity/common/Resources/Sounds/')]
    orchlines = []
    scorelines = []
    instrlist = []

    def finddir():
        print dirs
        for d in dirs:
            if os.path.isdir(d):
                return d
        return '.'

    def playSine(pitch=1000, amplitude=5000, duration=1, starttime=0,
                 pitch_envelope='default', amplitude_envelope='default'):
        """ Create a score to play a sine wave. """
        _play(pitch, amplitude, duration, starttime, pitch_envelope,
              amplitude_envelope, 1)

    def _play(pitch, amplitude, duration, starttime, pitch_envelope,
              amplitude_envelope, instrument):
        if pitch_envelope == 'default':
            pitenv = 99
        else:
            pitenv = pitch_envelope

        if amplitude_envelope == 'default':
            ampenv = 100
        else:
            ampenv = amplitude_envelope

        if 1 not in instrlist:
            orchlines.append("instr 1\n")
            orchlines.append("kpitenv oscil 1, 1/p3, p6\n")
            orchlines.append("aenv oscil 1, 1/p3, p7\n")
            orchlines.append("asig oscil p5*aenv, p4*kpitenv, p8\n")
            orchlines.append("out asig\n")
            orchlines.append("endin\n\n")
            instrlist.append(1)

        scorelines.append("i1 %s %s %s %s %s %s %s\n" %
                          (str(starttime), str(duration), str(pitch),
                           str(amplitude), str(pitenv), str(ampenv),
                           str(instrument)))

    def playWave(sound='horse', pitch=1, amplitude=1, loop=False, duration=1,
                 starttime=0, pitch_envelope='default',
                 amplitude_envelope='default'):
        """ Create a score to play a wave file. """

        if '/' in sound:
            fullname = sound
        else:
            fullname = finddir() + str(sound)

        if loop:
            lp = 1
        else:
            lp = 0

        if pitch_envelope == 'default':
            pitenv = 99
        else:
            pitenv = pitch_envelope

        if amplitude_envelope == 'default':
            ampenv = 100
        else:
            ampenv = amplitude_envelope

        if 9 not in instrlist:
            orchlines.append("instr 9\n")
            orchlines.append("kpitenv oscil 1, 1/p3, p8\n")
            orchlines.append("aenv oscil 1, 1/p3, p9\n")
            orchlines.append("asig diskin p4, p5*kpitenv, 0, p7\n")
            orchlines.append("out asig*p6*aenv\n")
            orchlines.append("endin\n\n")
            instrlist.append(9)

        scorelines.append('i9 %f %f "%s" %s %s %s %s %s\n' %
                          (float(starttime), float(duration), fullname,
                           str(pitch), str(amplitude), str(lp), str(pitenv),
                           str(ampenv)))

    def audioWrite(file):
        """ Compile a .csd file. """

        csd = open(file, "w")
        csd.write("<CsoundSynthesizer>\n\n")
        csd.write("<CsOptions>\n")
        csd.write("-+rtaudio=alsa -odevaudio -m0 -d -b256 -B512\n")
        csd.write("</CsOptions>\n\n")
        csd.write("<CsInstruments>\n\n")
        csd.write("sr=16000\n")
        csd.write("ksmps=50\n")
        csd.write("nchnls=1\n\n")
        # csd.write(orchlines.pop())
        for line in orchlines:
            csd.write(line)
        csd.write("\n</CsInstruments>\n\n")
        csd.write("<CsScore>\n\n")
        csd.write("f1 0 2048 10 1\n")
        csd.write("f2 0 2048 10 1 0 .33 0 .2 0 .143 0 .111\n")
        csd.write("f3 0 2048 10 1 .5 .33 .25 .2 .175 .143 .125 .111 .1\n")
        csd.write("f10 0 2048 10 1 0 0 .3 0 .2 0 0 .1\n")
        csd.write("f99 0 2048 7 1 2048 1\n")
        csd.write("f100 0 2048 7 0. 10 1. 1900 1. 132 0.\n")
        csd.write(scorelines.pop())
        csd.write("e\n")
        csd.write("\n</CsScore>\n")
        csd.write("\n</CsoundSynthesizer>")
        csd.close()

    if len(sound) == 1:
        if isinstance(sound[0], float) or isinstance(sound[0], int):
            playSine(pitch=float(sound[0]))
        else:  # Create a score from a prerecorded Wave file.
            playWave(sound[0])
    else:
        if len(sound) == 2:
            playSine(pitch=float(sound[0]), amplitude=float(sound[1]))
        else:
            playSine(pitch=float(sound[0]), amplitude=float(sound[1]),
                     duration=float(sound[2]))
    if tw.running_sugar:
        path = os.path.join(get_path(tw.activity, 'instance'), 'tmp.csd')
    else:
        path = os.path.join(tempfile.gettempdir(), 'tmp.csd')
    audioWrite(path)  # Create a csound file from the score.
    os.system('csound ' + path)  # Play the csound file.
Esempio n. 14
0
def myblock(tw, sound):
    ''' Plays a sound file '''

    from TurtleArt.tautils import get_path
    import os

    dirs = [os.path.join(
            os.environ['HOME'],
            'Activities/TamTamMini.activity/common/Resources/Sounds/')]
    orchlines = []
    scorelines = []
    instrlist = []

    def finddir():
        for d in dirs:
            if os.path.isdir(d):
                return d

    def playSine(pitch=1000, amplitude=5000, duration=1, starttime=0,
                 pitch_envelope='default', amplitude_envelope='default'):
        """ Create a score to play a sine wave. """
        _play(pitch, amplitude, duration, starttime, pitch_envelope,
              amplitude_envelope, 1)

    def _play(pitch, amplitude, duration, starttime, pitch_envelope,
              amplitude_envelope, instrument):
        if pitch_envelope == 'default':
            pitenv = 99
        else:
            pitenv = pitch_envelope

        if amplitude_envelope == 'default':
            ampenv = 100
        else:
            ampenv = amplitude_envelope

        if not 1 in instrlist:
            orchlines.append("instr 1\n")
            orchlines.append("kpitenv oscil 1, 1/p3, p6\n")
            orchlines.append("aenv oscil 1, 1/p3, p7\n")
            orchlines.append("asig oscil p5*aenv, p4*kpitenv, p8\n")
            orchlines.append("out asig\n")
            orchlines.append("endin\n\n")
            instrlist.append(1)

        scorelines.append("i1 %s %s %s %s %s %s %s\n" %
                          (str(starttime), str(duration), str(pitch),
                           str(amplitude), str(pitenv), str(ampenv),
                           str(instrument)))

    def playWave(sound='horse', pitch=1, amplitude=1, loop=False, duration=1,
                 starttime=0, pitch_envelope='default',
                 amplitude_envelope='default'):
        """ Create a score to play a wave file. """

        if '/' in sound:
            fullname = sound
        else:
            fullname = finddir() + str(sound)

        if loop:
            lp = 1
        else:
            lp = 0

        if pitch_envelope == 'default':
            pitenv = 99
        else:
            pitenv = pitch_envelope

        if amplitude_envelope == 'default':
            ampenv = 100
        else:
            ampenv = amplitude_envelope

        if not 9 in instrlist:
            orchlines.append("instr 9\n")
            orchlines.append("kpitenv oscil 1, 1/p3, p8\n")
            orchlines.append("aenv oscil 1, 1/p3, p9\n")
            orchlines.append("asig diskin p4, p5*kpitenv, 0, p7\n")
            orchlines.append("out asig*p6*aenv\n")
            orchlines.append("endin\n\n")
            instrlist.append(9)

        scorelines.append('i9 %f %f "%s" %s %s %s %s %s\n' %
                          (float(starttime), float(duration), fullname,
                           str(pitch), str(amplitude), str(lp), str(pitenv),
                           str(ampenv)))

    def audioWrite(file):
        """ Compile a .csd file. """

        csd = open(file, "w")
        csd.write("<CsoundSynthesizer>\n\n")
        csd.write("<CsOptions>\n")
        csd.write("-+rtaudio=alsa -odevaudio -m0 -d -b256 -B512\n")
        csd.write("</CsOptions>\n\n")
        csd.write("<CsInstruments>\n\n")
        csd.write("sr=16000\n")
        csd.write("ksmps=50\n")
        csd.write("nchnls=1\n\n")
        # csd.write(orchlines.pop())
        for line in orchlines:
            csd.write(line)
        csd.write("\n</CsInstruments>\n\n")
        csd.write("<CsScore>\n\n")
        csd.write("f1 0 2048 10 1\n")
        csd.write("f2 0 2048 10 1 0 .33 0 .2 0 .143 0 .111\n")
        csd.write("f3 0 2048 10 1 .5 .33 .25 .2 .175 .143 .125 .111 .1\n")
        csd.write("f10 0 2048 10 1 0 0 .3 0 .2 0 0 .1\n")
        csd.write("f99 0 2048 7 1 2048 1\n")
        csd.write("f100 0 2048 7 0. 10 1. 1900 1. 132 0.\n")
        csd.write(scorelines.pop())
        csd.write("e\n")
        csd.write("\n</CsScore>\n")
        csd.write("\n</CsoundSynthesizer>")
        csd.close()

    if type(sound) == float:
        playSine(pitch=float(sound))
    elif type(sound) == list:  # Create a score by computing a sinewave.
        if len(sound) == 1:
            playSine(pitch=float(sound[0]))
        elif len(sound) == 2:
            playSine(pitch=float(sound[0]), amplitude=float(sound[1]))
        else:
            playSine(pitch=float(sound[0]), amplitude=float(sound[1]),
                     duration=float(sound[2]))
    else:  # Create a score from a prerecorded Wave file.
        playWave(sound)
    if tw.running_sugar:
        path = os.path.join(get_path(tw.activity, 'instance'), 'tmp.csd')
    else:
        path = os.path.join('/tmp', 'tmp.csd')
    audioWrite(path)  # Create a csound file from the score.
    os.system('csound ' + path)  # Play the csound file.
Esempio n. 15
0
    def _prim_add_food(self, name, media, calories, protein, carbohydrates,
                       fiber, fat):
        # Add a new food item to the palette
        palette = make_palette('food',
                               colors=["#FFFFFF", "#A0A0A0"],
                               help_string=_('Palette of foods'))

        # We need to convert the media into two svgs, one for the
        # palette and one for the block.
        filepath = None
        if media is not None and os.path.exists(media.value):
            filepath = media.value
        elif self.tw.running_sugar:  # datastore object
            from sugar.datastore import datastore
            try:
                dsobject = datastore.get(media.value)
            except:
                debug_output("Couldn't find dsobject %s" % (media.value),
                             self.tw.running_sugar)
            if dsobject is not None:
                filepath = dsobject.file_path

        if filepath is None:
            self.tw.showlabel('nojournal', filepath)
            return

        pixbuf = None
        try:
            pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size(
                filepath, 40, 40)
            pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(filepath, 40, 40)
        except:
            self.tw.showlabel('nojournal', filepath)
            debug_output("Couldn't open food image %s" % (filepath),
                         self.tw.running_sugar)
            return

        def _draw_pixbuf(cr, pixbuf, x, y, w, h):
            # Build a gtk.gdk.CairoContext from a cairo.Context to access
            # the set_source_pixbuf attribute.
            cc = gtk.gdk.CairoContext(cr)
            cc.save()
            # center the rotation on the center of the image
            cc.translate(x + w / 2., y + h / 2.)
            cc.translate(-x - w / 2., -y - h / 2.)
            cc.set_source_pixbuf(pixbuf, x, y)
            cc.rectangle(x, y, w, h)
            cc.fill()
            cc.restore()

        if self.tw.running_sugar:
            path = os.path.join(get_path(self.tw.activity, 'instance'),
                                'output.svg')
        else:
            path = TMP_SVG_PATH

        svg_surface = cairo.SVGSurface(path, 40, 40)
        cr_svg = cairo.Context(svg_surface)
        _draw_pixbuf(cr_svg, pixbufsmall, 0, 0, 40, 40)
        cr_svg.show_page()
        svg_surface.flush()
        svg_surface.finish()
        destination = os.path.join(self.tw.path, 'plugins', 'food', 'images',
                                   name.encode('ascii') + 'small.svg')
        check_output(['mv', path, destination],
                     'problem moving %s to %s' % (path, destination))

        pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40)
        self.tw.media_shapes[name.encode('ascii') + 'small'] = pixbufsmall

        svg_surface = cairo.SVGSurface(path, 40, 40)
        cr_svg = cairo.Context(svg_surface)
        _draw_pixbuf(cr_svg, pixbufoff, 0, 0, 40, 40)
        cr_svg.show_page()
        svg_surface.flush()
        svg_surface.finish()
        destination = os.path.join(self.tw.path, 'plugins', 'food', 'images',
                                   name.encode('ascii') + 'off.svg')
        check_output(['mv', path, destination],
                     'problem moving %s to %s' % (path, destination))

        # Now that we have the images, we can make the new block
        self._make_polynominal(palette,
                               name.encode('ascii'),
                               name,
                               [calories, protein, carbohydrates, fiber, fat],
                               expand=(15, 15))

        pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40)
        self.tw.media_shapes[name.encode('ascii') + 'off'] = pixbufoff

        # Show the new block
        self.tw.show_toolbar_palette(palette_name_to_index('food'),
                                     regenerate=True)

        # Finally, we need to save new food item to a database so it
        # loads next time.
        food = name.encode('ascii')
        self.food_dictionary[food] = {}
        self.food_dictionary[food]['name'] = name
        self.food_dictionary[food]['calories'] = calories
        self.food_dictionary[food]['protein'] = protein
        self.food_dictionary[food]['carbohydrates'] = carbohydrates
        self.food_dictionary[food]['fiber'] = fiber
        self.food_dictionary[food]['fat'] = fat
        path = os.path.join(self.tw.path, 'plugins', 'food', 'food.db')
        data_to_file(self.food_dictionary, path)
        return