Exemplo n.º 1
0
    def _set_file_path(self, file_path):
        if file_path == self._file_path:
            return
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text('')
            return

        mime_type = mime.get_for_file(self._file_path)
        logging.debug('Detected mime type: %r' % mime_type)

        language_manager = gtksourceview2.language_manager_get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            logging.debug('Detected language: %r' % \
                    detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, 'r').read())
Exemplo n.º 2
0
    def _save_dsobject(self,
                       filename,
                       content,
                       mime_type=None,
                       description=None):
        parent_dir = os.path.join(self.get_activity_root(), 'tmp')
        try:
            os.makedirs(parent_dir)
        except OSError:
            pass
        fd, tmp_filename = tempfile.mkstemp(dir=parent_dir,
                                            suffix=filename,
                                            prefix='tmp')
        try:
            os.write(fd, content)
        except:
            raise
        else:
            dsobject = datastore.create()
            dsobject.metadata['title'] = filename
            if mime_type is None:
                mime_type = mime.get_for_file(tmp_filename)
            dsobject.metadata['mime_type'] = mime_type
            if description is None:
                description = _('From: %s') % (self.metadata['title'], )
            dsobject.metadata['description'] = description
            dsobject.set_file_path(tmp_filename)
            datastore.write(dsobject)
        finally:
            os.close(fd)
            os.unlink(tmp_filename)

        return dsobject
 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))
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
0
    def _select_hw_from_journal(self, widget):
        '''Abre un selector de objetos del diario'''
        chooser = ObjectChooser()
        response = chooser.run()

        if response == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            self._hw_path = str(jobject.get_file_path())
            self._notebook.set_current_page(-1)
            self._send.set_sensitive(True)
            self._hw_title.set_text(jobject.get_metadata()["title"])
            self._hw_mimetype = mime.get_for_file(self._hw_path)
Exemplo n.º 7
0
    def _copy_file(self, original_uri):
        uri = urlparse.urlparse(original_uri)
        path = uri.path  # pylint: disable=E1101
        directory_, file_name = os.path.split(path)

        root, ext = os.path.splitext(file_name)
        if not ext or ext == '.':
            mime_type = mime.get_for_file(path)
            ext = '.' + mime.get_primary_extension(mime_type)

        f_, new_file_path = tempfile.mkstemp(ext, root)
        del f_
        shutil.copyfile(path, new_file_path)
        os.chmod(new_file_path, 0644)

        return 'file://' + new_file_path
Exemplo n.º 8
0
    def onStateChange(self, web_progress, request, state_flags, status):
        if state_flags & interfaces.nsIWebProgressListener.STATE_START:
            self._create_journal_object()            
            self._object_id = self.dl_jobject.object_id
            
            alert = TimeoutAlert(9)
            alert.props.title = _('Download started')
            alert.props.msg = _('%s' % self._get_file_name()) 
            self._activity.add_alert(alert)
            alert.connect('response', self.__start_response_cb)
            alert.show()
            global _active_downloads
            _active_downloads.append(self)
            
        elif state_flags & interfaces.nsIWebProgressListener.STATE_STOP:
            if NS_FAILED(status): # download cancelled
                return

            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed') 
            self._stop_alert.props.msg = _('%s' % self._get_file_name()) 
            open_icon = Icon(icon_name='zoom-activity') 
            self._stop_alert.add_button(gtk.RESPONSE_APPLY, 
                                        _('Show in Journal'), open_icon) 
            open_icon.show() 
            ok_icon = Icon(icon_name='dialog-ok') 
            self._stop_alert.add_button(gtk.RESPONSE_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()

            self.dl_jobject.metadata['title'] = _('File %s from %s.') % \
                    (self._get_file_name(), self._source.spec)
            self.dl_jobject.metadata['progress'] = '100'
            self.dl_jobject.file_path = self._target_file.path

            if self._mime_type in ['application/octet-stream',
                                   'application/x-zip']:
                sniffed_mime_type = mime.get_for_file(self._target_file.path)
                self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

            datastore.write(self.dl_jobject,
                            transfer_ownership=True,
                            reply_handler=self._internal_save_cb,
                            error_handler=self._internal_save_error_cb,
                            timeout=360 * DBUS_PYTHON_TIMEOUT_UNITS_PER_SECOND)
Exemplo n.º 9
0
 def update_preview_cb(self, file_chooser, preview):
     filename = file_chooser.get_preview_filename()
     try:
         file_mimetype = mime.get_for_file(filename)
         if file_mimetype  == 'application/x-cbz' or file_mimetype == 'application/zip':
             fname = self.extract_image(filename)
             pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(fname, 
                 style.zoom(320), style.zoom(240))
             preview.set_from_pixbuf(pixbuf)
             have_preview = True
             os.remove(fname)
         else:
             have_preview = False
     except:
         have_preview = False
     file_chooser.set_preview_widget_active(have_preview)
     return
Exemplo n.º 10
0
 def update_preview_cb(self, file_chooser, preview):
     filename = file_chooser.get_preview_filename()
     try:
         file_mimetype = mime.get_for_file(filename)
         if file_mimetype == 'application/x-cbz' or file_mimetype == 'application/zip':
             fname = self.extract_image(filename)
             pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                 fname, style.zoom(320), style.zoom(240))
             preview.set_from_pixbuf(pixbuf)
             have_preview = True
             os.remove(fname)
         else:
             have_preview = False
     except:
         have_preview = False
     file_chooser.set_preview_widget_active(have_preview)
     return
