Exemplo n.º 1
0
        private void HandleActiveSourceChanged(SourceEventArgs args)
        {
            FilterFocused = false;

            if (current_source != null && current_source.TrackModel != null)
            {
                current_source.TrackModel.Reloaded          -= OnReloaded;
                current_source.TrackModel.Selection.Changed -= HandleSelectionChanged;
                current_source = null;
            }

            ITrackModelSource new_source = ActiveSource as ITrackModelSource;

            if (new_source != null)
            {
                new_source.TrackModel.Selection.Changed += HandleSelectionChanged;
                new_source.TrackModel.Reloaded          += OnReloaded;
                current_source = new_source;
                Selection      = new_source.TrackModel.Selection;
            }

            ThreadAssist.ProxyToMain(UpdateActions);
        }
Exemplo n.º 2
0
        public void ZoomFit(bool upscale)
        {
            var scrolled = Parent as Gtk.ScrolledWindow;

            if (scrolled != null)
            {
                scrolled.SetPolicy(Gtk.PolicyType.Never, Gtk.PolicyType.Never);
            }

            min_zoom = ComputeMinZoom(upscale);

            this.upscale = upscale;

            Fit = true;
            DoZoom(MIN_ZOOM, Allocation.Width / 2, Allocation.Height / 2);

            if (scrolled != null)
            {
                ThreadAssist.ProxyToMain(() => {
                    scrolled.SetPolicy(Gtk.PolicyType.Automatic, Gtk.PolicyType.Automatic);
                });
            }
        }
Exemplo n.º 3
0
        void DoImport(CancellationToken token)
        {
            scanThread?.Join();

            FireEvent(ImportEvent.ImportStarted);

            var importer = App.Instance.Container.Resolve <IImportController> ();

            importer.DoImport(App.Instance.Database, Photos, attachTags, DuplicateDetect, CopyFiles,
                              RemoveOriginals, (current, total) => ThreadAssist.ProxyToMain(() => ReportProgress(current, total)),
                              token);

            PhotosImported = importer.PhotosImported;
            FailedImports.Clear();
            FailedImports.AddRange(importer.FailedImports);

            if (!token.IsCancellationRequested)
            {
                importThread = null;
            }

            FireEvent(ImportEvent.ImportFinished);
        }
Exemplo n.º 4
0
        public void CheckAuthorization()
        {
            var args = new AuthorizationEventArgs();

            try {
                token = fr.CheckLogin(oauth_verification_code.Text);
            } catch (FlickrException e) {
                args.Exception = e;
            } catch (Exception e) {
                var md =
                    new HigMessageDialog(Dialog,
                                         Gtk.DialogFlags.Modal |
                                         Gtk.DialogFlags.DestroyWithParent,
                                         Gtk.MessageType.Error, Gtk.ButtonsType.Ok,
                                         Catalog.GetString("Unable to log on"), e.Message);

                md.Run();
                md.Destroy();
                return;
            }

            ThreadAssist.ProxyToMain(() => {
                do_export_flickr.Sensitive = token != null;
                if (token != null)
                {
                    CurrentState = State.Authorized;
                    Preferences.Set(current_service.PreferencePath, token.Token);
                    Preferences.Set(current_service.PreferencePath + "secret", token.TokenSecret);
                    Preferences.Set(current_service.PreferencePath + "userId", token.UserId);
                    Preferences.Set(current_service.PreferencePath + "userName", token.Username);
                }
                else
                {
                    CurrentState = State.Disconnected;
                }
            });
        }
