예제 #1
0
    def __export_png_cb(self, event):
        x, y, w, h, bitdepth = self._main_area.window.get_geometry()
        cmap = self._main_area.window.get_colormap()
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PNG)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'image/png'

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        pixmap = gtk.gdk.Pixmap(None, true_width, true_height, bitdepth)
        pixmap.set_colormap(cmap)
        self._main_area.export(pixmap.cairo_create(), true_width, true_height,
                               False)

        pb = gtk.gdk.Pixbuf.get_from_drawable(
            gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, true_width,
                           true_height),
            pixmap, gtk.gdk.colormap_get_system(), 0, 0, 0, 0, true_width,
            true_height)

        pb.save(filename, 'png')
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
예제 #2
0
    def __export_pdf_cb(self, event):
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PDF)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'application/pdf'

        # TODO: add text thoughts into fulltext metadata
        # fileObject.metadata['fulltext'] = ...

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        surface = cairo.PDFSurface(filename, true_width, true_height)
        cairo_context = cairo.Context(surface)
        context = pangocairo.CairoContext(cairo_context)
        self._main_area.export(context, true_width, true_height, False)
        surface.finish()
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
예제 #3
0
    def _file_part_receiver(self, target, filename, part, numparts,
                            bytes, title=None, color=None, sender=None):
        # ignore my own signal
        if sender == self._tube.get_unique_name():
            return
        
        if not (target == 'all' or target == self._tube.get_unique_name()):
            return
        
        # first chunk
        if part == 1:
            tmp_root = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance')
            temp_dir = tempfile.mkdtemp(dir=tmp_root)
            chmod(temp_dir, 0777)
            self.temp_file = join(temp_dir, 'game.zip')
            self.files[filename] = self.temp_file
            self.f = open(self.temp_file, 'a+b')
        
        self.f.write(bytes)
        
        percentage = int(float(part) / float(numparts) * 100.0)
        self.game.set_load_mode(_('Receiving game') + ': '
                                + str(percentage) + '% ' + _('done') + '.')

        # last chunk
        if part == numparts:
            self.f.close()   
            #file = self.files[filename]
            # Saves the zip in datastore
            gameObject = datastore.create()
            gameObject.metadata['title'] = title
            gameObject.metadata['mime_type'] = 'application/x-memorize-project'
            gameObject.metadata['icon-color'] = color
            gameObject.file_path = self.temp_file
            datastore.write(gameObject)
예제 #4
0
 def saveFile(self, _widget):
     fullPath= _widget.value;
     if self.script.journal:
         if type(fullPath.actualValue) == str:
             dsObject= datastore.create()
             print dir(dsObject.metadata)
             dsObject.metadata.get_dictionary().update(self.autogenerateMetadata())
             dsObject.metadata['title']= fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = dsObject
         else:
             dsObject= fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = fullPath.actualValue
         self.refreshPanel();
     else:
         fileName, fileExtension= os.path.splitext(fullPath);
         if fileExtension != information['filetype']:
             fullPath+= information['filetype'];
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"),
                                     [ _("This file already exists:"),
                                       os.path.basename(fullPath),
                                       _("Are you sure you want to overwrite it?")],
                                     okayFunction= self.script.saveFile, 
                                     arguments=fullPath);
         else:
             self.script.saveFile(fullPath);
예제 #5
0
파일: widgets.py 프로젝트: Daksh/devtutor
    def __activate_cb(self, menu_item, activity, abi, format):
        logger.debug("exporting file: %r" % format)

        exp_props = format["exp_props"]

        # special case HTML export to set the activity name as the HTML title
        if format["mime_type"] == "text/html":
            exp_props += " title:" + activity.metadata["title"] + ";"

        # create a new journal item
        fileObject = datastore.create()
        act_meta = activity.metadata
        fileObject.metadata["title"] = act_meta["title"] + " (" + format["jpostfix"] + ")"
        fileObject.metadata["title_set_by_user"] = act_meta["title_set_by_user"]
        fileObject.metadata["mime_type"] = format["mime_type"]
        fileObject.metadata["fulltext"] = abi.get_content(extension_or_mimetype=".txt")[:3000]

        fileObject.metadata["icon-color"] = act_meta["icon-color"]
        fileObject.metadata["activity"] = act_meta["activity"]
        fileObject.metadata["keep"] = act_meta["keep"]

        preview = activity.get_preview()
        if preview is not None:
            fileObject.metadata["preview"] = dbus.ByteArray(preview)

        fileObject.metadata["share-scope"] = act_meta["share-scope"]

        # write out the document contents in the requested format
        fileObject.file_path = os.path.join(activity.get_activity_root(), "instance", "%i" % time.time())
        abi.save("file://" + fileObject.file_path, format["mime_type"], exp_props)

        # store the journal item
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
예제 #6
0
    def _install_update(self, bundle_update, local_file_path):

        total = self._total_bundles_to_update
        current = total - len(self._bundles_to_update) - 0.5

        self.emit('progress', UpdateModel.ACTION_UPDATING,
                  bundle_update.bundle.get_name(),
                  current, total)

        # TODO: Should we first expand the zip async so we can provide progress
        # and only then copy to the journal?
        jobject = datastore.create()
        try:
            title = '%s-%s' % (bundle_update.bundle.get_name(),
                               bundle_update.version)
            jobject.metadata['title'] = title
            jobject.metadata['mime_type'] = ActivityBundle.MIME_TYPE
            jobject.file_path = local_file_path
            datastore.write(jobject, transfer_ownership=True)
        finally:
            jobject.destroy()

        self.emit('progress', UpdateModel.ACTION_UPDATING,
                  bundle_update.bundle.get_name(),
                  current + 0.5, total)

        if self._bundles_to_update:
            # do it in idle so the UI has a chance to refresh
            gobject.idle_add(self._download_next_update)
예제 #7
0
파일: frotz.py 프로젝트: sugarlabs/Frotz
 def open_url(self, url):
     """Ask the journal to open an URL for us."""
     from sugar import profile
     from shutil import rmtree
     from sugar.datastore import datastore
     from sugar.activity.activity import show_object_in_journal
     from tempfile import mkdtemp
     tmpfolder = mkdtemp('.tmp', 'url', os.path.join(self.get_activity_root(), 'instance'))
     tmpfilepath = os.path.join(tmpfolder, 'url')
     try:
         tmpfile = open(tmpfilepath, 'w')
         tmpfile.write(url)
         tmpfile.close()
         os.chmod(tmpfolder, 0755)
         os.chmod(tmpfilepath, 0755)
         jobject = datastore.create()
         metadata = {
             'title': url,
             'title_set_by_user': '******',
             'buddies': '',
             'preview': '',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/uri-list',
         }
         for k, v in metadata.items():
             jobject.metadata[k] = v # the dict.update method is missing =(
         jobject.file_path = tmpfilepath
         datastore.write(jobject)
         show_object_in_journal(jobject.object_id)
         jobject.destroy()
     finally:
         rmtree(tmpfilepath, ignore_errors=True) # clean up!
