source: trunk/gtk/main.c @ 891

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

Fix logic error in exit check.

  • Property svn:keywords set to Date Rev Author Id
File size: 36.1 KB
Line 
1/******************************************************************************
2 * $Id: main.c 891 2006-09-23 06:29:32Z 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       TR_NAT_TRAVERSAL_DISABLED != natstat ) ) {
552    updatemodel( data->cbdata );
553    return TRUE;
554  }
555
556  /* exit otherwise */
557  if(0 < data->timer)
558    g_source_remove(data->timer);
559  quittransmission(data->cbdata);
560  g_free(data);
561
562  return FALSE;
563}
564
565void
566gotdrag(GtkWidget *widget SHUTUP, GdkDragContext *dc, gint x SHUTUP,
567        gint y SHUTUP, GtkSelectionData *sel, guint info SHUTUP, guint time,
568        gpointer gdata) {
569  struct cbdata *data = gdata;
570  char prefix[] = "file:";
571  char *files, *decoded, *deslashed, *hostless;
572  int ii, len;
573  GList *errs;
574  struct stat sb;
575  int prelen = strlen(prefix);
576  GList *paths, *freeables;
577
578#ifdef DND_DEBUG
579  char *sele = gdk_atom_name(sel->selection);
580  char *targ = gdk_atom_name(sel->target);
581  char *type = gdk_atom_name(sel->type);
582
583  fprintf(stderr, "dropped file: sel=%s targ=%s type=%s fmt=%i len=%i\n",
584          sele, targ, type, sel->format, sel->length);
585  g_free(sele);
586  g_free(targ);
587  g_free(type);
588  if(8 == sel->format) {
589    for(ii = 0; ii < sel->length; ii++)
590      fprintf(stderr, "%02X ", sel->data[ii]);
591    fprintf(stderr, "\n");
592  }
593#endif
594
595  errs = NULL;
596  paths = NULL;
597  freeables = NULL;
598  if(gdk_atom_intern("XdndSelection", FALSE) == sel->selection &&
599     8 == sel->format) {
600    /* split file list on carriage returns and linefeeds */
601    files = g_new(char, sel->length + 1);
602    memcpy(files, sel->data, sel->length);
603    files[sel->length] = '\0';
604    for(ii = 0; '\0' != files[ii]; ii++)
605      if('\015' == files[ii] || '\012' == files[ii])
606        files[ii] = '\0';
607
608    /* try to get a usable filename out of the URI supplied and add it */
609    for(ii = 0; ii < sel->length; ii += len + 1) {
610      if('\0' == files[ii])
611        len = 0;
612      else {
613        len = strlen(files + ii);
614        /* de-urlencode the URI */
615        decoded = urldecode(files + ii, len);
616        freeables = g_list_append(freeables, decoded);
617        if(g_utf8_validate(decoded, -1, NULL)) {
618          /* remove the file: prefix */
619          if(prelen < len && 0 == strncmp(prefix, decoded, prelen)) {
620            deslashed = decoded + prelen;
621            /* trim excess / characters from the beginning */
622            while('/' == deslashed[0] && '/' == deslashed[1])
623              deslashed++;
624            /* if the file doesn't exist, the first part might be a hostname */
625            if(0 > g_stat(deslashed, &sb) &&
626               NULL != (hostless = strchr(deslashed + 1, '/')) &&
627               0 == g_stat(hostless, &sb))
628              deslashed = hostless;
629            /* finally, add it to the list of torrents to try adding */
630            paths = g_list_append(paths, deslashed);
631          }
632        }
633      }
634    }
635
636    /* try to add any torrents we found */
637    if(NULL != paths)
638      addtorrents(data, NULL, paths, NULL,
639                  addactionflag(cf_getpref(PREF_ADDSTD)));
640    freestrlist(freeables);
641    g_free(files);
642  }
643
644  gtk_drag_finish(dc, (NULL != paths), FALSE, time);
645}
646
647void
648setupdrag(GtkWidget *widget, struct cbdata *data) {
649  GtkTargetEntry targets[] = {
650    { "STRING",     0, 0 },
651    { "text/plain", 0, 0 },
652    { "text/uri-list", 0, 0 },
653  };
654
655  g_signal_connect(widget, "drag_data_received", G_CALLBACK(gotdrag), data);
656
657  gtk_drag_dest_set(widget, GTK_DEST_DEFAULT_ALL, targets,
658                    ALEN(targets), GDK_ACTION_COPY | GDK_ACTION_MOVE);
659}
660
661/* kludge to have the progress bars notice theme changes */
662static void
663stylekludge(GObject *obj, GParamSpec *spec, gpointer gdata) {
664  if(0 == strcmp("style", spec->name)) {
665    tr_cell_renderer_progress_reset_style(TR_CELL_RENDERER_PROGRESS(gdata));
666    gtk_widget_queue_draw(GTK_WIDGET(obj));
667  }
668}
669
670/* disable buttons the user shouldn't be able to click on */
671void
672fixbuttons(GtkTreeSelection *sel, gpointer gdata) {
673  struct cbdata *data = gdata;
674  gboolean selected;
675  unsigned int ii;
676  int status;
677
678  if(NULL == sel)
679    sel = gtk_tree_view_get_selection(data->view);
680  status = 0;
681  gtk_tree_selection_selected_foreach(sel, orstatus, &status);
682  selected = (0 < gtk_tree_selection_count_selected_rows(sel));
683
684  for(ii = 0; ii < ALEN(actionitems); ii++)
685    if(actionitems[ii].avail)
686      gtk_widget_set_sensitive(data->buttons[ii],
687                               (selected && (actionitems[ii].avail & status)));
688}
689
690void
691dfname(GtkTreeViewColumn *col SHUTUP, GtkCellRenderer *rend,
692       GtkTreeModel *model, GtkTreeIter *iter, gpointer gdata SHUTUP) {
693  char *name, *mb, *terr, *str, *top, *bottom, *timestr;
694  guint64 size;
695  gfloat prog;
696  int status, err, eta, tpeers, upeers, dpeers;
697
698  gtk_tree_model_get(model, iter, MC_NAME, &name, MC_STAT, &status,
699    MC_ERR, &err, MC_SIZE, &size, MC_PROG, &prog, MC_ETA, &eta,
700    MC_PEERS, &tpeers, MC_UPEERS, &upeers, MC_DPEERS, &dpeers, -1);
701
702  if(0 > tpeers)
703    tpeers = 0;
704  if(0 > upeers)
705    upeers = 0;
706  if(0 > dpeers)
707    dpeers = 0;
708  mb = readablesize(size);
709  prog *= 100;
710
711  if(status & TR_STATUS_CHECK)
712    top = g_strdup_printf(_("Checking existing files (%.1f%%)"), prog);
713  else if(status & TR_STATUS_DOWNLOAD) {
714    if(0 > eta)
715      top = g_strdup_printf(_("Stalled (%.1f%%)"), prog);
716    else {
717      timestr = readabletime(eta);
718      top = g_strdup_printf(_("Finishing in %s (%.1f%%)"), timestr, prog);
719      g_free(timestr);
720    }
721  }
722  else if(status & TR_STATUS_SEED)
723    top = g_strdup_printf(ngettext("Seeding, uploading to %d of %d peer",
724                                   "Seeding, uploading to %d of %d peers",
725                                   tpeers), dpeers, tpeers);
726  else if(status & TR_STATUS_STOPPING)
727    top = g_strdup(_("Stopping..."));
728  else if(status & TR_STATUS_PAUSE)
729    top = g_strdup_printf(_("Stopped (%.1f%%)"), prog);
730  else {
731    top = g_strdup("");
732    g_assert_not_reached();
733  }
734
735  if(TR_NOERROR != err) {
736    gtk_tree_model_get(model, iter, MC_TERR, &terr, -1);
737    bottom = g_strconcat(_("Error: "), terr, NULL);
738    g_free(terr);
739  }
740  else if(status & TR_STATUS_DOWNLOAD)
741    bottom = g_strdup_printf(ngettext("Downloading from %i of %i peer",
742                                      "Downloading from %i of %i peers",
743                                      tpeers), upeers, tpeers);
744  else
745    bottom = NULL;
746
747  str = g_markup_printf_escaped("<big>%s (%s)</big>\n<small>%s\n%s</small>",
748                                name, mb, top, (NULL == bottom ? "" : bottom));
749  g_object_set(rend, "markup", str, NULL);
750  g_free(name);
751  g_free(mb);
752  g_free(str);
753  g_free(top);
754  if(NULL != bottom)
755    g_free(bottom);
756}
757
758void
759dfprog(GtkTreeViewColumn *col SHUTUP, GtkCellRenderer *rend,
760       GtkTreeModel *model, GtkTreeIter *iter, gpointer gdata SHUTUP) {
761  char *dlstr, *ulstr, *str, *marked;
762  gfloat prog, dl, ul;
763  guint64 down, up;
764
765  gtk_tree_model_get(model, iter, MC_PROG, &prog, MC_DRATE, &dl, MC_URATE, &ul,
766                     MC_DOWN, &down, MC_UP, &up, -1);
767  if(0.0 > prog)
768    prog = 0.0;
769  else if(1.0 < prog)
770    prog = 1.0;
771
772  ulstr = readablesize(ul * 1024.0);
773  if(1.0 == prog) {
774    dlstr = ratiostr(down, up);
775    str = g_strdup_printf(_("Ratio: %s\nUL: %s/s"), dlstr, ulstr);
776  } else {
777    dlstr = readablesize(dl * 1024.0);
778    str = g_strdup_printf(_("DL: %s/s\nUL: %s/s"), dlstr, ulstr);
779  }
780  marked = g_markup_printf_escaped("<small>%s</small>", str);
781  g_object_set(rend, "markup", str, "progress", prog, NULL);
782  g_free(dlstr);
783  g_free(ulstr);
784  g_free(str);
785  g_free(marked);
786}
787
788gboolean
789updatemodel(gpointer gdata) {
790  struct cbdata *data = gdata;
791  TrTorrent *tor;
792  tr_stat_t *st;
793  tr_info_t *in;
794  GtkTreeIter iter;
795  float up, down;
796  char *upstr, *downstr, *str;
797
798  if(0 < global_sigcount) {
799    quittransmission(data);
800    return FALSE;
801  }
802
803  if(gtk_tree_model_get_iter_first(data->model, &iter)) {
804    do {
805      gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor, -1);
806      st = tr_torrent_stat(tor);
807      in = tr_torrent_info(tor);
808      g_object_unref(tor);
809      /* XXX find out if setting the same data emits changed signal */
810      gtk_list_store_set(GTK_LIST_STORE(data->model), &iter, MC_NAME, in->name,
811        MC_SIZE, in->totalSize, MC_STAT, st->status, MC_ERR, st->error,
812        MC_TERR, st->trackerError, MC_PROG, st->progress,
813        MC_DRATE, st->rateDownload, MC_URATE, st->rateUpload, MC_ETA, st->eta,
814        MC_PEERS, st->peersTotal, MC_UPEERS, st->peersUploading,
815        MC_DPEERS, st->peersDownloading, MC_DOWN, st->downloaded,
816        MC_UP, st->uploaded, -1);
817    } while(gtk_tree_model_iter_next(data->model, &iter));
818  }
819
820  /* update the status bar */
821  tr_torrentRates(tr_backend_handle(data->back), &up, &down);
822  downstr = readablesize(down * 1024.0);
823  upstr = readablesize(up * 1024.0);
824  str = g_strdup_printf(_("     Total DL: %s/s     Total UL: %s/s"),
825                        upstr, downstr);
826  gtk_statusbar_pop(data->bar, 0);
827  gtk_statusbar_push(data->bar, 0, str);
828  g_free(str);
829  g_free(upstr);
830  g_free(downstr);
831
832  /* the status of the selected item may have changed, so update the buttons */
833  fixbuttons(NULL, data);
834
835  /* check for politely stopped torrents unless we're exiting */
836  if(!data->closing)
837    tr_backend_torrents_stopped(data->back);
838
839  /* update the message window */
840  msgwin_update();
841
842  return TRUE;
843}
844
845/* show a popup menu for a right-click on the list */
846gboolean
847listclick(GtkWidget *widget SHUTUP, GdkEventButton *event, gpointer gdata) {
848  struct cbdata *data = gdata;
849  GtkTreeSelection *sel = gtk_tree_view_get_selection(data->view);
850  GtkTreePath *path;
851  GtkTreeIter iter;
852  int status;
853  TrTorrent *tor, *issel;
854
855  if(GDK_BUTTON_PRESS == event->type && 3 == event->button) {
856    /* find what row, if any, the user clicked on */
857    if(!gtk_tree_view_get_path_at_pos(data->view, event->x, event->y, &path,
858                                      NULL, NULL, NULL))
859      gtk_tree_selection_unselect_all(sel);
860    else {
861      if(gtk_tree_model_get_iter(data->model, &iter, path)) {
862        /* get torrent and status for the right-clicked row */
863        gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor,
864                           MC_STAT, &status, -1);
865        issel = tor;
866        gtk_tree_selection_selected_foreach(sel, istorsel, &issel);
867        g_object_unref(tor);
868        /* if the clicked row isn't selected, select only it */
869        if(NULL != issel) {
870          gtk_tree_selection_unselect_all(sel);
871          gtk_tree_selection_select_iter(sel, &iter);
872        }
873      }
874      gtk_tree_path_free(path);
875    }
876    dopopupmenu(event, data);
877    return TRUE;
878  }
879
880  return FALSE;
881}
882
883gboolean
884listpopup(GtkWidget *widget SHUTUP, gpointer gdata) {
885  dopopupmenu(NULL, gdata);
886  return TRUE;
887}
888
889void
890dopopupmenu(GdkEventButton *event, struct cbdata *data) {
891  GtkTreeSelection *sel = gtk_tree_view_get_selection(data->view);
892  int count = gtk_tree_selection_count_selected_rows(sel);
893  GtkWidget *menu = gtk_menu_new();
894  GtkWidget *item;
895  unsigned int ii;
896  int status = 0;
897
898  if(NULL != data->stupidpopuphack)
899    gtk_widget_destroy(data->stupidpopuphack);
900  data->stupidpopuphack = menu;
901
902  status = 0;
903  gtk_tree_selection_selected_foreach(sel, orstatus, &status);
904
905  for(ii = 0; ii < ALEN(actionitems); ii++) {
906    if(actionitems[ii].nomenu ||
907       (actionitems[ii].avail &&
908        (0 == count || !(actionitems[ii].avail & status))))
909      continue;
910    item = gtk_menu_item_new_with_label(gettext(actionitems[ii].name));
911    /* set the action for the menu item */
912    g_object_set_data(G_OBJECT(item), LIST_ACTION,
913                      GINT_TO_POINTER(actionitems[ii].act));
914    g_signal_connect(G_OBJECT(item), "activate",
915                     G_CALLBACK(actionclick), data);
916    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
917  }
918
919  gtk_widget_show_all(menu);
920
921  gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
922                 (NULL == event ? 0 : event->button),
923                 gdk_event_get_time((GdkEvent*)event));
924}
925
926void
927boolwindclosed(GtkWidget *widget SHUTUP, gpointer gdata) {
928  gboolean *preachy_gcc = gdata;
929 
930  *preachy_gcc = FALSE;
931}
932
933void
934actionclick(GtkWidget *widget, gpointer gdata) {
935  struct cbdata *data = gdata;
936  enum listact act;
937  GtkTreeSelection *sel;
938  GList *rows, *ii;
939  GtkTreeRowReference *ref;
940  GtkTreePath *path;
941  GtkTreeIter iter;
942  TrTorrent *tor;
943  unsigned int actoff, status;
944  gboolean changed;
945  GtkWidget * win;
946
947  act = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), LIST_ACTION));
948
949  switch(act) {
950    case ACT_OPEN:
951      makeaddwind(data->wind, addtorrents, data);
952      return;
953    case ACT_PREF:
954      if( !data->prefsopen ) {
955        data->prefsopen = TRUE;
956        win = makeprefwindow( data->wind, data->back );
957        g_signal_connect( win, "destroy", G_CALLBACK( boolwindclosed ),
958                          &data->prefsopen );
959      }
960      return;
961    case ACT_DEBUG:
962      if( !data->msgwinopen ) {
963        data->msgwinopen = TRUE;
964        win = msgwin_create();
965        g_signal_connect( win, "destroy", G_CALLBACK( boolwindclosed ),
966                          &data->msgwinopen );
967      }
968      return;
969    case ACT_START:
970    case ACT_STOP:
971    case ACT_DELETE:
972    case ACT_INFO:
973      break;
974  }
975
976  sel = gtk_tree_view_get_selection(data->view);
977  rows = gtk_tree_selection_get_selected_rows(sel, NULL);
978
979  for(ii = rows; NULL != ii; ii = ii->next) {
980    ref = gtk_tree_row_reference_new(data->model, ii->data);
981    gtk_tree_path_free(ii->data);
982    ii->data = ref;
983  }
984
985  for(actoff = 0; actoff < ALEN(actionitems); actoff++)
986    if(actionitems[actoff].act == act)
987      break;
988  g_assert(actoff < ALEN(actionitems));
989
990  changed = FALSE;
991  for(ii = rows; NULL != ii; ii = ii->next) {
992    if(NULL != (path = gtk_tree_row_reference_get_path(ii->data)) &&
993       gtk_tree_model_get_iter(data->model, &iter, path)) {
994      gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor,
995                         MC_STAT, &status, -1);
996      /* check if this action is valid for this torrent */
997      if((!actionitems[actoff].avail || actionitems[actoff].avail & status) &&
998         !actionitems[actoff].nomenu) {
999        switch(act) {
1000          case ACT_START:
1001            tr_torrentStart(tr_torrent_handle(tor));
1002            changed = TRUE;
1003            break;
1004          case ACT_STOP:
1005            tr_torrentStop(tr_torrent_handle(tor));
1006            changed = TRUE;
1007            break;
1008          case ACT_DELETE:
1009            /* tor will be unref'd in the politely_stopped signal handler */
1010            g_object_ref(tor);
1011            tr_torrent_stop_politely(tor);
1012            if(TR_FSAVEPRIVATE & tr_torrent_info(tor)->flags)
1013              tr_torrentRemoveSaved(tr_torrent_handle(tor));
1014            gtk_list_store_remove(GTK_LIST_STORE(data->model), &iter);
1015            changed = TRUE;
1016            break;
1017          case ACT_INFO:
1018            makeinfowind(data->wind, tor);
1019            break;
1020          case ACT_OPEN:
1021          case ACT_PREF:
1022          case ACT_DEBUG:
1023            break;
1024        }
1025      }
1026      g_object_unref(tor);
1027    }
1028    if(NULL != path)
1029      gtk_tree_path_free(path);
1030    gtk_tree_row_reference_free(ii->data);
1031  }
1032  g_list_free(rows);
1033
1034  if(changed) {
1035    savetorrents(data);
1036    updatemodel(data);
1037  }
1038}
1039
1040gint
1041intrevcmp(gconstpointer a, gconstpointer b) {
1042  int aint = GPOINTER_TO_INT(a);
1043  int bint = GPOINTER_TO_INT(b);
1044
1045  if(bint > aint)
1046    return 1;
1047  else if(bint < aint)
1048    return -1;
1049  else
1050    return 0;
1051}
1052
1053void
1054doubleclick(GtkWidget *widget SHUTUP, GtkTreePath *path,
1055            GtkTreeViewColumn *col SHUTUP, gpointer gdata) {
1056  struct cbdata *data = gdata;
1057  GtkTreeIter iter;
1058  TrTorrent *tor;
1059
1060  if(gtk_tree_model_get_iter(data->model, &iter, path)) {
1061    gtk_tree_model_get(data->model, &iter, MC_TORRENT, &tor, -1);
1062    makeinfowind(data->wind, tor);
1063    g_object_unref(tor);
1064  }
1065}
1066
1067void
1068addtorrents(void *vdata, void *state, GList *files,
1069            const char *dir, guint flags) {
1070  struct cbdata *data = vdata;
1071  GList *torlist, *errlist, *ii;
1072  char *errstr;
1073  TrTorrent *tor;
1074  GtkTreeIter iter;
1075  char *wd;
1076
1077  errlist = NULL;
1078  torlist = NULL;
1079
1080  if(NULL != state)
1081    torlist = tr_backend_load_state(data->back, state, &errlist);
1082
1083  if(NULL != files) {
1084    if(NULL == dir)
1085      dir = cf_getpref(PREF_DIR);
1086    wd = NULL;
1087    if(NULL == dir) {
1088      wd = g_new(char, MAX_PATH_LENGTH + 1);
1089      if(NULL == getcwd(wd, MAX_PATH_LENGTH + 1))
1090        dir = ".";
1091      else
1092        dir = wd;
1093    }
1094    for(ii = g_list_first(files); NULL != ii; ii = ii->next) {
1095      errstr = NULL;
1096      tor = tr_torrent_new(G_OBJECT(data->back), ii->data, dir,
1097                           flags, &errstr);
1098      if(NULL != tor)
1099        torlist = g_list_append(torlist, tor);
1100      if(NULL != errstr)
1101        errlist = g_list_append(errlist, errstr);
1102    }
1103    if(NULL != wd)
1104      g_free(wd);
1105  }
1106
1107  for(ii = g_list_first(torlist); NULL != ii; ii = ii->next) {
1108    gtk_list_store_append(GTK_LIST_STORE(data->model), &iter);
1109    gtk_list_store_set(GTK_LIST_STORE(data->model), &iter,
1110                       MC_TORRENT, ii->data, -1);
1111    /* we will always ref a torrent before politely stopping it */
1112    g_signal_connect(ii->data, "politely_stopped",
1113                     G_CALLBACK(g_object_unref), data);
1114    g_object_unref(ii->data);
1115  }
1116
1117  if(NULL != errlist) {
1118    errstr = joinstrlist(errlist, "\n");
1119    errmsg(data->wind, ngettext("Failed to load torrent file:\n%s",
1120                                "Failed to load torrent files:\n%s",
1121                                g_list_length(errlist)), errstr);
1122    g_list_foreach(errlist, (GFunc)g_free, NULL);
1123    g_list_free(errlist);
1124    g_free(errstr);
1125  }
1126
1127  if(NULL != torlist) {
1128    updatemodel(data);
1129    savetorrents(data);
1130  }
1131}
1132
1133void
1134savetorrents(struct cbdata *data) {
1135  char *errstr;
1136
1137  tr_backend_save_state(data->back, &errstr);
1138  if(NULL != errstr) {
1139    errmsg(data->wind, "%s", errstr);
1140    g_free(errstr);
1141  }
1142}
1143
1144/* use with gtk_tree_selection_selected_foreach to | status of selected rows */
1145void
1146orstatus(GtkTreeModel *model, GtkTreePath *path SHUTUP, GtkTreeIter *iter,
1147         gpointer gdata) {
1148  int *allstatus = gdata;
1149  int status;
1150
1151  gtk_tree_model_get(model, iter, MC_STAT, &status, -1);
1152  *allstatus |= status;
1153}
1154
1155/* data should be a TrTorrent**, will set torrent to NULL if it's selected */
1156void
1157istorsel(GtkTreeModel *model, GtkTreePath *path SHUTUP, GtkTreeIter *iter,
1158         gpointer gdata) {
1159  TrTorrent **torref = gdata;
1160  TrTorrent *tor;
1161
1162  if(NULL != *torref) {
1163    gtk_tree_model_get(model, iter, MC_TORRENT, &tor, -1);
1164    if(tor == *torref)
1165      *torref = NULL;
1166    g_object_unref(tor);
1167  }
1168}
1169
1170void
1171safepipe(void) {
1172  struct sigaction sa;
1173
1174  bzero(&sa, sizeof(sa));
1175  sa.sa_handler = SIG_IGN;
1176  sigaction(SIGPIPE, &sa, NULL);
1177}
1178
1179void
1180setupsighandlers(void) {
1181  int sigs[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2};
1182  struct sigaction sa;
1183  unsigned int ii;
1184
1185  bzero(&sa, sizeof(sa));
1186  sa.sa_handler = fatalsig;
1187  for(ii = 0; ii < ALEN(sigs); ii++)
1188    sigaction(sigs[ii], &sa, NULL);
1189}
1190
1191void
1192fatalsig(int sig) {
1193  struct sigaction sa;
1194
1195  if(SIGCOUNT_MAX <= ++global_sigcount) {
1196    bzero(&sa, sizeof(sa));
1197    sa.sa_handler = SIG_DFL;
1198    sigaction(sig, &sa, NULL);
1199    raise(sig);
1200  }
1201}
Note: See TracBrowser for help on using the repository browser.