root/branches/gajim_0.10.1/src/filetransfers_window.py

Revision 6407, 32.1 kB (checked in by dkirov, 2 years ago)

r6265, r6266, r6267, r6269, r6350, r6366

  • Property svn:eol-style set to LF
Line 
1##      filetransfers_window.py
2##
3## Copyright (C) 2003-2006 Yann Le Boulanger <asterix@lagaule.org>
4## Copyright (C) 2005-2006 Nikos Kouremenos <kourem@gmail.com>
5## Copyright (C) 2005
6##                    Dimitur Kirov <dkirov@gmail.com>
7##                    Travis Shirk <travis@pobox.com>
8## Copyright (C) 2004-2005 Vincent Hanquez <tab@snarc.org>
9##
10## This program is free software; you can redistribute it and/or modify
11## it under the terms of the GNU General Public License as published
12## by the Free Software Foundation; version 2 only.
13##
14## This program is distributed in the hope that it will be useful,
15## but WITHOUT ANY WARRANTY; without even the implied warranty of
16## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17## GNU General Public License for more details.
18##
19
20import gtk
21import gtk.glade
22import gobject
23import pango
24import os
25import time
26
27import gtkgui_helpers
28import tooltips
29import dialogs
30
31from common import gajim
32from common import helpers
33from common import i18n
34
35_ = i18n._
36APP = i18n.APP
37gtk.glade.bindtextdomain (APP, i18n.DIR)
38gtk.glade.textdomain (APP)
39
40C_IMAGE = 0
41C_LABELS = 1
42C_FILE = 2
43C_TIME = 3
44C_PROGRESS = 4
45C_PERCENT = 5
46C_SID = 6
47
48
49class FileTransfersWindow:
50        def __init__(self):
51                self.files_props = {'r' : {}, 's': {}}
52                self.height_diff = 0
53                self.xml = gtkgui_helpers.get_glade('filetransfers.glade')
54                self.window = self.xml.get_widget('file_transfers_window')
55                self.tree = self.xml.get_widget('transfers_list')
56                self.cancel_button = self.xml.get_widget('cancel_button')
57                self.pause_button = self.xml.get_widget('pause_restore_button')
58                self.cleanup_button = self.xml.get_widget('cleanup_button')
59                self.notify_ft_checkbox = self.xml.get_widget(
60                        'notify_ft_complete_checkbox')
61                notify = gajim.config.get('notify_on_file_complete')
62                if notify:
63                        self.notify_ft_checkbox.set_active(True)
64                else:
65                        self.notify_ft_checkbox.set_active(False)
66                self.model = gtk.ListStore(gtk.gdk.Pixbuf, str, str, str, str, int, str)
67                self.tree.set_model(self.model)
68                col = gtk.TreeViewColumn()
69               
70                render_pixbuf = gtk.CellRendererPixbuf()
71               
72                col.pack_start(render_pixbuf, expand = True)
73                render_pixbuf.set_property('xpad', 3)
74                render_pixbuf.set_property('ypad', 3)
75                render_pixbuf.set_property('yalign', .0)
76                col.add_attribute(render_pixbuf, 'pixbuf', 0)
77                self.tree.append_column(col)
78               
79                col = gtk.TreeViewColumn(_('File'))
80                renderer = gtk.CellRendererText()
81                col.pack_start(renderer, expand=False)
82                col.add_attribute(renderer, 'markup' , C_LABELS)
83                renderer.set_property('yalign', 0.)
84                renderer = gtk.CellRendererText()
85                col.pack_start(renderer, expand=True)
86                col.add_attribute(renderer, 'markup' , C_FILE)
87                renderer.set_property('xalign', 0.)
88                renderer.set_property('yalign', 0.)
89                renderer.set_property('ellipsize', pango.ELLIPSIZE_END)
90                col.set_resizable(True)
91                col.set_expand(True)
92                self.tree.append_column(col)
93               
94                col = gtk.TreeViewColumn(_('Time'))
95                renderer = gtk.CellRendererText()
96                col.pack_start(renderer, expand=False)
97                col.add_attribute(renderer, 'markup' , C_TIME)
98                renderer.set_property('yalign', 0.5)
99                renderer.set_property('xalign', 0.5)
100                renderer = gtk.CellRendererText()
101                renderer.set_property('ellipsize', pango.ELLIPSIZE_END)
102                col.set_resizable(True)
103                col.set_expand(False)
104                self.tree.append_column(col)
105               
106                col = gtk.TreeViewColumn(_('Progress'))
107                renderer = gtk.CellRendererProgress()
108                renderer.set_property('yalign', 0.5)
109                renderer.set_property('xalign', 0.5)
110                col.pack_start(renderer, expand = False)
111                col.add_attribute(renderer, 'text' , C_PROGRESS)
112                col.add_attribute(renderer, 'value' , C_PERCENT)
113                col.set_resizable(True)
114                col.set_expand(False)
115                self.tree.append_column(col)
116               
117                self.set_images()
118                self.tree.get_selection().set_mode(gtk.SELECTION_SINGLE)
119                self.tree.get_selection().connect('changed', self.selection_changed)
120                self.tooltip = tooltips.FileTransfersTooltip()
121                self.file_transfers_menu = self.xml.get_widget('file_transfers_menu')
122                self.open_folder_menuitem = self.xml.get_widget('open_folder_menuitem')
123                self.cancel_menuitem = self.xml.get_widget('cancel_menuitem')
124                self.pause_menuitem = self.xml.get_widget('pause_menuitem')
125                self.continue_menuitem = self.xml.get_widget('continue_menuitem')
126                self.continue_menuitem.hide()
127                self.continue_menuitem.set_no_show_all(True)
128                self.remove_menuitem = self.xml.get_widget('remove_menuitem')
129                self.xml.signal_autoconnect(self)
130               
131        def find_transfer_by_jid(self, account, jid):
132                ''' find all transfers with peer 'jid' that belong to 'account' '''
133                active_transfers = [[],[]] # ['senders', 'receivers']
134               
135                # 'account' is the sender
136                for file_props in self.files_props['s'].values():
137                        if file_props['tt_account'] == account:
138                                receiver_jid = unicode(file_props['receiver']).split('/')[0]
139                                if jid == receiver_jid:
140                                        if not self.is_transfer_stoped(file_props):
141                                                active_transfers[0].append(file_props)
142               
143                # 'account' is the recipient
144                for file_props in self.files_props['r'].values():
145                        if file_props['tt_account'] == account:
146                                sender_jid = unicode(file_props['sender']).split('/')[0]
147                                if jid == sender_jid:
148                                        if not self.is_transfer_stoped(file_props):
149                                                active_transfers[1].append(file_props)
150                return active_transfers
151       
152        def show_completed(self, jid, file_props):
153                ''' show a dialog saying that file (file_props) has been transferred'''
154                self.window.present()
155                self.window.window.focus()
156
157                def on_open(widget, file_props):
158                        self.dialog.destroy()
159                        if not file_props.has_key('file-name'):
160                                return
161                        (path, file) = os.path.split(file_props['file-name'])
162                        if os.path.exists(path) and os.path.isdir(path):
163                                helpers.launch_file_manager(path)
164                        self.tree.get_selection().unselect_all()
165
166                if file_props['type'] == 'r':
167                        # file path is used below in 'Save in'
168                        (file_path, file_name) = os.path.split(file_props['file-name'])
169                else:
170                        file_name = file_props['name']
171                sectext = '\t' + _('Filename: %s') % file_name
172                sectext += '\n\t' + _('Size: %s') % \
173                helpers.convert_bytes(file_props['size'])
174                if file_props['type'] == 'r':
175                        jid = unicode(file_props['sender']).split('/')[0]
176                        sender_name = gajim.contacts.get_first_contact_from_jid( 
177                                file_props['tt_account'], jid).get_shown_name()
178                        sender = sender_name
179                else:
180                        #You is a reply of who sent a file
181                        sender = _('You')
182                sectext += '\n\t' +_('Sender: %s') % sender
183                sectext += '\n\t' +_('Recipient: ')
184                if file_props['type'] == 's':
185                        jid = unicode(file_props['receiver']).split('/')[0]
186                        receiver_name = gajim.contacts.get_first_contact_from_jid( 
187                                file_props['tt_account'], jid).get_shown_name()
188                        recipient = receiver_name
189                else:
190                        #You is a reply of who received a file
191                        recipient = _('You')
192                sectext += recipient
193                if file_props['type'] == 'r':
194                        sectext += '\n\t' +_('Saved in: %s') % file_path
195                self.dialog = dialogs.HigDialog(None, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, 
196                                _('File transfer completed'), sectext)
197                if file_props['type'] == 'r':
198                        button = gtk.Button(_('_Open Containing Folder'))
199                        button.connect('clicked', on_open, file_props)
200                        self.dialog.action_area.pack_start(button)
201                ok_button = self.dialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
202                def on_ok(widget):
203                        self.dialog.destroy()
204                ok_button.connect('clicked', on_ok)
205                self.dialog.show_all()
206
207        def show_request_error(self, file_props):
208                ''' show error dialog to the recipient saying that transfer
209                has been canceled'''
210                self.window.present()
211                self.window.window.focus()
212                dialogs.InformationDialog(_('File transfer canceled'), _('Connection with peer cannot be established.'))
213                self.tree.get_selection().unselect_all()
214
215        def show_send_error(self, file_props):
216                ''' show error dialog to the sender saying that transfer
217                has been canceled'''
218                self.window.present()
219                self.window.window.focus()
220                dialogs.InformationDialog(_('File transfer canceled'),
221_('Connection with peer cannot be established.'))
222                self.tree.get_selection().unselect_all()
223
224        def show_stopped(self, jid, file_props):
225                self.window.present()
226                self.window.window.focus()
227                if file_props['type'] == 'r':
228                        file_name = os.path.basename(file_props['file-name'])
229                else:
230                        file_name = file_props['name']
231                sectext = '\t' + _('Filename: %s') % file_name
232                sectext += '\n\t' + _('Sender: %s') % jid
233                dialogs.ErrorDialog(_('File transfer stopped by the contact of the other side'), \
234                        sectext)
235                self.tree.get_selection().unselect_all()
236
237        def show_file_send_request(self, account, contact):
238                def on_ok(widget):
239                        file_dir = None
240                        files_path_list = self.dialog.get_filenames()
241                        files_path_list = gtkgui_helpers.decode_filechooser_file_paths(
242                                files_path_list)
243                        for file_path in files_path_list:
244                                if self.send_file(account, contact, file_path) and file_dir is None:
245                                        file_dir = os.path.dirname(file_path)
246                        if file_dir:
247                                gajim.config.set('last_send_dir', file_dir)
248                                self.dialog.destroy()
249
250                self.dialog = dialogs.FileChooserDialog(_('Choose File to Send...'), 
251                        gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
252                        gtk.RESPONSE_OK,
253                        True, # select multiple true as we can select many files to send
254                        gajim.config.get('last_send_dir'),
255                        )
256
257                btn = self.dialog.add_button(_('_Send'), gtk.RESPONSE_OK)
258                btn.set_use_stock(True) # FIXME: add send icon to this button (JUMP_TO)
259                btn.connect('clicked', on_ok)
260
261        def send_file(self, account, contact, file_path):
262                ''' start the real transfer(upload) of the file '''
263                if gtkgui_helpers.file_is_locked(file_path):
264                        pritext = _('Gajim cannot access this file')
265                        sextext = _('This file is being used by another process.')
266                        dialogs.ErrorDialog(pritext, sextext)
267                        return
268
269                if isinstance(contact, str):
270                        if contact.find('/') == -1:
271                                return
272                        (jid, resource) = contact.split('/', 1)
273                        contact = gajim.contacts.create_contact(jid = jid,
274                                resource = resource)
275                (file_dir, file_name) = os.path.split(file_path)
276                file_props = self.get_send_file_props(account, contact, 
277                                file_path, file_name)
278                if file_props is None:
279                        return False
280                self.add_transfer(account, contact, file_props)
281                gajim.connections[account].send_file_request(file_props)
282                return True
283
284        def _start_receive(self, file_path, account, contact, file_props):
285                file_dir = os.path.dirname(file_path)
286                if file_dir:
287                        gajim.config.set('last_save_dir', file_dir)
288                file_props['file-name'] = file_path
289                self.add_transfer(account, contact, file_props)
290                gajim.connections[account].send_file_approval(file_props)
291
292        def show_file_request(self, account, contact, file_props):
293                ''' show dialog asking for comfirmation and store location of new
294                file requested by a contact'''
295                if file_props is None or not file_props.has_key('name'):
296                        return
297                sec_text = '\t' + _('File: %s') % file_props['name']
298                if file_props.has_key('size'):
299                        sec_text += '\n\t' + _('Size: %s') % \
300                                helpers.convert_bytes(file_props['size'])
301                if file_props.has_key('mime-type'):
302                        sec_text += '\n\t' + _('Type: %s') % file_props['mime-type']
303                if file_props.has_key('desc'):
304                        sec_text += '\n\t' + _('Description: %s') % file_props['desc']
305                prim_text = _('%s wants to send you a file:') % contact.jid
306                dialog, dialog2 = None, None
307
308                def on_response_ok(widget, account, contact, file_props):
309                        dialog.destroy()
310
311                        def on_ok(widget, account, contact, file_props):
312                                file_path = dialog2.get_filename()
313                                file_path = gtkgui_helpers.decode_filechooser_file_paths(
314                                        (file_path,))[0]
315                                if os.path.exists(file_path):
316                                        stat = os.stat(file_path)
317                                        dl_size = stat.st_size
318                                        file_size = file_props['size']
319                                        dl_finished = dl_size >= file_size
320                                        dialog = dialogs.FTOverwriteConfirmationDialog(
321                                                _('This file already exists'), _('What do you want to do?'),
322                                                not dl_finished)
323                                        dialog.set_transient_for(dialog2)
324                                        dialog.set_destroy_with_parent(True)
325                                        response = dialog.get_response()
326                                        if response < 0:
327                                                return
328                                        elif response == 100:
329                                                file_props['offset'] = dl_size
330                                dialog2.destroy()
331                                self._start_receive(file_path, account, contact, file_props)
332
333                        def on_cancel(widget, account, contact, file_props):
334                                dialog2.destroy()
335                                gajim.connections[account].send_file_rejection(file_props)
336
337                        dialog2 = dialogs.FileChooserDialog(
338                                title_text = _('Save File as...'), 
339                                action = gtk.FILE_CHOOSER_ACTION_SAVE, 
340                                buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, 
341                                gtk.STOCK_SAVE, gtk.RESPONSE_OK),
342                                default_response = gtk.RESPONSE_OK,
343                                current_folder = gajim.config.get('last_save_dir'),
344                                on_response_ok = (on_ok, account, contact, file_props),
345                                on_response_cancel = (on_cancel, account, contact, file_props))
346
347                        dialog2.set_current_name(file_props['name'])
348                        dialog2.connect('delete-event', lambda widget, event:
349                                on_cancel(widget, account, contact, file_props))
350
351                def on_response_cancel(widget, account, file_props):
352                        dialog.destroy()
353                        gajim.connections[account].send_file_rejection(file_props)
354
355                dialog = dialogs.NonModalConfirmationDialog(prim_text, sec_text,
356                        on_response_ok = (on_response_ok, account, contact, file_props),
357                        on_response_cancel = (on_response_cancel, account, file_props))
358                dialog.connect('delete-event', lambda widget, event: 
359                        on_response_cancel(widget, account, file_props))
360                dialog.popup()
361
362        def set_images(self):
363                ''' create pixbufs for status images in transfer rows'''
364                self.images = {}
365                self.images['upload'] = self.window.render_icon(gtk.STOCK_GO_UP, 
366                        gtk.ICON_SIZE_MENU)
367                self.images['download'] = self.window.render_icon(gtk.STOCK_GO_DOWN, 
368                        gtk.ICON_SIZE_MENU)
369                self.images['stop'] = self.window.render_icon(gtk.STOCK_STOP, 
370                        gtk.ICON_SIZE_MENU)
371                self.images['waiting'] = self.window.render_icon(gtk.STOCK_REFRESH, 
372                        gtk.ICON_SIZE_MENU)
373                self.images['pause'] = self.window.render_icon(gtk.STOCK_MEDIA_PAUSE, 
374                        gtk.ICON_SIZE_MENU)
375                self.images['continue'] = self.window.render_icon(gtk.STOCK_MEDIA_PLAY, 
376                        gtk.ICON_SIZE_MENU)
377                self.images['ok'] = self.window.render_icon(gtk.STOCK_APPLY, 
378                        gtk.ICON_SIZE_MENU)
379                       
380        def set_status(self, typ, sid, status):
381                ''' change the status of a transfer to state 'status' '''
382                iter = self.get_iter_by_sid(typ, sid)
383                if iter is None:
384                        return
385                sid = self.model[iter][C_SID].decode('utf-8')
386                file_props = self.files_props[sid[0]][sid[1:]]
387                if status == 'stop':
388                        file_props['stopped'] = True
389                elif status == 'ok':
390                        file_props['completed'] = True
391                self.model.set(iter, C_IMAGE, self.images[status])
392               
393        def _format_percent(self, percent):
394                ''' add extra spaces from both sides of the percent, so that
395                progress string has always a fixed size'''
396                _str = '          '
397                if percent != 100.:
398                        _str += ' '
399                if percent < 10:
400                        _str += ' '
401                _str += unicode(percent) + '%          \n'
402                return _str
403               
404        def _format_time(self, _time):
405                times = { 'hours': 0, 'minutes': 0, 'seconds': 0 }
406                _time = int(_time)
407                times['seconds'] = _time % 60
408                if _time >= 60:
409                        _time /= 60
410                        times['minutes'] = _time % 60
411                        if _time >= 60:
412                                times['hours'] = _time / 60
413               
414                #Print remaining time in format 00:00:00
415                #You can change the places of (hours), (minutes), (seconds) -
416                #they are not translatable.
417                return _('%(hours)02.d:%(minutes)02.d:%(seconds)02.d')  % times
418               
419        def _get_eta_and_speed(self, full_size, transfered_size, elapsed_time):
420                if elapsed_time == 0:
421                        return 0., 0.
422                speed = round(float(transfered_size) / elapsed_time)
423                if speed == 0.:
424                        return 0., 0.
425                remaining_size = full_size - transfered_size
426                eta = remaining_size / speed
427                return eta, speed
428               
429        def _remove_transfer(self, iter, sid, file_props):
430                self.model.remove(iter)
431                if  file_props.has_key('tt_account'):
432                        # file transfer is set
433                        account = file_props['tt_account']
434                        if gajim.connections.has_key(account):
435                                # there is a connection to the account
436                                gajim.connections[account].remove_transfer(file_props)
437                        if file_props['type'] == 'r': # we receive a file
438                                other = file_props['sender']
439                        else: # we send a file
440                                other = file_props['receiver']
441                        if isinstance(other, unicode):
442                                jid = gajim.get_jid_without_resource(other)
443                        else: # It's a Contact instance
444                                jid = other.jid
445                        if gajim.awaiting_events[account].has_key(jid):
446                                for event in gajim.awaiting_events[account][jid]:
447                                        if event[0] in ('file-error', 'file-completed',
448                                                'file-request-error', 'file-send-error', 'file-stopped') and \
449                                                event[1]['sid'] == file_props['sid']:
450                                                gajim.interface.remove_event(account, jid, event)
451                del(self.files_props[sid[0]][sid[1:]])
452                del(file_props)
453               
454        def set_progress(self, typ, sid, transfered_size, iter = None):
455                ''' change the progress of a transfer with new transfered size'''
456                if not self.files_props[typ].has_key(sid):
457                        return
458                file_props = self.files_props[typ][sid]
459                full_size = int(file_props['size'])
460                if full_size == 0:
461                        percent = 0
462                else:
463                        percent = round(float(transfered_size) / full_size * 100)
464                if iter is None:
465                        iter = self.get_iter_by_sid(typ, sid)
466                if iter is not None:
467                        text = self._format_percent(percent)
468                        if transfered_size == 0:
469                                text += '0'
470                        else:
471                                text += helpers.convert_bytes(transfered_size)
472                        text += '/' + helpers.convert_bytes(full_size)
473                        # Kb/s
474                       
475                        # remaining time
476                        if file_props.has_key('offset') and file_props['offset']:
477                                transfered_size -= file_props['offset'] 
478                                full_size -= file_props['offset']
479                        eta, speed = self._get_eta_and_speed(full_size, transfered_size, 
480                                file_props['elapsed-time'])
481                       
482                        self.model.set(iter, C_PROGRESS, text)
483                        self.model.set(iter, C_PERCENT, int(percent))
484                        text = self._format_time(eta)
485                        text += '\n'
486                        #This should make the string Kb/s,
487                        #where 'Kb' part is taken from %s.
488                        #Only the 's' after / (which means second) should be translated.
489                        text += _('(%(filesize_unit)s/s)') % {'filesize_unit':
490                                helpers.convert_bytes(speed)}
491                        self.model.set(iter, C_TIME, text)
492                       
493                        # try to guess what should be the status image
494                        if file_props['type'] == 'r':
495                                status = 'download'
496                        else:
497                                status = 'upload'
498                        if file_props.has_key('paused') and file_props['paused'] == True:
499                                status = 'pause'
500                        elif file_props.has_key('stalled') and file_props['stalled'] == True:
501                                status = 'waiting'
502                        if file_props.has_key('connected') and file_props['connected'] == False:
503                                status = 'stop'
504                        self.model.set(iter, 0, self.images[status])
505                        if transfered_size == full_size:
506                                self.set_status(typ, sid, 'ok')
507       
508        def get_iter_by_sid(self, typ, sid):
509                '''returns iter to the row, which holds file transfer, identified by the
510                session id'''
511                iter = self.model.get_iter_root()
512                while iter:
513                        if typ + sid == self.model[iter][C_SID].decode('utf-8'):
514                                return iter
515                        iter = self.model.iter_next(iter)
516       
517        def get_send_file_props(self, account, contact, file_path, file_name):
518                ''' create new file_props dict and set initial file transfer
519                properties in it'''
520                file_props = {'file-name' : file_path, 'name' : file_name, 
521                        'type' : 's'}
522                if os.path.isfile(file_path):
523                        stat = os.stat(file_path)
524                else:
525                        dialogs.ErrorDialog(_('Invalid File'), _('File: ')  + file_path)
526                        return None
527                if stat[6] == 0:
528                        dialogs.ErrorDialog(_('Invalid File'), 
529                        _('It is not possible to send empty files'))
530                        return None
531                file_props['elapsed-time'] = 0
532                file_props['size'] = unicode(stat[6])
533                file_props['sid'] = helpers.get_random_string_16()
534                file_props['completed'] = False
535                file_props['started'] = False
536                file_props['sender'] = account
537                file_props['receiver'] = contact
538                file_props['tt_account'] = account
539                return file_props
540