Exemplo n.º 5
0
        public override void Activate()
        {
            if (client != null || is_activating)
            {
                return;
            }

            ClearErrorView();

            is_activating = true;
            base.Activate();

            SetStatus(String.Format(Catalog.GetString("Connecting to {0}"), service.Name), false);

            ThreadAssist.Spawn(delegate {
                try {
                    client          = new DAAP.Client(service);
                    client.Updated += OnClientUpdated;

                    if (client.AuthenticationMethod == DAAP.AuthenticationMethod.None)
                    {
                        client.Login();
                    }
                    else
                    {
                        ThreadAssist.ProxyToMain(PromptLogin);
                    }
                } catch (Exception e) {
                    ThreadAssist.ProxyToMain(delegate {
                        ShowErrorView(DaapErrorType.BrokenAuthentication);
                    });
                    Hyena.Log.Exception(e);
                }

                is_activating = false;
            });
        }
        private bool RemovePodcastFromLibrary(PodcastInfo pi, bool commit_podcast)
        {
            if (pi == null)
            {
                throw new ArgumentNullException("pi");
            }

            if (pi.IsQueued)
            {
                return(false);
            }

            podcasts.Remove(pi.Key);

            if (pi.Track != null)
            {
                ThreadAssist.ProxyToMain(delegate {
                    RemoveTrack(pi.Track, true);
                });
            }

            if (!pi.IsActive)
            {
                return(true);
            }
            else
            {
                pi.IsActive = false;
            }

            if (commit_podcast)
            {
                PodcastDBManager.Deactivate(pi);
            }

            return(true);
        }
Exemplo n.º 7
0
        void DoReload()
        {
            Task.Delay(200);

            var years_tmp     = query.Store.PhotosPerMonth();
            int startyear_tmp = int.MaxValue;
            int endyear_tmp   = int.MinValue;

            foreach (int year in years_tmp.Keys)
            {
                startyear_tmp = Math.Min(year, startyear_tmp);
                endyear_tmp   = Math.Max(year, endyear_tmp);
            }

            ThreadAssist.ProxyToMain(() => {
                years     = years_tmp;
                startyear = startyear_tmp;
                endyear   = endyear_tmp;

                Changed?.Invoke(this);
            });

            Log.DebugTimerPrint(timer, "TimeAdaptor REAL Reload took {0}");
        }
Exemplo n.º 8
0
        protected void ScanPhotoDirectory(ImportController controller, SafeUri uri, PhotoList photo_list)
        {
            var enumerator = new RecursiveFileEnumerator(uri)
            {
                Recurse        = controller.RecurseSubdirectories,
                CatchErrors    = true,
                IgnoreSymlinks = true
            };
            var infos = new List <FileImportInfo> ();

            foreach (var file in enumerator)
            {
                if (ImageFile.HasLoader(new SafeUri(file.Uri.ToString(), true)))
                {
                    infos.Add(new FileImportInfo(new SafeUri(file.Uri.ToString(), true)));
                }

                if (infos.Count % 10 == 0 || infos.Count < 10)
                {
                    var to_add = infos;                     // prevents race condition
                    ThreadAssist.ProxyToMain(() => photo_list.Add(to_add.ToArray()));
                    infos = new List <FileImportInfo> ();
                }

                if (!run_photoscanner)
                {
                    return;
                }
            }

            if (infos.Count > 0)
            {
                var to_add = infos;                 // prevents race condition
                ThreadAssist.ProxyToMain(() => photo_list.Add(to_add.ToArray()));
            }
        }
Exemplo n.º 9
0
        private void Process()
        {
            var handler = payload_handler;

            while (processing)
            {
                manual_event.WaitOne();
                while (handler != null && QueueCount() > 0)
                {
                    handler(this, Dequeue());
                }
            }

            // flush queue
            for (int i = QueueCount() - 1; i >= 0; i--)
            {
                handler(this, Dequeue());
            }

            ThreadAssist.ProxyToMain(delegate {
                processed = true;
                OnProcessingComplete(EventArgs.Empty);
            });
        }
Exemplo n.º 10
0
        public void SetActiveSource(Source source, bool notify)
        {
            ThreadAssist.AssertInMainThread();
            if (source == null || !source.CanActivate || active_source == source)
            {
                return;
            }

            if (active_source != null)
            {
                active_source.Deactivate();
            }

            active_source = source;
            if (source.Parent != null)
            {
                source.Parent.Expanded = true;
            }

            if (!notify)
            {
                source.Activate();
                return;
            }

            SourceEventHandler handler = ActiveSourceChanged;

            if (handler != null)
            {
                SourceEventArgs args = new SourceEventArgs();
                args.Source = active_source;
                handler(args);
            }

            source.Activate();
        }