예제 #8
0
    def install(self):
        if os.environ.has_key('SUGAR_ACTIVITY_ROOT'):
            install_dir = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'], 'instance')
        else:
            install_dir = tempfile.gettempdir()
        uid = self.get_entry_id()
        bundle_dir = os.path.join(install_dir, uid)
        self._unzip(install_dir)
        try:
            metadata = self.get_metadata()
            jobject = datastore.create()
            try:
                for key, value in metadata.iteritems():
                    jobject.metadata[key] = value

                preview = self.get_preview()
                if preview != '':
                    jobject.metadata['preview'] = dbus.ByteArray(preview)
                jobject.metadata['uid'] = ''

                if jobject.metadata.has_key('mountpoint'):
                    del jobject.metadata['mountpoint']

                os.chmod(bundle_dir, RWXR_XR_X)

                if( os.path.exists( os.path.join(bundle_dir, uid) ) ):
                    jobject.file_path = os.path.join(bundle_dir, uid)
                    os.chmod(jobject.file_path, RW_R__R__)

                datastore.write(jobject)
            finally:
                jobject.destroy()
        finally:
            shutil.rmtree(bundle_dir, ignore_errors=True)
예제 #9
0
    def _save_dsobject(self,
                       filename,
                       content,
                       mime_type=None,
                       description=None):
        parent_dir = os.path.join(self.get_activity_root(), 'tmp')
        try:
            os.makedirs(parent_dir)
        except OSError:
            pass
        fd, tmp_filename = tempfile.mkstemp(dir=parent_dir,
                                            suffix=filename,
                                            prefix='tmp')
        try:
            os.write(fd, content)
        except:
            raise
        else:
            dsobject = datastore.create()
            dsobject.metadata['title'] = filename
            if mime_type is None:
                mime_type = mime.get_for_file(tmp_filename)
            dsobject.metadata['mime_type'] = mime_type
            if description is None:
                description = _('From: %s') % (self.metadata['title'], )
            dsobject.metadata['description'] = description
            dsobject.set_file_path(tmp_filename)
            datastore.write(dsobject)
        finally:
            os.close(fd)
            os.unlink(tmp_filename)

        return dsobject
예제 #10
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()
예제 #11
0
def generate_bundle(nick, new_basename):
    """Generate a new .xo bundle for the activity and copy it into the
    Journal.

    """
    new_activity_name = _customize_activity_info(
        nick, new_basename)

    user_activities_path = get_user_activities_path()
    if os.path.exists(os.path.join(user_activities_path, new_basename,
                                   'dist')):
        for path in glob.glob(os.path.join(user_activities_path, new_basename,
                                           'dist', '*')):
            os.remove(path)

    config = bundlebuilder.Config(source_dir=os.path.join(
            user_activities_path, new_basename),
            dist_name='%s-1.xo' % (new_activity_name))
    bundlebuilder.cmd_dist_xo(config, None)

    dsobject = datastore.create()
    dsobject.metadata['title'] = '%s-1.xo' % (new_activity_name)
    dsobject.metadata['mime_type'] = 'application/vnd.olpc-sugar'
    dsobject.set_file_path(os.path.join(
            user_activities_path, new_basename, 'dist',
            '%s-1.xo' % (new_activity_name)))
    datastore.write(dsobject)
    dsobject.destroy()
예제 #12
0
 def view_source(self):
     """Implement the 'view source' key by saving pippy_app.py to the
     datastore, and then telling the Journal to view it."""
     if self.__source_object_id is None:
         from sugar import profile
         from sugar.datastore import datastore
         from sugar.activity.activity \
              import get_bundle_name, get_bundle_path
         from gettext import gettext as _
         import os.path
         jobject = datastore.create()
         metadata = {
             'title': _('%s Source') % get_bundle_name(),
             'title_set_by_user': '******',
             'suggested_filename': 'pippy_app.py',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/x-python',
             }
         for k, v in metadata.items():
             jobject.metadata[k] = v  # dict.update method is missing =(
         jobject.file_path = os.path.join(get_bundle_path(), 'pippy_app.py')
         datastore.write(jobject)
         self.__source_object_id = jobject.object_id
         jobject.destroy()
     self.journal_show_object(self.__source_object_id)
예제 #13
0
    def __export_png_cb(self, event):
        x, y, w, h, bitdepth = self._main_area.window.get_geometry()
        cmap = self._main_area.window.get_colormap()
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PNG)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'image/png'

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        pixmap = gtk.gdk.Pixmap(None, true_width, true_height, bitdepth)
        pixmap.set_colormap(cmap)
        self._main_area.export(pixmap.cairo_create(), true_width, true_height,
                               False)

        pb = gtk.gdk.Pixbuf.get_from_drawable(
            gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8,
                           true_width, true_height), pixmap,
            gtk.gdk.colormap_get_system(), 0, 0, 0, 0, true_width, true_height)

        pb.save(filename, 'png')
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
 def create_journal_entry(self,  widget,  data=None):
     filename = self._filechooser.get_filename()
     journal_entry = datastore.create()
     journal_entry.metadata['title'] = self.make_new_filename(filename)
     journal_entry.metadata['title_set_by_user'] = '******'
     journal_entry.metadata['keep'] = '0'
     file_mimetype = mime.get_for_file(filename)
     if not file_mimetype is None:
         journal_entry.metadata['mime_type'] = file_mimetype
     journal_entry.metadata['buddies'] = ''
     if file_mimetype.startswith('image/')  and file_mimetype != 'image/vnd.djvu':
         preview = self.create_preview_metadata(filename)
     elif file_mimetype  == 'application/x-cbz':
         fname = self.extract_image(filename)
         preview = self.create_preview_metadata(fname)
         os.remove(fname)
     else:
         preview = ''
     if not preview  == '':
         journal_entry.metadata['preview'] =  dbus.ByteArray(preview)
     else:
         journal_entry.metadata['preview'] =  ''
         
     journal_entry.file_path = filename
     datastore.write(journal_entry)
     self.update_log_entries += '\n' + _('File %s copied to the Journal.') % filename
     self.alert(_('Success'),  _('%s added to Journal.') 
                 % self.make_new_filename(filename))
