Esempio n. 1
0
    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if not "comments" in self._reflection.data:
            self._reflection.data["comments"] = []
        data = {
            "nick": profile.get_nick_name(),
            "color": self._reflection.activity.fg_color.get_html(),
            "comment": text,
        }
        self._reflection.data["comments"].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            self._reflection.activity.send_event(
                "%s|%s|%s|%s|%s"
                % (COMMENT_CMD, self._reflection.data["obj_id"], data["nick"], data["color"], data["comment"])
            )
        entry.set_text("")

        # Update journal entry
        dsobj = datastore.get(self._reflection.data["obj_id"])
        if "comments" in dsobj.metadata:
            data = json.loads(dsobj.metadata["comments"])
        else:
            data = []
        data.append({"from": profile.get_nick_name(), "message": text, "icon-color": profile.get_color().to_string()})
        dsobj.metadata["comments"] = json.dumps(data)
        datastore.write(
            dsobj,
            update_mtime=False,
            reply_handler=self.datastore_write_cb,
            error_handler=self.datastore_write_error_cb,
        )
Esempio n. 2
0
    def _process_tags(self, text_buffer, text):
        """ process tag data from textview """
        self._reflection.data["tags"] = []
        label = ""
        tags = text.split()
        for tag in tags:
            if len(label) > 0:
                label += ", "
            tag = tag.rstrip(",")
            tag = tag.rstrip(";")
            if tag[0] == "#":
                self._reflection.data["tags"].append(tag)
                label += tag
            else:
                self._reflection.data["tags"].append("#" + tag)
                label += "#" + tag
        text_buffer.set_text(label.replace("\12", ""))
        if self._reflection.activity.sharing:
            data = json.dumps(self._reflection.data["tags"])
            self._reflection.activity.send_event("%s|%s|%s" % (TAG_CMD, self._reflection.data["obj_id"], data))
        self._reflection.set_modification_time()

        # Update journal entry
        dsobj = datastore.get(self._reflection.data["obj_id"])
        logging.error("setting tags to %s" % label)
        dsobj.metadata["tags"] = label
        datastore.write(
            dsobj,
            update_mtime=False,
            reply_handler=self.datastore_write_cb,
            error_handler=self.datastore_write_error_cb,
        )
Esempio n. 3
0
 def insert_comment(self, obj_id, comment):
     for item in self._reflections:
         if item.obj_id == obj_id:
             item.graphics.add_new_comment(comment)
             item.graphics.notify_button.show()
             # Update journal entry
             if obj_id[0:4] == "obj-":
                 break
             try:
                 dsobj = datastore.get(obj_id)
             except Exception as e:
                 logging.error("Could not open %s: %e" % (obj_id, e))
                 break
             if "comments" in dsobj.metadata:
                 data = json.loads(dsobj.metadata["comments"])
             else:
                 data = []
             data.append(
                 {
                     "from": comment["nick"],
                     "message": comment["comment"],
                     "icon-color": "%s,%s" % (comment["color"], comment["color"]),
                 }
             )
             dsobj.metadata["comments"] = json.dumps(data)
             datastore.write(
                 dsobj,
                 update_mtime=False,
                 reply_handler=self.datastore_write_cb,
                 error_handler=self.datastore_write_error_cb,
             )
             break
Esempio n. 4
0
    def export_font(self):
        """
        Export the current font loaded in globals.FONT as a .otf file.

        The file will be saved in the activity data folder
        """
        # create the file path

        file_path =\
            os.path.join(self.get_activity_root(),
                         'data', '%s.otf' % self.get_title)
        # save the otf
        globals.FONT.export_binary(file_path)

        # create a journal entry
        jobject = datastore.create()
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = 'application/x-font-opentype'
        jobject.metadata['title'] = '%s.otf' % self.get_title
        jobject.file_path = file_path
        datastore.write(jobject, transfer_ownership=True)
        self._object_id = jobject.object_id

        success_title = 'Success'
        success_msg = 'A OTF Font file was created in the Journal'
        self._show_journal_alert(_(success_title), _(success_msg))
Esempio n. 5
0
 def create_journal_entry(self,  tempfile):
     journal_entry = datastore.create()
     journal_title = self.selected_title
     if self.selected_volume != '':
         journal_title +=  ' ' + _('Volume') + ' ' +  self.selected_volume
     if self.selected_author != '':
         journal_title = journal_title  + ', by ' + self.selected_author
     journal_entry.metadata['title'] = journal_title
     journal_entry.metadata['title_set_by_user'] = '******'
     journal_entry.metadata['keep'] = '0'
     if _NEW_TOOLBAR_SUPPORT:
         format = self.format_combo.props.value
     else:
         format = self._books_toolbar.format_combo.props.value
     if format == '.epub':
         journal_entry.metadata['mime_type'] = 'application/epub+zip'
     if format == '.djvu':
         journal_entry.metadata['mime_type'] = 'image/vnd.djvu'
     if format == '.pdf' or format == '_bw.pdf':
         journal_entry.metadata['mime_type'] = 'application/pdf'
     journal_entry.metadata['buddies'] = ''
     journal_entry.metadata['preview'] = ''
     journal_entry.metadata['icon-color'] = profile.get_color().to_string()
     textbuffer = self.textview.get_buffer()
     journal_entry.metadata['description'] = textbuffer.get_text(textbuffer.get_start_iter(),  textbuffer.get_end_iter(),  True)
     journal_entry.file_path = tempfile
     datastore.write(journal_entry)
     os.remove(tempfile)
     self.progressbar.hide()
     self._alert(_('Success'), self.selected_title + _(' added to Journal.'))