Exemplo n.º 11
0
        public void CheckAuthorization()
        {
            AuthorizationEventArgs args = new AuthorizationEventArgs();

            try {
                args.Auth = fr.CheckLogin();
            } catch (FlickrException e) {
                args.Exception = e;
            } catch (Exception e) {
                HigMessageDialog md =
                    new HigMessageDialog(Dialog,
                                         Gtk.DialogFlags.Modal |
                                         Gtk.DialogFlags.DestroyWithParent,
                                         Gtk.MessageType.Error, Gtk.ButtonsType.Ok,
                                         Catalog.GetString("Unable to log on"), e.Message);

                md.Run();
                md.Destroy();
                return;
            }

            ThreadAssist.ProxyToMain(() => {
                do_export_flickr.Sensitive = args.Auth != null;
                if (args.Auth != null)
                {
                    token        = args.Auth.Token;
                    auth         = args.Auth;
                    CurrentState = State.Authorized;
                    Preferences.Set(current_service.PreferencePath, token);
                }
                else
                {
                    CurrentState = State.Disconnected;
                }
            });
        }
Exemplo n.º 12
0
        private void LoadStations()
        {
            total_stations = 0;
            station_groups.Clear();

            try {
                Directory.CreateDirectory(stations_path);

                foreach (string xspf_file in Directory.GetFiles(stations_path, "*.xspf"))
                {
                    LoadStation(xspf_file);
                }

                foreach (string xspf_file in Directory.GetFiles(Path.Combine(stations_path, "user"), "*.xspf"))
                {
                    LoadStation(xspf_file);
                }
            } catch {
            }

            ThreadAssist.ProxyToMain(delegate {
                OnStationsLoaded();
            });
        }
        public void ShowRecommendations(string artist)
        {
            if (current_artist == artist)
            {
                Show();
                return;
            }

            Hide();

            ThreadAssist.Spawn(delegate {
                XmlNodeList artists, tracks, albums;
                try {
                    if (QueryRecommendationData(artist, out artists, out tracks, out albums))
                    {
                        ThreadAssist.ProxyToMain(delegate {
                            RenderRecommendationData(artist, artists, tracks, albums);
                        });
                    }
                } catch (Exception e) {
                    Console.Error.WriteLine("Could not fetch recommendations: {0}", e.Message);
                }
            });
        }
Exemplo n.º 14
0
        private void OnShuffleModeChanged(object o, EventArgs <string> args)
        {
            if (shuffle_modes[active_action.Value] != args.Value)
            {
                // This happens only when changing the mode using DBus.
                // In this case we need to locate the action by its value.
                ThreadAssist.ProxyToMain(delegate {
                    foreach (RadioAction action in this)
                    {
                        if (shuffle_modes[action.Value] == args.Value)
                        {
                            active_action = action;
                            break;
                        }
                    }
                });
            }

            if (saved_action == null)
            {
                ShuffleMode.Set(ActionNameToConfigId(active_action.Name));
            }
            OnChanged();
        }
Exemplo n.º 15
0
        public void RunDialog()
        {
            ResponseType response = (ResponseType)dialog.Run();

            //int w = -1, h = -1;
            //dialog.GetSize (out w, out h);
            //Console.WriteLine ("w = {0}, h = {1}", w, h);

            if (response == ResponseType.Ok)
            {
                string name         = Name;
                string condition    = Condition;
                string order_by     = OrderBy;
                string limit_number = LimitNumber;

                ThreadAssist.Spawn(delegate {
                    //Console.WriteLine ("Name = {0}, Cond = {1}, OrderAndLimit = {2}", name, condition, order_by, limit_number);
                    if (playlist == null)
                    {
                        playlist = new SmartPlaylist(name, condition, order_by, limit_number);
                        playlist.Source.Commit();
                        SourceManager.AddSource(playlist.Source);
                    }
                    else
                    {
                        playlist.Name        = name;
                        playlist.Condition   = condition;
                        playlist.OrderBy     = order_by;
                        playlist.LimitNumber = limit_number;
                        playlist.Commit();
                    }
                });
            }

            dialog.Destroy();
        }