예제 #15
0
 def _show_via_journal(self, url):
     """Ask the journal to display a URL"""
     import os
     import time
     from sugar import profile
     from sugar.activity.activity import show_object_in_journal
     from sugar.datastore import datastore
     logger.debug('Create journal entry for URL: %s', url)
     jobject = datastore.create()
     metadata = {
         'title': "%s: %s" % (_('URL from Chat'), url),
         'title_set_by_user': '******',
         'icon-color': profile.get_color().to_string(),
         'mime_type': 'text/uri-list',
     }
     for k, v in metadata.items():
         jobject.metadata[k] = v
     file_path = os.path.join(get_activity_root(), 'instance',
                              '%i_' % time.time())
     open(file_path, 'w').write(url + '\r\n')
     os.chmod(file_path, 0755)
     jobject.set_file_path(file_path)
     datastore.write(jobject)
     show_object_in_journal(jobject.object_id)
     jobject.destroy()
     os.unlink(file_path)
예제 #16
0
    def __export_pdf_cb(self, event):
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PDF)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'application/pdf'

        # TODO: add text thoughts into fulltext metadata
        # fileObject.metadata['fulltext'] = ...

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        surface = cairo.PDFSurface(filename, true_width, true_height)
        cairo_context = cairo.Context(surface)
        context = pangocairo.CairoContext(cairo_context)
        self._main_area.export(context, true_width, true_height, False)
        surface.finish()
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
예제 #17
0
    def __init__(self, file_transfer):
        BaseTransferButton.__init__(self, file_transfer)

        self._ds_object = datastore.create()

        file_transfer.connect('notify::state', self.__notify_state_cb)
        file_transfer.connect('notify::transferred-bytes',
                              self.__notify_transferred_bytes_cb)

        icons = gio.content_type_get_icon(file_transfer.mime_type).props.names
        icons.append('application-octet-stream')
        for icon_name in icons:
            icon_name = 'transfer-from-%s' % icon_name
            file_name = get_icon_file_name(icon_name)
            if file_name is not None:
                self.props.icon_widget.props.icon_name = icon_name
                self.notif_icon.props.icon_name = icon_name
                break

        icon_color = file_transfer.buddy.props.color
        self.props.icon_widget.props.xo_color = icon_color
        self.notif_icon.props.xo_color = icon_color

        frame = jarabe.frame.get_view()
        frame.add_notification(self.notif_icon,
                               gtk.CORNER_TOP_LEFT)
예제 #18
0
 def exportFile(self, _widget, fancy, amount, dialog):
     fullPath = _widget.value
     dialog.close()
     if self.script.journal:
         dsObject = datastore.create()
         print dir(dsObject.metadata)
         dsObject.metadata.get_dictionary().update(
             self.autogenerateMetadata())
         dsObject.metadata['title'] = fullPath.actualValue
         if fancy == "Fancy":
             dsObject.metadata['mime_type'] = 'text/html'
         else:
             dsObject.metadata['mime_type'] = 'text/plain'
         fullPath = directories['instance'] + 'temp.bdw'
         self.script.export(
             (directories['instance'] + 'temp.bdw', fancy, amount))
         dsObject.set_file_path(fullPath)
         datastore.write(dsObject)
     else:
         fileName, fileExtension = os.path.splitext(fullPath)
         if fancy == "Fancy" and fileExtension != ".html":
             fullPath += ".html"
         elif fancy == "Plain" and fileExtension != ".txt":
             fullPath += ".txt"
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"), [
                 _("This file already exists:"),
                 os.path.basename(fullPath),
                 _("Are you sure you want to overwrite it?")
             ],
                                      okayFunction=self.script.export,
                                      arguments=(fullPath, fancy, amount))
         else:
             self.script.export((fullPath, fancy, amount))
예제 #19
0
    def __init__(self, handle):
    
        activity.Activity.__init__(self, handle)
        """ Create the official Sugar toolbox at the top of the screen"""
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        
        file_location = activity.get_activity_root() + \
                        "/data/reckonprimer_report.txt" 
        file_handle = open(file_location, 'w')
        file_handle.write("Report: " + profile.get_nick_name() + \
                          strftime(" %Y-%m-%d %H:%M:%S") + "\n")        
        file_handle.close()
        
        title = "Report: " + profile.get_nick_name() + \
                strftime(" %Y-%m-%d %H:%M:%S")
        mime = "text/plain"
        file_path = activity.get_activity_root() + \
                    "/data/reckonprimer_report.txt"
        favorite = "1"
        tags = "ReckonPrimer"
        
        journal_object = datastore.create()
        journal_object.metadata['title'] = title
        journal_object.metadata['mime_type'] = mime
        journal_object.file_path = file_path  
        journal_object.metadata['keep'] = favorite
        journal_object.metadata['tags'] = tags
        journal_object.metadata['icon-color'] = '#AFD600,#5B615C' 
        datastore.write( journal_object )
        journal_object.destroy()

        self.run_session()
예제 #20
0
 def saveFile(self, _widget):
     fullPath = _widget.value
     if self.script.journal:
         if type(fullPath.actualValue) == str:
             dsObject = datastore.create()
             print dir(dsObject.metadata)
             dsObject.metadata.get_dictionary().update(
                 self.autogenerateMetadata())
             dsObject.metadata['title'] = fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = dsObject
         else:
             dsObject = fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = fullPath.actualValue
         self.refreshPanel()
     else:
         fileName, fileExtension = os.path.splitext(fullPath)
         if fileExtension != information['filetype']:
             fullPath += information['filetype']
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"), [
                 _("This file already exists:"),
                 os.path.basename(fullPath),
                 _("Are you sure you want to overwrite it?")
             ],
                                      okayFunction=self.script.saveFile,
                                      arguments=fullPath)
         else:
             self.script.saveFile(fullPath)
예제 #21
0
 def exportFile(self, _widget, fancy, amount, dialog):
     fullPath= _widget.value;
     dialog.close()
     if self.script.journal:
         dsObject= datastore.create()
         print dir(dsObject.metadata)
         dsObject.metadata.get_dictionary().update(self.autogenerateMetadata())
         dsObject.metadata['title']= fullPath.actualValue
         if fancy == "Fancy":
             dsObject.metadata['mime_type'] = 'text/html'
         else:
             dsObject.metadata['mime_type'] = 'text/plain'
         fullPath = directories['instance'] + 'temp.bdw'
         self.script.export((directories['instance'] + 'temp.bdw', fancy, amount));
         dsObject.set_file_path(fullPath)
         datastore.write(dsObject)
     else:
         fileName, fileExtension= os.path.splitext(fullPath);
         if fancy == "Fancy" and fileExtension != ".html":
             fullPath+= ".html"
         elif fancy == "Plain" and fileExtension != ".txt":
             fullPath+= ".txt"
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"),
                                     [ _("This file already exists:"),
                                       os.path.basename(fullPath),
                                       _("Are you sure you want to overwrite it?")],
                                     okayFunction= self.script.export, 
                                     arguments=(fullPath,fancy, amount));
         else:
             self.script.export((fullPath, fancy, amount));
