source: trunk/gtk/main.c @ 4404

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

set copyright info to 2008

  • Property svn:keywords set to Date Rev Author Id
File size: 31.9 KB
Line 
1/******************************************************************************
2 * $Id: main.c 4404 2008-01-01 17:20:20Z charles $
3 *
4 * Copyright (c) 2005-2008 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 "actions.h"
39#include "conf.h"
40#include "dialogs.h"
41#include "ipc.h"
42#include "makemeta-ui.h"
43#include "msgwin.h"
44#include "stats.h"
45#include "torrent-inspector.h"
46#include "tr_core.h"
47#include "tr_icon.h"
48#include "tr_prefs.h"
49#include "tr_torrent.h"
50#include "tr_window.h"
51#include "util.h"
52#include "ui.h"
53
54#include <libtransmission/transmission.h>
55#include <libtransmission/version.h>
56
57/* interval in milliseconds to update the torrent list display */
58#define UPDATE_INTERVAL         1000
59
60/* interval in milliseconds to check for stopped torrents and update display */
61#define EXIT_CHECK_INTERVAL     500
62
63/* number of fatal signals required to cause an immediate exit */
64#define SIGCOUNT_MAX            3
65
66#if GTK_CHECK_VERSION(2,8,0)
67#define SHOW_LICENSE
68static const char * LICENSE = 
69"The Transmission binaries and most of its source code is distributed "
70"license. "
71"\n\n"
72"Some files are copyrighted by Charles Kerr and are covered by "
73"the GPL version 2.  Works owned by the Transmission project "
74"are granted a special exemption to clause 2(b) so that the bulk "
75"of its code can remain under the MIT license.  This exemption does "
76"not extend to original or derived works not owned by the "
77"Transmission project. "
78"\n\n"
79"Permission is hereby granted, free of charge, to any person obtaining "
80"a copy of this software and associated documentation files (the "
81"'Software'), to deal in the Software without restriction, including "
82"without limitation the rights to use, copy, modify, merge, publish, "
83"distribute, sublicense, and/or sell copies of the Software, and to "
84"permit persons to whom the Software is furnished to do so, subject to "
85"the following conditions: "
86"\n\n"
87"The above copyright notice and this permission notice shall be included "
88"in all copies or substantial portions of the Software. "
89"\n\n"
90"THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, "
91"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
92"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. "
93"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY "
94"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, "
95"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE "
96"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.";
97#endif
98
99struct cbdata {
100    GtkWindow    * wind;
101    TrCore       * core;
102    GtkWidget    * icon;
103    GtkWidget    * msgwin;
104    GtkWidget    * prefs;
105    guint          timer;
106    gboolean       closing;
107    GList        * errqueue;
108};
109
110#define CBDATA_PTR "callback-data-pointer"
111
112static GtkUIManager * myUIManager = NULL;
113
114static sig_atomic_t global_sigcount = 0;
115
116static gboolean
117sendremote( GList * files, gboolean sendquit );
118static void
119appsetup( TrWindow * wind, GList * args,
120          struct cbdata * , gboolean paused );
121static void
122winsetup( struct cbdata * cbdata, TrWindow * wind );
123static void
124makeicon( struct cbdata * cbdata );
125static void
126wannaquit( void * vdata );
127static void
128setupdrag(GtkWidget *widget, struct cbdata *data);
129static void
130gotdrag(GtkWidget *widget, GdkDragContext *dc, gint x, gint y,
131        GtkSelectionData *sel, guint info, guint time, gpointer gdata);
132
133static void
134coreerr( TrCore * core, enum tr_core_err code, const char * msg,
135         gpointer gdata );
136static void
137coreprompt( TrCore *, GList *, enum tr_torrent_action, gboolean, gpointer );
138static void
139corepromptdata( TrCore *, uint8_t *, size_t, gboolean, gpointer );
140static void
141initializeFromPrefs( struct cbdata * cbdata );
142static void
143prefschanged( TrCore * core, const char * key, gpointer data );
144static gboolean
145updatemodel(gpointer gdata);
146static GList *
147getselection( struct cbdata * cbdata );
148
149static void
150setupsighandlers(void);
151static void
152fatalsig(int sig);
153
154struct counts_data
155{
156    int totalCount;
157    int activeCount;
158    int inactiveCount;
159};
160
161static void
162accumulateStatusForeach( GtkTreeModel * model,
163                         GtkTreePath  * path UNUSED,
164                         GtkTreeIter  * iter,
165                         gpointer       user_data )
166{
167    int status = 0;
168    struct counts_data * counts = user_data;
169
170    ++counts->totalCount;
171
172    gtk_tree_model_get( model, iter, MC_STATUS, &status, -1 );
173
174    if( TR_STATUS_IS_ACTIVE( status ) )
175        ++counts->activeCount;
176    else
177        ++counts->inactiveCount;
178}
179
180static void
181accumulateCanUpdateForeach (GtkTreeModel * model,
182                            GtkTreePath  * path UNUSED,
183                            GtkTreeIter  * iter,
184                            gpointer       accumulated_status)
185{
186    tr_torrent * tor;
187    gtk_tree_model_get( model, iter, MC_TORRENT_RAW, &tor, -1 );
188    *(int*)accumulated_status |= tr_torrentCanManualUpdate( tor );
189}
190
191static void
192refreshTorrentActions( GtkTreeSelection * s )
193{
194    int canUpdate;
195    struct counts_data counts;
196
197    counts.activeCount = 0;
198    counts.inactiveCount = 0;
199    counts.totalCount = 0;
200    gtk_tree_selection_selected_foreach( s, accumulateStatusForeach, &counts );
201    action_sensitize( "pause-torrent", counts.activeCount!=0 );
202    action_sensitize( "start-torrent", counts.inactiveCount!=0 );
203    action_sensitize( "remove-torrent", counts.totalCount!=0 );
204    action_sensitize( "verify-torrent", counts.totalCount!=0 );
205    action_sensitize( "show-torrent-details", counts.totalCount!=0 );
206
207    canUpdate = 0;
208    gtk_tree_selection_selected_foreach( s, accumulateCanUpdateForeach, &canUpdate );
209    action_sensitize( "update-tracker", canUpdate!=0 );
210}
211
212static void
213selectionChangedCB( GtkTreeSelection * s, gpointer unused UNUSED )
214{
215    refreshTorrentActions( s );
216}
217
218int
219main( int argc, char ** argv )
220{
221    char * err;
222    struct cbdata * cbdata = g_new (struct cbdata, 1);
223    GList * argfiles;
224    GError * gerr;
225    gboolean didinit = FALSE;
226    gboolean didlock = FALSE;
227    gboolean sendquit = FALSE;
228    gboolean startpaused = FALSE;
229    char * domain = "transmission";
230    GOptionEntry entries[] = {
231        { "paused", 'p', 0, G_OPTION_ARG_NONE, &startpaused,
232          _("Start with all torrents paused"), NULL },
233        { "quit", 'q', 0, G_OPTION_ARG_NONE, &sendquit,
234          _( "Request that the running instance quit"), NULL },
235        { NULL, 0, 0, 0, NULL, NULL, NULL }
236    };
237
238    /* bind the gettext domain */
239    bindtextdomain( domain, TRANSMISSIONLOCALEDIR );
240    bind_textdomain_codeset( domain, "UTF-8" );
241    textdomain( domain );
242    g_set_application_name( _( "Transmission" ) );
243
244    /* initialize gtk */
245    g_thread_init( NULL );
246    gerr = NULL;
247    if( !gtk_init_with_args( &argc, &argv, _("[torrent files]"), entries, domain, &gerr ) ) {
248        g_message( "%s", gerr->message );
249        g_clear_error( &gerr );
250        return 0;
251    }
252
253    didinit = cf_init( tr_getPrefsDirectory(), NULL ); /* must come before actions_init */
254    tr_prefs_init_global( );
255    myUIManager = gtk_ui_manager_new ();
256    actions_init ( myUIManager, cbdata );
257    gtk_ui_manager_add_ui_from_string (myUIManager, fallback_ui_file, -1, NULL);
258    gtk_ui_manager_ensure_update (myUIManager);
259    gtk_window_set_default_icon_name ( "transmission-logo" );
260
261    argfiles = checkfilenames( argc-1, argv+1 );
262    didlock = didinit && sendremote( argfiles, sendquit );
263    setupsighandlers( ); /* set up handlers for fatal signals */
264
265    if( ( didinit || cf_init( tr_getPrefsDirectory(), &err ) ) &&
266        ( didlock || cf_lock( &err ) ) )
267    {
268        cbdata->core = tr_core_new( );
269
270        /* create main window now to be a parent to any error dialogs */
271        GtkWindow * mainwind = GTK_WINDOW( tr_window_new( myUIManager, cbdata->core ) );
272
273        /* set message level here before tr_init() */
274        msgwin_loadpref( );
275
276        appsetup( mainwind, argfiles, cbdata, startpaused );
277    }
278    else
279    {
280        gtk_widget_show( errmsg_full( NULL, (callbackfunc_t)gtk_main_quit,
281                                      NULL, "%s", err ) );
282        g_free( err );
283    }
284
285    freestrlist(argfiles);
286
287    gtk_main();
288
289    return 0;
290}
291
292static gboolean
293sendremote( GList * files, gboolean sendquit )
294{
295    const gboolean didlock = cf_lock( NULL );
296
297    /* send files if there's another instance, otherwise start normally */
298    if( !didlock && files )
299        exit( ipc_sendfiles_blocking( files ) ? 0 : 1 );
300
301    /* either send a quit message or exit if no other instance */
302    if( sendquit )
303        exit( didlock ? 0 : !ipc_sendquit_blocking() );
304
305    return didlock;
306}
307
308static void
309appsetup( TrWindow * wind, GList * args,
310          struct cbdata * cbdata, gboolean paused )
311{
312    enum tr_torrent_action action;
313
314    /* fill out cbdata */
315    cbdata->wind       = NULL;
316    cbdata->icon       = NULL;
317    cbdata->msgwin     = NULL;
318    cbdata->prefs      = NULL;
319    cbdata->timer      = 0;
320    cbdata->closing    = FALSE;
321    cbdata->errqueue   = NULL;
322
323    actions_set_core( cbdata->core );
324
325    /* set up core handlers */
326    g_signal_connect( cbdata->core, "error", G_CALLBACK( coreerr ), cbdata );
327    g_signal_connect( cbdata->core, "directory-prompt",
328                      G_CALLBACK( coreprompt ), cbdata );
329    g_signal_connect( cbdata->core, "directory-prompt-data",
330                      G_CALLBACK( corepromptdata ), cbdata );
331    g_signal_connect_swapped( cbdata->core, "quit",
332                              G_CALLBACK( wannaquit ), cbdata );
333    g_signal_connect( cbdata->core, "prefs-changed",
334                      G_CALLBACK( prefschanged ), cbdata );
335
336    /* apply a few prefs */
337    initializeFromPrefs( cbdata );
338
339    /* add torrents from command-line and saved state */
340    tr_core_load( cbdata->core, paused );
341
342    if( NULL != args )
343    {
344        action = tr_prefs_get_action( PREF_KEY_ADDIPC );
345        tr_core_add_list( cbdata->core, args, action, paused );
346    }
347    tr_core_torrents_added( cbdata->core );
348
349    /* set up the ipc socket */
350    ipc_socket_setup( GTK_WINDOW( wind ), cbdata->core );
351
352    /* set up main window */
353    winsetup( cbdata, wind );
354
355    /* start model update timer */
356    cbdata->timer = g_timeout_add( UPDATE_INTERVAL, updatemodel, cbdata );
357    updatemodel( cbdata );
358
359    /* show the window */
360    gtk_widget_show( GTK_WIDGET(wind) );
361}
362
363static gboolean
364winclose( GtkWidget * w UNUSED, GdkEvent * event UNUSED, gpointer gdata )
365{
366    struct cbdata * cbdata = gdata;
367
368    if( cbdata->icon != NULL )
369        gtk_widget_hide( GTK_WIDGET( cbdata->wind ) );
370    else
371        askquit( cbdata->core, cbdata->wind, wannaquit, cbdata );
372
373    return TRUE; /* don't propagate event further */
374}
375
376static void
377rowChangedCB( GtkTreeModel  * model UNUSED,
378              GtkTreePath   * path,
379              GtkTreeIter   * iter UNUSED,
380              gpointer        sel)
381{
382    if( gtk_tree_selection_path_is_selected ( sel, path ) )
383        refreshTorrentActions( GTK_TREE_SELECTION(sel) );
384}
385
386static void
387winsetup( struct cbdata * cbdata, TrWindow * wind )
388{
389    GtkTreeModel * model;
390    GtkTreeSelection * sel;
391
392    g_assert( NULL == cbdata->wind );
393    cbdata->wind = GTK_WINDOW( wind );
394
395    sel = tr_window_get_selection( cbdata->wind );
396    g_signal_connect( sel, "changed", G_CALLBACK(selectionChangedCB), NULL );
397    selectionChangedCB( sel, NULL );
398    model = tr_core_model( cbdata->core );
399    g_signal_connect( model, "row-changed", G_CALLBACK(rowChangedCB), sel );
400    g_signal_connect( wind, "delete-event", G_CALLBACK( winclose ), cbdata );
401    refreshTorrentActions( sel );
402   
403    setupdrag( GTK_WIDGET(wind), cbdata );
404}
405
406static void
407makeicon( struct cbdata * cbdata )
408{
409    if( cbdata->icon == NULL )
410        cbdata->icon = tr_icon_new( );
411}
412
413static gpointer
414quitThreadFunc( gpointer gdata )
415{
416    struct cbdata * cbdata = gdata;
417
418    tr_close( tr_core_handle( cbdata->core ) );
419
420    /* shutdown the gui */
421    if( cbdata->prefs )
422        gtk_widget_destroy( GTK_WIDGET( cbdata->prefs ) );
423    if( cbdata->wind )
424        gtk_widget_destroy( GTK_WIDGET( cbdata->wind ) );
425    g_object_unref( cbdata->core );
426    if( cbdata->icon )
427        g_object_unref( cbdata->icon );
428    if( cbdata->errqueue ) {
429        g_list_foreach( cbdata->errqueue, (GFunc)g_free, NULL );
430        g_list_free( cbdata->errqueue );
431    }
432    g_free( cbdata );
433
434    /* exit the gtk main loop */
435    gtk_main_quit( );
436    return NULL;
437}
438
439/* since there are no buttons in the dialog, gtk tries to
440 * select one of the labels, which looks ugly... so force
441 * the dialog's primary and secondary labels to be unselectable */
442static void
443deselectLabels( GtkWidget * w, gpointer unused UNUSED )
444{
445    if( GTK_IS_LABEL( w ) )
446        gtk_label_set_selectable( GTK_LABEL(w), FALSE );
447    else if( GTK_IS_CONTAINER( w ) )
448        gtk_container_foreach( GTK_CONTAINER(w), deselectLabels, NULL );
449}
450
451static void
452do_exit_cb( GtkWidget *w UNUSED, gpointer data UNUSED )
453{
454    exit( 0 );
455}
456
457static void
458wannaquit( void * vdata )
459{
460    char * str;
461    GtkWidget * r, * p, * b, * w, *c;
462    struct cbdata * cbdata = vdata;
463
464    /* stop the update timer */
465    if( cbdata->timer ) {
466        g_source_remove( cbdata->timer );
467        cbdata->timer = 0;
468    }
469
470    c = GTK_WIDGET( cbdata->wind );
471    gtk_container_remove( GTK_CONTAINER( c ), gtk_bin_get_child( GTK_BIN( c ) ) );
472
473    r = gtk_alignment_new(0.5, 0.5, 0.01, 0.01);
474    gtk_container_add(GTK_CONTAINER(c), r);
475
476    p = gtk_table_new(2, 2, FALSE);
477    gtk_container_add(GTK_CONTAINER(r), p);
478
479    w = gtk_image_new_from_stock( GTK_STOCK_NETWORK, GTK_ICON_SIZE_DIALOG );
480    gtk_table_attach(GTK_TABLE(p), w, 0, 1, 0, 1, GTK_FILL, GTK_FILL, 2, 2);
481
482    w = gtk_label_new("");
483    str = g_strdup_printf( "<b>%s</b>\n%s", _("Closing Connections"), _("Sending upload/download totals to tracker...") );
484    gtk_label_set_markup(GTK_LABEL(w), str );
485    gtk_table_attach(GTK_TABLE(p), w, 1, 2, 0, 1, GTK_FILL, GTK_FILL, 10, 0);
486    g_free( str );
487
488    b = gtk_alignment_new(0.0, 1.0, 0.01, 0.01);
489    w = gtk_button_new_with_label( _( "_Quit Immediately" ) );
490    gtk_button_set_image( GTK_BUTTON(w), gtk_image_new_from_stock( GTK_STOCK_QUIT, GTK_ICON_SIZE_BUTTON ) );
491    g_signal_connect(w, "clicked", G_CALLBACK(do_exit_cb), NULL);
492    gtk_container_add(GTK_CONTAINER(b), w);
493    gtk_table_attach(GTK_TABLE(p), b, 1, 2, 1, 2, GTK_FILL, GTK_FILL, 10, 0);
494
495    gtk_widget_show_all(r);
496
497    /* clear the UI */
498    gtk_list_store_clear( GTK_LIST_STORE( tr_core_model( cbdata->core ) ) );
499
500    /* shut down libT */
501    g_thread_create( quitThreadFunc, vdata, TRUE, NULL );
502}
503
504static void
505gotdrag( GtkWidget         * widget UNUSED,
506         GdkDragContext    * dc,
507         gint                x UNUSED,
508         gint                y UNUSED,
509         GtkSelectionData  * sel,
510         guint               info UNUSED,
511         guint               time,
512         gpointer            gdata )
513{
514    struct cbdata * data = gdata;
515    GList * paths = NULL;
516    GList * freeme = NULL;
517
518#ifdef DND_DEBUG
519    char *sele = gdk_atom_name(sel->selection);
520    char *targ = gdk_atom_name(sel->target);
521    char *type = gdk_atom_name(sel->type);
522
523    g_message( "dropped file: sel=%s targ=%s type=%s fmt=%i len=%i",
524               sele, targ, type, sel->format, sel->length );
525    g_free(sele);
526    g_free(targ);
527    g_free(type);
528    if( sel->format == 8 ) {
529        for( i=0; i<sel->length; ++i )
530            fprintf(stderr, "%02X ", sel->data[i]);
531        fprintf(stderr, "\n");
532    }
533#endif
534
535    if( ( sel->format == 8 ) &&
536        ( sel->selection == gdk_atom_intern( "XdndSelection", FALSE ) ) )
537    {
538        int i;
539        char * str = g_strndup( (char*)sel->data, sel->length );
540        gchar ** files = g_strsplit_set( str, "\r\n", -1 );
541        for( i=0; files && files[i]; ++i )
542        {
543            char * filename;
544            if( !*files[i] ) /* empty filename... */
545                continue;
546
547            /* decode the filename */
548            filename = urldecode( files[i], -1 );
549            freeme = g_list_prepend( freeme, filename );
550            if( !g_utf8_validate( filename, -1, NULL ) )
551                continue;
552
553            /* walk past "file://", if present */
554            if( g_str_has_prefix( filename, "file:" ) ) {
555                filename += 5;
556                while( g_str_has_prefix( filename, "//" ) )
557                    ++filename;
558            }
559
560            /* if the file doesn't exist, the first part
561               might be a hostname ... walk past it. */
562            if( !g_file_test( filename, G_FILE_TEST_EXISTS ) ) {
563                char * pch = strchr( filename + 1, '/' );
564                if( pch != NULL )
565                    filename = pch;
566            }
567
568            /* finally, add it to the list of torrents to try adding */
569            if( g_file_test( filename, G_FILE_TEST_EXISTS ) )
570                paths = g_list_prepend( paths, filename );
571        }
572
573        /* try to add any torrents we found */
574        if( paths != NULL )
575        {
576            enum tr_torrent_action action = tr_prefs_get_action( PREF_KEY_ADDSTD );
577            paths = g_list_reverse( paths );
578            tr_core_add_list( data->core, paths, action, FALSE );
579            tr_core_torrents_added( data->core );
580            g_list_free( paths );
581        }
582
583        freestrlist( freeme );
584        g_strfreev( files );
585        g_free( str );
586    }
587
588    gtk_drag_finish(dc, (NULL != paths), FALSE, time);
589}
590
591static void
592setupdrag(GtkWidget *widget, struct cbdata *data) {
593  GtkTargetEntry targets[] = {
594    { "STRING",     0, 0 },
595    { "text/plain", 0, 0 },
596    { "text/uri-list", 0, 0 },
597  };
598
599  g_signal_connect(widget, "drag_data_received", G_CALLBACK(gotdrag), data);
600
601  gtk_drag_dest_set(widget, GTK_DEST_DEFAULT_ALL, targets,
602                    ALEN(targets), GDK_ACTION_COPY | GDK_ACTION_MOVE);
603}
604
605static void
606coreerr( TrCore * core UNUSED, enum tr_core_err code, const char * msg,
607         gpointer gdata )
608{
609    struct cbdata * cbdata = gdata;
610    char          * joined;
611
612    switch( code )
613    {
614        case TR_CORE_ERR_ADD_TORRENT:
615            cbdata->errqueue = g_list_append( cbdata->errqueue,
616                                              g_strdup( msg ) );
617            return;
618        case TR_CORE_ERR_NO_MORE_TORRENTS:
619            if( NULL != cbdata->errqueue )
620            {
621                joined = joinstrlist( cbdata->errqueue, "\n" );
622                errmsg( cbdata->wind,
623                        ngettext( "Failed to load torrent file:\n%s",
624                                  "Failed to load torrent files:\n%s",
625                                  g_list_length( cbdata->errqueue ) ),
626                        joined );
627                g_list_foreach( cbdata->errqueue, (GFunc) g_free, NULL );
628                g_list_free( cbdata->errqueue );
629                cbdata->errqueue = NULL;
630                g_free( joined );
631            }
632            return;
633        case TR_CORE_ERR_SAVE_STATE:
634            errmsg( cbdata->wind, "%s", msg );
635            return;
636    }
637
638    g_assert_not_reached();
639}
640
641void
642coreprompt( TrCore * core, GList * paths, enum tr_torrent_action act,
643            gboolean paused, gpointer gdata )
644{
645    struct cbdata * cbdata = gdata;
646
647    promptfordir( cbdata->wind, core, paths, NULL, 0, act, paused );
648}
649
650void
651corepromptdata( TrCore * core, uint8_t * data, size_t size,
652                gboolean paused, gpointer gdata )
653{
654    struct cbdata * cbdata = gdata;
655
656    promptfordir( cbdata->wind, core, NULL, data, size, TR_TOR_LEAVE, paused );
657}
658
659static void
660initializeFromPrefs( struct cbdata * cbdata )
661{
662    prefschanged( NULL, PREF_KEY_SYSTRAY, cbdata );
663}
664
665static void
666prefschanged( TrCore * core UNUSED, const char * key, gpointer data )
667{
668    struct cbdata * cbdata = data;
669    tr_handle     * tr     = tr_core_handle( cbdata->core );
670
671    if( !strcmp( key, PREF_KEY_ENCRYPTED_ONLY ) )
672    {
673        const gboolean crypto_only = pref_flag_get( key );
674        tr_setEncryptionMode( tr, crypto_only ? TR_ENCRYPTION_REQUIRED
675                                              : TR_ENCRYPTION_PREFERRED );
676    }
677    else if( !strcmp( key, PREF_KEY_PORT ) )
678    {
679        const int port = pref_int_get( key );
680        tr_setBindPort( tr, port );
681    }
682    else if( !strcmp( key, PREF_KEY_DL_LIMIT_ENABLED ) )
683    {
684        const gboolean b = pref_flag_get( key );
685        tr_setUseGlobalSpeedLimit( tr, TR_DOWN, b );
686    }
687    else if( !strcmp( key, PREF_KEY_DL_LIMIT ) )
688    {
689        const int limit = pref_int_get( key );
690        tr_setGlobalSpeedLimit( tr, TR_DOWN, limit );
691    }
692    else if( !strcmp( key, PREF_KEY_UL_LIMIT_ENABLED ) )
693    {
694        const gboolean b = pref_flag_get( key );
695        tr_setUseGlobalSpeedLimit( tr, TR_UP, b );
696    }
697    else if( !strcmp( key, PREF_KEY_UL_LIMIT ) )
698    {
699        const int limit = pref_int_get( key );
700        tr_setGlobalSpeedLimit( tr, TR_UP, limit );
701    }
702    else if( !strcmp( key, PREF_KEY_NAT ) )
703    {
704        const gboolean enabled = pref_flag_get( key );
705        tr_natTraversalEnable( tr, enabled );
706    }
707    else if( !strcmp( key, PREF_KEY_SYSTRAY ) )
708    {
709        if( pref_flag_get( key ) )
710        {
711            makeicon( cbdata );
712        }
713        else if( cbdata->icon )
714        {
715            g_object_unref( cbdata->icon );
716            cbdata->icon = NULL;
717        }
718    }
719    else if( !strcmp( key, PREF_KEY_PEX ) )
720    {
721        const gboolean enabled = pref_flag_get( key );
722        tr_setPexEnabled( tr_core_handle( cbdata->core ), enabled );
723    }
724}
725
726gboolean
727updatemodel(gpointer gdata) {
728  struct cbdata *data = gdata;
729
730  if( !data->closing && 0 < global_sigcount )
731  {
732      wannaquit( data );
733      return FALSE;
734  }
735
736  /* update the torrent data in the model */
737  tr_core_update( data->core );
738
739  /* update the main window's statusbar and toolbar buttons */
740  if( data->wind )
741      tr_window_update( data->wind );
742
743  /* update the message window */
744  msgwin_update();
745
746  return TRUE;
747}
748
749/* returns a GList of GtkTreeRowReferences to each selected row */
750static GList *
751getselection( struct cbdata * cbdata )
752{
753    GList * rows = NULL;
754
755    if( NULL != cbdata->wind )
756    {
757        GList * l;
758        GtkTreeSelection *s = tr_window_get_selection(cbdata->wind);
759        GtkTreeModel * filter_model;
760        GtkTreeModel * store_model;
761        rows = gtk_tree_selection_get_selected_rows( s, &filter_model );
762        store_model = gtk_tree_model_filter_get_model(
763                                                 GTK_TREE_MODEL_FILTER( filter_model ) );
764        for( l=rows; l!=NULL; l=l->next )
765        {
766            GtkTreePath * path = gtk_tree_model_filter_convert_path_to_child_path(
767                                        GTK_TREE_MODEL_FILTER( filter_model ), l->data );
768            GtkTreeRowReference * ref = gtk_tree_row_reference_new( store_model, path );
769            gtk_tree_path_free( path );
770            gtk_tree_path_free( l->data );
771            l->data = ref;
772        }
773    }
774
775    return rows;
776}
777
778static void
779about ( void )
780{
781  GtkWidget * w = gtk_about_dialog_new ();
782  GtkAboutDialog * a = GTK_ABOUT_DIALOG (w);
783  const char *authors[] = { "Charles Kerr (Backend; GTK+)",
784                            "Mitchell Livingston (Backend; OS X)",
785                            "Eric Petit (Backend; OS X)",
786                            "Josh Elsasser (Daemon; Backend; GTK+)",
787                            "Bryan Varner (BeOS)", 
788                            NULL };
789  gtk_about_dialog_set_version (a, LONG_VERSION_STRING );
790#ifdef SHOW_LICENSE
791  gtk_about_dialog_set_license (a, LICENSE);
792  gtk_about_dialog_set_wrap_license (a, TRUE);
793#endif
794  gtk_about_dialog_set_logo_icon_name( a, "transmission-logo" );
795  gtk_about_dialog_set_comments( a, _("A fast and easy BitTorrent client") );
796  gtk_about_dialog_set_website( a, "http://www.transmissionbt.com/" );
797  gtk_about_dialog_set_copyright( a, _("Copyright 2005-2008 The Transmission Project") );
798  gtk_about_dialog_set_authors( a, authors );
799  /* note to translators: put yourself here for credit in the "About" dialog */
800  gtk_about_dialog_set_translator_credits( a, _("translator-credits") );
801  g_signal_connect_swapped( w, "response", G_CALLBACK (gtk_widget_destroy), w );
802  gtk_widget_show_all( w );
803}
804
805static void
806startTorrentForeach (GtkTreeModel * model,
807                     GtkTreePath  * path UNUSED,
808                     GtkTreeIter  * iter,
809                     gpointer       data UNUSED)
810{
811    TrTorrent * tor = NULL;
812    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
813    tr_torrent_start( tor );
814    g_object_unref( G_OBJECT( tor ) );
815}
816
817static void
818stopTorrentForeach (GtkTreeModel * model,
819                    GtkTreePath  * path UNUSED,
820                    GtkTreeIter  * iter,
821                    gpointer       data UNUSED)
822{
823    TrTorrent * tor = NULL;
824    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
825    tr_torrent_stop( tor );
826    g_object_unref( G_OBJECT( tor ) );
827}
828
829static void
830updateTrackerForeach (GtkTreeModel * model,
831                      GtkTreePath  * path UNUSED,
832                      GtkTreeIter  * iter,
833                      gpointer       data UNUSED)
834{
835    TrTorrent * tor = NULL;
836    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
837    tr_manualUpdate( tr_torrent_handle( tor ) );
838    g_object_unref( G_OBJECT( tor ) );
839}
840
841static void
842showInfoForeach (GtkTreeModel * model,
843                 GtkTreePath  * path UNUSED,
844                 GtkTreeIter  * iter,
845                 gpointer       data UNUSED)
846{
847    TrTorrent * tor = NULL;
848    GtkWidget * w;
849    gtk_tree_model_get( model, iter, MC_TORRENT, &tor, -1 );
850    w = torrent_inspector_new( GTK_WINDOW(data), tor );
851    gtk_widget_show( w );
852    g_object_unref( G_OBJECT( tor ) );
853}
854
855static void
856recheckTorrentForeach (GtkTreeModel * model,
857                       GtkTreePath  * path UNUSED,
858                       GtkTreeIter  * iter,
859                       gpointer       data UNUSED)
860{
861    TrTorrent * gtor = NULL;
862    gtk_tree_model_get( model, iter, MC_TORRENT, &gtor, -1 );
863    tr_torrentRecheck( tr_torrent_handle( gtor ) );
864    g_object_unref( G_OBJECT( gtor ) );
865}
866
867static gboolean
868msgwinclosed()
869{
870  action_toggle( "toggle-message-log", FALSE );
871  return FALSE;
872}
873
874void
875doAction ( const char * action_name, gpointer user_data )
876{
877    struct cbdata * data = (struct cbdata *) user_data;
878    gboolean changed = FALSE;
879
880    if (!strcmp (action_name, "add-torrent"))
881    {
882        makeaddwind( data->wind, data->core );
883    }
884    else if (!strcmp (action_name, "show-stats"))
885    {
886        GtkWidget * dialog = stats_dialog_create( data->wind,
887                                                  data->core );
888        gtk_widget_show( dialog );
889    }
890    else if (!strcmp (action_name, "start-torrent"))
891    {
892        GtkTreeSelection * s = tr_window_get_selection(data->wind);
893        gtk_tree_selection_selected_foreach( s, startTorrentForeach, NULL );
894        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
895    }
896    else if (!strcmp (action_name, "pause-torrent"))
897    {
898        GtkTreeSelection * s = tr_window_get_selection(data->wind);
899        gtk_tree_selection_selected_foreach( s, stopTorrentForeach, NULL );
900        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
901    }
902    else if (!strcmp (action_name, "verify-torrent"))
903    {
904        GtkTreeSelection * s = tr_window_get_selection(data->wind);
905        gtk_tree_selection_selected_foreach( s, recheckTorrentForeach, NULL );
906        changed |= gtk_tree_selection_count_selected_rows( s ) != 0;
907    }
908    else if (!strcmp (action_name, "show-torrent-details"))
909    {
910        GtkTreeSelection * s = tr_window_get_selection(data->wind);
911        gtk_tree_selection_selected_foreach( s, showInfoForeach, data->wind );
912    }
913    else if (!strcmp( action_name, "update-tracker"))
914    {
915        GtkTreeSelection * s = tr_window_get_selection(data->wind);
916        gtk_tree_selection_selected_foreach( s, updateTrackerForeach, data->wind );
917    }
918    else if (!strcmp (action_name, "create-torrent"))
919    {
920        GtkWidget * w = make_meta_ui( GTK_WINDOW( data->wind ),
921                                      tr_core_handle( data->core ) );
922        gtk_widget_show_all( w );
923    }
924    else if (!strcmp (action_name, "remove-torrent"))
925    {
926        /* this modifies the model's contents, so can't use foreach */
927        GList *l, *sel = getselection( data );
928        GtkTreeModel *model = tr_core_model( data->core );
929        for( l=sel; l!=NULL; l=l->next )
930        {
931            GtkTreeIter iter;
932            GtkTreeRowReference * reference = l->data;
933            GtkTreePath * path = gtk_tree_row_reference_get_path( reference );
934            gtk_tree_model_get_iter( model, &iter, path );
935            tr_core_delete_torrent( data->core, &iter );
936            gtk_tree_row_reference_free( reference );
937            changed = TRUE;
938        }
939        g_list_free( sel );
940    }
941    else if (!strcmp (action_name, "close"))
942    {
943        if( data->wind != NULL )
944            winclose( NULL, NULL, data );
945    }
946    else if (!strcmp (action_name, "quit"))
947    {
948        askquit( data->core, data->wind, wannaquit, data );
949    }
950    else if (!strcmp (action_name, "select-all"))
951    {
952        GtkTreeSelection * s = tr_window_get_selection(data->wind);
953        gtk_tree_selection_select_all( s );
954    }
955    else if (!strcmp (action_name, "unselect-all"))
956    {
957        GtkTreeSelection * s = tr_window_get_selection(data->wind);
958        gtk_tree_selection_unselect_all( s );
959    }
960    else if (!strcmp (action_name, "edit-preferences"))
961    {
962        if( NULL == data->prefs )
963        {
964            data->prefs = tr_prefs_dialog_new( G_OBJECT(data->core), data->wind );
965            g_signal_connect( data->prefs, "destroy",
966                             G_CALLBACK( gtk_widget_destroyed ), &data->prefs );
967            gtk_widget_show( GTK_WIDGET( data->prefs ) );
968        }
969    }
970    else if (!strcmp (action_name, "toggle-message-log"))
971    {
972        if( !data->msgwin )
973        {
974            GtkWidget * win = msgwin_create( data->core );
975            g_signal_connect( win, "destroy", G_CALLBACK( msgwinclosed ), 
976                             NULL );
977            data->msgwin = win;
978        }
979        else
980        {
981            action_toggle("toggle-message-log", FALSE);
982            gtk_widget_destroy( data->msgwin );
983            data->msgwin = NULL;
984        }
985    }
986    else if (!strcmp (action_name, "show-about-dialog"))
987    {
988        about();
989    }
990    else if (!strcmp (action_name, "toggle-main-window"))
991    {
992        GtkWidget * w = GTK_WIDGET (data->wind);
993        if (GTK_WIDGET_VISIBLE(w))
994            gtk_widget_hide (w);
995        else
996            gtk_window_present (GTK_WINDOW(w));
997    }
998    else g_error ("Unhandled action: %s", action_name );
999
1000    if( changed )
1001        updatemodel( data );
1002}
1003
1004
1005static void
1006setupsighandlers(void) {
1007  int sigs[] = {SIGHUP, SIGINT, SIGQUIT, SIGTERM};
1008  struct sigaction sa;
1009  int ii;
1010
1011  memset(&sa, 0,  sizeof(sa));
1012  sa.sa_handler = fatalsig;
1013  for(ii = 0; ii < ALEN(sigs); ii++)
1014    sigaction(sigs[ii], &sa, NULL);
1015}
1016
1017static void
1018fatalsig(int sig) {
1019  struct sigaction sa;
1020
1021  if(SIGCOUNT_MAX <= ++global_sigcount) {
1022    memset(&sa, 0,  sizeof(sa));
1023    sa.sa_handler = SIG_DFL;
1024    sigaction(sig, &sa, NULL);
1025    raise(sig);
1026  }
1027}
Note: See TracBrowser for help on using the repository browser.