Exemplo n.º 16
0
 // FIXME filter
 private void OnRateSelectedTracks(object o, EventArgs args)
 {
     ThreadAssist.SpawnFromMain(delegate {
         ((DatabaseSource)ActiveSource).RateSelectedTracks(selected_tracks_rating_proxy.LastRating);
     });
 }
Exemplo n.º 17
0
 private void OnJobUpdated(object o, EventArgs args)
 {
     ThreadAssist.ProxyToMain(Update);
 }
Exemplo n.º 18
0
 private void OnReloaded(object sender, EventArgs args)
 {
     ThreadAssist.ProxyToMain(delegate {
         UpdateActions();
     });
 }
Exemplo n.º 19
0
 private void OnPlayerEvent(PlayerEventArgs args)
 {
     ThreadAssist.ProxyToMain(() => {
         UpdateActions();
     });
 }
Exemplo n.º 20
0
 private void HandleActiveSourceUpdated(object o, EventArgs args)
 {
     ThreadAssist.ProxyToMain(delegate {
         UpdateActions(true);
     });
 }
 private void OnFeedTitleUpdated(object sender, FeedTitleUpdatedEventArgs args)
 {
     ThreadAssist.ProxyToMain(delegate {
         Reorder();
     });
 }
Exemplo n.º 22
0
        void DoLogin()
        {
            if (!account.Authenticated)
            {
                HigMessageDialog error = new HigMessageDialog(this, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
                                                              Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString("Error logging into Facebook"),
                                                              Catalog.GetString("There was a problem logging into Facebook.  Check your credentials and try again."));
                error.Run();
                error.Destroy();

                DoLogout();
            }
            else
            {
                log_buttons_hbox.Sensitive   = false;
                dialog_action_area.Sensitive = false;
                LoginProgress(0.0, Catalog.GetString("Authorizing Session"));
                ThreadPool.QueueUserWorkItem(delegate {
                    try {
                        bool perm_offline = account.HasPermission("offline_access");
                        bool perm_upload  = photo_perm_check.Active = account.HasPermission("photo_upload");

                        ThreadAssist.ProxyToMain(() => {
                            offline_perm_check.Active = perm_offline;
                            photo_perm_check.Active   = perm_upload;
                            LoginProgress(0.2, Catalog.GetString("Session established, fetching user info..."));
                        });

                        User me = account.Facebook.GetLoggedInUser().GetUserInfo();

                        ThreadAssist.ProxyToMain(() => {
                            LoginProgress(0.4, Catalog.GetString("Session established, fetching friend list..."));
                        });

                        Friend[] friend_list = account.Facebook.GetFriends();
                        long[] uids          = new long [friend_list.Length];

                        for (int i = 0; i < friend_list.Length; i++)
                        {
                            uids [i] = friend_list [i].UId;
                        }

                        ThreadAssist.ProxyToMain(() => {
                            LoginProgress(0.6, Catalog.GetString("Session established, fetching friend details..."));
                        });

                        if (uids.Length > 0)
                        {
                            User[] infos = account.Facebook.GetUserInfo(uids, new string[] { "first_name", "last_name" });
                            friends      = new Dictionary <long, User> ();

                            foreach (User user in infos)
                            {
                                friends.Add(user.uid, user);
                            }
                        }

                        ThreadAssist.ProxyToMain(() => {
                            LoginProgress(0.8, Catalog.GetString("Session established, fetching photo albums..."));
                        });
                        Album[] albums = account.Facebook.GetAlbums();
                        ThreadAssist.ProxyToMain(() => {
                            album_info_vbox.Sensitive   = true;
                            picture_info_vbox.Sensitive = true;
                            permissions_hbox.Sensitive  = true;
                            login_button.Visible        = false;
                            logout_button.Visible       = true;
                            // Note for translators: {0} and {1} are respectively firstname and surname of the user
                            LoginProgress(1.0, String.Format(Catalog.GetString("{0} {1} is logged into Facebook"), me.first_name, me.last_name));

                            existing_album_combobox.Model  = new AlbumStore(albums);
                            existing_album_combobox.Active = 0;
                        });
                    } catch (Exception e) {
                        Log.DebugException(e);
                        ThreadAssist.ProxyToMain(() => {
                            HigMessageDialog error = new HigMessageDialog(this, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
                                                                          Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString("Facebook Connection Error"),
                                                                          String.Format(Catalog.GetString("There was an error when downloading your information from Facebook.\n\nFacebook said: {0}"), e.Message));
                            error.Run();
                            error.Destroy();
                        });

                        account.Deauthenticate();
                        DoLogout();
                    } finally {
                        ThreadAssist.ProxyToMain(() => {
                            log_buttons_hbox.Sensitive   = true;
                            dialog_action_area.Sensitive = true;
                        });
                    }
                });
            }
        }