Esempio n. 6
0
    def __export_as_html_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = \
            _('{} as HTML').format(self.metadata['title'])
        jobject.metadata['mime_type'] = 'text/html'
        preview = self.get_preview()
        if preview is not None:
            jobject.metadata['preview'] = dbus.ByteArray(preview)

        # write out the document contents in the requested format
        path = os.path.join(self.get_activity_root(),
                            'instance', str(time.time()))
        with open(path, 'w') as f:
            f.write('''<html>
                         <head>
                           <title>{title}</title>
                         </head>

                         <body>
                           <h1>{title}</h1>
                    '''.format(title=jobject.metadata['title']))
            for item in self._main_list.all():
                f.write('<p>{}</p>'.format(
                    item[self._main_list.COLUMN_TEXT]))
            f.write('''
                         </body>
                       </html>
                    ''')
        jobject.file_path = path

        datastore.write(jobject, transfer_ownership=True)
        self._journal_alert(jobject.object_id, _('Success'), _('Your'
                            ' Bibliography was saved to the journal as HTML'))
        jobject.destroy()
        del jobject
Esempio n. 7
0
    def save(self):
        """
        Save the current font loaded in globals.FONT as a .ufo.zip file.

        The file will be saved in the activity data folder
        """
        ufo_path = self._create_font_instance()
        title = self.get_title()
        zip_path =\
            os.path.join(self.get_activity_root(),
                         'data', '%s_ufo.zip' % (title))
        if globals.FONT.save_zip(ufo_path, zip_path) is True:
            # create a journal entry
            jobject = datastore.create()

            # FIXME: This method of setting the metadata is not working
            # set the title to the output of self.get_title()
            jobject.metadata['icon-color'] = profile.get_color().to_string()
            jobject.metadata['mime_type'] = 'application/zip'
            jobject.metadata['title'] = title
            jobject.file_path = zip_path
            datastore.write(jobject, transfer_ownership=True)
            self._object_id = jobject.object_id

            # create an alert
            success_title = 'Success'
            success_msg = 'A UFO Font zip file was created in the Journal'
            self._show_journal_alert(_(success_title), _(success_msg))

        else:
            # create an alert
            failure_title = 'Error'
            failure_msg = 'Could not create the Zip file'
            self._show_journal_alert(_(failure_title), _(failure_msg))
Esempio n. 8
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
            GLib.idle_add(self._download_next_update)
Esempio n. 9
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()
Esempio n. 10
0
    def _photo_created_cb(self, fb_photo, fb_object_id, tmp_file):
        logging.debug("_photo_created_cb")

        if os.path.exists(tmp_file):
            os.unlink(tmp_file)

        metadata = self._get_metadata()

        comment = ''
        if 'title' in metadata:
            comment += '%s:' % str(metadata['title'])
        if 'description' in metadata:
            comment += str(metadata['description'])

        fb_photo.connect('comment-added', self._comment_added_cb)
        fb_photo.connect('comment-add-failed', self._comment_add_failed_cb)
        fb_photo.add_comment(comment)

        try:
            ds_object = datastore.get(metadata['uid'])
            ds_object.metadata['fb_object_id'] = fb_object_id
            datastore.write(ds_object, update_mtime=False)
        except Exception as ex:
            logging.debug("_photo_created_cb failed to write to datastore: " %
                          str(ex))
Esempio n. 11
0
def initialize_journal_object(title=None, bundle_id=None,
                              activity_id=None, project_metadata=None,
                              icon_color=None, invited=False):

    if not icon_color:
        settings = Gio.Settings('org.sugarlabs.user')
        icon_color = settings.get_string('color')

    if not activity_id:
        activity_id = activityfactory.create_activity_id()

    jobject = datastore.create()
    jobject.metadata['title'] = title
    jobject.metadata['title_set_by_user'] = '******'
    jobject.metadata['activity_id'] = activity_id
    jobject.metadata['keep'] = '0'
    jobject.metadata['preview'] = ''
    jobject.metadata['icon-color'] = icon_color
    jobject.file_path = ''

    if bundle_id == PROJECT_BUNDLE_ID:
        jobject.metadata['activity'] = PROJECT_BUNDLE_ID

    elif project_metadata is not None:
        jobject.metadata['mountpoints'] = ['/']
        jobject.metadata['activity'] = bundle_id
        jobject.metadata['share-scope'] = SCOPE_PRIVATE
        jobject.metadata['launch-times'] = str(int(time.time()))
        jobject.metadata['spent-times'] = '0'
        jobject.metadata['project_id'] = project_metadata['uid']
    # 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
    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
Esempio n. 13
0
    def _fb_comments_downloaded_cb(self, fb_photo, comments):
        logging.debug('_fb_comments_downloaded_cb')

        ds_object = datastore.get(self._metadata['uid'])
        if not COMMENTS in ds_object.metadata:
            ds_comments = []
        else:
            ds_comments = json.loads(ds_object.metadata[COMMENTS])
        if not COMMENT_IDS in ds_object.metadata:
            ds_comment_ids = []
        else:
            ds_comment_ids = json.loads(ds_object.metadata[COMMENT_IDS])
        new_comment = False
        for comment in comments:
            if comment['id'] not in ds_comment_ids:
                # TODO: get avatar icon and add it to icon_theme
                ds_comments.append({'from': comment['from'],
                                    'message': comment['message'],
                                    'icon': 'facebook-share'})
                ds_comment_ids.append(comment['id'])
                new_comment = True
        if new_comment:
            ds_object.metadata[COMMENTS] = json.dumps(ds_comments)
            ds_object.metadata[COMMENT_IDS] = json.dumps(ds_comment_ids)
            self.emit('comments-changed', ds_object.metadata[COMMENTS])

        datastore.write(ds_object, update_mtime=False)
Esempio n. 14
0
 def insert_comment(self, obj_id, comment):
     for item in self._reflections:
         if item.obj_id == obj_id:
             item.graphics.add_new_comment(comment)
             item.graphics.notify_button.show()
             # Update journal entry
             if obj_id[0:4] == 'obj-':
                 break
             try:
                 dsobj = datastore.get(obj_id)
             except Exception as e:
                 logging.error('Could not open %s: %e' % (obj_id, e))
                 break
             if 'comments' in dsobj.metadata:
                 data = json.loads(dsobj.metadata['comments'])
             else:
                 data = []
             data.append({'from': comment['nick'],
                          'message': comment['comment'],
                          'icon-color': '%s,%s' % (
                              comment['color'], comment['color'])
                        })
             dsobj.metadata['comments'] = json.dumps(data)
             datastore.write(dsobj,
                             update_mtime=False,
                             reply_handler=self.datastore_write_cb,
                             error_handler=self.datastore_write_error_cb)
             break
