summaryrefslogtreecommitdiffstats
path: root/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
blob: 607fc406f0fb7909807b6071bf401d4c57442b99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#
# gtkui.py
#
# Copyright (C) 2009 Ian Martin <ianmartin@cantab.net>
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007, 2008 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge.    If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA    02110-1301, USA.
#
#    In addition, as a special exception, the copyright holders give
#    permission to link the code of portions of this program with the OpenSSL
#    library.
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version. If you delete this exception

import gtk
import gobject
from gtk.glade import XML

import graph
import deluge
from deluge import component
from deluge.log import LOG as log
from deluge.common import fspeed
from deluge.ui.client import client
from deluge.ui.gtkui.torrentdetails import Tab
from deluge.plugins.pluginbase import GtkPluginBase

import common

DEFAULT_CONF = { 'version': 1,
                 'colors' :{
                 'bandwidth_graph': {'upload_rate': str(gtk.gdk.Color("blue")),
                                     'download_rate': str(gtk.gdk.Color("green")),
                                    },
                 'connections_graph': { 'dht_nodes': str(gtk.gdk.Color("orange")),
                                        'dht_cache_nodes': str(gtk.gdk.Color("blue")),
                                        'dht_torrents': str(gtk.gdk.Color("green")),
                                        'num_connections': str(gtk.gdk.Color("darkred")),
                                      },
                 'seeds_graph': { 'num_peers': str(gtk.gdk.Color("blue")),
                                  },
                 }
                 }

def neat_time(column, cell, model, iter):
    """Render seconds as seconds or minutes with label"""
    seconds = model.get_value(iter, 0)
    if seconds >60:
        text = "%d %s" % (seconds / 60, _("minutes"))
    elif seconds == 60:
        text = _("1 minute")
    elif seconds == 1:
        text = _("1 second")
    else:
        text = "%d %s" % (seconds, _("seconds"))
    cell.set_property('text', text)
    return

def int_str(number):
    return (str(int(number)))

def gtk_to_graph_color(color):
    """Turns a gtk.gdk.Color into a tuple with range 0-1 as used by the graph"""
    MAX = float(65535)
    gtk_color = gtk.gdk.Color(color)
    red = gtk_color.red / MAX
    green = gtk_color.green / MAX
    blue = gtk_color.blue / MAX
    return (red, green, blue)