Exemplo n.º 23
0
        private void OnClientUpdated(object o, EventArgs args)
        {
            try {
                if (database == null && client.Databases.Count > 0)
                {
                    database = client.Databases[0];
                    DaapService.ProxyServer.RegisterDatabase(database);
                    database.TrackAdded   += OnDatabaseTrackAdded;
                    database.TrackRemoved += OnDatabaseTrackRemoved;

                    SetStatus(String.Format(Catalog.GetPluralString(
                                                "Loading {0} track", "Loading {0} tracks", database.TrackCount),
                                            database.TrackCount), false
                              );

                    // Notify (eg reload the source before sync is done) at most 5 times
                    int notify_every = Math.Max(250, (database.Tracks.Count / 4));
                    notify_every -= notify_every % 250;

                    int           count      = 0;
                    DaapTrackInfo daap_track = null;

                    HyenaSqliteConnection conn = ServiceManager.DbConnection;
                    conn.BeginTransaction();
                    foreach (DAAP.Track track in database.Tracks)
                    {
                        daap_track = new DaapTrackInfo(track, this);

                        // Only notify once in a while because otherwise the source Reloading slows things way down
                        if (++count % notify_every == 0)
                        {
                            conn.CommitTransaction();
                            daap_track.Save(true);
                            conn.BeginTransaction();
                        }
                        else
                        {
                            daap_track.Save(false);
                        }
                    }
                    conn.CommitTransaction();

                    // Save the last track once more to trigger the NotifyTrackAdded
                    if (daap_track != null)
                    {
                        daap_track.Save();
                    }

                    SetStatus(Catalog.GetString("Loading playlists"), false);
                    AddPlaylistSources();
                    connected = true;
                    Reload();
                    HideStatus();
                }

                Name = client.Name;

                UpdateIcon();
                OnUpdated();
            } catch (Exception e) {
                Hyena.Log.Exception("Caught exception while loading daap share", e);
                ThreadAssist.ProxyToMain(delegate {
                    HideStatus();
                    ShowErrorView(DaapErrorType.UserDisconnect);
                });
            }
        }