예제 #22
0
    def write_file(self, file_path):
        """ Write data to journal on quit """
        if hasattr(self, 'ji') and len(self.ji.temp_buffer) > 0:
            # Append new data to Journal entry
            writer = csv.writer(open(file_path, 'ab'))

            # Also output to a separate file as a workaround to Ticket 2127
            tmp_file_path = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance',
                                 'sensor_data' + '.csv')
            log.debug('saving sensor data to %s' % (tmp_file_path))
            writer2 = csv.writer(open(tmp_file_path, 'ab'))

            for datum in self.ji.temp_buffer:
                writer.writerow([datum])
                writer2.writerow([datum])

            # Set the mimetype so that the file can be read by other Activities
            self.metadata['mime_type'] = 'text/csv'

            jobject = datastore.create()
            jobject.metadata['title'] = _('Measure Log')
            jobject.metadata['keep'] = '0'
            jobject.metadata['buddies'] = ''
            jobject.metadata['preview'] = ''
            jobject.metadata['icon-color'] = self.icon_colors
            jobject.metadata['mime_type'] = 'text/csv'
            jobject.file_path = tmp_file_path
            datastore.write(jobject)
            jobject.destroy()
            del jobject
            remove(tmp_file_path)
예제 #23
0
    def install(self):
        if os.environ.has_key('SUGAR_ACTIVITY_ROOT'):
            install_dir = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'],
                                       'instance')
        else:
            install_dir = tempfile.gettempdir()
        uid = self.get_entry_id()
        bundle_dir = os.path.join(install_dir, uid)
        self._unzip(install_dir)
        try:
            metadata = self.get_metadata()
            jobject = datastore.create()
            try:
                for key, value in metadata.iteritems():
                    jobject.metadata[key] = value

                preview = self.get_preview()
                if preview != '':
                    jobject.metadata['preview'] = dbus.ByteArray(preview)
                jobject.metadata['uid'] = ''

                if jobject.metadata.has_key('mountpoint'):
                    del jobject.metadata['mountpoint']

                os.chmod(bundle_dir, RWXR_XR_X)

                if (os.path.exists(os.path.join(bundle_dir, uid))):
                    jobject.file_path = os.path.join(bundle_dir, uid)
                    os.chmod(jobject.file_path, RW_R__R__)

                datastore.write(jobject)
            finally:
                jobject.destroy()
        finally:
            shutil.rmtree(bundle_dir, ignore_errors=True)
