Ejemplo n.º 1
0
    def _create_journal_object(self):
        logging.debug('_create_journal_object')
        self.dl_jobject = datastore.create()
        filename = self._download.get_response().get_suggested_filename()
        self.dl_jobject.metadata['title'] = \
            _('Downloading %(filename)s from \n%(source)s.') % \
            {'filename': 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 = self._dest_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)
 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.'))
Ejemplo n.º 3
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))
Ejemplo n.º 4
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))
Ejemplo n.º 5
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)

    source_dir = os.path.join(user_activities_path, new_basename)
    config = bundlebuilder.Config(source_dir=source_dir,
                                  dist_dir=os.path.join(source_dir, 'dist'),
                                  dist_name='%s-1' % (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()
Ejemplo n.º 6
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.CornerType.TOP_LEFT)
Ejemplo n.º 7
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()
Ejemplo n.º 8
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 = 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
Ejemplo n.º 9
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
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
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'))
Ejemplo n.º 13
0
    def _save_as_image(self):
        ''' Grab the current canvas and save it to the Journal. '''
        if self._uid is None:
            self._uid = generate_uid()

        if self._game.get_mode() == 'array':
            target = self._uid
        else:
            target = '%s-%d' % (self._uid, self._game.current_image)

        file_path = os.path.join(self.datapath, 'story.png')
        png_surface = self._game.export()
        png_surface.write_to_png(file_path)

        dsobject = datastore.create()
        dsobject.metadata['title'] = '%s %s' % \
            (self.metadata['title'], _('image'))
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.metadata['tags'] = target
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        GObject.timeout_add(1000, self._remove_alert)
Ejemplo n.º 14
0
    def _save_recording(self):
        self.metadata['dirty'] = 'True'  # So we know that we've done work
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            _logger.debug('Saving recording to Journal...')
            if self._uid is None:
                self._uid = generate_uid()

            if self._game.get_mode() == 'array':
                target = self._uid
            else:
                target = '%s-%d' % (self._uid, self._game.current_image)

            dsobject = self._search_for_audio_note(target)
            if dsobject is None:
                dsobject = datastore.create()

            dsobject.metadata['title'] = \
                _('audio note for %s') % (self.metadata['title'])
            dsobject.metadata['icon-color'] = profile.get_color().to_string()
            dsobject.metadata['mime_type'] = 'audio/ogg'
            if self._uid is not None:
                dsobject.metadata['tags'] = target
            dsobject.set_file_path(os.path.join(self.datapath, 'output.ogg'))
            datastore.write(dsobject)
            dsobject.destroy()

            # Enable playback after record is finished
            self._game.set_play_icon_state(True)

            self.metadata['dirty'] = 'True'
            # Always save an image with the recording.
            # self._do_save_as_image_cb()
        else:
            _logger.debug('Nothing to save...')
        return
Ejemplo 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))
Ejemplo n.º 16
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()
Ejemplo n.º 17
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
Ejemplo n.º 18
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
Ejemplo n.º 19
0
def publish(activity, force=False):
    if not [i for i in book.custom.index if i['ready']]:
        alert = NotifyAlert(5)
        alert.props.title = _('Nothing to publish')
        alert.props.msg = _('Mark arcticles from "Custom" '
                            'panel and try again.')
        alert.connect('response', __alert_notify_response_cb, activity)
        activity.add_alert(alert)
        alert.show()
        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:
            alert = ConfirmationAlert()
            alert.props.title = _('Overwrite existed bundle?')
            alert.props.msg = _(
                'A bundle for current object was already created. '
                'Click "OK" to overwrite it.')
            alert.connect('response', __alert_response_cb, activity, True)
            activity.add_alert(alert)
            alert.show()
            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()

    alert = NotifyAlert()
    alert.props.title = _('Book published to your Journal')
    alert.props.msg = _('You can read the book in Browse or '
                        'access the .xol file from your Journal')
    alert.connect('response', __alert_notify_response_cb, activity)
    activity.add_alert(alert)
    alert.show()