class GraphsTab(Tab):
    def __init__(self, glade, colors):
        Tab.__init__(self)
        self.glade = glade
        self.window = self.glade.get_widget('graph_tab')
        self.notebook = self.glade.get_widget('graph_notebook')
        self.label = self.glade.get_widget('graph_label')

        self._name = 'Graphs'
        self._child_widget = self.window
        self._tab_label = self.label

        self.colors = colors

        self.bandwidth_graph = self.glade.get_widget('bandwidth_graph')
        self.bandwidth_graph.connect('expose_event', self.graph_expose)

        self.connections_graph = self.glade.get_widget('connections_graph')
        self.connections_graph.connect('expose_event', self.graph_expose)

        self.seeds_graph = self.glade.get_widget('seeds_graph')
        self.seeds_graph.connect('expose_event', self.graph_expose)

        self.notebook.connect('switch-page', self._on_notebook_switch_page)

        self.selected_interval = 1 #should come from config or similar
        self.select_bandwidth_graph()

        self.window.unparent()
        self.label.unparent()

        self.intervals = None
        self.intervals_combo = self.glade.get_widget('combo_intervals')
        cell = gtk.CellRendererText()
        self.intervals_combo.pack_start(cell, True)
        self.intervals_combo.set_cell_data_func(cell, neat_time)
        self.intervals_combo.connect("changed", self._on_selected_interval_changed)
        self.update_intervals()


    def graph_expose(self, widget, event):
        context = self.graph_widget.window.cairo_create()
        # set a clip region
        context.rectangle(event.area.x, event.area.y,
                           event.area.width, event.area.height)
        context.clip()
        self.graph.draw_to_context(context,
                                   self.graph_widget.allocation.width,
                                   self.graph_widget.allocation.height)
        #Do not propagate the event
        return False

    def update(self):
        d1 = client.stats.get_stats(self.graph.stat_info.keys(), self.selected_interval)
        d1.addCallback(self.graph.set_stats)
        def _update_complete(result):
            self.graph_widget.queue_draw()
        d1.addCallback(_update_complete)
        return True

    def clear(self):
        pass

    def update_intervals(self):
        client.stats.get_intervals().addCallback(self._on_intervals_changed)

    def select_bandwidth_graph(self):
        log.debug("Selecting bandwidth graph")
        self.graph_widget =  self.bandwidth_graph
        self.graph = graph.Graph()
        colors = self.colors['bandwidth_graph']
        self.graph.add_stat('download_rate', label='Download Rate',
                            color=gtk_to_graph_color(colors['download_rate']))
        self.graph.add_stat('upload_rate', label='Upload Rate',
                            color=gtk_to_graph_color(colors['upload_rate']))
        self.graph.set_left_axis(formatter=fspeed, min=10240,
                                 formatter_scale=graph.size_formatter_scale)

    def select_connections_graph(self):
        log.debug("Selecting connections graph")
        self.graph_widget =  self.connections_graph
        g = graph.Graph()
        self.graph = g
        colors = self.colors['connections_graph']
        g.add_stat('dht_nodes', color=gtk_to_graph_color(colors['dht_nodes']))
        g.add_stat('dht_cache_nodes', color=gtk_to_graph_color(colors['dht_cache_nodes']))
        g.add_stat('dht_torrents', color=gtk_to_graph_color(colors['dht_torrents']))
        g.add_stat('num_connections', color=gtk_to_graph_color(colors['num_connections']))
        g.set_left_axis(formatter=int_str, min=10)

    def select_seeds_graph(self):
        log.debug("Selecting connections graph")
        self.graph_widget =  self.seeds_graph
        self.graph = graph.Graph()
        colors = self.colors['seeds_graph']
        self.graph.add_stat('num_peers', color=gtk_to_graph_color(colors['num_peers']))
        self.graph.set_left_axis(formatter=int_str, min=10)

    def set_colors(self, colors):
        self.colors = colors
        # Fake switch page to update the graph colors (HACKY)
        self._on_notebook_switch_page(self.notebook,
                                      None, #This is unused
                                      self.notebook.get_current_page())

    def _on_intervals_changed(self, intervals):
        liststore = gtk.ListStore(int)
        for inter in intervals:
            liststore.append([inter])
        self.intervals_combo.set_model(liststore)
        try:
            current = intervals.index(self.selected_interval)
        except:
            current = 0
        #should select the value saved in config
        self.intervals_combo.set_active(current)

    def _on_selected_interval_changed(self, combobox):
        model = combobox.get_model()
        iter = combobox.get_active_iter()
        self.selected_interval = model.get_value(iter, 0)
        self.update()
        return True

    def _on_notebook_switch_page(self, notebook, page, page_num):
        p = notebook.get_nth_page(page_num)
        if p is self.bandwidth_graph:
            self.select_bandwidth_graph()
            self.update()
        elif p is self.connections_graph:
            self.select_connections_graph()
            self.update()
        elif p is self.seeds_graph:
            self.select_seeds_graph()
            self.update()
        return True

class GtkUI(GtkPluginBase):
    def enable(self):
        log.debug("Stats plugin enable called")
        self.config = deluge.configmanager.ConfigManager("stats.gtkui.conf", DEFAULT_CONF)
        self.glade = XML(common.get_resource("config.glade"))
        component.get("Preferences").add_page("Stats", self.glade.get_widget("prefs_box"))
        component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs)
        component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs)
        self.on_show_prefs()

        self.graphs_tab = GraphsTab(XML(common.get_resource("tabs.glade")), self.config['colors'])
        self.torrent_details = component.get('TorrentDetails')
        self.torrent_details.add_tab(self.graphs_tab)

    def disable(self):
        component.get("Preferences").remove_page("Stats")
        component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_prefs)
        component.get("PluginManager").deregister_hook("on_show_prefs", self.on_show_prefs)
        self.torrent_details.remove_tab(self.graphs_tab.get_name())

    def on_apply_prefs(self):
        log.debug("applying prefs for Stats")
        gtkconf = {}
        for graph, colors in self.config['colors'].items():
            gtkconf[graph] = {}
            for value, color in colors.items():
                try:
                    color_btn = self.glade.get_widget("%s_%s_color" % (graph, value))
                    gtkconf[graph][value] = str(color_btn.get_color())
                except:
                    gtkconf[graph][value] = DEFAULT_CONF['colors'][graph][value]
        self.config['colors'] = gtkconf
        self.graphs_tab.set_colors(self.config['colors'])

        config = { }
        client.stats.set_config(config)

    def on_show_prefs(self):
        for graph, colors in self.config['colors'].items():
            for value, color in colors.items():
                try:
                    color_btn = self.glade.get_widget("%s_%s_color" % (graph, value))
                    color_btn.set_color(gtk.gdk.Color(color))
                except:
                    log.debug("Unable to set %s %s %s" % (graph, value, color))
        client.stats.get_config().addCallback(self.cb_get_config)

    def cb_get_config(self, config):
        "callback for on show_prefs"
        pass