Esempio n. 15
0
 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))
Esempio n. 16
0
    def _process_tags(self, text_buffer, text):
        ''' process tag data from textview '''
        self._reflection.data['tags'] = []
        label = ''
        tags = text.split()
        for tag in tags:
            if len(label) > 0:
                label += ', '
            tag = tag.rstrip(',')
            tag = tag.rstrip(';')
            if tag[0] == '#':
                self._reflection.data['tags'].append(tag)
                label += tag
            else:
                self._reflection.data['tags'].append('#' + tag)
                label += '#' + tag
        text_buffer.set_text(label.replace('\12', ''))
        if self._reflection.activity.sharing:
            data = json.dumps(self._reflection.data['tags'])
            self._reflection.activity.send_event(TAG_CMD,
                {"obj_id": self._refelection.data["ob_id"],
                 "reflection": data})
        self._reflection.set_modification_time()

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        logging.error('setting tags to %s' % label)
        dsobj.metadata['tags'] = label
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
Esempio n. 17
0
    def resize_button_press_event_cb(self, entry, event):
        jobject = self.selected_journal_entry
        filename = jobject.get_file_path()
        im = pygame.image.load(filename)
        image_width, image_height = im.get_size()
        resize_to_width = int(self.resize_width_entry.get_text())
        if (image_width < resize_to_width):
            self.alert(_('Error'),  _('Image cannot be made larger, only smaller.')) 
            return
        tempfile = os.path.join(self.get_activity_root(), 'instance',
                            'tmp%i' % time.time())
        try:
            scaled_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename, resize_to_width, ARBITRARY_LARGE_HEIGHT)
            scaled_pixbuf.save(tempfile, "jpeg", {"quality":"%d" % JPEG_QUALITY})
        except:
            print 'File could not be converted'
            return

        jobject.file_path = tempfile
        jobject.metadata['mime_type'] = 'image/jpeg'
        im = pygame.image.load(tempfile)
        image_width, image_height = im.get_size()
        self.dimension_label.set_text(str(image_width) + "x" + str(image_height))
        self.dimension_label.show()
        datastore.write(jobject, update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
        title = jobject.metadata.get('title', None)
        self.update_log_entries += '\n' + _('Entry %s resized.') % title
Esempio n. 18
0
    def update_entry(self):
        needs_update = False
        
        if self.selected_journal_entry is None:
            return

        object_id = self.selected_journal_entry.object_id
        jobject = datastore.get(object_id)
        
        old_title = jobject.metadata.get('title', None)
        if old_title != self.title_entry.props.text:
            jobject.metadata['title'] = self.title_entry.props.text
            jobject.metadata['title_set_by_user'] = '******'
            self.update_log_entries += '\n' + _('Entry title changed to %s') % self.title_entry.props.text
            needs_update = True

        old_tags = jobject.metadata.get('tags', None)
        new_tags = self.tags_textview.props.buffer.props.text
        if old_tags != new_tags:
            jobject.metadata['tags'] = new_tags
            self.update_log_entries += '\n' + _('Entry %s tags updated.') % self.title_entry.props.text
            needs_update = True

        old_description = jobject.metadata.get('description', None)
        new_description = self.description_textview.props.buffer.props.text
        if old_description != new_description:
            jobject.metadata['description'] = new_description
            self.update_log_entries += '\n' + _('Entry %s description updated.') % self.title_entry.props.text
            needs_update = True

        if needs_update:
            datastore.write(jobject, update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)
        self.btn_save.props.sensitive = False
Esempio n. 19
0
 def __notify_state_cb(self, file_transfer, pspec):
     if file_transfer.props.state == filetransfer.FT_STATE_OPEN:
         logging.debug("__notify_state_cb OPEN")
         self._ds_object.metadata["title"] = file_transfer.title
         self._ds_object.metadata["description"] = file_transfer.description
         self._ds_object.metadata["progress"] = "0"
         self._ds_object.metadata["keep"] = "0"
         self._ds_object.metadata["buddies"] = ""
         self._ds_object.metadata["preview"] = ""
         self._ds_object.metadata["icon-color"] = file_transfer.buddy.props.color.to_string()
         self._ds_object.metadata["mime_type"] = file_transfer.mime_type
     elif file_transfer.props.state == filetransfer.FT_STATE_COMPLETED:
         logging.debug("__notify_state_cb COMPLETED")
         self._ds_object.metadata["progress"] = "100"
         self._ds_object.file_path = file_transfer.destination_path
         datastore.write(
             self._ds_object,
             transfer_ownership=True,
             reply_handler=self.__reply_handler_cb,
             error_handler=self.__error_handler_cb,
         )
     elif file_transfer.props.state == filetransfer.FT_STATE_CANCELLED:
         logging.debug("__notify_state_cb CANCELLED")
         object_id = self._ds_object.object_id
         if object_id is not None:
             self._ds_object.destroy()
             datastore.delete(object_id)
             self._ds_object = None
Esempio n. 20
0
    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if not 'comments' in self._reflection.data:
            self._reflection.data['comments'] = []
        data = {'nick': profile.get_nick_name(),
                'color': self._reflection.activity.fg_color.get_html(),
                'comment': text}
        self._reflection.data['comments'].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            send_data = data.copy()
            send_data["obj_id"] = self._reflection.data["obj_id"]
            self._reflection.activity.send_event(COMMENT_CMD, send_data)

        entry.set_text('')

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        if 'comments' in dsobj.metadata:
            data = json.loads(dsobj.metadata['comments'])
        else:
            data = []
        data.append({'from': profile.get_nick_name(),
                     'message': text,
                     'icon-color': profile.get_color().to_string()})
        dsobj.metadata['comments'] = json.dumps(data)
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
    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 = Pango.create_context(cairo_context)
        self._main_area.export(context, true_width, true_height, False)
        surface.finish()
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
Esempio n. 22
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')

        window = self.activity.wave.get_window()
        width, height = window.get_width(), window.get_height()
        surface = Gdk.Window.create_similar_surface(window,
                                                    cairo.CONTENT_COLOR,
                                                    width, height)
        cr = cairo.Context(surface)
        Gdk.cairo_set_source_window(cr, window, 0, 0)
        cr.paint()
        surface.write_to_png(tmp_file_path)

        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'] = self._get_preview_data(surface)
                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
Esempio n. 23
0
    def save_as_pdf(self, widget):
        tmp_dir = os.path.join(self._activity.get_activity_root(), "tmp")
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        page = self._canvas.get_current_page()
        webview = self._canvas.get_children()[page].get_children()[0]

        operation = Gtk.PrintOperation.new()
        operation.set_export_filename(file_path)

        webview.get_main_frame().print_full(operation, Gtk.PrintOperationAction.EXPORT)

        client = GConf.Client.get_default()
        jobject = datastore.create()
        color = client.get_string("/desktop/sugar/user/color")
        try:
            jobject.metadata["title"] = _("Browse activity as PDF")
            jobject.metadata["icon-color"] = color
            jobject.metadata["mime_type"] = "application/pdf"
            jobject.file_path = file_path
            datastore.write(jobject)
        finally:
            self.__pdf_alert(jobject.object_id)
            jobject.destroy()
            del jobject
Esempio n. 24
0
 def __notify_state_cb(self, file_transfer, pspec):
     if file_transfer.props.state == filetransfer.FT_STATE_OPEN:
         logging.debug('__notify_state_cb OPEN')
         self._ds_object.metadata['title'] = file_transfer.title
         self._ds_object.metadata['description'] = file_transfer.description
         self._ds_object.metadata['progress'] = '0'
         self._ds_object.metadata['keep'] = '0'
         self._ds_object.metadata['buddies'] = ''
         self._ds_object.metadata['preview'] = ''
         self._ds_object.metadata['icon-color'] = \
             file_transfer.buddy.props.color.to_string()
         self._ds_object.metadata['mime_type'] = file_transfer.mime_type
     elif file_transfer.props.state == filetransfer.FT_STATE_COMPLETED:
         logging.debug('__notify_state_cb COMPLETED')
         self._ds_object.metadata['progress'] = '100'
         self._ds_object.file_path = file_transfer.destination_path
         datastore.write(self._ds_object, transfer_ownership=True,
                         reply_handler=self.__reply_handler_cb,
                         error_handler=self.__error_handler_cb)
     elif file_transfer.props.state == filetransfer.FT_STATE_CANCELLED:
         logging.debug('__notify_state_cb CANCELLED')
         object_id = self._ds_object.object_id
         if object_id is not None:
             self._ds_object.destroy()
             datastore.delete(object_id)
             self._ds_object = None
Esempio n. 25
0
    def save_bundle(self, btn):
        # create bundle
        builder = XOPackager(Builder(Config(self.activity_dir, '/tmp')))
        builder.package()
        logging.error('Packaging %s', builder.package_path)
        jobject = datastore.create()
        icon_color = profile.get_color().to_string()

        metadata = {
            'title': '%s-%s.xo' % (builder.config.bundle_name,
                                   builder.config.version),
            'title_set_by_user': '******',
            'suggested_filename': '%s-%s.xo' % (builder.config.bundle_name,
                                                builder.config.version),
            'icon-color': icon_color,
            'mime_type': 'application/vnd.olpc-sugar',
            'activity': '',
            'activity_id': '',
            'share-scope': activity.SCOPE_PRIVATE,
            'preview': '',
            'source': self.activity_dir, }

        for k, v in metadata.items():
            jobject.metadata[k] = v
        jobject.file_path = builder.package_path
        datastore.write(jobject)
        jobject.destroy()
        self._show_alert(_('The bundle has been saved in the journal.'),
                         _('Success'))
Esempio n. 26
0
    def __export_as_abiword_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = \
            _('{} as Write document').format(self.metadata['title'])
        jobject.metadata['mime_type'] = 'application/x-abiword'
        preview = self.get_preview()
        if preview is not None:
            jobject.metadata['preview'] = dbus.ByteArray(preview)

        path = os.path.join(self.get_activity_root(),
                            'instance', str(time.time()))
        with open(path, 'w') as f:
            f.write('<?xml version="1.0" encoding="UTF-8"?>\n<abiword>\n'
                    '<section>')
            entries = []
            for item in self._main_list.all():
                markup = item[self._main_list.COLUMN_TEXT]
                abiword = '<p><c>{}</c></p>'.format(markup) \
                    .replace('<b>', '<c props="font-weight:bold">') \
                    .replace('<i>', '<c props="font-style:italic;'
                             ' font-weight:normal">') \
                    .replace('</b>', '</c>').replace('</i>', '</c>')
                entries.append(abiword)
            f.write('\n<p><c></c></p>\n'.join(entries))
            f.write('</section>\n</abiword>')
        jobject.file_path = path

        datastore.write(jobject, transfer_ownership=True)
        self._journal_alert(jobject.object_id, _('Success'), _('Your'
                            ' Bibliography was saved to the journal as a Write'
                            ' document'))
        jobject.destroy()
        del jobject
Esempio n. 27
0
    def do_drag_data_get(self, path, selection):
        data = self.get_iter(path)
        mime_type = self.get_value(data, 13)
        fileid = self.get_value(data, 14)
        title = self.get_value(data, 15)
        data = self._account.download_file(fileid, self._display_alert)

        fd, file_path = tempfile.mkstemp(dir="/tmp/")
        os.close(fd)

        if data[0]:
            f = open(file_path, 'w')
            f.write(data[0])
            f.close()

        jobject = datastore.create()
        jobject.metadata['title'] = title
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = mime_type
        if data[1]:
            jobject.metadata['activity'] = data[1]

        if data[0]:
            jobject.file_path = file_path
        datastore.write(jobject)
        self._load_files()
        self._journal_button.set_active(True)
        self._listview.refresh()
Esempio n. 28
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 target != self._tube.get_unique_name() and target != 'all':
            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)