Ejemplo n.º 20
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
Ejemplo n.º 21
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))
Ejemplo n.º 22
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
Ejemplo n.º 23
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.new('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_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
Ejemplo n.º 25
0
    def __save_data_cb(self, button):
        if type(self.get_canvas()) is not PollCanvas:
            return

        chart_params = {}
        axis = {
            'tickFont': 'Sans',
            'labelFont': 'Sans',
            'labelFontSize': 14,
            'labelColor': '#666666',
            'lineColor': '#b3b3b3',
            'tickColor': '#000000',
            'tickFontSize': 12
        }
        chart_params['font_options'] = {
            'titleFont': 'Sans',
            'titleFontSize': 12,
            'titleColor': '#000000',
            'axis': axis
        }

        title = _('Results from poll "%s"') % self._poll.title
        chart_params['title'] = title
        chart_params['x_label'] = ''
        chart_params['y_label'] = ''
        chart_params['current_chart.type'] = 1
        xo_color = profile.get_color()
        chart_params['chart_line_color'] = xo_color.get_stroke_color()
        chart_params['chart_color'] = xo_color.get_fill_color()
        """
        'chart_data': [
            ['hello', 200.0],
            ['mrch', 100.0]],
        """
        data = []

        for choice in range(self._poll.number_of_options):
            # data is used by the chart
            data.append([self._poll.options[choice], self._poll.data[choice]])

        chart_params['chart_data'] = data

        logging.debug('chart_data %s', chart_params)

        # save to the journal
        data_file = tempfile.NamedTemporaryFile(mode='w+b', suffix='.json')
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = title
        journal_entry.metadata['keep'] = '0'
        journal_entry.metadata['mime_type'] = 'application/x-chart-activity'
        journal_entry.metadata['activity'] = 'org.sugarlabs.SimpleGraph'

        json.dump(chart_params, data_file.file)
        data_file.file.close()
        journal_entry.file_path = data_file.name

        logging.debug('Create %s data file', data_file.name)
        datastore.write(journal_entry)
        self._show_journal_alert(_('Exported data'), _('Open in the Journal'),
                                 journal_entry.object_id)
Ejemplo n.º 26
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
Ejemplo n.º 27
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
Ejemplo n.º 28
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
Ejemplo n.º 29
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))
Ejemplo n.º 30
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)
Ejemplo n.º 31
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))
Ejemplo n.º 32
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'))
Ejemplo n.º 33
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)
    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
Ejemplo n.º 35
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()
Ejemplo n.º 36
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
Ejemplo n.º 37
0
def publish(activity, force=False):
    if not [i for i in book.custom.index if i['ready']]:
        alert = NotifyAlert(5)
        alert.props.title = _('Nothing to publish')
        alert.props.msg = _('Mark arcticles from "Custom" '
                            'panel and try again.')
        alert.connect('response', __alert_notify_response_cb, activity)
        activity.add_alert(alert)
        alert.show()
        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:
            alert = ConfirmationAlert()
            alert.props.title = _('Overwrite existed bundle?')
            alert.props.msg = _('A bundle for current object was already created. '
                                'Click "OK" to overwrite it.')
            alert.connect('response', __alert_response_cb, activity, True)
            activity.add_alert(alert)
            alert.show()
            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()

    alert = NotifyAlert()
    alert.props.title = _('Book published to your Journal')
    alert.props.msg = _('You can read the book in Browse or '
                        'access the .xol file from your Journal')
    alert.connect('response', __alert_notify_response_cb, activity)
    activity.add_alert(alert)
    alert.show()
Ejemplo n.º 38
0
def take_screenshot():
    tmp_dir = os.path.join(env.get_profile_path(), 'data')
    fd, file_path = tempfile.mkstemp(dir=tmp_dir)
    os.close(fd)

    window = Gdk.get_default_root_window()
    width, height = window.get_width(), window.get_height()

    screenshot_surface = Gdk.Window.create_similar_surface(
        window, cairo.CONTENT_COLOR, width, height)

    cr = cairo.Context(screenshot_surface)
    Gdk.cairo_set_source_window(cr, window, 0, 0)
    cr.paint()
    screenshot_surface.write_to_png(file_path)

    settings = Gio.Settings('org.sugarlabs.user')
    color = settings.get_string('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 is not None:
            content_title = activity.get_title()
            if content_title is 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_surface)
        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

    return title
Ejemplo n.º 39
0
def take_screenshot():
    tmp_dir = os.path.join(env.get_profile_path(), 'data')
    fd, file_path = tempfile.mkstemp(dir=tmp_dir)
    os.close(fd)

    window = Gdk.get_default_root_window()
    width, height = window.get_width(), window.get_height()

    screenshot_surface = Gdk.Window.create_similar_surface(
        window, cairo.CONTENT_COLOR, width, height)

    cr = cairo.Context(screenshot_surface)
    Gdk.cairo_set_source_window(cr, window, 0, 0)
    cr.paint()
    screenshot_surface.write_to_png(file_path)

    settings = Gio.Settings('org.sugarlabs.user')
    color = settings.get_string('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 is not None:
            content_title = activity.get_title()
            if content_title is 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_surface)
        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

    return title