Exemplo n.º 11
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)
    def create_preview_metadata(self,  filename):

        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype.startswith('image/'):
            return ''
            
        scaled_pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename,
                                                              style.zoom(320), style.zoom(240))
        preview_data = []

        def save_func(buf, data):
            data.append(buf)

        scaled_pixbuf.save_to_callback(save_func, 'png', 
                                       user_data=preview_data)
        preview_data = ''.join(preview_data)

        return preview_data
Exemplo n.º 13
0
    def get_mime_type(self):
        if not self._formats:
            return ''

        format_ = mime.choose_most_significant(self._formats.keys())
        if format_ == 'text/uri-list':
            data = self._formats['text/uri-list'].get_data()
            uri = urlparse.urlparse(mime.split_uri_list(data)[0], 'file')
            scheme = uri.scheme  # pylint: disable=E1101
            if scheme == 'file':
                path = uri.path  # pylint: disable=E1101
                if os.path.exists(path):
                    format_ = mime.get_for_file(path)
                else:
                    format_ = mime.get_from_file_name(path)
                logging.debug('Chose %r!', format_)

        return format_
Exemplo n.º 14
0
    def get_mime_type(self):
        if not self._formats:
            return ''

        format_ = mime.choose_most_significant(self._formats.keys())
        if format_ == 'text/uri-list':
            data = self._formats['text/uri-list'].get_data()
            uri = urlparse.urlparse(mime.split_uri_list(data)[0], 'file')
            scheme = uri.scheme  # pylint: disable=E1101
            if scheme == 'file':
                path = uri.path  # pylint: disable=E1101
                if os.path.exists(path):
                    format_ = mime.get_for_file(path)
                else:
                    format_ = mime.get_from_file_name(path)
                logging.debug('Chose %r!', format_)

        return format_
Exemplo n.º 15
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)
Exemplo n.º 16
0
    def __friend_selected_cb(self, menu_item, buddy):
        logging.debug('__friend_selected_cb')
        file_name = model.get_file(self._metadata['uid'])

        if not file_name or not os.path.exists(file_name):
            logging.warn('Entries without a file cannot be sent.')
            self.emit('volume-error',
                      _('Entries without a file cannot be sent.'),
                      _('Warning'))
            return

        title = str(self._metadata['title'])
        description = str(self._metadata.get('description', ''))
        mime_type = str(self._metadata['mime_type'])

        if not mime_type:
            mime_type = mime.get_for_file(file_name)

        filetransfer.start_transfer(buddy, file_name, title, description,
                                    mime_type)
Exemplo n.º 17
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text('')
            return

        mime_type = mime.get_for_file(self._file_path)
        _logger.debug('Detected mime type: %r', mime_type)

        language_manager = gtksourceview2.language_manager_get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug('Detected language: %r',
                          detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, 'r').read())
Exemplo n.º 18
0
    def load_document(self, file_path):

        file_name = file_path.replace('file://', '')
        mimetype = mime.get_for_file(file_path)
        if mimetype == 'application/zip':
            logging.error('opening zip file')
            self.zf = zipfile.ZipFile(file_path.replace('file://', ''), 'r')
            self.book_files = self.zf.namelist()
            extract_path = os.path.join(self._activity.get_activity_root(),
                                        'instance')
            for book_file in self.book_files:
                if (book_file != 'annotations.pkl'):
                    self.zf.extract(book_file, extract_path)
                    file_name = os.path.join(extract_path, book_file)

        logging.error('opening file_name %s' % file_name)
        self._etext_file = open(file_name, 'r')

        self.page_index = [0]
        pagecount = 0
        linecount = 0
        while self._etext_file:
            line = self._etext_file.readline()
            if not line:
                break
            line_increment = (len(line) / 80) + 1
            linecount = linecount + line_increment
            if linecount >= PAGE_SIZE:
                position = self._etext_file.tell()
                self.page_index.append(position)
                linecount = 0
                pagecount = pagecount + 1
        self._pagecount = pagecount + 1
        self.set_current_page(0)

        speech.highlight_cb = self.highlight_next_word