Esempio n. 29
0
    def _update_progress(self):
        if self._progress > self._last_update_progress:
            self._last_update_progress = self._progress
            self.dl_jobject.metadata['progress'] = str(self._progress)
            datastore.write(self.dl_jobject)

        self._progress_sid = None
        return False
Esempio n. 30
0
 def _status_updated_cb(self, status, data, tmp_file):
     if os.path.exists(tmp_file):
         os.unlink(tmp_file)
     try:
         ds_object = datastore.get(self._metadata['uid'])
         ds_object.metadata['twr_object_id'] = status._status_id
         datastore.write(ds_object, update_mtime=False)
     except Exception as e:
         logging.debug('_status_updated_cb failed to write: %s', str(e))
Esempio n. 31
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
Esempio n. 32
0
    def _copy_to_journal(self):
        formats = list(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':
            uri = format_.get_data()
            if uri.startswith('file://'):
                parsed_url = urllib.parse.urlparse(uri)
                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 = urllib.parse.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'] = ''
        settings = Gio.Settings('org.sugarlabs.user')
        color = settings.get_string('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
Esempio n. 33
0
    def _create_image(self, text):
        fd = open('/tmp/cloud_data.txt', 'w')
        data = json_dump({'repeat': self._repeat_tags,
                          'layout': self._layout,
                          'font': self._font_name,
                          'colors': self._color_scheme})
        fd.write(data)
        fd.close()
        fd = open('/tmp/cloud_text.txt', 'w')
        fd.write(text)
        fd.close()
        path = os.path.join('/tmp/cloud_large.png')
        try:
            subprocess.check_call(
                [os.path.join(activity.get_bundle_path(), 'wordcloud.py')])
        except subprocess.CalledProcessError as e:
            self.get_window().set_cursor(
                Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))
            alert = NotifyAlert(5)
            alert.props.title = _('WordCloud error')
            logging.error(e)
            logging.error(e.returncode)
            if e.returncode == 255:
                logging.error('STOP WORD ERROR')
                MESSAGE = _('All of your words are "stop words."'
                            ' Please try adding more words.')
            else:
                logging.error('MEMORY ERROR')
                MESSAGE = _('Oops. There was a problem. Please try again.')
            alert.props.msg = MESSAGE
            alert.connect('response', self._remove_alert_cb)
            self.add_alert(alert)
            return

        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))

        self._show_image(path)

        dsobject = datastore.create()
        dsobject.metadata['title'] = _('Word Cloud')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.set_file_path(path)
        datastore.write(dsobject)
        dsobject.destroy()
