source: trunk/gtk/main.c @ 2491

Last change on this file since 2491 was 2491, checked in by charles, 15 years ago

gtk: fix minor "unused variable" warning.

  • Property svn:keywords set to Date Rev Author Id
File size: 32.1 KB
Line 
1/******************************************************************************
2 * $Id: main.c 2491 2007-07-25 16:04:27Z charles $
3 *
4 * Copyright (c) 2005-2007 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 <getopt.h>
28#include <signal.h>
29#include <string.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <time.h>
33#include <unistd.h>
34
35#include <gtk/gtk.h>
36#include <glib/gi18n.h>
37#include <glib/gstdio.h>
38
39#include "actions.h"
40#include "conf.h"
41#include "dialogs.h"
42#include "ipc.h"
43#include "makemeta-ui.h"
44#include "msgwin.h"
45#include "torrent-inspector.h"
46#include "tr_cell_renderer_progress.h"
47#include "tr_core.h"
48#include "tr_icon.h"
49#include "tr_prefs.h"
50#include "tr_torrent.h"
51#include "tr_window.h"
52#include "util.h"
53#include "ui.h"
54
55#include <libtransmission/transmission.h>
56#include <libtransmission/version.h>
57
58/* time in seconds to wait for torrents to stop when exiting */
59#define TRACKER_EXIT_TIMEOUT    10
60
61/* interval in milliseconds to update the torrent list display */
62#define UPDATE_INTERVAL         1000
63
64/* interval in milliseconds to check for stopped torrents and update display */
65#define EXIT_CHECK_INTERVAL     500
66
67/* number of fatal signals required to cause an immediate exit */
68#define SIGCOUNT_MAX            3
69
70#if GTK_CHECK_VERSION(2,8,0)
71#define SHOW_LICENSE
72static const char * LICENSE = 
73"The Transmission binaries and most of its source code is distributed "
74"license. "
75"\n\n"
76"Some files are copyrighted by Charles Kerr and are covered by "
77"the GPL version 2.  Works owned by the Transmission project "
78"are granted a special exemption to clause 2(b) so that the bulk "
79"of its code can remain under the MIT license.  This exemption does "
80"not extend to original or derived works not owned by the "
81"Transmission project. "
82"\n\n"
83"Permission is hereby granted, free of charge, to any person obtaining "
84"a copy of this software and associated documentation files (the "
85"'Software'), to deal in the Software without restriction, including "
86"without limitation the rights to use, copy, modify, merge, publish, "
87"distribute, sublicense, and/or sell copies of the Software, and to "
88"permit persons to whom the Software is furnished to do so, subject to "
89"the following conditions: "
90"\n\n"
91"The above copyright notice and this permission notice shall be included "
92"in all copies or substantial portions of the Software. "
93"\n\n"
94"THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, "
95"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
96"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. "
97"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY "
98"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, "
99"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE "
100"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.";
101#endif
102
103struct cbdata {
104    GtkWindow    * wind;
105    TrCore       * core;
106    GtkWidget    * icon;
107    TrPrefs      * prefs;
108    guint          timer;
109    gboolean       msgwinopen;
110    gboolean       closing;
111    GList        * errqueue;
112};
113
114struct exitdata {
115    struct cbdata * cbdata;
116    time_t          started;
117    guint           timer;
118};
119
120#define CBDATA_PTR              "callback-data-pointer"
121
122static GtkUIManager * myUIManager = NULL;
123
124static sig_atomic_t global_sigcount = 0;
125
126static GList *
127readargs( int argc, char ** argv, gboolean * sendquit, gboolean * paused );
128static gboolean
129sendremote( GList * files, gboolean sendquit );
130static void
131gtksetup( int * argc, char *** argv, struct cbdata* );
132static void
133appsetup( TrWindow * wind, GList * args,
134          struct cbdata * , gboolean paused );
135static void
136winsetup( struct cbdata * cbdata, TrWindow * wind );
137static void
138makeicon( struct cbdata * cbdata );
139static void
140wannaquit( void * vdata );
141static gboolean
142exitcheck(gpointer gdata);
143static void
144setupdrag(GtkWidget *widget, struct cbdata *data);
145static void
146gotdrag(GtkWidget *widget, GdkDragContext *dc, gint x, gint y,
147        GtkSelectionData *sel, guint info, guint time, gpointer gdata);
148
149static void
150coreerr( TrCore * core, enum tr_core_err code, const char * msg,
151         gpointer gdata );
152static void
153coreprompt( TrCore *, GList *, enum tr_torrent_action, gboolean, gpointer );
154static void
155corepromptdata( TrCore *, uint8_t *, size_t, gboolean, gpointer );
156static void
157readinitialprefs( struct cbdata * cbdata );
158static void
159prefschanged( TrCore * core, int id, gpointer data );
160static void
161setpex( tr_torrent_t * tor, void * arg );
162static gboolean
163updatemodel(gpointer gdata);
164static void
165boolwindclosed(GtkWidget *widget, gpointer gdata);
166static GList *
167getselection( struct cbdata * cbdata );
168
169static void
170safepipe(void);
171static void
172setupsighandlers(void);
173static void
174fatalsig(int sig);
175
176static void
177accumulateStatusForeach (GtkTreeModel * model,
178                         GtkTreePath  * path UNUSED,
179                         GtkTreeIter  * iter,
180                         gpointer       accumulated_status)
181{
182    int status = 0;
183    gtk_tree_model_get( model, iter, MC_STAT, &status, -1 );
184    *(int*)accumulated_status |= status;
185}
186
187static void
188refreshTorrentActions( GtkTreeSelection * s )
189{
190    int status = 0;
191    gtk_tree_selection_selected_foreach( s, accumulateStatusForeach, &status );
192    action_sensitize( "stop-torrent", (status & TR_STATUS_ACTIVE) != 0);
193    action_sensitize( "start-torrent", (status & TR_STATUS_INACTIVE) != 0);
194    action_sensitize( "remove-torrent", status != 0);
195    action_sensitize( "recheck-torrent", status != 0);
196    action_sensitize( "show-torrent-inspector", status != 0);
197}
198
199static void
200selectionChangedCB( GtkTreeSelection * s, gpointer unused UNUSED )
201{
202    refreshTorrentActions( s );
203}
204
205int
206main( int argc, char ** argv )
207{
208    struct cbdata * cbdata = g_new (struct cbdata, 1);
209    char       * err;
210    benc_val_t * state;
211    GList      * argfiles;
212    gboolean     didinit, didlock, sendquit, startpaused;
213
214    safepipe();                 /* ignore SIGPIPE */
215    argfiles = readargs( argc, argv, &sendquit, &startpaused );
216    didinit = cf_init( tr_getPrefsDirectory(), NULL );
217    didlock = FALSE;
218    if( didinit )
219    {
220        /* maybe send remote commands, also try cf_lock() */
221        didlock = sendremote( argfiles, sendquit );
222    }
223    setupsighandlers();         /* set up handlers for fatal signals */
224    gtksetup( &argc, &argv, cbdata );   /* set up gtk and gettext */
225
226    if( ( didinit || cf_init( tr_getPrefsDirectory(), &err ) ) &&
227        ( didlock || cf_lock( &err ) ) )
228    {
229        GtkWindow  * mainwind;
230
231        /* create main window now to be a parent to any error dialogs */
232        mainwind = GTK_WINDOW( tr_window_new( myUIManager ) );
233
234        /* try to load prefs and saved state */
235        cf_loadprefs( &err );
236        if( NULL != err )
237        {
238            errmsg( mainwind, "%s", err );
239            g_free( err );
240        }
241        state = cf_loadstate( &err );
242        if( NULL != err )
243        {
244            errmsg( mainwind, "%s", err );
245            g_free( err );
246        }
247
248        msgwin_loadpref();      /* set message level here before tr_init() */
249        appsetup( mainwind, argfiles, cbdata, startpaused );
250        cf_freestate( state );
251    }
252    else
253    {
254        gtk_widget_show( errmsg_full( NULL, (callbackfunc_t)gtk_main_quit,
255                                      NULL, "%s", err ) );
256        g_free( err );
257    }
258
259    freestrlist(argfiles);
260
261    gtk_main();
262
263    return 0;
264}
265
266GList *
267readargs( int argc, char ** argv, gboolean * sendquit, gboolean * startpaused )
268{
269    struct option opts[] =
270    {
271        { "help",    no_argument, NULL, 'h' },
272        { "paused",  no_argument, NULL, 'p' },
273        { "quit",    no_argument, NULL, 'q' },
274        { "version", no_argument, NULL, 'v' },
275        { NULL, 0, NULL, 0 }
276    };
277    int          opt;
278    const char * name;
279
280    *sendquit    = FALSE;
281    *startpaused = FALSE;
282
283    gtk_parse_args( &argc, &argv );
284    name = g_get_prgname();
285
286    while( 0 <= ( opt = getopt_long( argc, argv, "hpqv", opts, NULL ) ) )
287    {
288        switch( opt )
289        {
290            case 'p':
291                *startpaused = TRUE;
292                break;
293            case 'q':
294                *sendquit = TRUE;
295                break;
296            case 'v':
297            case 'h':
298                printf(
299_("usage: %s [-hpq] [files...]\n"
300  "\n"
301  "Transmission %s http://transmission.m0k.org/\n"
302  "A free, lightweight BitTorrent client with a simple, intuitive interface\n"
303  "\n"
304  "  -h --help    display this message and exit\n"
305  "  -p --paused  start with all torrents paused\n"
306  "  -q --quit    request that the running %s instance quit\n"
307  "\n"
308  "Only one instance of %s may run at one time. Multiple\n"
309  "torrent files may be loaded at startup by adding them to the command\n"
310  "line. If %s is already running, those torrents will be\n"
311  "opened in the running instance.\n"),
312                        name, LONG_VERSION_STRING,
313                        name, name, name );
314                exit(0);
315                break;
316        }
317    }
318
319    argc -= optind;
320    argv += optind;
321
322    return checkfilenames( argc, argv );
323}
324
325static gboolean
326sendremote( GList * files, gboolean sendquit )
327{
328    gboolean didlock;
329
330    didlock = cf_lock( NULL );
331
332    if( NULL != files )
333    {
334        /* send files if there's another instance, otherwise start normally */
335        if( !didlock )
336        {
337            exit( ipc_sendfiles_blocking( files ) ? 0 : 1 );
338        }
339    }
340
341    if( sendquit )
342    {
343        /* either send a quit message or exit if no other instance */
344        if( !didlock )
345        {
346            exit( ipc_sendquit_blocking() ? 0 : 1 );
347        }
348        exit( 0 );
349    }
350
351    return didlock;
352}
353
354static void
355gtksetup( int * argc, char *** argv, struct cbdata * callback_data )
356{
357
358    bindtextdomain( "transmission-gtk", LOCALEDIR );
359    bind_textdomain_codeset( "transmission-gtk", "UTF-8" );
360    textdomain( "transmission-gtk" );
361
362    g_set_application_name( _("Transmission") );
363    gtk_init( argc, argv );
364
365    /* connect up the actions */
366    myUIManager = gtk_ui_manager_new ();
367    actions_init ( myUIManager, callback_data );
368    gtk_ui_manager_add_ui_from_string (myUIManager, fallback_ui_file, -1, NULL);
369    gtk_ui_manager_ensure_update (myUIManager);
370
371    /* tweak some style properties in dialogs to get closer to the GNOME HiG */
372    gtk_rc_parse_string(
373        "style \"transmission-standard\"\n"
374        "{\n"
375        "    GtkDialog::action-area-border  = 6\n"
376        "    GtkDialog::button-spacing      = 12\n"
377        "    GtkDialog::content-area-border = 6\n"
378        "}\n"
379        "widget \"TransmissionDialog\" style \"transmission-standard\"\n" );
380
381    gtk_window_set_default_icon_name ( "ICON_TRANSMISSION" );
382}
383
384static void
385appsetup( TrWindow * wind, GList * args,
386          struct cbdata * cbdata, gboolean paused )
387{
388    enum tr_torrent_action action;
389
390    /* fill out cbdata */
391    cbdata->wind       = NULL;
392    cbdata->core       = tr_core_new();
393    cbdata->icon       = NULL;
394    cbdata->prefs      = NULL;
395    cbdata->timer      = 0;
396    cbdata->msgwinopen = FALSE;
397    cbdata->closing    = FALSE;
398    cbdata->errqueue   = NULL;
399
400    /* set up core handlers */
401    g_signal_connect( cbdata->core, "error", G_CALLBACK( coreerr ), cbdata );
402    g_signal_connect( cbdata->core, "directory-prompt",
403                      G_CALLBACK( coreprompt ), cbdata );
404    g_signal_connect( cbdata->core, "directory-prompt-data",
405                      G_CALLBACK( corepromptdata ), cbdata );
406    g_signal_connect_swapped( cbdata->core, "quit",
407                              G_CALLBACK( wannaquit ), cbdata );
408    g_signal_connect( cbdata->core, "prefs-changed",
409                      G_CALLBACK( prefschanged ), cbdata );
410
411    /* apply a few prefs */
412    readinitialprefs( cbdata );
413
414    /* add torrents from command-line and saved state */
415    tr_core_load( cbdata->core, paused );
416
417    if( NULL != args )
418    {
419        action = toraddaction( tr_prefs_get( PREF_ID_ADDIPC ) );
420        tr_core_add_list( cbdata->core, args, action, paused );
421    }
422    tr_core_torrents_added( cbdata->core );
423
424    /* set up the ipc socket */
425    ipc_socket_setup( GTK_WINDOW( wind ), cbdata->core );
426
427    /* set up main window */
428    winsetup( cbdata, wind );
429
430    /* start model update timer */
431    cbdata->timer = g_timeout_add( UPDATE_INTERVAL, updatemodel, cbdata );
432    updatemodel( cbdata );
433
434    /* show the window */
435    gtk_widget_show( GTK_WIDGET(wind) );
436}
437
438static gboolean
439winclose( GtkWidget * widget UNUSED, GdkEvent * event UNUSED, gpointer gdata )
440{
441    struct cbdata * cbdata = (struct cbdata *) gdata;
442
443    if( cbdata->icon != NULL )
444        gtk_widget_hide( GTK_WIDGET( cbdata->wind ) );
445    else
446        askquit( cbdata->core, cbdata->wind, wannaquit, cbdata );
447
448    return TRUE; /* don't propagate event further */
449}
450
451static void
452rowChangedCB( GtkTreeModel  * model UNUSED,
453              GtkTreePath   * path UNUSED,
454              GtkTreeIter   * iter UNUSED,
455              gpointer        sel)
456{
457    refreshTorrentActions( GTK_TREE_SELECTION(sel) );
458}
459
460static void
461winsetup( struct cbdata * cbdata, TrWindow * wind )
462{
463    GtkTreeModel * model;
464    GtkTreeSelection * sel;
465
466    g_assert( NULL == cbdata->wind );
467    cbdata->wind = GTK_WINDOW( wind );
468
469    sel = tr_window_get_selection( cbdata->wind );
470    g_signal_connect( sel, "changed", G_CALLBACK(selectionChangedCB), NULL );
471    selectionChangedCB( sel, NULL );
472    model = tr_core_model( cbdata->core );
473    gtk_tree_view_set_model ( gtk_tree_selection_get_tree_view(sel), model );
474    g_signal_connect( model, "row-changed", G_CALLBACK(rowChangedCB), sel );
475    g_signal_connect( wind, "delete-event", G_CALLBACK( winclose ), cbdata );
476   
477    setupdrag( GTK_WIDGET(wind), cbdata );
478}
479
480static void
481makeicon( struct cbdata * cbdata )
482{
483    if( NULL == cbdata->icon )
484        cbdata->icon = tr_icon_new( );
485}
486
487static void
488wannaquit( void * vdata )
489{
490  struct cbdata * data;
491  struct exitdata *edata;
492
493  data = vdata;
494  if( data->closing )
495  {
496      return;
497  }
498  data->closing = TRUE;
499
500  /* stop the update timer */
501  if(0 < data->timer)
502    g_source_remove(data->timer);
503  data->timer = 0;
504
505  /* pause torrents and stop nat traversal */
506  tr_core_shutdown( data->core );
507
508  /* set things up to wait for torrents to stop */
509  edata = g_new0(struct exitdata, 1);
510  edata->cbdata = data;
511  edata->started = time(NULL);
512  /* check if torrents are still running */
513  if(exitcheck(edata)) {
514    /* yes, start the exit timer and disable widgets */
515    edata->timer = g_timeout_add(EXIT_CHECK_INTERVAL, exitcheck, edata);
516    if( NULL != data->wind )
517    {
518        gtk_widget_set_sensitive( GTK_WIDGET( data->wind ), FALSE );
519    }
520  }
521}
522
523static gboolean
524exitcheck( gpointer gdata )
525{
526    struct exitdata    * edata;
527    struct cbdata      * cbdata;
528
529    edata  = gdata;
530    cbdata = edata->cbdata;
531
532    /* keep waiting until we're ready to quit or we hit the exit timeout */
533    if( time( NULL ) - edata->started < TRACKER_EXIT_TIMEOUT )
534    {
535        if( !tr_core_quiescent( cbdata->core ) )
536        {
537            updatemodel( cbdata );
538            return TRUE;
539        }
540    }
541
542    /* exit otherwise */
543    if( 0 < edata->timer )
544    {
545        g_source_remove( edata->timer );
546    }
547    g_free( edata );
548    /* note that cbdata->prefs holds a reference to cbdata->core, and
549       it's destruction may trigger callbacks that use cbdata->core */
550    if( NULL != cbdata->prefs )
551    {
552        gtk_widget_destroy( GTK_WIDGET( cbdata->prefs ) );
553    }
554    if( NULL != cbdata->wind )
555    {
556        gtk_widget_destroy( GTK_WIDGET( cbdata->wind ) );
557    }
558    g_object_unref( cbdata->core );
559    if( NULL != cbdata->icon )
560    {
561        g_object_unref( cbdata->icon );
562    }
563    g_assert( 0 == cbdata->timer );
564    if( NULL != cbdata->errqueue )
565    {
566        g_list_foreach( cbdata->errqueue, (GFunc) g_free, NULL );
567        g_list_free( cbdata->errqueue );
568    }
569    g_free( cbdata );
570    gtk_main_quit();
571
572    return FALSE;
573}
574
575static void
576gotdrag(GtkWidget *widget SHUTUP, GdkDragContext *dc, gint x SHUTUP,
577        gint y SHUTUP, GtkSelectionData *sel, guint info SHUTUP, guint time,
578        gpointer gdata) {
579  struct cbdata *data = gdata;
580  char prefix[] = "file:";
581  char *files, *decoded, *deslashed, *hostless;
582  int ii, len;
583  GList *errs;
584  struct stat sb;
585  int prelen = strlen(prefix);
586  GList *paths, *freeables;
587  enum tr_torrent_action action;
588
589#ifdef DND_DEBUG
590  char *sele = gdk_atom_name(sel->selection);
591  char *targ = gdk_atom_name(sel->target);
592  char *type = gdk_atom_name(sel->type);
593
594  fprintf(stderr, "dropped file: sel=%s targ=%s type=%s fmt=%i len=%i\n",
595          sele, targ, type, sel->format, sel->length);
596  g_free(sele);
597  g_free(targ);
598  g_free(type);
599  if(8 == sel->format) {
600    for(ii = 0; ii < sel->length; ii++)
601      fprintf(stderr, "%02X ", sel->data[ii]);
602    fprintf(stderr, "\n");
603  }
604#endif
605
606  errs = NULL;
607  paths = NULL;
608  freeables = NULL;
609  if(gdk_atom_intern("XdndSelection", FALSE) == sel->selection &&
610     8 == sel->format) {
611    /* split file list on carriage returns and linefeeds */
612    files = g_new(char, sel->length + 1);
613    memcpy(files, sel->data, sel->length);
614    files[sel->length] = '\0';
615    for(ii = 0; '\0' != files[ii]; ii++)
616      if('\015' == files[ii] || '\012' == files[ii])
617        files[ii] = '\0';
618
619    /* try to get a usable filename out of the URI supplied and add it */
620    for(ii = 0; ii < sel->length; ii += len + 1) {
621      if('\0' == files[ii])
622        len = 0;
623      else {
624        len = strlen(files + ii);
625        /* de-urlencode the URI */
626        decoded = urldecode(files + ii, len);
627        freeables = g_list_append(freeables, decoded);
628        if(g_utf8_validate(decoded, -1, NULL)) {
629          /* remove the file: prefix */
630          if(prelen < len && 0 == strncmp(prefix, decoded, prelen)) {
631            deslashed = decoded + prelen;
632            /* trim excess / characters from the beginning */
633            while('/' == deslashed[0] && '/' == deslashed[1])
634              deslashed++;
635            /* if the file doesn't exist, the first part might be a hostname */
636            if(0 > g_stat(deslashed, &sb) &&
637               NULL != (hostless = strchr(deslashed + 1, '/')) &&
638               0 == g_stat(hostless, &sb))
639              deslashed = hostless;
640            /* finally, add it to the list of torrents to try adding */
641            paths = g_list_append(paths, deslashed);
642          }
643        }
644      }
645    }
646
647    /* try to add any torrents we found */
648    if( NULL != paths )
649    {
650        action = toraddaction( tr_prefs_get( PREF_ID_ADDSTD ) );
651        tr_core_add_list( data->core, paths, action, FALSE );
652        tr_core_torrents_added( data->core );
653        g_list_free(paths);
654    }
655    freestrlist(freeables);
656    g_free(files);
657  }
658
659  gtk_drag_finish(dc, (NULL != paths), FALSE, time);
660}
661
662static void
663setupdrag(GtkWidget *widget, struct cbdata *data) {
664  GtkTargetEntry targets[] = {
665    { "STRING",     0, 0 },
666    { "text/plain", 0, 0 },
667    { "text/uri-list", 0, 0 },
668  };
669
670  g_signal_connect(widget, "drag_data_received", G_CALLBACK(gotdrag), data);
671
672  gtk_drag_dest_set(widget, GTK_DEST_DEFAULT_ALL, targets,
673                    ALEN(targets), GDK_ACTION_COPY | GDK_ACTION_MOVE);
674}
675
676static void
677coreerr( TrCore * core SHUTUP, enum tr_core_err code, const char * msg,
678         gpointer gdata )
679{
680    struct cbdata * cbdata = gdata;
681    char          * joined;
682
683    switch( code )
684    {
685        case TR_CORE_ERR_ADD_TORRENT:
686            cbdata->errqueue = g_list_append( cbdata->errqueue,
687                                              g_strdup( msg ) );
688            return;
689        case TR_CORE_ERR_NO_MORE_TORRENTS:
690            if( NULL != cbdata->errqueue )
691            {
692                joined = joinstrlist( cbdata->errqueue, "\n" );
693                errmsg( cbdata->wind,
694                        ngettext( "Failed to load torrent file:\n%s",
695                                  "Failed to load torrent files:\n%s",
696                                  g_list_length( cbdata->errqueue ) ),
697                        joined );
698                g_list_foreach( cbdata->errqueue, (GFunc) g_free, NULL );
699                g_list_free( cbdata->errqueue );
700                cbdata->errqueue = NULL;
701                g_free( joined );
702            }
703            return;
704        case TR_CORE_ERR_SAVE_STATE:
705            errmsg( cbdata->wind, "%s", msg );
706            return;
707    }
708
709    g_assert_not_reached();
710}
711
712void
713coreprompt( TrCore * core, GList * paths, enum tr_torrent_action act,
714            gboolean paused, gpointer gdata )
715{
716    struct cbdata * cbdata = gdata;
717
718    promptfordir( cbdata->wind, core, paths, NULL, 0, act, paused );
719}
720
721void
722corepromptdata( TrCore * core, uint8_t * data, size_t size,
723                gboolean paused, gpointer gdata )
724{
725    struct cbdata * cbdata = gdata;
726
727    promptfordir( cbdata->wind, core, NULL, data, size, TR_TOR_LEAVE, paused );
728}
729
730static void
731readinitialprefs( struct cbdata * cbdata )
732{
733    int prefs[] =
734    {
735        PREF_ID_PORT,
736        PREF_ID_DOWNLIMIT,
737        PREF_ID_USEDOWNLIMIT,
738        PREF_ID_UPLIMIT,
739        PREF_ID_USEUPLIMIT,
740        PREF_ID_NAT,
741        PREF_ID_ICON,
742        PREF_ID_PEX,
743    };
744    int ii;
745
746    for( ii = 0; ALEN( prefs ) > ii; ii++ )
747    {
748        prefschanged( NULL, prefs[ii], cbdata );
749    }
750}
751
752static void
753prefschanged( TrCore * core SHUTUP, int id, gpointer data )
754{
755    struct cbdata * cbdata = data;
756    tr_handle_t   * tr     = tr_core_handle( cbdata->core );
757    gboolean        boolval;
758
759    switch( id )
760    {
761        case PREF_ID_PORT:
762            tr_setBindPort( tr, tr_prefs_get_int_with_default( id ) );
763            break;
764
765        case PREF_ID_USEDOWNLIMIT:
766            tr_setUseGlobalSpeedLimit( tr, TR_DOWN,
767                tr_prefs_get_bool_with_default( PREF_ID_USEDOWNLIMIT ) );
768            break;
769
770        case PREF_ID_DOWNLIMIT:
771            tr_setGlobalSpeedLimit( tr, TR_DOWN,
772                tr_prefs_get_int_with_default( PREF_ID_DOWNLIMIT ) );
773            break;
774
775        case PREF_ID_USEUPLIMIT:
776            tr_setUseGlobalSpeedLimit( tr, TR_UP,
777                tr_prefs_get_bool_with_default( PREF_ID_USEUPLIMIT ) );
778            break;
779
780        case PREF_ID_UPLIMIT:
781            tr_setGlobalSpeedLimit( tr, TR_UP,
782                tr_prefs_get_int_with_default( PREF_ID_UPLIMIT ) );
783            break;
784
785        case PREF_ID_NAT:
786            tr_natTraversalEnable( tr, tr_prefs_get_bool_with_default( id ) );
787            break;
788
789        case PREF_ID_ICON:
790            if( tr_prefs_get_bool_with_default( id ) )
791            {
792                makeicon( cbdata );
793            }
794            else if( NULL != cbdata->icon )
795            {
796g_message ("foo");
797                g_object_unref( cbdata->icon );
798                cbdata->icon = NULL;
799            }
800            break;
801
802        case PREF_ID_PEX:
803            boolval = tr_prefs_get_bool_with_default( id );
804            tr_torrentIterate( tr, setpex, &boolval );
805            break;
806
807        case PREF_ID_DIR:
808        case PREF_ID_ASKDIR:
809        case PREF_ID_ADDSTD:
810        case PREF_ID_ADDIPC:
811        case PREF_ID_MSGLEVEL:
812        case PREF_MAX_ID:
813            break;
814    }
815}
816
817void
818setpex( tr_torrent_t * tor, void * arg )
819{
820    gboolean * val;
821
822    val = arg;
823    tr_torrentDisablePex( tor, !(*val) );
824}
825
826gboolean
827updatemodel(gpointer gdata) {
828  struct cbdata *data = gdata;
829  float up, down;
830
831  if( !data->closing && 0 < global_sigcount )
832  {
833      wannaquit( data );
834      return FALSE;
835  }
836
837  /* update the torrent data in the model */
838  tr_core_update( data->core );
839
840  /* update the main window's statusbar and toolbar buttons */
841  if( NULL != data->wind )
842  {
843      tr_torrentRates( tr_core_handle( data->core ), &down, &up );
844      tr_window_update( data->wind, down, up );
845  }
846
847  /* update the message window */
848  msgwin_update();
849
850  return TRUE;
851}
852
853static void
854boolwindclosed(GtkWidget *widget SHUTUP, gpointer gdata) {
855  gboolean *preachy_gcc = gdata;
856 
857  *preachy_gcc = FALSE;
858}
859
860/* returns a GList containing a GtkTreeRowReference to each selected row */
861static GList *
862getselection( struct cbdata * cbdata )
863{
864    GList * rows = NULL;
865
866    if( NULL != cbdata->wind )
867    {
868        GList * ii;
869        GtkTreeSelection *s = tr_window_get_selection(cbdata->wind);
870        GtkTreeModel * model = tr_core_model( cbdata->core );
871        rows = gtk_tree_selection_get_selected_rows( s, NULL );
872        for( ii = rows; NULL != ii; ii = ii->next )
873        {
874            GtkTreeRowReference * ref = gtk_tree_row_reference_new(
875                model, ii->data );
876            gtk_tree_path_free( ii->data );
877            ii->data = ref;
878        }
879    }
880
881    return rows;
882}
883
884static void
885about ( void )
886{
887  GtkWidget * w = gtk_about_dialog_new ();
888  GtkAboutDialog * a = GTK_ABOUT_DIALOG (w);
889  const char *authors[] = { "Eric Petit (Back-end; OS X)",
890                            "Josh Elsasser (Back-end; GTK+)",
891                            "Mitchell Livingston (Back-end; OS X)",
892                            "Charles Kerr (Back-end; GTK+)",
893                            "Bryan Varner (BeOS)", 
894                            NULL };
895  gtk_about_dialog_set_version (a, LONG_VERSION_STRING );
896#ifdef SHOW_LICENSE
897  gtk_about_dialog_set_license (a, LICENSE);
898  gtk_about_dialog_set_wrap_license (a, TRUE);
899#endif
900  gtk_about_dialog_set_website (a, "http://transmission.m0k.org/");
901  gtk_about_dialog_set_copyright (a, _("Copyright 2005-2007 The Transmission Project"));
902  gtk_about_dialog_set_authors (a, authors);
903  gtk_about_dialog_set_translator_credits (a, _("translator-credits"));
904  g_signal_connect_swapped (w, "response", G_CALLBACK (gtk_widget_destroy), w);
905  gtk_widget_show_all (w);
906}
907
908static void
909startTorrentForeach (GtkTreeModel * model,
910                     GtkTreePath  * path UNUSED,
911                     GtkTreeIter  * iter,
912                     gpointer       data UNUSED)
913{
914    TrTorrent * tor = NULL;
915    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
916    tr_torrent_start( tor );
917    g_object_unref( G_OBJECT( tor ) );
918}
919
920static void
921stopTorrentForeach (GtkTreeModel * model,
922                    GtkTreePath  * path UNUSED,
923                    GtkTreeIter  * iter,
924                    gpointer       data UNUSED)
925{
926    TrTorrent * tor = NULL;
927    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
928    tr_torrent_stop( tor );
929    g_object_unref( G_OBJECT( tor ) );
930}
931
932static void
933showInfoForeach (GtkTreeModel * model,
934                 GtkTreePath  * path UNUSED,
935                 GtkTreeIter  * iter,
936                 gpointer       data UNUSED)
937{
938    TrTorrent * tor = NULL;
939    GtkWidget * w;
940    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
941    w = torrent_inspector_new( GTK_WINDOW(data), tor );
942    gtk_widget_show( w );
943    g_object_unref( G_OBJECT( tor ) );
944}
945
946static void
947recheckTorrentForeach (GtkTreeModel * model,
948                       GtkTreePath  * path UNUSED,
949                       GtkTreeIter  * iter,
950                       gpointer       data UNUSED)
951{
952    TrTorrent * gtor = NULL;
953    gtk_tree_model_get( model, iter, MC_TORRENT, &gtor, -1 );
954    tr_torrentRecheck( tr_torrent_handle( gtor ) );
955    g_object_unref( G_OBJECT( gtor ) );
956}
957
958void
959doAction ( const char * action_name, gpointer user_data )
960{
961    struct cbdata * data = (struct cbdata *) user_data;
962    gboolean changed = FALSE;
963
964    if (!strcmp (action_name, "add-torrent"))
965    {
966        makeaddwind( data->wind, data->core );
967    }
968    else if (!strcmp (action_name, "start-torrent"))
969    {
970        GtkTreeSelection * s = tr_window_get_selection(data->wind);
971        gtk_tree_selection_selected_foreach( s, startTorrentForeach, NULL );
972        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
973    }
974    else if (!strcmp (action_name, "stop-torrent"))
975    {
976        GtkTreeSelection * s = tr_window_get_selection(data->wind);
977        gtk_tree_selection_selected_foreach( s, stopTorrentForeach, NULL );
978        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
979    }
980    else if (!strcmp (action_name, "recheck-torrent"))
981    {
982        GtkTreeSelection * s = tr_window_get_selection(data->wind);
983        gtk_tree_selection_selected_foreach( s, recheckTorrentForeach, NULL );
984        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
985    }
986    else if (!strcmp (action_name, "show-torrent-inspector"))
987    {
988        GtkTreeSelection * s = tr_window_get_selection(data->wind);
989        gtk_tree_selection_selected_foreach( s, showInfoForeach, data->wind );
990    }
991    else if (!strcmp (action_name, "create-torrent"))
992    {
993        GtkWidget * w = make_meta_ui( GTK_WINDOW( data->wind ), tr_core_handle( data->core ) );
994        gtk_widget_show_all( w );
995    }
996    else if (!strcmp (action_name, "remove-torrent"))
997    {
998        /* this modifies the model's contents, so can't use foreach */
999        GList *l, *sel = getselection( data );
1000        GtkTreeModel *model = tr_core_model( data->core );
1001        for( l=sel; l!=NULL; l=l->next )
1002        {
1003            GtkTreeIter iter;
1004            GtkTreeRowReference * reference = (GtkTreeRowReference *) l->data;
1005            GtkTreePath * path = gtk_tree_row_reference_get_path( reference );
1006            gtk_tree_model_get_iter( model, &iter, path );
1007            tr_core_delete_torrent( data->core, &iter );
1008            gtk_tree_row_reference_free( reference );
1009            changed = TRUE;
1010        }
1011        g_list_free( sel );
1012    }
1013    else if (!strcmp (action_name, "close"))
1014    {
1015        if( data->wind != NULL )
1016            winclose( NULL, NULL, data );
1017    }
1018    else if (!strcmp (action_name, "quit"))
1019    {
1020        askquit( data->core, data->wind, wannaquit, data );
1021    }
1022    else if (!strcmp (action_name, "edit-preferences"))
1023    {
1024        if( NULL == data->prefs )
1025        {
1026            data->prefs = tr_prefs_new_with_parent( G_OBJECT( data->core ),
1027                                                    data->wind );
1028            g_signal_connect( data->prefs, "destroy",
1029                             G_CALLBACK( gtk_widget_destroyed ), &data->prefs );
1030            gtk_widget_show( GTK_WIDGET( data->prefs ) );
1031        }
1032    }
1033    else if (!strcmp (action_name, "show-debug-window"))
1034    {
1035        if( !data->msgwinopen )
1036        {
1037            GtkWidget * win = msgwin_create( data->core );
1038            g_signal_connect( win, "destroy", G_CALLBACK( boolwindclosed ),
1039                                &data->msgwinopen );
1040            data->msgwinopen = TRUE;
1041        }
1042    }
1043    else if (!strcmp (action_name, "show-about-dialog"))
1044    {
1045        about();
1046    }
1047    else if (!strcmp (action_name, "toggle-main-window"))
1048    {
1049        GtkWidget * w = GTK_WIDGET (data->wind);
1050        if (GTK_WIDGET_VISIBLE(w))
1051            gtk_widget_hide (w);
1052        else
1053            gtk_window_present (GTK_WINDOW(w));
1054    }
1055    else g_error ("Unhandled action: %s", action_name );
1056
1057    if(changed)
1058    {
1059        updatemodel( data );
1060        tr_core_save( data->core );
1061    }
1062}
1063
1064
1065static void
1066safepipe(void) {
1067  struct sigaction sa;
1068
1069  memset(&sa, 0,  sizeof(sa));
1070  sa.sa_handler = SIG_IGN;
1071  sigaction(SIGPIPE, &sa, NULL);
1072}
1073
1074static void
1075setupsighandlers(void) {
1076  int sigs[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM};
1077  struct sigaction sa;
1078  int ii;
1079
1080  memset(&sa, 0,  sizeof(sa));
1081  sa.sa_handler = fatalsig;
1082  for(ii = 0; ii < ALEN(sigs); ii++)
1083    sigaction(sigs[ii], &sa, NULL);
1084}
1085
1086static void
1087fatalsig(int sig) {
1088  struct sigaction sa;
1089
1090  if(SIGCOUNT_MAX <= ++global_sigcount) {
1091    memset(&sa, 0,  sizeof(sa));
1092    sa.sa_handler = SIG_DFL;
1093    sigaction(sig, &sa, NULL);
1094    raise(sig);
1095  }
1096}
Note: See TracBrowser for help on using the repository browser.