Ejemplo n.º 40
0
	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()
    def _add_to_journal(self, title, file_path):
        jobject = datastore.create()

        jobject.metadata['title'] = title
        jobject.metadata['description'] = "Saved from web console"
        jobject.metadata['mime_type'] = "application/zip"
        jobject.file_path = file_path
        datastore.write(jobject)
        # Cleans the instance directory after every save
        self.__clean_fiddler_dir()
Ejemplo n.º 42
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 = Gdk.get_default_root_window()
    width, height = window.get_width(), window.get_height()

    window_cr = Gdk.cairo_create(window)
    window_surface = window_cr.get_target()
    screenshot_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    cr = cairo.Context(screenshot_surface)
    cr.set_source_surface(window_surface)
    cr.paint()
    screenshot_surface.write_to_png(file_path)

    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_surface)
        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
Ejemplo n.º 43
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 = Gdk.get_default_root_window()
    width, height = window.get_width(), window.get_height()

    window_cr = Gdk.cairo_create(window)
    window_surface = window_cr.get_target()
    screenshot_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    cr = cairo.Context(screenshot_surface)
    cr.set_source_surface(window_surface)
    cr.paint()
    screenshot_surface.write_to_png(file_path)

    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_surface)
        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
Ejemplo n.º 44
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)
Ejemplo n.º 45
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)
Ejemplo n.º 46
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()
Ejemplo n.º 47
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()
    def __save_as_ogg_cb(self, button):
        self._commit_all_changes()

        directory = tempfile.mkdtemp()
        output_path = os.path.join(directory, 'output.ogv')

        first_box = self.page.boxs[1]
        width = first_box.width
        height = first_box.height

        framerate = first_box.slideshow_duration
        if len(self.page.boxs) > 2:
            for box in self.page.boxs[1:]:
                framerate = gcd(framerate, box.slideshow_duration)
        framerate = int(framerate)

        i = 0
        for box in self.page.boxs[1:]:
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
            context = cairo.Context(surface)

            context.set_source_rgb(1.0, 1.0, 1.0)
            context.paint()
            box.draw_in_context(context)

            for __ in range(int(box.slideshow_duration / framerate)):
                path = os.path.join(directory, '{}.png'.format(i))
                surface.write_to_png(path)
                i += 1

        Gst.init(None)
        pipeline_string = VIDEO_PIPELINE.format(
            os.path.join(directory, '%d.png'), framerate, output_path)
        pipeline = Gst.parse_launch(pipeline_string)

        pipeline.set_state(Gst.State.PLAYING)
        pipeline.get_bus().timed_pop_filtered(
            Gst.CLOCK_TIME_NONE, Gst.MessageType.ERROR | Gst.MessageType.EOS)
        pipeline.set_state(Gst.State.NULL)

        jobject = datastore.create()
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = 'video/ogg'
        jobject.metadata['title'] = \
            _('{} as a movie').format(self.metadata['title'])
        jobject.file_path = output_path

        datastore.write(jobject, transfer_ownership=True)
        self._object_id = jobject.object_id

        self._show_journal_alert(_('Success'),
                                 _('A movie was saved in the Journal'))
        shutil.rmtree(directory)
Ejemplo n.º 49
0
    def __save_as_ogg_cb(self, button):
        self._commit_all_changes()

        directory = tempfile.mkdtemp()
        output_path = os.path.join(directory, 'output.ogv')

        first_box = self.page.boxs[1]
        width = first_box.width
        height = first_box.height

        framerate = first_box.slideshow_duration
        if len(self.page.boxs) > 2:
            for box in self.page.boxs[1:]:
                framerate = gcd(framerate, box.slideshow_duration)
        framerate = int(framerate)

        i = 0
        for box in self.page.boxs[1:]:
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
            context = cairo.Context(surface)

            context.set_source_rgb(1.0, 1.0, 1.0)
            context.paint()
            box.draw_in_context(context)

            for __ in range(int(box.slideshow_duration / framerate)):
                path = os.path.join(directory, '{}.png'.format(i))
                surface.write_to_png(path)
                i += 1

        Gst.init(None)
        pipeline_string = VIDEO_PIPELINE.format(
            os.path.join(directory, '%d.png'), framerate, output_path)
        pipeline = Gst.parse_launch(pipeline_string)

        pipeline.set_state(Gst.State.PLAYING)
        pipeline.get_bus().timed_pop_filtered(
            Gst.CLOCK_TIME_NONE, Gst.MessageType.ERROR | Gst.MessageType.EOS)
        pipeline.set_state(Gst.State.NULL)

        jobject = datastore.create()
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = 'video/ogg'
        jobject.metadata['title'] = \
            _('{} as a movie').format(self.metadata['title'])
        jobject.file_path = output_path

        datastore.write(jobject, transfer_ownership=True)
        self._object_id = jobject.object_id

        self._show_journal_alert(_('Success'),
                                 _('A movie was saved in the Journal'))
        shutil.rmtree(directory)
