source: trunk/gtk/main.c @ 918

Last change on this file since 918 was 918, checked in by joshe, 15 years ago

Revert a change that was made on the wrong branch.

  • Property svn:keywords set to Date Rev Author Id
File size: 36.0 KB
Line 
1/******************************************************************************
2 * $Id: main.c 918 2006-09-25 07:17:43Z joshe $
3 *
4 * Copyright (c) 2005-2006 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <sys/param.h>
26#include <errno.h>
27#include <signal.h>
28#include <string.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <time.h>
32#include <unistd.h>
33
34#include <gtk/gtk.h>
35#include <glib/gi18n.h>
36#include <glib/gstdio.h>
37
38#include "conf.h"
39#include "dialogs.h"
40#include "ipc.h"
41#include "msgwin.h"
42#include "tr_backend.h"
43#include "tr_torrent.h"
44#include "tr_cell_renderer_progress.h"
45#include "transmission.h"
46#include "util.h"
47
48/* time in seconds to wait for torrents to stop when exiting */
49#define TRACKER_EXIT_TIMEOUT    10
50
51/* interval in milliseconds to update the torrent list display */
52#define UPDATE_INTERVAL         1000
53
54/* interval in milliseconds to check for stopped torrents and update display */
55#define EXIT_CHECK_INTERVAL     500
56
57struct cbdata {
58  TrBackend *back;
59  GtkWindow *wind;
60  GtkTreeModel *model;
61  GtkTreeView *view;
62  GtkStatusbar *bar;
63  GtkWidget **buttons;
64  guint timer;
65  gboolean prefsopen;
66  gboolean msgwinopen;
67  GtkWidget *stupidpopuphack;
68  gboolean closing;
69};
70
71struct exitdata {
72  struct cbdata *cbdata;
73  time_t started;
74  guint timer;
75};
76
77GList *
78readargs(int argc, char **argv);
79
80void
81makewind(GtkWidget *wind, TrBackend *back, benc_val_t *state, GList *args);
82void
83quittransmission(struct cbdata *data);
84GtkWidget *
85makewind_toolbar(struct cbdata *data);
86GtkWidget *
87makewind_list(struct cbdata *data, GObject **sizehack);
88gboolean
89winclose(GtkWidget *widget, GdkEvent *event, gpointer gdata);
90gboolean
91exitcheck(gpointer gdata);
92void
93setupdrag(GtkWidget *widget, struct cbdata *data);
94void
95gotdrag(GtkWidget *widget, GdkDragContext *dc, gint x, gint y,
96        GtkSelectionData *sel, guint info, guint time, gpointer gdata);
97static void
98stylekludge(GObject *obj, GParamSpec *spec, gpointer gdata);
99void
100fixbuttons(GtkTreeSelection *sel, gpointer gdata);
101void
102dfname(GtkTreeViewColumn *col, GtkCellRenderer *rend, GtkTreeModel *model,
103       GtkTreeIter *iter, gpointer gdata);
104void
105dfprog(GtkTreeViewColumn *col, GtkCellRenderer *rend, GtkTreeModel *model,
106       GtkTreeIter *iter, gpointer gdata);
107
108gboolean
109updatemodel(gpointer gdata);
110gboolean
111listclick(GtkWidget *widget, GdkEventButton *event, gpointer gdata);
112gboolean
113listpopup(GtkWidget *widget, gpointer gdata);
114void
115dopopupmenu(GdkEventButton *event, struct cbdata *data);
116void
117boolwindclosed(GtkWidget *widget SHUTUP, gpointer gdata);
118void
119actionclick(GtkWidget *widget, gpointer gdata);
120gint
121intrevcmp(gconstpointer a, gconstpointer b);
122void
123doubleclick(GtkWidget *widget, GtkTreePath *path, GtkTreeViewColumn *col,
124            gpointer gdata);
125
126void
127addtorrents(void *vdata, void *state, GList *files,
128            const char *dir, guint flags);
129void
130savetorrents(struct cbdata *data);
131void
132orstatus(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter,
133         gpointer gdata);
134void
135istorsel(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter,
136         gpointer gdata);
137void
138safepipe(void);
139void
140setupsighandlers(void);
141void
142fatalsig(int sig);
143
144#define LIST_ACTION           "torrent-list-action"
145enum listact {
146  ACT_OPEN, ACT_START, ACT_STOP, ACT_DELETE, ACT_INFO, ACT_PREF, ACT_DEBUG };
147
148struct { const gchar *name; const gchar *id; enum listact act; gboolean nomenu;
149  int avail; const char *ttext; const char *tpriv; }
150actionitems[] = {
151  {N_("Add"),         GTK_STOCK_ADD,          ACT_OPEN,   FALSE,  0,
152   N_("Add a new torrent"), "XXX"},
153  {N_("Start"),       GTK_STOCK_EXECUTE,      ACT_START,  FALSE,
154   TR_STATUS_INACTIVE,
155   N_("Start a torrent that is not running"), "XXX"},
156  {N_("Stop"),        GTK_STOCK_STOP,         ACT_STOP,   FALSE,
157   TR_STATUS_ACTIVE,
158   N_("Stop a torrent that is running"), "XXX"},
159  {N_("Remove"),      GTK_STOCK_REMOVE,       ACT_DELETE, FALSE, ~0,
160   N_("Remove a torrent"), "XXX"},
161  {N_("Properties"),  GTK_STOCK_PROPERTIES,   ACT_INFO,   FALSE, ~0,
162   N_("Show additional information about a torrent"), "XXX"},
163  {N_("Preferences"), GTK_STOCK_PREFERENCES,  ACT_PREF,   TRUE,   0,
164   N_("Customize application behavior"), "XXX"},
165  {N_("Open debug window"), NULL, ACT_DEBUG,  FALSE,  0, NULL, NULL},
166};
167
168#define CBDATA_PTR              "callback-data-pointer"
169
170#define SIGCOUNT_MAX            3
171
172static sig_atomic_t global_sigcount = 0;
173
174int
175main(int argc, char **argv) {
176  GtkWidget *mainwind, *preferr, *stateerr;
177  char *err;
178  TrBackend *back;
179  benc_val_t *state;
180  const char *pref;
181  long intval;
182  GList *argfiles;
183  gboolean didinit, didlock;
184
185  safepipe();
186
187  argfiles = readargs(argc, argv);
188
189  didinit = cf_init(tr_getPrefsDirectory(), NULL);
190  didlock = FALSE;
191  if(NULL != argfiles && didinit && !(didlock = cf_lock(NULL)))
192    return !ipc_sendfiles_blocking(argfiles);
193
194  setupsighandlers();
195
196  gtk_init(&argc, &argv);
197
198  bindtextdomain("transmission-gtk", LOCALEDIR);
199  bind_textdomain_codeset("transmission-gtk", "UTF-8");
200  textdomain("transmission-gtk");
201
202  g_set_application_name(_("Transmission"));
203
204  gtk_rc_parse_string(
205    "style \"transmission-standard\" {\n"
206    " GtkDialog::action-area-border = 6\n"
207    " GtkDialog::button-spacing = 12\n"
208    " GtkDialog::content-area-border = 6\n"
209    "}\n"
210    "widget \"TransmissionDialog\" style \"transmission-standard\"\n");
211
212  if(didinit || cf_init(tr_getPrefsDirectory(), &err)) {
213    if(didlock || cf_lock(&err)) {
214
215      /* create main window now so any error dialogs can be it's children */
216      mainwind = gtk_window_new(GTK_WINDOW_TOPLEVEL);
217      preferr = NULL;
218      stateerr = NULL;
219
220      cf_loadprefs(&err);
221      if(NULL != err) {
222        preferr = errmsg(GTK_WINDOW(mainwind), "%s", err);
223        g_free(err);
224      }
225      state = cf_loadstate(&err);
226      if(NULL != err) {
227        stateerr = errmsg(GTK_WINDOW(mainwind), "%s", err);
228        g_free(err);
229      }
230
231      /* set libT message level */
232      msgwin_loadpref();
233
234      back = tr_backend_new();
235
236      /* set the upload limit */
237      setlimit(back);
238
239      /* set the listening port */
240      if(NULL != (pref = cf_getpref(PREF_PORT)) &&
241         0 < (intval = strtol(pref, NULL, 10)) && 0xffff >= intval)
242        tr_setBindPort(tr_backend_handle(back), intval);
243
244      makewind(mainwind, back, state, argfiles);
245
246      if(NULL != state)
247        cf_freestate(state);
248      g_object_unref(back);
249
250      if(NULL != preferr)
251        gtk_widget_show_all(preferr);
252      if(NULL != stateerr)
253        gtk_widget_show_all(stateerr);
254    } else {
255      gtk_widget_show(errmsg_full(NULL, (callbackfunc_t)gtk_main_quit,
256                                  NULL, "%s", err));
257      g_free(err);
258    }
259  } else {
260    gtk_widget_show(errmsg_full(NULL, (callbackfunc_t)gtk_main_quit,
261                                NULL, "%s", err));
262    g_free(err);
263  }
264
265  if(NULL != argfiles)
266    freestrlist(argfiles);
267
268  gtk_main();
269
270  return 0;
271}
272
273GList *
274readargs(int argc, char **argv) {
275  char *name;
276
277  if(NULL == (name = strrchr(argv[0], '/')) || '\0' == *(++name))
278    name = argv[0];
279
280  while(0 < --argc) {
281    argv++;
282    if(0 == strcmp("--", *argv))
283      return checkfilenames(argc - 1, argv + 1);
284    else if('-' != argv[0][0])
285      return checkfilenames(argc, argv);
286    else if(0 == strcmp("-v", *argv) || 0 == strcmp("--version", *argv)) {
287      printf("%s %s (%d) http://transmission.m0k.org/\n",
288             name, VERSION_STRING, VERSION_REVISION);
289      exit(0);
290    }
291    else if(0 == strcmp("-h", *argv) || 0 == strcmp("--help", *argv)) {
292      printf("usage: %1$s [-hv] [files...]\n\n"
293"If %1$s is already running then a second copy will not be\n"
294"started, any torrents on the command-line will be opened in the first.\n",
295             name);
296      exit(0);
297    }
298  }
299
300  return NULL;
301}
302
303void
304makewind(GtkWidget *wind, TrBackend *back, benc_val_t *state, GList *args) {
305  GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
306  GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
307  GtkWidget *status = gtk_statusbar_new();
308  struct cbdata *data = g_new0(struct cbdata, 1);
309  GtkWidget *list;
310  GtkRequisition req;
311  gint width, height;
312  GObject *sizehack;
313  GdkScreen *screen;
314
315  g_object_ref(G_OBJECT(back));
316  data->back = back;
317  data->wind = GTK_WINDOW(wind);
318  data->timer = 0;
319  /* filled in by makewind_list */
320  data->model = NULL;
321  data->view = NULL;
322  data->bar = GTK_STATUSBAR(status);
323  data->buttons = NULL;
324  data->prefsopen = FALSE;
325  data->msgwinopen = FALSE;
326  data->stupidpopuphack = NULL;
327  data->closing = FALSE;
328
329  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_NEVER,
330                                 GTK_POLICY_ALWAYS);
331
332  gtk_box_pack_start(GTK_BOX(vbox), makewind_toolbar(data), FALSE, FALSE, 0);
333
334  sizehack = NULL;
335  list = makewind_list(data, &sizehack);
336  gtk_container_add(GTK_CONTAINER(scroll), list);
337  gtk_box_pack_start(GTK_BOX(vbox), scroll, TRUE, TRUE, 0);
338
339  gtk_statusbar_push(GTK_STATUSBAR(status), 0, "");
340  gtk_box_pack_start(GTK_BOX(vbox), status, FALSE, FALSE, 0);
341
342  gtk_container_set_focus_child(GTK_CONTAINER(vbox), scroll);
343  gtk_container_add(GTK_CONTAINER(wind), vbox);
344  gtk_window_set_title(data->wind, g_get_application_name());
345  g_signal_connect(G_OBJECT(wind), "delete_event", G_CALLBACK(winclose), data);
346
347  setupdrag(list, data);
348
349  addtorrents(data, state, args, NULL, addactionflag(cf_getpref(PREF_ADDIPC)));
350
351  data->timer = g_timeout_add(UPDATE_INTERVAL, updatemodel, data);
352  updatemodel(data);
353
354  /* some evil magic to try to get a nice initial window size */
355  gtk_widget_show_all(vbox);
356  gtk_widget_realize(wind);
357  gtk_widget_size_request(list, &req);
358  height = req.height;
359  gtk_widget_size_request(scroll, &req);
360  height -= req.height;
361  gtk_widget_size_request(wind, &req);
362  height += req.height;
363  screen = gtk_widget_get_screen(wind);
364  width = MIN(req.width, gdk_screen_get_width(screen) / 2);
365  height = MIN(height, gdk_screen_get_height(screen) / 5 * 4);
366  if(height > req.width)
367    height = MIN(height, width * 8 / 5);
368  else
369    height = MAX(height, width * 5 / 8);
370  height = (height > req.width ?
371            MIN(height, width * 8 / 5) : MAX(height, width * 5 / 8));
372  g_object_set(sizehack, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
373  gtk_widget_show_now(wind);
374  gtk_window_resize(GTK_WINDOW(wind), width, height);
375
376  /* set up the ipc socket now that we're ready to get torrents from it */
377  ipc_socket_setup(GTK_WINDOW(wind), addtorrents, data);
378}
379
380void
381quittransmission(struct cbdata *data) {
382  g_object_unref(G_OBJECT(data->back));
383  gtk_widget_destroy(GTK_WIDGET(data->wind));
384  if(0 < data->timer)
385    g_source_remove(data->timer);
386  if(NULL != data->stupidpopuphack)
387    gtk_widget_destroy(data->stupidpopuphack);
388  g_free(data->buttons);
389  g_free(data);
390  gtk_main_quit();
391}
392
393GtkWidget *
394makewind_toolbar(struct cbdata *data) {
395  GtkWidget *bar = gtk_toolbar_new();
396  GtkToolItem *item;
397  unsigned int ii;
398
399  gtk_toolbar_set_tooltips(GTK_TOOLBAR(bar), TRUE);
400  gtk_toolbar_set_show_arrow(GTK_TOOLBAR(bar), FALSE);
401
402  data->buttons = g_new(GtkWidget*, ALEN(actionitems));
403
404  for(ii = 0; ii < ALEN(actionitems); ii++) {
405    if( NULL == actionitems[ii].id ) {
406      data->buttons[ii] = NULL;
407      continue;
408    }
409    item = gtk_tool_button_new_from_stock(actionitems[ii].id);
410    data->buttons[ii] = GTK_WIDGET(item);
411    gtk_tool_button_set_label(GTK_TOOL_BUTTON(item),
412                              gettext(actionitems[ii].name));
413    gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(item), GTK_TOOLBAR(bar)->tooltips,
414                              gettext(actionitems[ii].ttext),
415                              actionitems[ii].tpriv);
416    g_object_set_data(G_OBJECT(item), LIST_ACTION,
417                      GINT_TO_POINTER(actionitems[ii].act));
418    g_signal_connect(G_OBJECT(item), "clicked", G_CALLBACK(actionclick), data);
419    gtk_toolbar_insert(GTK_TOOLBAR(bar), item, -1);
420  }
421
422  return bar;
423}
424
425/* XXX check for unused data in model */
426enum {
427  MC_NAME, MC_SIZE, MC_STAT, MC_ERR, MC_TERR,
428  MC_PROG, MC_DRATE, MC_URATE, MC_ETA, MC_PEERS,
429  MC_UPEERS, MC_DPEERS, MC_DOWN, MC_UP,
430  MC_TORRENT, MC_ROW_COUNT,
431};
432
433GtkWidget *
434makewind_list(struct cbdata *data, GObject **sizehack) {
435  GType types[] = {
436    /* info->name, info->totalSize, status,     error,      trackerError, */
437    G_TYPE_STRING, G_TYPE_UINT64,   G_TYPE_INT, G_TYPE_INT, G_TYPE_STRING,
438    /* progress,  rateDownload, rateUpload,   eta,        peersTotal, */
439    G_TYPE_FLOAT, G_TYPE_FLOAT, G_TYPE_FLOAT, G_TYPE_INT, G_TYPE_INT,
440    /* peersUploading, peersDownloading, downloaded,    uploaded */
441    G_TYPE_INT,        G_TYPE_INT,       G_TYPE_UINT64, G_TYPE_UINT64,
442    /* the torrent object */
443    TR_TORRENT_TYPE};
444  GtkListStore *store;
445  GtkWidget *view;
446  GtkTreeViewColumn *col;
447  GtkTreeSelection *sel;
448  GtkCellRenderer *namerend, *progrend;
449  char *str;
450
451  g_assert(MC_ROW_COUNT == ALEN(types));
452
453  store = gtk_list_store_newv(MC_ROW_COUNT, types);
454  view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store));
455  /* XXX do I need to worry about reference counts anywhere else? */
456  g_object_unref(G_OBJECT(store));
457  data->model = GTK_TREE_MODEL(store);
458  data->view = GTK_TREE_VIEW(view);
459
460  namerend = gtk_cell_renderer_text_new();
461  *sizehack = G_OBJECT(namerend);
462  /* note that this renderer is set to ellipsize, just not here */
463  col = gtk_tree_view_column_new_with_attributes(_("Name"), namerend, NULL);
464  gtk_tree_view_column_set_cell_data_func(col, namerend, dfname, NULL, NULL);
465  gtk_tree_view_column_set_expand(col, TRUE);
466  gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
467  gtk_tree_view_append_column(GTK_TREE_VIEW(view), col);
468
469  progrend = tr_cell_renderer_progress_new();
470  /* this string is only used to determing the size of the progress bar */
471  str = g_markup_printf_escaped("<big>%s</big>", _("  fnord    fnord  "));
472  g_object_set(progrend, "bar-sizing", str, NULL);
473  g_free(str);
474  col = gtk_tree_view_column_new_with_attributes(_("Progress"), progrend, NULL);
475  gtk_tree_view_column_set_cell_data_func(col, progrend, dfprog, NULL, NULL);
476  gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
477  gtk_tree_view_append_column(GTK_TREE_VIEW(view), col);
478
479  /* XXX this shouldn't be necessary */
480  g_signal_connect(view, "notify", G_CALLBACK(stylekludge), progrend);
481
482  gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(view), TRUE);
483  sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
484  gtk_tree_selection_set_mode(GTK_TREE_SELECTION(sel), GTK_SELECTION_MULTIPLE);
485  g_signal_connect(G_OBJECT(sel), "changed", G_CALLBACK(fixbuttons), data);
486  g_signal_connect(G_OBJECT(view), "button-press-event",
487                   G_CALLBACK(listclick), data);
488  g_signal_connect(G_OBJECT(view), "popup-menu", G_CALLBACK(listpopup), data);
489  g_signal_connect(G_OBJECT(view), "row-activated",
490                   G_CALLBACK(doubleclick), data);
491  gtk_widget_show_all(view);
492
493  return view;
494}
495
496gboolean
497winclose(GtkWidget *widget SHUTUP, GdkEvent *event SHUTUP, gpointer gdata) {
498  struct cbdata *data = gdata;
499  struct exitdata *edata;
500  unsigned int ii;
501  GtkTreeIter iter;
502  TrTorrent *tor;
503
504  data->closing = TRUE;
505
506  /* stop the update timer */
507  if(0 < data->timer)
508    g_source_remove(data->timer);
509  data->timer = 0;
510
511  /*
512    Add a reference to all torrents in the list, which will be removed
513    when the politely-stopped signal is emitted.  This is necessary
514    because actionclick() adds a reference when it removes a torrent
515    from the model and calls tr_torrent_stop_polite() on it.
516  */
517  if(gtk_tree_model_get_iter_first(data->model, &iter)) {
518    do
519      gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor, -1);
520    while(gtk_tree_model_iter_next(data->model, &iter));
521  }
522
523  /* try to politely stop all the torrents */
524  tr_backend_stop_torrents(data->back);
525
526  /* set things up to wait for torrents to stop */
527  edata = g_new0(struct exitdata, 1);
528  edata->cbdata = data;
529  edata->started = time(NULL);
530  /* check if torrents are still running */
531  if(exitcheck(edata)) {
532    /* yes, start the exit timer and disable widgets */
533    edata->timer = g_timeout_add(EXIT_CHECK_INTERVAL, exitcheck, edata);
534    for(ii = 0; ii < ALEN(actionitems); ii++)
535      if( NULL != data->buttons[ii] )
536        gtk_widget_set_sensitive(data->buttons[ii], FALSE);
537    gtk_widget_set_sensitive(GTK_WIDGET(data->view), FALSE);
538  }
539
540  /* returning FALSE means to destroy the window */
541  return TRUE;
542}
543
544gboolean
545exitcheck(gpointer gdata) {
546  struct exitdata *data = gdata;
547
548  /* keep going if we still have torrents and haven't hit the exit timeout */
549  if(time(NULL) - data->started < TRACKER_EXIT_TIMEOUT &&
550     !tr_backend_torrents_stopped(data->cbdata->back)) {
551    updatemodel(data->cbdata);
552    return TRUE;
553  }
554
555  /* exit otherwise */
556  if(0 < data->timer)
557    g_source_remove(data->timer);
558  quittransmission(data->cbdata);
559  g_free(data);
560
561  return FALSE;
562}
563
564void
565gotdrag(GtkWidget *widget SHUTUP, GdkDragContext *dc, gint x SHUTUP,
566        gint y SHUTUP, GtkSelectionData *sel, guint info SHUTUP, guint time,
567        gpointer gdata) {
568  struct cbdata *data = gdata;
569  char prefix[] = "file:";
570  char *files, *decoded, *deslashed, *hostless;
571  int ii, len;
572  GList *errs;
573  struct stat sb;
574  int prelen = strlen(prefix);
575  GList *paths, *freeables;
576
577#ifdef DND_DEBUG
578  char *sele = gdk_atom_name(sel->selection);
579  char *targ = gdk_atom_name(sel->target);
580  char *type = gdk_atom_name(sel->type);
581
582  fprintf(stderr, "dropped file: sel=%s targ=%s type=%s fmt=%i len=%i\n",
583          sele, targ, type, sel->format, sel->length);
584  g_free(sele);
585  g_free(targ);
586  g_free(type);
587  if(8 == sel->format) {
588    for(ii = 0; ii < sel->length; ii++)
589      fprintf(stderr, "%02X ", sel->data[ii]);
590    fprintf(stderr, "\n");
591  }
592#endif
593
594  errs = NULL;
595  paths = NULL;
596  freeables = NULL;
597  if(gdk_atom_intern("XdndSelection", FALSE) == sel->selection &&
598     8 == sel->format) {
599    /* split file list on carriage returns and linefeeds */
600    files = g_new(char, sel->length + 1);
601    memcpy(files, sel->data, sel->length);
602    files[sel->length] = '\0';
603    for(ii = 0; '\0' != files[ii]; ii++)
604      if('\015' == files[ii] || '\012' == files[ii])
605        files[ii] = '\0';
606
607    /* try to get a usable filename out of the URI supplied and add it */
608    for(ii = 0; ii < sel->length; ii += len + 1) {
609      if('\0' == files[ii])
610        len = 0;
611      else {
612        len = strlen(files + ii);
613        /* de-urlencode the URI */
614        decoded = urldecode(files + ii, len);
615        freeables = g_list_append(freeables, decoded);
616        if(g_utf8_validate(decoded, -1, NULL)) {
617          /* remove the file: prefix */
618          if(prelen < len && 0 == strncmp(prefix, decoded, prelen)) {
619            deslashed = decoded + prelen;
620            /* trim excess / characters from the beginning */
621            while('/' == deslashed[0] && '/' == deslashed[1])
622              deslashed++;
623            /* if the file doesn't exist, the first part might be a hostname */
624            if(0 > g_stat(deslashed, &sb) &&
625               NULL != (hostless = strchr(deslashed + 1, '/')) &&
626               0 == g_stat(hostless, &sb))
627              deslashed = hostless;
628            /* finally, add it to the list of torrents to try adding */
629            paths = g_list_append(paths, deslashed);
630          }
631        }
632      }
633    }
634
635    /* try to add any torrents we found */
636    if(NULL != paths)
637      addtorrents(data, NULL, paths, NULL,
638                  addactionflag(cf_getpref(PREF_ADDSTD)));
639    freestrlist(freeables);
640    g_free(files);
641  }
642
643  gtk_drag_finish(dc, (NULL != paths), FALSE, time);
644}
645
646void
647setupdrag(GtkWidget *widget, struct cbdata *data) {
648  GtkTargetEntry targets[] = {
649    { "STRING",     0, 0 },
650    { "text/plain", 0, 0 },
651    { "text/uri-list", 0, 0 },
652  };
653
654  g_signal_connect(widget, "drag_data_received", G_CALLBACK(gotdrag), data);
655
656  gtk_drag_dest_set(widget, GTK_DEST_DEFAULT_ALL, targets,
657                    ALEN(targets), GDK_ACTION_COPY | GDK_ACTION_MOVE);
658}
659
660/* kludge to have the progress bars notice theme changes */
661static void
662stylekludge(GObject *obj, GParamSpec *spec, gpointer gdata) {
663  if(0 == strcmp("style", spec->name)) {
664    tr_cell_renderer_progress_reset_style(TR_CELL_RENDERER_PROGRESS(gdata));
665    gtk_widget_queue_draw(GTK_WIDGET(obj));
666  }
667}
668
669/* disable buttons the user shouldn't be able to click on */
670void
671fixbuttons(GtkTreeSelection *sel, gpointer gdata) {
672  struct cbdata *data = gdata;
673  gboolean selected;
674  unsigned int ii;
675  int status;
676
677  if(NULL == sel)
678    sel = gtk_tree_view_get_selection(data->view);
679  status = 0;
680  gtk_tree_selection_selected_foreach(sel, orstatus, &status);
681  selected = (0 < gtk_tree_selection_count_selected_rows(sel));
682
683  for(ii = 0; ii < ALEN(actionitems); ii++)
684    if(actionitems[ii].avail)
685      gtk_widget_set_sensitive(data->buttons[ii],
686                               (selected && (actionitems[ii].avail & status)));
687}
688
689void
690dfname(GtkTreeViewColumn *col SHUTUP, GtkCellRenderer *rend,
691       GtkTreeModel *model, GtkTreeIter *iter, gpointer gdata SHUTUP) {
692  char *name, *mb, *terr, *str, *top, *bottom, *timestr;
693  guint64 size;
694  gfloat prog;
695  int status, err, eta, tpeers, upeers, dpeers;
696
697  gtk_tree_model_get(model, iter, MC_NAME, &name, MC_STAT, &status,
698    MC_ERR, &err, MC_SIZE, &size, MC_PROG, &prog, MC_ETA, &eta,
699    MC_PEERS, &tpeers, MC_UPEERS, &upeers, MC_DPEERS, &dpeers, -1);
700
701  if(0 > tpeers)
702    tpeers = 0;
703  if(0 > upeers)
704    upeers = 0;
705  if(0 > dpeers)
706    dpeers = 0;
707  mb = readablesize(size);
708  prog *= 100;
709
710  if(status & TR_STATUS_CHECK)
711    top = g_strdup_printf(_("Checking existing files (%.1f%%)"), prog);
712  else if(status & TR_STATUS_DOWNLOAD) {
713    if(0 > eta)
714      top = g_strdup_printf(_("Stalled (%.1f%%)"), prog);
715    else {
716      timestr = readabletime(eta);
717      top = g_strdup_printf(_("Finishing in %s (%.1f%%)"), timestr, prog);
718      g_free(timestr);
719    }
720  }
721  else if(status & TR_STATUS_SEED)
722    top = g_strdup_printf(ngettext("Seeding, uploading to %d of %d peer",
723                                   "Seeding, uploading to %d of %d peers",
724                                   tpeers), dpeers, tpeers);
725  else if(status & TR_STATUS_STOPPING)
726    top = g_strdup(_("Stopping..."));
727  else if(status & TR_STATUS_PAUSE)
728    top = g_strdup_printf(_("Stopped (%.1f%%)"), prog);
729  else {
730    top = g_strdup("");
731    g_assert_not_reached();
732  }
733
734  if(TR_NOERROR != err) {
735    gtk_tree_model_get(model, iter, MC_TERR, &terr, -1);
736    bottom = g_strconcat(_("Error: "), terr, NULL);
737    g_free(terr);
738  }
739  else if(status & TR_STATUS_DOWNLOAD)
740    bottom = g_strdup_printf(ngettext("Downloading from %i of %i peer",
741                                      "Downloading from %i of %i peers",
742                                      tpeers), upeers, tpeers);
743  else
744    bottom = NULL;
745
746  str = g_markup_printf_escaped("<big>%s (%s)</big>\n<small>%s\n%s</small>",
747                                name, mb, top, (NULL == bottom ? "" : bottom));
748  g_object_set(rend, "markup", str, NULL);
749  g_free(name);
750  g_free(mb);
751  g_free(str);
752  g_free(top);
753  if(NULL != bottom)
754    g_free(bottom);
755}
756
757void
758dfprog(GtkTreeViewColumn *col SHUTUP, GtkCellRenderer *rend,
759       GtkTreeModel *model, GtkTreeIter *iter, gpointer gdata SHUTUP) {
760  char *dlstr, *ulstr, *str, *marked;
761  gfloat prog, dl, ul;
762  guint64 down, up;
763
764  gtk_tree_model_get(model, iter, MC_PROG, &prog, MC_DRATE, &dl, MC_URATE, &ul,
765                     MC_DOWN, &down, MC_UP, &up, -1);
766  if(0.0 > prog)
767    prog = 0.0;
768  else if(1.0 < prog)
769    prog = 1.0;
770
771  ulstr = readablesize(ul * 1024.0);
772  if(1.0 == prog) {
773    dlstr = ratiostr(down, up);
774    str = g_strdup_printf(_("Ratio: %s\nUL: %s/s"), dlstr, ulstr);
775  } else {
776    dlstr = readablesize(dl * 1024.0);
777    str = g_strdup_printf(_("DL: %s/s\nUL: %s/s"), dlstr, ulstr);
778  }
779  marked = g_markup_printf_escaped("<small>%s</small>", str);
780  g_object_set(rend, "markup", str, "progress", prog, NULL);
781  g_free(dlstr);
782  g_free(ulstr);
783  g_free(str);
784  g_free(marked);
785}
786
787gboolean
788updatemodel(gpointer gdata) {
789  struct cbdata *data = gdata;
790  TrTorrent *tor;
791  tr_stat_t *st;
792  tr_info_t *in;
793  GtkTreeIter iter;
794  float up, down;
795  char *upstr, *downstr, *str;
796
797  if(0 < global_sigcount) {
798    quittransmission(data);
799    return FALSE;
800  }
801
802  if(gtk_tree_model_get_iter_first(data->model, &iter)) {
803    do {
804      gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor, -1);
805      st = tr_torrent_stat(tor);
806      in = tr_torrent_info(tor);
807      g_object_unref(tor);
808      /* XXX find out if setting the same data emits changed signal */
809      gtk_list_store_set(GTK_LIST_STORE(data->model), &iter, MC_NAME, in->name,
810        MC_SIZE, in->totalSize, MC_STAT, st->status, MC_ERR, st->error,
811        MC_TERR, st->trackerError, MC_PROG, st->progress,
812        MC_DRATE, st->rateDownload, MC_URATE, st->rateUpload, MC_ETA, st->eta,
813        MC_PEERS, st->peersTotal, MC_UPEERS, st->peersUploading,
814        MC_DPEERS, st->peersDownloading, MC_DOWN, st->downloaded,
815        MC_UP, st->uploaded, -1);
816    } while(gtk_tree_model_iter_next(data->model, &iter));
817  }
818
819  /* update the status bar */
820  tr_torrentRates(tr_backend_handle(data->back), &up, &down);
821  downstr = readablesize(down * 1024.0);
822  upstr = readablesize(up * 1024.0);
823  str = g_strdup_printf(_("     Total DL: %s/s     Total UL: %s/s"),
824                        upstr, downstr);
825  gtk_statusbar_pop(data->bar, 0);
826  gtk_statusbar_push(data->bar, 0, str);
827  g_free(str);
828  g_free(upstr);
829  g_free(downstr);
830
831  /* the status of the selected item may have changed, so update the buttons */
832  fixbuttons(NULL, data);
833
834  /* check for politely stopped torrents unless we're exiting */
835  if(!data->closing)
836    tr_backend_torrents_stopped(data->back);
837
838  /* update the message window */
839  msgwin_update();
840
841  return TRUE;
842}
843
844/* show a popup menu for a right-click on the list */
845gboolean
846listclick(GtkWidget *widget SHUTUP, GdkEventButton *event, gpointer gdata) {
847  struct cbdata *data = gdata;
848  GtkTreeSelection *sel = gtk_tree_view_get_selection(data->view);
849  GtkTreePath *path;
850  GtkTreeIter iter;
851  int status;
852  TrTorrent *tor, *issel;
853
854  if(GDK_BUTTON_PRESS == event->type && 3 == event->button) {
855    /* find what row, if any, the user clicked on */
856    if(!gtk_tree_view_get_path_at_pos(data->view, event->x, event->y, &path,
857                                      NULL, NULL, NULL))
858      gtk_tree_selection_unselect_all(sel);
859    else {
860      if(gtk_tree_model_get_iter(data->model, &iter, path)) {
861        /* get torrent and status for the right-clicked row */
862        gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor,
863                           MC_STAT, &status, -1);
864        issel = tor;
865        gtk_tree_selection_selected_foreach(sel, istorsel, &issel);
866        g_object_unref(tor);
867        /* if the clicked row isn't selected, select only it */
868        if(NULL != issel) {
869          gtk_tree_selection_unselect_all(sel);
870          gtk_tree_selection_select_iter(sel, &iter);
871        }
872      }
873      gtk_tree_path_free(path);
874    }
875    dopopupmenu(event, data);
876    return TRUE;
877  }
878
879  return FALSE;
880}
881
882gboolean
883listpopup(GtkWidget *widget SHUTUP, gpointer gdata) {
884  dopopupmenu(NULL, gdata);
885  return TRUE;
886}
887
888void
889dopopupmenu(GdkEventButton *event, struct cbdata *data) {
890  GtkTreeSelection *sel = gtk_tree_view_get_selection(data->view);
891  int count = gtk_tree_selection_count_selected_rows(sel);
892  GtkWidget *menu = gtk_menu_new();
893  GtkWidget *item;
894  unsigned int ii;
895  int status = 0;
896
897  if(NULL != data->stupidpopuphack)
898    gtk_widget_destroy(data->stupidpopuphack);
899  data->stupidpopuphack = menu;
900
901  status = 0;
902  gtk_tree_selection_selected_foreach(sel, orstatus, &status);
903
904  for(ii = 0; ii < ALEN(actionitems); ii++) {
905    if(actionitems[ii].nomenu ||
906       (actionitems[ii].avail &&
907        (0 == count || !(actionitems[ii].avail & status))))
908      continue;
909    item = gtk_menu_item_new_with_label(gettext(actionitems[ii].name));
910    /* set the action for the menu item */
911    g_object_set_data(G_OBJECT(item), LIST_ACTION,
912                      GINT_TO_POINTER(actionitems[ii].act));
913    g_signal_connect(G_OBJECT(item), "activate",
914                     G_CALLBACK(actionclick), data);
915    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
916  }
917
918  gtk_widget_show_all(menu);
919
920  gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
921                 (NULL == event ? 0 : event->button),
922                 gdk_event_get_time((GdkEvent*)event));
923}
924
925void
926boolwindclosed(GtkWidget *widget SHUTUP, gpointer gdata) {
927  gboolean *preachy_gcc = gdata;
928 
929  *preachy_gcc = FALSE;
930}
931
932void
933actionclick(GtkWidget *widget, gpointer gdata) {
934  struct cbdata *data = gdata;
935  enum listact act;
936  GtkTreeSelection *sel;
937  GList *rows, *ii;
938  GtkTreeRowReference *ref;
939  GtkTreePath *path;
940  GtkTreeIter iter;
941  TrTorrent *tor;
942  unsigned int actoff, status;
943  gboolean changed;
944  GtkWidget * win;
945
946  act = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), LIST_ACTION));
947
948  switch(act) {
949    case ACT_OPEN:
950      makeaddwind(data->wind, addtorrents, data);
951      return;
952    case ACT_PREF:
953      if( !data->prefsopen ) {
954        data->prefsopen = TRUE;
955        win = makeprefwindow( data->wind, data->back );
956        g_signal_connect( win, "destroy", G_CALLBACK( boolwindclosed ),
957                          &data->prefsopen );
958      }
959      return;
960    case ACT_DEBUG:
961      if( !data->msgwinopen ) {
962        data->msgwinopen = TRUE;
963        win = msgwin_create();
964        g_signal_connect( win, "destroy", G_CALLBACK( boolwindclosed ),
965                          &data->msgwinopen );
966      }
967      return;
968    case ACT_START:
969    case ACT_STOP:
970    case ACT_DELETE:
971    case ACT_INFO:
972      break;
973  }
974
975  sel = gtk_tree_view_get_selection(data->view);
976  rows = gtk_tree_selection_get_selected_rows(sel, NULL);
977
978  for(ii = rows; NULL != ii; ii = ii->next) {
979    ref = gtk_tree_row_reference_new(data->model, ii->data);
980    gtk_tree_path_free(ii->data);
981    ii->data = ref;
982  }
983
984  for(actoff = 0; actoff < ALEN(actionitems); actoff++)
985    if(actionitems[actoff].act == act)
986      break;
987  g_assert(actoff < ALEN(actionitems));
988
989  changed = FALSE;
990  for(ii = rows; NULL != ii; ii = ii->next) {
991    if(NULL != (path = gtk_tree_row_reference_get_path(ii->data)) &&
992       gtk_tree_model_get_iter(data->model, &iter, path)) {
993      gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor,
994                         MC_STAT, &status, -1);
995      /* check if this action is valid for this torrent */
996      if((!actionitems[actoff].avail || actionitems[actoff].avail & status) &&
997         !actionitems[actoff].nomenu) {
998        switch(act) {
999          case ACT_START:
1000            tr_torrentStart(tr_torrent_handle(tor));
1001            changed = TRUE;
1002            break;
1003          case ACT_STOP:
1004            tr_torrentStop(tr_torrent_handle(tor));
1005            changed = TRUE;
1006            break;
1007          case ACT_DELETE:
1008            /* tor will be unref'd in the politely_stopped signal handler */
1009            g_object_ref(tor);
1010            tr_torrent_stop_politely(tor);
1011            if(TR_FSAVEPRIVATE & tr_torrent_info(tor)->flags)
1012              tr_torrentRemoveSaved(tr_torrent_handle(tor));
1013            gtk_list_store_remove(GTK_LIST_STORE(data->model), &iter);
1014            changed = TRUE;
1015            break;
1016          case ACT_INFO:
1017            makeinfowind(data->wind, tor);
1018            break;
1019          case ACT_OPEN:
1020          case ACT_PREF:
1021          case ACT_DEBUG:
1022            break;
1023        }
1024      }
1025      g_object_unref(tor);
1026    }
1027    if(NULL != path)
1028      gtk_tree_path_free(path);
1029    gtk_tree_row_reference_free(ii->data);
1030  }
1031  g_list_free(rows);
1032
1033  if(changed) {
1034    savetorrents(data);
1035    updatemodel(data);
1036  }
1037}
1038
1039gint
1040intrevcmp(gconstpointer a, gconstpointer b) {
1041  int aint = GPOINTER_TO_INT(a);
1042  int bint = GPOINTER_TO_INT(b);
1043
1044  if(bint > aint)
1045    return 1;
1046  else if(bint < aint)
1047    return -1;
1048  else
1049    return 0;
1050}
1051
1052void
1053doubleclick(GtkWidget *widget SHUTUP, GtkTreePath *path,
1054            GtkTreeViewColumn *col SHUTUP, gpointer gdata) {
1055  struct cbdata *data = gdata;
1056  GtkTreeIter iter;
1057  TrTorrent *tor;
1058
1059  if(gtk_tree_model_get_iter(data->model, &iter, path)) {
1060    gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor, -1);
1061    makeinfowind(data->wind, tor);
1062    g_object_unref(tor);
1063  }
1064}
1065
1066void
1067addtorrents(void *vdata, void *state, GList *files,
1068            const char *dir, guint flags) {
1069  struct cbdata *data = vdata;
1070  GList *torlist, *errlist, *ii;
1071  char *errstr;
1072  TrTorrent *tor;
1073  GtkTreeIter iter;
1074  char *wd;
1075
1076  errlist = NULL;
1077  torlist = NULL;
1078
1079  if(NULL != state)
1080    torlist = tr_backend_load_state(data->back, state, &errlist);
1081
1082  if(NULL != files) {
1083    if(NULL == dir)
1084      dir = cf_getpref(PREF_DIR);
1085    wd = NULL;
1086    if(NULL == dir) {
1087      wd = g_new(char, MAX_PATH_LENGTH + 1);
1088      if(NULL == getcwd(wd, MAX_PATH_LENGTH + 1))
1089        dir = ".";
1090      else
1091        dir = wd;
1092    }
1093    for(ii = g_list_first(files); NULL != ii; ii = ii->next) {
1094      errstr = NULL;
1095      tor = tr_torrent_new(G_OBJECT(data->back), ii->data, dir,
1096                           flags, &errstr);
1097      if(NULL != tor)
1098        torlist = g_list_append(torlist, tor);
1099      if(NULL != errstr)
1100        errlist = g_list_append(errlist, errstr);
1101    }
1102    if(NULL != wd)
1103      g_free(wd);
1104  }
1105
1106  for(ii = g_list_first(torlist); NULL != ii; ii = ii->next) {
1107    gtk_list_store_append(GTK_LIST_STORE(data->model), &iter);
1108    gtk_list_store_set(GTK_LIST_STORE(data->model), &iter,
1109                       MC_TORRENT, ii->data, -1);
1110    /* we will always ref a torrent before politely stopping it */
1111    g_signal_connect(ii->data, "politely_stopped",
1112                     G_CALLBACK(g_object_unref), data);
1113    g_object_unref(ii->data);
1114  }
1115
1116  if(NULL != errlist) {
1117    errstr = joinstrlist(errlist, "\n");
1118    errmsg(data->wind, ngettext("Failed to load torrent file:\n%s",
1119                                "Failed to load torrent files:\n%s",
1120                                g_list_length(errlist)), errstr);
1121    g_list_foreach(errlist, (GFunc)g_free, NULL);
1122    g_list_free(errlist);
1123    g_free(errstr);
1124  }
1125
1126  if(NULL != torlist) {
1127    updatemodel(data);
1128    savetorrents(data);
1129  }
1130}
1131
1132void
1133savetorrents(struct cbdata *data) {
1134  char *errstr;
1135
1136  tr_backend_save_state(data->back, &errstr);
1137  if(NULL != errstr) {
1138    errmsg(data->wind, "%s", errstr);
1139    g_free(errstr);
1140  }
1141}
1142
1143/* use with gtk_tree_selection_selected_foreach to | status of selected rows */
1144void
1145orstatus(GtkTreeModel *model, GtkTreePath *path SHUTUP, GtkTreeIter *iter,
1146         gpointer gdata) {
1147  int *allstatus = gdata;
1148  int status;
1149
1150  gtk_tree_model_get(model, iter, MC_STAT, &status, -1);
1151  *allstatus |= status;
1152}
1153
1154/* data should be a TrTorrent**, will set torrent to NULL if it's selected */
1155void
1156istorsel(GtkTreeModel *model, GtkTreePath *path SHUTUP, GtkTreeIter *iter,
1157         gpointer gdata) {
1158  TrTorrent **torref = gdata;
1159  TrTorrent *tor;
1160
1161  if(NULL != *torref) {
1162    gtk_tree_model_get(model, iter, MC_TORRENT, &tor, -1);
1163    if(tor == *torref)
1164      *torref = NULL;
1165    g_object_unref(tor);
1166  }
1167}
1168
1169void
1170safepipe(void) {
1171  struct sigaction sa;
1172
1173  bzero(&sa, sizeof(sa));
1174  sa.sa_handler = SIG_IGN;
1175  sigaction(SIGPIPE, &sa, NULL);
1176}
1177
1178void
1179setupsighandlers(void) {
1180  int sigs[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2};
1181  struct sigaction sa;
1182  unsigned int ii;
1183
1184  bzero(&sa, sizeof(sa));
1185  sa.sa_handler = fatalsig;
1186  for(ii = 0; ii < ALEN(sigs); ii++)
1187    sigaction(sigs[ii], &sa, NULL);
1188}
1189
1190void
1191fatalsig(int sig) {
1192  struct sigaction sa;
1193
1194  if(SIGCOUNT_MAX <= ++global_sigcount) {
1195    bzero(&sa, sizeof(sa));
1196    sa.sa_handler = SIG_DFL;
1197    sigaction(sig, &sa, NULL);
1198    raise(sig);
1199  }
1200}
Note: See TracBrowser for help on using the repository browser.