예제 #24
0
 def _save_recording(self):
     if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
         _logger.debug('Saving recording to Journal...')
         obj_id = self._get_audio_obj_id()
         copyfile(os.path.join(self.datapath, 'output.ogg'),
                  os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         dsobject = self._search_for_audio_note(obj_id)
         if dsobject is None:
             dsobject = datastore.create()
         if dsobject is not None:
             _logger.debug(self.dsobjects[self.i].metadata['title'])
             dsobject.metadata['title'] = _('Audio recording by %s') % \
                 (self.metadata['title'])
             dsobject.metadata['icon-color'] = \
                 profile.get_color().to_string()
             dsobject.metadata['tags'] = obj_id
             dsobject.metadata['mime_type'] = 'audio/ogg'
             dsobject.set_file_path(
                 os.path.join(self.datapath, '%s.ogg' % (obj_id)))
             datastore.write(dsobject)
             dsobject.destroy()
         self._add_playback_button(
             profile.get_nick_name(), self.colors,
             os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         if hasattr(self, 'chattube') and self.chattube is not None:
             self._share_audio()
     else:
         _logger.debug('Nothing to save...')
     return
예제 #25
0
파일: frotz.py 프로젝트: srevinsaju/Frotz
 def open_url(self, url):
     """Ask the journal to open an URL for us."""
     from sugar import profile
     from shutil import rmtree
     from sugar.datastore import datastore
     from sugar.activity.activity import show_object_in_journal
     from tempfile import mkdtemp
     tmpfolder = mkdtemp('.tmp', 'url',
                         os.path.join(self.get_activity_root(), 'instance'))
     tmpfilepath = os.path.join(tmpfolder, 'url')
     try:
         tmpfile = open(tmpfilepath, 'w')
         tmpfile.write(url)
         tmpfile.close()
         os.chmod(tmpfolder, 0755)
         os.chmod(tmpfilepath, 0755)
         jobject = datastore.create()
         metadata = {
             'title': url,
             'title_set_by_user': '******',
             'buddies': '',
             'preview': '',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/uri-list',
         }
         for k, v in metadata.items():
             jobject.metadata[k] = v  # the dict.update method is missing =(
         jobject.file_path = tmpfilepath
         datastore.write(jobject)
         show_object_in_journal(jobject.object_id)
         jobject.destroy()
     finally:
         rmtree(tmpfilepath, ignore_errors=True)  # clean up!
예제 #26
0
 def get_new_dsobject(self):
     jobject = datastore.create()
     jobject.metadata['title'] = 'PyDebug'
     jobject.metadata['activity'] = 'org.laptop.PyDebug'
     jobject.metadata['keep'] = '1'
     jobject.metadata['preview'] = ''
     datastore.write(jobject)
     return jobject
예제 #27
0
def publish(activity, force=False):
    if not [i for i in book.custom.index if i['ready']]:
        activity.notify_alert(
            _('Nothing to publish'),
            _('Mark arcticles from "Custom" panel and try again.'))
        return

    title = activity.metadata['title']
    jobject = datastore.find({
        'activity_id': activity.get_id(),
        'activity': book.custom.uid
    })[0] or None

    logger.debug('publish: title=%s jobject=%s force=%s' \
            % (title, jobject and jobject[0].metadata['activity'], force))

    if jobject:
        if force:
            jobject = jobject[0]
        else:
            try:
                # check for 0.84 code
                from jarabe import config
            except:
                # 0.82 couldn't override .xol bundles
                activity.notify_alert(
                        _('Bundle exists'),
                        _('A bundle by "%s" name already exists. Please ' \
                        'click "Erase" in the Journal. You can click ' \
                        '"Publish" again afterwards.') % \
                        jobject[0].metadata['title'])
                return

            activity.confirmation_alert(
                    _('Overwrite existed bundle?'),
                    _('A bundle for current object was already created. ' \
                          'Click "OK" to overwrite it.'),
                    publish, activity, True)
            jobject[0].destroy()
            return
    else:
        jobject = datastore.create()
        jobject.metadata['activity_id'] = activity.get_id()
        jobject.metadata['activity'] = book.custom.uid
        jobject.metadata['mime_type'] = 'application/vnd.olpc-content'
        jobject.metadata['description'] = \
                'This is a bundle containing articles on %s.\n' \
                'To view these articles, open the \'Browse\' Activity.\n' \
                'Go to \'Books\', and select \'%s\'.' % (title, title)

    book.custom.sync_article()
    book.custom.revision += 1

    jobject.metadata['title'] = title
    _publish(title, jobject)
    jobject.destroy()

    book.custom.sync_index()
예제 #28
0
 def export(self, widget, data):
     jobject = datastore.create()
     jobject.metadata['title'] = self.metadata['title']
     mime_type = data[1]
     jobject.metadata['mime_type'] = mime_type
     file_path = tempfile.mktemp()
     self.canvas.exports[mime_type](file_path)
     jobject.set_file_path(file_path)
     datastore.write(jobject)
예제 #29
0
def store_data(entry_title, mime_type, file_path):
    file_dsobject = datastore.create()
    file_dsobject.metadata['TimeLapse'] = 'yes'
    file_dsobject.metadata['TimeLapsetitle'] = entry_title
    file_dsobject.metadata['title'] = entry_title
    file_dsobject.metadata['mime_type'] = mime_type
    file_dsobject.metadata['description'] = ''
    file_dsobject.set_file_path(file_path)
    datastore.write(file_dsobject)
    file_dsobject.destroy()
 def copiar_al_diario(self, widget):
     descripcion = utils.describe_archivo(utils.Archivos)
     mime = utils.describe_mime(utils.Archivos)
     if not 'directory' in descripcion:
         acopiar = datastore.create()
         acopiar.metadata['title'] = utils.Archivos
         acopiar.metadata['mime_type'] = mime
         acopiar.set_file_path(os.getcwd() + "/" + utils.Archivos)
         datastore.write(acopiar)
         acopiar.destroy()
예제 #31
0
def handle_key_press(key):
    tmp_dir = os.path.join(env.get_profile_path(), 'data')
    fd, file_path = tempfile.mkstemp(dir=tmp_dir)
    os.close(fd)

    window = gtk.gdk.get_default_root_window()
    width, height = window.get_size()
    x_orig, y_orig = window.get_origin()

    screenshot = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=False,
                                    bits_per_sample=8, width=width,
                                    height=height)
    screenshot.get_from_drawable(window, window.get_colormap(), x_orig,
                                    y_orig, 0, 0, width, height)
    screenshot.save(file_path, 'png')

    client = gconf.client_get_default()
    color = client.get_string('/desktop/sugar/user/color')

    content_title = None
    shell_model = shell.get_model()
    zoom_level = shell_model.zoom_level

    # TRANS: Nouns of what a screenshot contains
    if zoom_level == shell_model.ZOOM_MESH:
        content_title = _('Mesh')
    elif zoom_level == shell_model.ZOOM_GROUP:
        content_title = _('Group')
    elif zoom_level == shell_model.ZOOM_HOME:
        content_title = _('Home')
    elif zoom_level == shell_model.ZOOM_ACTIVITY:
        activity = shell_model.get_active_activity()
        if activity != None:
            content_title = activity.get_title()
            if content_title == None:
                content_title = _('Activity')

    if content_title is None:
        title = _('Screenshot')
    else:
        title = _('Screenshot of \"%s\"') % content_title

    jobject = datastore.create()
    try:
        jobject.metadata['title'] = title
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = _get_preview_data(screenshot)
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = 'image/png'
        jobject.file_path = file_path
        datastore.write(jobject, transfer_ownership=True)
    finally:
        jobject.destroy()
        del jobject
예제 #32
0
파일: ssb.py 프로젝트: lucian1900/Webified
 def show_in_journal(self):
     '''send the generated .xo bundle to the journal'''
     jobject = datastore.create()
     jobject.metadata['title'] = self.title
     jobject.metadata['mime_type'] = 'application/vnd.olpc-sugar'
     jobject.metadata['icon-color'] = profile.get_color().to_string()
     jobject.file_path = self.xo_path
     
     datastore.write(jobject)
     
     activity.show_object_in_journal(jobject.object_id) 
예제 #33
0
    def _save_as_image(self, widget):
        if self.current_chart:
            jobject = datastore.create()

            jobject.metadata['title'] = self.metadata["title"]
            jobject.metadata['mime_type'] = "image/png"

            self.current_chart.as_png(_CHART_FILE)
            jobject.set_file_path(_CHART_FILE)

            datastore.write(jobject)
예제 #34
0
    def _save_as_image(self, widget):
        if self.current_chart:
            jobject = datastore.create()

            jobject.metadata['title'] = self.metadata["title"]
            jobject.metadata['mime_type'] = "image/png"

            self.current_chart.as_png(_CHART_FILE)
            jobject.set_file_path(_CHART_FILE)

            datastore.write(jobject)
 def _save_recording_cb(self, button=None):
     savename = self._sounds[self._selected_sound].lower() + '.ogg'
     if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
         dsobject = datastore.create()
         dsobject.metadata['title'] = savename
         dsobject.metadata['icon-color'] = \
             profile.get_color().to_string()
         dsobject.metadata['mime_type'] = 'audio/ogg'
         dsobject.set_file_path(os.path.join(self.datapath, 'output.ogg'))
         datastore.write(dsobject)
         dsobject.destroy()
     return
예제 #36
0
    def save_image(self,image):
        journalobj = datastore.create()
        journalobj.metadata['title'] = _('Panorama')
        journalobj.metadata['mime_type'] = 'image/jpeg'

        file_path = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'], 'data', 'panorama.jpg')

        pygame.image.save(image,file_path)
        journalobj.set_file_path(file_path)
        datastore.write(journalobj)

        journalobj.destroy()
예제 #37
0
    def save_byte_array(self, path, title= None, color= None):
        if color == None:
            color = profile.get_color().to_string()
        _logger.debug('Save new game in datastore')

        # Saves the zip in datastore
        gameObject = datastore.create()
        gameObject.metadata['title'] = title
        gameObject.metadata['mime_type'] = 'application/x-memorize-project'
        gameObject.metadata['icon-color'] = color
        gameObject.file_path = path
        datastore.write(gameObject)
예제 #38
0
    def save_image(self,image):
        journalobj = datastore.create()
        journalobj.metadata['title'] = _('Pointillism')
        journalobj.metadata['mime_type'] = 'image/jpeg'

        file_path = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'], 'data', 'pointillism.jpg')

        pygame.image.save(image,file_path)
        journalobj.set_file_path(file_path)
        datastore.write(journalobj)

        journalobj.destroy()
예제 #39
0
    def __save_to_journal_clicked_cb(self, gobject):
        filename = self._images[self._pic_index]['name']
        imgpath = os.path.join(self._instance_directory, filename)

        journal_entry = datastore.create()
        journal_entry.metadata['title'] =\
                self._images[self._pic_index]['title']
        journal_entry.metadata['mime_type'] = 'image/jpeg'
        journal_entry.metadata['tags'] = 'XoScope'
        journal_entry.set_file_path(imgpath)
        datastore.write(journal_entry)
        journal_entry.destroy()
예제 #40
0
def save_document(sftp, subject, document, mimetype):
    path = os.path.join(MYFILES, document)
    sftp.get(os.path.join(subject, document), path)

    jobject = datastore.create()
    jobject.metadata['title'] = document
    jobject.metadata['icon-color'] = \
            profile.get_color().to_string()
    jobject.metadata['mime_type'] = mimetype
    jobject.file_path = path
    datastore.write(jobject)

    save_log(sftp, 'Saving document: %s' % (document))
예제 #41
0
    def write_file(self, file_path):
        ''' Write data to journal, if there is any data to write '''
        # Check to see if there are any new instruments to save
        if hasattr(self, 'new_instrument_toolbar'):
            for i, instrument in enumerate(
                    self.new_instrument_toolbar.new_instruments):
                log.debug('saving %s' % (instrument))
                notes = ''
                for i, note in enumerate(INSTRUMENT_DICT[instrument]):
                    notes += '%0.3f' % note
                    if i < len(INSTRUMENT_DICT[instrument]) - 1:
                        notes += ' '
                self.metadata['%s%s' % (PREFIX, instrument)] = notes

        # FIXME: Don't use ""s around data
        if hasattr(self, 'data_logger') and \
                self.new_recording and \
                len(self.data_logger.data_buffer) > 0:
            # Append new data to Journal entry
            fd = open(file_path, 'ab')
            writer = csv.writer(fd)
            # Also output to a separate file as a workaround to Ticket 2127
            # (the assumption being that this file will be opened by the user)
            tmp_data_file = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'],
                                         'instance', 'sensor_data' + '.csv')
            log.debug('saving sensor data to %s' % (tmp_data_file))
            if self._dsobject is None:  # first time, so create
                fd2 = open(tmp_data_file, 'wb')
            else:  # we've been here before, so append
                fd2 = open(tmp_data_file, 'ab')
            writer2 = csv.writer(fd2)
            # Pop data off start of buffer until it is empty
            for i in range(len(self.data_logger.data_buffer)):
                datum = self.data_logger.data_buffer.pop(0)
                writer.writerow([datum])
                writer2.writerow([datum])
            fd.close()
            fd2.close()

            # Set the proper mimetype
            self.metadata['mime_type'] = 'text/csv'

            if os.path.exists(tmp_data_file):
                if self._dsobject is None:
                    self._dsobject = datastore.create()
                    self._dsobject.metadata['title'] = _('Measure Log')
                    self._dsobject.metadata['icon-color'] = self.icon_colors
                    self._dsobject.metadata['mime_type'] = 'text/csv'
                self._dsobject.set_file_path(tmp_data_file)
                datastore.write(self._dsobject)