Ejemplo n.º 50
0
    def _export_json_cb(self, button):
        jobject = datastore.create()
        jobject.metadata["title"] = _("Physics export")
        jobject.metadata["mime_type"] = "text/plain"

        tmp_dir = os.path.join(self.get_activity_root(), "instance")
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        self.game.world.json_save(file_path)

        jobject.set_file_path(file_path)
        datastore.write(jobject)
Ejemplo n.º 51
0
    def _export_json_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = _('Physics export')
        jobject.metadata['mime_type'] = 'text/plain'

        tmp_dir = os.path.join(self.get_activity_root(), 'instance')
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        self.game.world.json_save(file_path)

        jobject.set_file_path(file_path)
        datastore.write(jobject)
Ejemplo n.º 52
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)
Ejemplo n.º 53
0
    def _save_to_journal(self, widget):
        if self._selected_image is None:
            return

        basename = os.path.basename(self._selected_image)
        dsobject = datastore.create()
        dsobject.metadata['title'] = basename[:-4]
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = MIME_TYPES[basename.split('.')[-1]]
        dsobject.set_file_path(self._selected_image)
        datastore.write(dsobject)
        dsobject.destroy()

        self.save_button.set_sensitive(False)
Ejemplo n.º 54
0
    def _save_to_journal(self, widget):
        if self._selected_image is None:
            return

        basename = os.path.basename(self._selected_image)
        dsobject = datastore.create()
        dsobject.metadata['title'] = basename[:-4]
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = MIME_TYPES[basename.split('.')[-1]]
        dsobject.set_file_path(self._selected_image)
        datastore.write(dsobject)
        dsobject.destroy()

        self.save_button.set_sensitive(False)
Ejemplo n.º 55
0
    def _export_json_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = _('Physics export')
        jobject.metadata['mime_type'] = 'text/plain'

        tmp_dir = os.path.join(self.get_activity_root(), 'instance')
        fd, file_path = tempfile.mkstemp(dir=tmp_dir)
        os.close(fd)

        data = self.game.full_pos_list
        jsonfile = open(file_path, 'wb')
        jsonfile.write(json.dumps(data))
        jsonfile.close()

        jobject.set_file_path(os.path.abspath(jsonfile.name))
        datastore.write(jobject)
Ejemplo n.º 56
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']
        # due to http://bugzilla.abisource.com/show_bug.cgi?id=13585
        if abi.get_version() != '3.0':
            fileObject.metadata['fulltext'] = abi.get_content('text/plain',
                                                              None)[: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
Ejemplo n.º 57
0
    def _save_as_pdf(self, widget):
        self._commit_all_changes()

        file_name = os.path.join(self.get_activity_root(), 'instance',
                                 'tmp-%i.pdf' % time.time())
        file_obj = open(file_name, 'w')

        page_width = self.page.boxs[1].width
        page_height = self.page.boxs[1].height

        surface = cairo.PDFSurface(file_obj, page_width, page_height)

        context = cairo.Context(surface)

        for box in self.page.boxs[0:]:
            context.save()
            if box.width != page_width:
                # for the first box, scale and center
                scale = float(page_width) / float(box.width)
                top_margin = (page_height - box.height) / 2
                context.translate(0, top_margin)
                context.scale(scale, scale)

            box.draw_in_context(context)
            context.show_page()
            context.restore()

        surface.finish()
        file_obj.close()

        jobject = datastore.create()
        jobject.metadata['icon-color'] = \
            profile.get_color().to_string()
        jobject.metadata['mime_type'] = 'application/pdf'

        jobject.metadata['title'] = \
            self.metadata['title'] + " as book"
        jobject.file_path = file_name

        # jobject.metadata['preview'] = \
        #    self._get_preview_image(file_name)

        datastore.write(jobject, transfer_ownership=True)
        self._object_id = jobject.object_id

        self._show_journal_alert(_('Success'),
                                 _('A PDF was created in the Journal'))