Exemplo n.º 24
0
        internal void Execute(HyenaSqliteConnection hconnection, Connection connection)
        {
            if (finished)
            {
                throw new Exception("Command is already set to finished; result needs to be claimed before command can be rerun");
            }

            execution_exception = null;
            result = null;
            int execution_ms = 0;

            string command_text = null;

            try {
                command_text = CurrentSqlText;
                ticks        = System.Environment.TickCount;

                switch (CommandType)
                {
                case HyenaCommandType.Reader:
                    using (var reader = connection.Query(command_text)) {
                        result = new ArrayDataReader(reader, command_text);
                    }
                    break;

                case HyenaCommandType.Scalar:
                    result = connection.Query <object> (command_text);
                    break;

                case HyenaCommandType.Execute:
                default:
                    connection.Execute(command_text);
                    result = connection.LastInsertRowId;
                    break;
                }

                execution_ms = System.Environment.TickCount - ticks;
                if (LogAll)
                {
                    Log.DebugFormat("Executed in {0}ms {1}", execution_ms, command_text);
                }
                else if (Log.Debugging && execution_ms > 500)
                {
                    Log.WarningFormat("Executed in {0}ms {1}", execution_ms, command_text);
                }
            } catch (Exception e) {
                Log.DebugFormat("Exception executing command: {0}", command_text ?? Text);
                Log.Exception(e);
                execution_exception = e;
            }

            // capture the text
            string raise_text = null;

            if (RaiseCommandExecuted && execution_ms >= RaiseCommandExecutedThresholdMs)
            {
                raise_text = Text;
            }

            finished_event.Reset();
            finished = true;

            if (RaiseCommandExecuted && execution_ms >= RaiseCommandExecutedThresholdMs)
            {
                var handler = CommandExecuted;
                if (handler != null)
                {
                    // Don't raise this on this thread; this thread is dedicated for use by the db connection
                    ThreadAssist.ProxyToMain(delegate {
                        handler(this, new CommandExecutedArgs(raise_text, execution_ms));
                    });
                }
            }
        }
Exemplo n.º 25
0
 public void FetchMore()
 {
     ThreadAssist.SpawnFromMain(delegate {
         ThreadedFetch(search.Page + 1);
     });
 }
Exemplo n.º 26
0
 private void HandleSelectionChanged(object sender, EventArgs args)
 {
     ThreadAssist.SpawnFromMain(ReloadBrowsingModel);
 }
 private static void OnUserEventCancelRequestedHandler(object sender, EventArgs args)
 {
     ThreadAssist.ProxyToMain(OnUserEventCancelRequestedHandlerProxy);
 }
 private static void CreateUserEvent()
 {
     ThreadAssist.ProxyToMain(CreateUserEventProxy);
 }
        private bool ProcessMusicFolderPath(string path)
        {
            string[] itunes_music_uri_parts = ConvertToLocalUriFormat(path).Split(Path.DirectorySeparatorChar);
            string[] library_uri_parts      = Path.GetDirectoryName(data.library_uri).Split(Path.DirectorySeparatorChar);

            string itunes_dir_name = library_uri_parts[library_uri_parts.Length - 1];
            int    i     = 0;
            bool   found = false;

            for (i = itunes_music_uri_parts.Length - 1; i >= 0; i--)
            {
                if (itunes_music_uri_parts[i] == itunes_dir_name)
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                var builder = new StringBuilder(path.Length - 17);
                for (int j = 3; j < itunes_music_uri_parts.Length; j++)
                {
                    string part = itunes_music_uri_parts[j];
                    builder.Append(part);
                    if (part.Length > 0)
                    {
                        builder.Append(Path.DirectorySeparatorChar);
                    }
                }

                string local_path = builder.ToString();

                System.Threading.Monitor.Enter(mutex);

                ThreadAssist.ProxyToMain(delegate {
                    System.Threading.Monitor.Enter(mutex);
                    using (var dialog = new ItunesMusicDirectoryDialog(local_path)) {
                        if (dialog.Run() == (int)ResponseType.Ok)
                        {
                            data.local_prefix         = dialog.UserMusicDirectory;
                            data.user_provided_prefix = true;
                            data.default_query        = local_path;
                            ok = true;
                        }
                        else
                        {
                            ok = false;
                        }
                        dialog.Destroy();
                        System.Threading.Monitor.Pulse(mutex);
                        System.Threading.Monitor.Exit(mutex);
                    }
                });

                System.Threading.Monitor.Wait(mutex);
                System.Threading.Monitor.Exit(mutex);

                if (ok)
                {
                    return(true);
                }
                else
                {
                    LogError(data.library_uri, "Unable to locate iTunes directory from iTunes URI");
                    return(false);
                }
            }

            string[] tmp_query_dirs = new string[itunes_music_uri_parts.Length];
            string   upstream_uri;
            string   tmp_upstream_uri = null;
            int      step             = 0;
            string   root             = Path.GetPathRoot(data.library_uri);
            bool     same_root        = library_uri_parts[0] == root.Split(Path.DirectorySeparatorChar)[0];

            do
            {
                upstream_uri     = tmp_upstream_uri;
                tmp_upstream_uri = root;
                for (int j = same_root ? 1 : 0; j < library_uri_parts.Length - step - 1; j++)
                {
                    tmp_upstream_uri = Path.Combine(tmp_upstream_uri, library_uri_parts[j]);
                }
                tmp_upstream_uri  = Path.Combine(tmp_upstream_uri, itunes_music_uri_parts[i - step]);
                data.fallback_dir = tmp_query_dirs[step] = itunes_music_uri_parts[i - step];
                step++;
            } while (Banshee.IO.Directory.Exists(tmp_upstream_uri));
            if (upstream_uri == null)
            {
                LogError(data.library_uri, "Unable to resolve iTunes URIs to local URIs");
                return(false);
            }
            data.query_dirs    = new string[step - 2];
            data.default_query = string.Empty;

            for (int j = step - 2; j >= 0; j--)
            {
                if (j > 0)
                {
                    data.query_dirs[j - 1] = tmp_query_dirs[j];
                }
                data.default_query += tmp_query_dirs[j] + Path.DirectorySeparatorChar;
            }

            data.local_prefix = string.Empty;
            for (int j = 0; j <= library_uri_parts.Length - step; j++)
            {
                data.local_prefix += library_uri_parts[j] + Path.DirectorySeparatorChar;
            }

            return(true);
        }