Esempio n. 34
0
    def __clicked_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('text/plain', None)[0][:3000]

        fileObject.metadata['icon-color'] = act_meta['icon-color']

        # don't set application if PDF because Write can't open PDF files
        if format['mime_type'] != 'application/pdf':
            fileObject.metadata['activity'] = act_meta['activity']

        fileObject.metadata['keep'] = act_meta.get('keep', '0')

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

        fileObject.metadata['share-scope'] = act_meta.get('share-scope',
                                                          SCOPE_PRIVATE)

        # 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
Esempio n. 35
0
 def _save_stats(self, stats, nick=_('NONE'), colors='#FFFFFF,#000000'):
     stats_path = os.path.join(activity.get_activity_root(), 'instance',
                               'journalstats')
     json.dump(stats, open(stats_path, 'w'))
     # Create a datastore object to go with these data
     dsobject = datastore.create()
     dsobject.metadata['title'] = '%s %s' % (nick, _('Journal Statistics'))
     dsobject.metadata['icon-color'] = colors
     dsobject.metadata['mime_type'] = 'text/csv'
     dsobject.set_file_path(stats_path)
     dsobject.metadata['activity'] = 'org.sugarlabs.ShareStats'
     datastore.write(dsobject)
     dsobject.destroy()
     self._notify_alert(title=_('Share Stats'),
                        msg='%s %s' %
                        (_('Received journal statistics from'), nick))
     icon = self._create_icon(colors)
     self._add_buddy(icon, nick)
Esempio n. 36
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)
Esempio n. 37
0
    def __save_to_journal_cb(self, widget):
        """Save the PDF in the Journal.

        Put the PDF title as the title, or if the PDF doesn't have
        one, use the filename instead.  Put the requested uri as the
        description.

        """
        jobject = datastore.create()

        jobject.metadata['title'] = self._browser.props.title
        jobject.metadata['description'] = _('From: %s') % self._requested_uri

        jobject.metadata['mime_type'] = "application/pdf"
        jobject.file_path = self._pdf_uri[len("file://"):]
        datastore.write(jobject)

        # display the new URI:
        self._browser.props.uri = self.__journal_id_to_uri(jobject.object_id)
Esempio n. 38
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 target != self._tube.get_unique_name() and target != 'all':
            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)
