source: trunk/gtk/main.c @ 1125

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

Fix a stupid mistake that could cause the fastresume data to not be saved on exit.

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