Exemplo n.º 30
0
        private void ThreadedFetch(int page)
        {
            bool success = false;

            total_results = 0;
            status_text   = "";
            Exception err      = null;
            int       old_page = search.Page;

            search.Page = page;

            ThreadAssist.ProxyToMain(delegate {
                SetStatus(Catalog.GetString("Searching the Internet Archive"), false, true, "gtk-find");
            });

            IA.SearchResults results = null;

            try {
                results       = search.GetResults();
                total_results = results.TotalResults;
            } catch (System.Net.WebException e) {
                Log.Error("Error searching the Internet Archive", e);
                results = null;
                err     = e;
            }

            if (results != null)
            {
                try {
                    foreach (var result in results)
                    {
                        model.Add(result);

                        // HACK to remove ugly empty description
                        //if (track.Comment == "There is currently no description for this item.")
                        //track.Comment = null;
                    }

                    success = true;
                } catch (Exception e) {
                    err = e;
                    Log.Error("Error searching the Internet Archive", e);
                }
            }

            if (success)
            {
                int count = model.Count;
                if (total_results == 0)
                {
                    ThreadAssist.ProxyToMain(delegate {
                        SetStatus(Catalog.GetString("No matches."), false, false, "gtk-info");
                    });
                }
                else
                {
                    ThreadAssist.ProxyToMain(ClearMessages);
                    status_text = String.Format(Catalog.GetPluralString(
                                                    "Showing 1 match", "Showing 1 to {0:N0} of {1:N0} total matches", total_results),
                                                count, total_results
                                                );
                }
            }
            else
            {
                search.Page = old_page;
                ThreadAssist.ProxyToMain(delegate {
                    var web_e = err as System.Net.WebException;
                    if (web_e != null && web_e.Status == System.Net.WebExceptionStatus.Timeout)
                    {
                        SetStatus(Catalog.GetString("Timed out searching the Internet Archive"), true);
                        CurrentMessage.AddAction(new MessageAction(Catalog.GetString("Try Again"), (o, a) => {
                            if (page == 0)
                            {
                                Reload();
                            }
                            else
                            {
                                FetchMore();
                            }
                        }));
                    }
                    else
                    {
                        SetStatus(Catalog.GetString("Error searching the Internet Archive"), true);
                    }
                });
            }

            ThreadAssist.ProxyToMain(delegate {
                model.Reload();
                OnUpdated();
            });
        }