예제 #42
0
 def _copy(self, path):
     os.chdir('/tmp/')
     pp = self.nombre.get_text() + '.xo'
     file = open(pp, 'w')
     file.close()
     self.compress(path, pp)
     acopiar = datastore.create()
     acopiar.metadata['title'] = pp
     acopiar.metadata['mime_type'] = 'application/vnd.olpc-sugar'
     acopiar.set_file_path('/tmp/' + pp)
     datastore.write(acopiar)
     acopiar.destroy()
     shutil.rmtree(path)
     os.remove(pp)
예제 #43
0
    def _export_turtleblocks(self, alert):
        data = self.game.tu.current
        step = 75
        first = data[0] * step
        second = data[1] * step
        third = data[2] * step
        fourth = data[3] * step
        fifth = data[4] * step

        turtle_data = (
            '[[0, ["start", 219], 248, 92, [null, 1]],'
            + '[1, ["repeat", 189], 266, 138, [0, 2, 3, null]],'
            + '[2, ["number", 4], 322, 138, [1, null]],'
            + '[3, "forward", 284, 180, [1, 4, 5]],'
            + ('[4, ["number", %s], 348, 180, [3, null]],' % first)
            + '[5, "right", 284, 222, [3, 6, 7]],'
            + '[6, ["number", 90], 342, 222, [5, null]],'
            + '[7, "forward", 284, 264, [5, 8, 9]],'
            + ('[8, ["number", %s], 348, 264, [7, null]],' % second)
            + '[9, "right", 284, 306, [7, 10, 11]],'
            + '[10, ["number", 90], 342, 306, [9, null]],'
            + '[11, "forward", 284, 348, [9, 12, 13]],'
            + ('[12, ["number", %s], 348, 348, [11, null]],' % third)
            + '[13, "right", 284, 390, [11, 14, 15]],'
            + '[14, ["number", 90], 342, 390, [13, null]],'
            + '[15, "forward", 284, 432, [13, 16, 17]],'
            + ('[16, ["number", %s], 348, 432, [15, null]],' % fourth)
            + '[17, "right", 284, 474, [15, 18, 19]],'
            + '[18, ["number", 90], 342, 474, [17, null]],'
            + '[19, "forward", 284, 516, [17, 20, 21]],'
            + ('[20, ["number", %s], 348, 516, [19, null]],' % fifth)
            + '[21, "right", 284, 558, [19, 22, null]],'
            + '[22, ["number", 90], 342, 558, [21, null]]]'
        )

        file_path = os.path.join(self.datapath, "output.tb")
        with open(file_path, "w") as file:
            file.write(turtle_data)

        dsobject = datastore.create()
        dsobject.metadata["title"] = "%s %s" % (self.metadata["title"], _("TurtleBlocks"))
        dsobject.metadata["icon-color"] = profile.get_color().to_string()
        dsobject.metadata["mime_type"] = "application/x-turtle-art"
        dsobject.metadata["activity"] = "org.laptop.TurtleArtActivity"
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        gobject.timeout_add(1000, self._remove_alert, alert)
예제 #44
0
    def _export_turtleblocks(self, alert):
        data = self.game.tu.current
        step = 75
        first = data[0] * step
        second = data[1] * step
        third = data[2] * step
        fourth = data[3] * step
        fifth = data[4] * step

        turtle_data = '[[0, ["start", 219], 248, 92, [null, 1]],' +\
                      '[1, ["repeat", 189], 266, 138, [0, 2, 3, null]],' +\
                      '[2, ["number", 4], 322, 138, [1, null]],' +\
                      '[3, "forward", 284, 180, [1, 4, 5]],' +\
                      ('[4, ["number", %s], 348, 180, [3, null]],' % first) +\
                      '[5, "right", 284, 222, [3, 6, 7]],' +\
                      '[6, ["number", 90], 342, 222, [5, null]],' +\
                      '[7, "forward", 284, 264, [5, 8, 9]],' +\
                      ('[8, ["number", %s], 348, 264, [7, null]],' % second) +\
                      '[9, "right", 284, 306, [7, 10, 11]],' +\
                      '[10, ["number", 90], 342, 306, [9, null]],' +\
                      '[11, "forward", 284, 348, [9, 12, 13]],' +\
                      ('[12, ["number", %s], 348, 348, [11, null]],'% third)  +\
                      '[13, "right", 284, 390, [11, 14, 15]],' +\
                      '[14, ["number", 90], 342, 390, [13, null]],' +\
                      '[15, "forward", 284, 432, [13, 16, 17]],' +\
                      ('[16, ["number", %s], 348, 432, [15, null]],'% fourth)  +\
                      '[17, "right", 284, 474, [15, 18, 19]],' +\
                      '[18, ["number", 90], 342, 474, [17, null]],' +\
                      '[19, "forward", 284, 516, [17, 20, 21]],' +\
                      ('[20, ["number", %s], 348, 516, [19, null]],'% fifth)  +\
                      '[21, "right", 284, 558, [19, 22, null]],' +\
                      '[22, ["number", 90], 342, 558, [21, null]]]'

        file_path = os.path.join(self.datapath, 'output.tb')
        with open(file_path, "w") as file:
            file.write(turtle_data)

        dsobject = datastore.create()
        dsobject.metadata['title'] = '%s %s' % (self.metadata['title'],
                                                _('TurtleBlocks'))
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/x-turtle-art'
        dsobject.metadata['activity'] = 'org.laptop.TurtleArtActivity'
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        gobject.timeout_add(1000, self._remove_alert, alert)
예제 #45
0
def screen_shot(pixbuf):
    tmpdir = '/tmp'

    filename = 'fp%03d.png' % i
    filepath = os.path.join(tmpdir, filename)
    pixbuf.save(filepath, 'png')

    from sugar.datastore import datastore
    mediaObject = datastore.create()
    mediaObject.metadata['title'] = 'FlipSticks PNG'
    thumbData = _get_base64_pixbuf_data(pixbuf)
    mediaObject.metadata['preview'] = thumbData
    #medaiObject.metadata['icon-color'] = ''
    mediaObject.metadata['mime_type'] = 'image/png'
    mediaObject.file_path = filepath
    datastore.write(mediaObject)