Esempio n. 39
0
 def view_source(self):
     """Implement the 'view source' key by saving show.py to the
     datastore, and then telling the Journal to view it."""
     if self.__source_object_id is None:
         jobject = datastore.create()
         metadata = {
             'title': _('%s Source') % get_bundle_name(),
             'title_set_by_user': '******',
             'suggested_filename': 'show.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(), 'show.py')
         datastore.write(jobject)
         self.__source_object_id = jobject.object_id
         jobject.destroy()
     self.journal_show_object(self.__source_object_id)
Esempio n. 40
0
    def create_object(self, file_path, metadata, preview_content):
        new_dsobject = datastore.create()
        #Set the file_path in the datastore.
        new_dsobject.set_file_path(file_path)

        for key in metadata.keys():
            new_dsobject.metadata[key] = metadata[key]

        if preview_content is not None and preview_content != '':
            new_dsobject.metadata['preview'] = \
                dbus.ByteArray(preview_content)
        datastore.write(new_dsobject)
        if self._shared_items == ['*']:
            # mark as favorite
            new_dsobject.metadata['keep'] = '1'
            self._update_temporary_files()
        else:
            self.append_to_shared_items(new_dsobject.object_id)
        return False
    def create_journal_entry(self, path):
        journal_entry = datastore.create()
        journal_title = self.selected_title
        if self.selected_author != '':
            journal_title = journal_title + ', by ' + self.selected_author
        journal_entry.metadata['title'] = journal_title
        journal_entry.metadata['title_set_by_user'] = '******'
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = \
                self.format_combo.props.value
        # Fix fake mime type for black&white pdfs
        if journal_entry.metadata['mime_type'] == _MIMETYPES['PDF BW']:
            journal_entry.metadata['mime_type'] = _MIMETYPES['PDF']

        journal_entry.metadata['buddies'] = ''
        journal_entry.metadata['icon-color'] = profile.get_color().to_string()
        textbuffer = self.textview.get_buffer()
        journal_entry.metadata['description'] = \
            textbuffer.get_text(textbuffer.get_start_iter(),
                                textbuffer.get_end_iter(), True)
        if self.exist_cover_image:
            image_buffer = self._get_preview_image_buffer()
            journal_entry.metadata['preview'] = dbus.ByteArray(image_buffer)
            image_buffer = self._get_cover_image_buffer()
            journal_entry.metadata['cover_image'] = \
                dbus.ByteArray(base64.b64encode(image_buffer))
        else:
            journal_entry.metadata['cover_image'] = ""

        journal_entry.metadata['tags'] = self.source
        journal_entry.metadata['source'] = self.source
        journal_entry.metadata['author'] = self.selected_author
        journal_entry.metadata['publisher'] = self.selected_publisher
        journal_entry.metadata['summary'] = self.selected_summary
        journal_entry.metadata['language'] = self.selected_language_code

        journal_entry.file_path = path
        datastore.write(journal_entry)
        os.remove(path)
        self.progress_hide()
        self._object_id = journal_entry.object_id
        self._show_journal_alert(_('Download completed'), self.selected_title)
Esempio n. 42
0
    def _title_focus_out_cb(self, widget, event):
        ''' process title text from textview '''
        bounds = widget.get_buffer().get_bounds()
        text = widget.get_buffer().get_text(bounds[0], bounds[1], True)
        self._reflection.data['title'] = text
        if self._reflection.activity.sharing:
            self._reflection.activity.send_event(
                TITLE_CMD, {
                    "obj_id": self._reflection.data["obj_id"],
                    "title": text
                })
        self._reflection.set_modification_time()

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        dsobj.metadata['title'] = text
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
Esempio n. 43
0
 def __open_on_journal(self, widget, url):
     '''Ask the journal to display a URL'''
     jobject = datastore.create()
     metadata = {
         'title': '%s: %s' % (_('URL from Speak'), 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)
Esempio n. 44
0
    def __handle_link_cb(self, widget, url_object):
        url = url_object.get_uri()
        logging.debug('Create journal entry for URL: %s', url)
        jobject = datastore.create()
        metadata = {
            'title': "%s: %s" % (_('URL from Read'), 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)
Esempio n. 45
0
    def save_source_jobject(self, activity_dir, file_path, filenames=None):
        if not activity_dir:
            raise NotImplementedError

        # fix up datastore object
        # FIXME: some of this is overkill,
        # legacy from when I created a new jobject each save
        jobject = self._jobject
        icon_color = profile.get_color().to_string()

        metadata = {
            'title': self.metadata['title'],
            'title_set_by_user': '******',
            # 'suggested_filename': '%s-%s.xo' % (builder.config.bundle_name,
            #                                    builder.config.version),
            'icon-color': icon_color,
            'mime_type': 'application/develop-session',
            'activity': self.get_bundle_id(),
            'activity_id': self.get_id(),
            'share-scope': activity.SCOPE_PRIVATE,
            'preview': '',
            'source': activity_dir,
        }

        for k, v in metadata.items():
            jobject.metadata[k] = v  # dict.update method is missing =(
        dev_session_data = {}

        if filenames:
            dev_session_data['open_filenames'] = filenames

        f = open(file_path, 'w')
        try:
            json.dump(dev_session_data, f)
        finally:
            f.close()
        jobject.file_path = file_path
        datastore.write(jobject)
        jobject.destroy()
        return jobject
Esempio n. 46
0
    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
Esempio n. 47
0
    def update_entry(self):
        needs_update = False

        if self.selected_journal_entry is None:
            return

        object_id = self.selected_journal_entry.object_id
        jobject = datastore.get(object_id)

        old_title = jobject.metadata.get('title', None)
        if old_title != self.title_entry.props.text:
            jobject.metadata['title'] = self.title_entry.props.text
            jobject.metadata['title_set_by_user'] = '******'
            self.update_log_entries += '\n' + _(
                'Entry title changed to %s') % self.title_entry.props.text
            needs_update = True

        old_tags = jobject.metadata.get('tags', None)
        new_tags = self.tags_textview.props.buffer.props.text
        if old_tags != new_tags:
            jobject.metadata['tags'] = new_tags
            self.update_log_entries += '\n' + _(
                'Entry %s tags updated.') % self.title_entry.props.text
            needs_update = True

        old_description = jobject.metadata.get('description', None)
        new_description = self.description_textview.props.buffer.props.text
        if old_description != new_description:
            jobject.metadata['description'] = new_description
            self.update_log_entries += '\n' + _(
                'Entry %s description updated.') % self.title_entry.props.text
            needs_update = True

        if needs_update:
            datastore.write(jobject,
                            update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)
        self.btn_save.props.sensitive = False
Esempio n. 48
0
def initialize_journal_object(title=None,
                              bundle_id=None,
                              activity_id=None,
                              project_metadata=None,
                              icon_color=None,
                              invited=False):

    if not icon_color:
        settings = Gio.Settings('org.sugarlabs.user')
        icon_color = settings.get_string('color')

    if not activity_id:
        activity_id = activityfactory.create_activity_id()

    jobject = datastore.create()
    jobject.metadata['title'] = title
    jobject.metadata['title_set_by_user'] = '******'
    jobject.metadata['activity_id'] = activity_id
    jobject.metadata['keep'] = '0'
    jobject.metadata['preview'] = ''
    jobject.metadata['icon-color'] = icon_color
    jobject.file_path = ''

    if bundle_id == PROJECT_BUNDLE_ID:
        jobject.metadata['activity'] = PROJECT_BUNDLE_ID

    elif project_metadata is not None:
        jobject.metadata['mountpoints'] = ['/']
        jobject.metadata['activity'] = bundle_id
        jobject.metadata['share-scope'] = SCOPE_PRIVATE
        jobject.metadata['launch-times'] = str(int(time.time()))
        jobject.metadata['spent-times'] = '0'
        jobject.metadata['project_id'] = project_metadata['uid']
    # 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
Esempio n. 49
0
    def save_bundle(self, btn):
        # create bundle
        builder = XOPackager(Builder(Config(self.activity_dir, '/tmp')))
        builder.package()
        logging.error('Packaging %s', builder.package_path)
        jobject = datastore.create()
        icon_color = profile.get_color().to_string()

        metadata = {
            'title':
            '%s-%s.xo' % (builder.config.bundle_name, builder.config.version),
            'title_set_by_user':
            '******',
            'suggested_filename':
            '%s-%s.xo' % (builder.config.bundle_name, builder.config.version),
            'icon-color':
            icon_color,
            'mime_type':
            'application/vnd.olpc-sugar',
            'activity':
            '',
            'activity_id':
            '',
            'share-scope':
            activity.SCOPE_PRIVATE,
            'preview':
            '',
            'source':
            self.activity_dir,
        }

        for k, v in metadata.items():
            jobject.metadata[k] = v
        jobject.file_path = builder.package_path
        datastore.write(jobject)
        jobject.destroy()
        self._show_alert(_('The bundle has been saved in the journal.'),
                         _('Success'))
Esempio n. 50
0
    def _initialize_journal_object(self):
        title = _('%s Activity') % get_bundle_name()
        client = GConf.Client.get_default()
        icon_color = client.get_string('/desktop/sugar/user/color')

        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
Esempio n. 51
0
    def __save_image_cb(self, widget):
        image_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = self.chart.title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'image/png'

        # generate the image
        self.chart.generate_image(image_file.file, 800, 600)
        image_file.file.close()
        journal_entry.file_path = image_file.name

        # generate the preview
        preview_str = io.BytesIO()
        self.chart.generate_image(preview_str, activity.PREVIEW_SIZE[0],
                                  activity.PREVIEW_SIZE[1])
        journal_entry.metadata['preview'] = dbus.ByteArray(
            preview_str.getvalue())

        logging.debug('Create %s image file', image_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(_('Chart created'), _('Open in the Journal'),
                                 journal_entry.object_id)
Esempio n. 52
0
    def _save_ogg_eos_cb(self, bus, message, pipe):
        bus.remove_signal_watch()
        pipe.set_state(Gst.State.NULL)

        title = '%s saved as audio' % self.metadata['title']

        jobject = datastore.create()
        jobject.metadata['title'] = title
        jobject.metadata['keep'] = '0'
        jobject.metadata['mime_type'] = 'audio/ogg'
        jobject.file_path = self._ogg_tempfile.name
        datastore.write(jobject)

        self._wav_tempfile.close()
        self._ogg_tempfile.close()

        alert = NotifyAlert(10)
        alert.props.title = _('Audio recorded')
        alert.props.msg = _('The audio file was saved in the Journal')
        alert.connect('response', self.__alert_response_cb)
        self.add_alert(alert)

        return False
Esempio n. 53
0
    def __save_image_cb(self, button):
        if type(self.get_canvas()) is not PollCanvas:
            return
        chart = self.get_canvas().chart
        image_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = \
            '"%s" results chart' % self._poll.title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'image/png'

        # generate the image
        preview_str = chart.save_image(image_file.file, 800, 600)
        image_file.file.close()
        journal_entry.file_path = image_file.name

        journal_entry.metadata['preview'] = dbus.ByteArray(
            preview_str.getvalue())

        logging.debug('Create %s image file', image_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(_('Chart created'), _('Open in the Journal'),
                                 journal_entry.object_id)
Esempio n. 54
0
    def _save_as_pdf(self):
        self.speak_text_cb()
        file_path = os.path.join(self.datapath, 'output.pdf')
        if 'description' in self.metadata:
            save_pdf(self,
                     file_path,
                     self._nick,
                     description=self.metadata['description'])
        else:
            save_pdf(self, file_path, self._nick)

        dsobject = datastore.create()
        dsobject.metadata['title'] = '%s %s' % \
            (self.metadata['title'], _('PDF'))
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/pdf'
        dsobject.metadata['activity'] = 'org.laptop.sugar3.ReadActivity'
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        GObject.timeout_add(1000, self._remove_alert)
Esempio n. 55
0
    def _on_send_button_clicked_cb(self, button):
        identifier = str(int(time.time()))
        filename = '%s.zip' % identifier
        filepath = os.path.join(activity.get_activity_root(), filename)
        success = True
        try:
            self._collector.write_logs(archive=filepath, logbytes=0)
        except:
            success = False

        self.popdown(True)

        if not success:
            title = _('Logs not captured')
            msg = _('The logs could not be captured.')

            notify = NotifyAlert()
            notify.props.title = title
            notify.props.msg = msg
            notify.connect('response', _notify_response_cb, self._activity)
            self._activity.add_alert(notify)

        jobject = datastore.create()
        metadata = {
            'title': _('log-%s') % filename,
            'title_set_by_user': '******',
            'suggested_filename': filename,
            'mime_type': 'application/zip',
        }
        for k, v in metadata.items():
            jobject.metadata[k] = v
        jobject.file_path = filepath
        datastore.write(jobject)
        self._last_log = jobject.object_id
        jobject.destroy()
        activity.show_object_in_journal(self._last_log)
        os.remove(filepath)
Esempio n. 56
0
    def write_file(self, file_path):

        def write_playlist_to_file(file_path):
            """Open the file at file_path and write the playlist.

            It is saved in audio/x-mpegurl format.

            """

            list_file = open(file_path, 'w')
            for uri in self.playlist_widget._items:
                list_file.write('#EXTINF:%s\n' % uri['title'])
                list_file.write('%s\n' % uri['path'])
            list_file.close()

        if not self.metadata['mime_type']:
            self.metadata['mime_type'] = 'audio/x-mpegurl'

        if self.metadata['mime_type'] == 'audio/x-mpegurl':
            write_playlist_to_file(file_path)

        else:
            if self._playlist_jobject is None:
                self._playlist_jobject = \
                    self.playlist_widget.create_playlist_jobject()

            # Add the playlist to the playlist jobject description.
            # This is only done if the activity was not started from a
            # playlist or from scratch:
            description = ''
            for uri in self.playlist_widget._items:
                description += '%s\n' % uri['title']
            self._playlist_jobject.metadata['description'] = description

            write_playlist_to_file(self._playlist_jobject.file_path)
            datastore.write(self._playlist_jobject)
Esempio n. 57
0
    def save_as_pdf(self, widget):
        tmp_dir = os.path.join(self._activity.get_activity_root(), 'tmp')
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        page = self._canvas.get_current_page()
        webview = self._canvas.get_children()[page].get_children()[0]

        operation = Gtk.PrintOperation.new()
        operation.set_export_filename(file_path)

        webview.get_main_frame().print_full(operation,
                                            Gtk.PrintOperationAction.EXPORT)

        jobject = datastore.create()
        try:
            jobject.metadata['title'] = _('Browse activity as PDF')
            jobject.metadata['mime_type'] = 'application/pdf'
            jobject.file_path = file_path
            datastore.write(jobject)
        finally:
            self.__pdf_alert(jobject.object_id)
            jobject.destroy()
            del jobject
Esempio n. 58
0
    def __export_as_html_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = \
            _('{} as HTML').format(self.metadata['title'])
        jobject.metadata['mime_type'] = 'text/html'
        preview = self.get_preview()
        if preview is not None:
            jobject.metadata['preview'] = dbus.ByteArray(preview)

        # write out the document contents in the requested format
        path = os.path.join(self.get_activity_root(), 'instance',
                            str(time.time()))
        with open(path, 'w') as f:
            f.write('''<html>
                         <head>
                           <title>{title}</title>
                         </head>

                         <body>
                           <h1>{title}</h1>
                    '''.format(title=jobject.metadata['title']))
            for item in self._main_list.all():
                f.write('<p>{}</p>'.format(item[self._main_list.COLUMN_TEXT]))
            f.write('''
                         </body>
                       </html>
                    ''')
        jobject.file_path = path

        datastore.write(jobject, transfer_ownership=True)
        self._journal_alert(
            jobject.object_id, _('Success'),
            _('Your'
              ' Bibliography was saved to the journal as HTML'))
        jobject.destroy()
        del jobject
    def _create_journal_object(self):
        self.dl_jobject = datastore.create()
        self.dl_jobject.metadata['title'] = \
            _('Downloading %(filename)s from \n%(source)s.') % \
            {'filename': self._download.get_suggested_filename(),
             'source': self._source}

        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.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)
Esempio n. 60
0
    def __download_finished_cb(self, download):
        if hasattr(self._activity, 'busy'):
            self._activity.unbusy()

        if self._progress_sid is not None:
            GObject.source_remove(self._progress_sid)

        if self.dl_jobject is None:
            return  # the "failed" signal was observed

        self.dl_jobject.metadata['title'] = self._suggested_filename
        self.dl_jobject.metadata['description'] = _('From: %s') \
            % self._source
        self.dl_jobject.metadata['progress'] = '100'
        self.dl_jobject.file_path = self._dest_path

        mime_type = Gio.content_type_guess(self._dest_path)[0]
        if mime_type != 'application/vnd.olpc-sugar':
            mime_type = download.get_response().get_mime_type()

        self.dl_jobject.metadata['mime_type'] = mime_type

        if mime_type in ('image/bmp', 'image/gif', 'image/jpeg', 'image/png',
                         'image/tiff'):
            preview = self._get_preview()
            if preview is not None:
                self.dl_jobject.metadata['preview'] = \
                    dbus.ByteArray(preview)

        datastore.write(self.dl_jobject,
                        transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_error_cb,
                        timeout=360)

        if self._start_alert is not None:
            self._activity.remove_alert(self._start_alert)
        self._stop_alert = Alert()
        self._stop_alert.props.title = _('Downloaded')
        self._stop_alert.props.msg = self._suggested_filename

        bundle = None
        if _HAS_BUNDLE_LAUNCHER:
            bundle = get_bundle(object_id=self._object_id)

        if bundle is not None:
            icon = Icon(file=bundle.get_icon())
            label = _('Open with %s') % bundle.get_name()
            response_id = Gtk.ResponseType.APPLY
        else:
            icon = Icon(icon_name='zoom-activity')
            label = _('Show in Journal')
            response_id = Gtk.ResponseType.ACCEPT

        self._stop_alert.add_button(response_id, label, icon)
        icon.show()

        ok_icon = Icon(icon_name='dialog-ok')
        self._stop_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
        ok_icon.show()

        self._activity.add_alert(self._stop_alert)
        self._stop_alert.connect('response', self.__stop_response_cb)
        self._stop_alert.show()