예제 #46
0
    def _copy_to_journal(self):
        formats = self._cb_object.get_formats().keys()
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uris = mime.split_uri_list(format_.get_data())
            if len(uris) == 1 and uris[0].startswith('file://'):
                parsed_url = urlparse.urlparse(uris[0])
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urlparse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        client = gconf.client_get_default()
        color = client.get_string('/desktop/sugar/user/color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
    def on_render_completed(self, *args):
        """Rendering protozoon is completed.
        pre: self._export_surface is not None
        pre: self._thumb_surface is not None
        """
        ka_debug.info('export: on_render_completed: ' + str(args[0]))
        unique_id = 'kandidimage' + self._protozoon.get_unique_id()
        export_filename = unique_id + '.png'
        export_path = os.path.join(self._activity_root, 'instance',
                                   export_filename)

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

        # Write any metadata (here we specifically set the title of the file
        # and specify that this is a portable network graphics file).
        file_dsobject.metadata['title'] = 'Kandid Image ' + \
                                            self._protozoon.get_unique_id()[1:]
        file_dsobject.metadata['mime_type'] = 'image/png'

        #Write the actual file to the data directory of this activity's root.
        try:
            self._export_surface.write_to_png(export_path)
        except:
            ka_debug.err('export: failed exporting to [%s] [%s] [%s]' % \
                   (export_path, sys.exc_info()[0], sys.exc_info()[1]))

        #insert thumbnail image into metadata
        thumb_filename = unique_id + '.thumb.png'
        thumb_path = os.path.join(self._activity_root, 'instance',
                                  thumb_filename)
        try:
            self._thumb_surface.write_to_png(thumb_path)
            thumb_in = open(thumb_path, 'rb')
            file_dsobject.metadata['preview'] = \
                                             base64.b64encode(thumb_in.read())
            thumb_in.close()
            os.unlink(thumb_path)
        except:
            ka_debug.err('export: failed creating preview image [%s] [%s] [%s]' % \
                   (thumb_path, sys.exc_info()[0], sys.exc_info()[1]))

        #Set the file_path in the datastore.
        file_dsobject.set_file_path(export_path)
        datastore.write(file_dsobject)
        file_dsobject.destroy()
예제 #48
0
    def _copy_to_journal(self):
        formats = self._cb_object.get_formats().keys()
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uris = mime.split_uri_list(format_.get_data())
            if len(uris) == 1 and uris[0].startswith('file://'):
                parsed_url = urlparse.urlparse(uris[0])
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urlparse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        client = gconf.client_get_default()
        color = client.get_string('/desktop/sugar/user/color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
예제 #49
0
    def __keep_in_journal_cb(self, menu_item):
        mime_type = mime.get_from_file_name(self._document_path)
        if mime_type == 'application/octet-stream':
            mime_type = mime.get_for_file(self._document_path)

        self._jobject = datastore.create()
        title = _('Source') + ': ' + self._title
        self._jobject.metadata['title'] = title
        self._jobject.metadata['keep'] = '0'
        self._jobject.metadata['buddies'] = ''
        self._jobject.metadata['preview'] = ''
        self._jobject.metadata['icon-color'] = self._color
        self._jobject.metadata['mime_type'] = mime_type
        self._jobject.metadata['source'] = '1'
        self._jobject.file_path = self._document_path
        datastore.write(self._jobject, transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_save_error_cb)
예제 #50
0
    def __keep_in_journal_cb(self, menu_item):
        mime_type = mime.get_from_file_name(self._document_path)
        if mime_type == 'application/octet-stream':
            mime_type = mime.get_for_file(self._document_path)

        self._jobject = datastore.create()
        title = _('Source') + ': ' + self._title
        self._jobject.metadata['title'] = title
        self._jobject.metadata['keep'] = '0'
        self._jobject.metadata['buddies'] = ''
        self._jobject.metadata['preview'] = ''
        self._jobject.metadata['icon-color'] = self._color
        self._jobject.metadata['mime_type'] = mime_type
        self._jobject.metadata['source'] = '1'
        self._jobject.file_path = self._document_path
        datastore.write(self._jobject,
                        transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_save_error_cb)
예제 #51
0
 def _save_as_pdf_cb(self, button=None):
     ''' Export an PDF version of the slideshow to the Journal. '''
     _logger.debug('saving to PDF...')
     if 'description' in self.metadata:
         tmp_file = save_pdf(self, self._buddies,
                             description=self.metadata['description'])
     else:
         tmp_file = save_pdf(self, self._buddies)
     _logger.debug('copying PDF file to Journal...')
     dsobject = datastore.create()
     dsobject.metadata['title'] = profile.get_nick_name() + ' ' + \
                                  _('Bboard')
     dsobject.metadata['icon-color'] = profile.get_color().to_string()
     dsobject.metadata['mime_type'] = 'application/pdf'
     dsobject.set_file_path(tmp_file)
     dsobject.metadata['activity'] = 'org.laptop.sugar.ReadActivity'
     datastore.write(dsobject)
     dsobject.destroy()
     return
예제 #52
0
파일: box.py 프로젝트: Gopaal/2014-interns
 def _show_via_journal(self, url):
     """Ask the journal to display a URL"""
     logging.debug('Create journal entry for URL: %s', url)
     jobject = datastore.create()
     metadata = {
         'title': "%s: %s" % (_('URL from Chat'), url),
         'title_set_by_user': '******',
         'icon-color': profile.get_color().to_string(),
         'mime_type': 'text/uri-list',
         }
     for k, v in metadata.items():
         jobject.metadata[k] = v
     file_path = join(get_activity_root(), 'instance', '%i_' % time.time())
     open(file_path, 'w').write(url + '\r\n')
     os.chmod(file_path, 0755)
     jobject.set_file_path(file_path)
     datastore.write(jobject)
     show_object_in_journal(jobject.object_id)
     jobject.destroy()
     os.unlink(file_path)
예제 #53
0
    def _create_journal_object(self):
        self.dl_jobject = datastore.create()
        self.dl_jobject.metadata['title'] = _('Downloading %s from \n%s.') % \
                (self._get_file_name(), self._source.spec)

        self.dl_jobject.metadata['progress'] = '0'
        self.dl_jobject.metadata['keep'] = '0'
        self.dl_jobject.metadata['buddies'] = ''
        self.dl_jobject.metadata['preview'] = ''
        self.dl_jobject.metadata['icon-color'] = \
                profile.get_color().to_string()
        self.dl_jobject.metadata['mime_type'] = self._mime_type
        self.dl_jobject.file_path = ''
        datastore.write(self.dl_jobject)

        bus = dbus.SessionBus()
        obj = bus.get_object(DS_DBUS_SERVICE, DS_DBUS_PATH)
        datastore_dbus = dbus.Interface(obj, DS_DBUS_INTERFACE)
        self.datastore_deleted_handler = datastore_dbus.connect_to_signal(
            'Deleted', self.__datastore_deleted_cb,
            arg0=self.dl_jobject.object_id)
예제 #54
0
    def __export_txt_cb(self, event):

        # Create the new journal entry
        fileObject = datastore.create()
        fileObject.metadata['title'] = self.metadata['title'] + ' (TXT)'
        fileObject.metadata['title_set_by_user'] = \
            self.metadata['title_set_by_user']
        fileObject.metadata['mime_type'] = 'text/plain'

        fileObject.metadata['icon-color'] = self.metadata['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        text_file = open(filename, "w")

        # Convert the thoughts and links to a graph
        graph = Graph()

        for t in self._main_area.thoughts:
            graph.add_vertex(t.text)

        for l in self._main_area.links:
            graph.add_edge(l.parent.text, l.child.text)

        # Print tree function
        def printTree(temp, level, text_file):
            for x in graph.graphDict()[temp]:
                text_file.write('\n' + (level + 1) * '\t' + x)
                if(graph.graphDict()[x] != {}):
                    printTree(x, level + 1, text_file)

        # Add text to the file
        root = self._main_area.links[0].parent.text
        text_file.write(root)
        printTree(root, 0, text_file)
        text_file.close

        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
예제 #55
0
    def take_screenshot(self, capture_count=1):
        ''' Take a screenshot and save to the Journal '''
        tmp_file_path = os.path.join(
            os.environ['SUGAR_ACTIVITY_ROOT'], 'instance',
            'screen_capture_' + str(capture_count) + '.png')

        log.debug('saving screen capture to temp file %s' % (tmp_file_path))

        gtk.threads_enter()

        win = self.activity.wave.get_window()
        width, height = win.get_size()
        cr = win.cairo_create()
        surface = cr.get_target()
        img_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
        cr = cairo.Context(img_surface)
        cr.set_source_surface(surface)
        cr.paint()
        img_surface.write_to_png(tmp_file_path)

        gtk.threads_leave()
        if os.path.exists(tmp_file_path):
            dsobject = datastore.create()
            try:
                dsobject.metadata['title'] = '%s %d' % (_('Waveform'),
                                                       capture_count)
                dsobject.metadata['keep'] = '0'
                dsobject.metadata['buddies'] = ''
                dsobject.metadata['preview'] = ''
                dsobject.metadata['icon-color'] = self.activity.icon_colors
                dsobject.metadata['mime_type'] = 'image/png'
                dsobject.set_file_path(tmp_file_path)
                datastore.write(dsobject)
            finally:
                dsobject.destroy()
                del dsobject
            os.remove(tmp_file_path)
            return True
        return False
예제 #56
0
    def save_image(self, widget):
        """
        Save the curren phase to image and show alert
        """

        w, h = self.get_size()
        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                    int(w / 1.70), h - 55)

        shot = pixbuf.get_from_drawable(self.window, self.get_colormap(),
                    w - int(w / 1.70), 55, 0, 0, int(w / 1.70), h - 55)

        path = os.path.join(activity.get_activity_root(), "instance",
            "shot.png")

        shot.save(path, "png")
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = "%s %s" % \
            (self.metadata['title'], _("Image"))
        journal_entry.metadata['icon-color'] = profile.get_color().to_string()
        journal_entry.metadata['mime_type'] = "image/png"
        journal_entry.set_file_path(path)
        datastore.write(journal_entry)
        journal_entry.destroy()

        # Alert
        HAS_ALERT = False
        try:
            from sugar.graphics.alert import NotifyAlert
            HAS_ALERT = True
        except:
            pass

        if HAS_ALERT:
            alert = NotifyAlert(5)
            alert.props.title =_('Image saved')
            alert.props.msg = _('An image of the current phase of the moon has been saved to the Journal')
            alert.connect('response', lambda x, y: self.remove_alert(x))
            self.add_alert(alert)
예제 #57
0
    def _initialize_journal_object(self):
        title = _('%s Activity') % get_bundle_name()
        icon_color = get_color().to_string()

        jobject = datastore.create()
        jobject.metadata['title'] = title
        jobject.metadata['title_set_by_user'] = '******'
        jobject.metadata['activity'] = self.get_bundle_id()
        jobject.metadata['activity_id'] = self.get_id()
        jobject.metadata['keep'] = '0'
        jobject.metadata['preview'] = ''
        jobject.metadata['share-scope'] = SCOPE_PRIVATE
        jobject.metadata['icon-color'] = icon_color
        jobject.metadata['launch-times'] = str(int(time.time()))
        jobject.file_path = ''

        # FIXME: We should be able to get an ID synchronously from the DS,
        # then call async the actual create.
        # http://bugs.sugarlabs.org/ticket/2169
        datastore.write(jobject)

        return jobject