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); }); } }
internal void Execute(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 (log_all) { 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 ?? command); Log.Error(e); execution_exception = e; } // capture the text string raise_text = null; if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) { raise_text = Text; } finished_event.Reset(); finished = true; if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) { 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)); }); } } }
private void OnJobUpdated(object o, EventArgs args) { ThreadAssist.ProxyToMain(Update); }
protected override void OnCleared() { ThreadAssist.ProxyToMain(base.OnCleared); }
private void OnSyncUpdated(DapSync sync) { ThreadAssist.ProxyToMain(UpdateActions); }
private void OnFeedMenuNewActivated(object sender, EventArgs args) { ThreadAssist.ProxyToMain(delegate { PodcastCore.RunSubscribeDialog(); }); }
protected override void Initialize() { PurgeTemporaryPlaylists(); base.Initialize(); Expanded = true; Properties.SetStringList("Icon.Name", GetIconNames()); Properties.Set <string> ("SourcePropertiesActionLabel", Catalog.GetString("Device Properties")); Properties.Set <OpenPropertiesDelegate> ("SourceProperties.GuiHandler", delegate { new DapPropertiesDialog(this).RunDialog(); }); Properties.Set <bool> ("Nereid.SourceContents.HeaderVisible", false); Properties.Set <System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", System.Reflection.Assembly.GetExecutingAssembly()); Properties.SetString("ActiveSourceUIResource", "ActiveSourceUI.xml"); sync = new DapSync(this); dap_info_bar = new DapInfoBar(this); Properties.Set <Gtk.Widget> ("Nereid.SourceContents.FooterWidget", dap_info_bar); /*dap_properties_display = new DapPropertiesDisplay (this); * Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", dap_properties_display);*/ if (String.IsNullOrEmpty(GenericName)) { GenericName = Catalog.GetString("Media Player"); } if (String.IsNullOrEmpty(Name)) { Name = device.Name; } AddDapProperty(Catalog.GetString("Product"), device.Product); AddDapProperty(Catalog.GetString("Vendor"), device.Vendor); if (acceptable_mimetypes == null) { acceptable_mimetypes = HasMediaCapabilities ? MediaCapabilities.PlaybackMimeTypes : null; if (acceptable_mimetypes == null || acceptable_mimetypes.Length == 0) { acceptable_mimetypes = new string [] { "taglib/mp3" }; } } AddChildSource(music_group_source = new MusicGroupSource(this)); if (SupportsVideo) { video_group_source = new VideoGroupSource(this); } if (SupportsPodcasts) { podcast_group_source = new PodcastGroupSource(this); } BuildPreferences(); ThreadAssist.ProxyToMain(delegate { Properties.Set <Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", new DapContent(this)); }); }
private void OnSelectionFocusChanged(object o, EventArgs a) { ThreadAssist.ProxyToMain(EmitDescendantChanged); }
public void Upload() { // FIXME: use mkstemp try { ThreadAssist.ProxyToMain(Dialog.Hide); GLib.File source = GLib.FileFactory.NewForPath(Path.Combine(gallery_path, gallery_name)); GLib.File target = GLib.FileFactory.NewForPath(Path.Combine(dest.Path, source.Basename)); if (dest.IsNative) { gallery_path = dest.Path; } progress_dialog.Message = Catalog.GetString("Building Gallery"); progress_dialog.Fraction = 0.0; FolderGallery gallery; if (static_radio.Active) { gallery = new HtmlGallery(selection, gallery_path, gallery_name); } else if (original_radio.Active) { gallery = new OriginalGallery(selection, gallery_path, gallery_name); } else { gallery = new FolderGallery(selection, gallery_path, gallery_name); } if (scale) { Log.DebugFormat("Resize Photos to {0}.", size); gallery.SetScale(size); } else { Log.Debug("Exporting full size."); } if (exportTags) { gallery.ExportTags = true; } if (exportTagIcons) { gallery.ExportTagIcons = true; } gallery.Description = description; gallery.GenerateLayout(); FilterSet filter_set = new FilterSet(); if (scale) { filter_set.Add(new ResizeFilter((uint)size)); } filter_set.Add(new ChmodFilter()); filter_set.Add(new UniqueNameFilter(new SafeUri(gallery_path))); for (int photo_index = 0; photo_index < selection.Count; photo_index++) { try { progress_dialog.Message = System.String.Format(Catalog.GetString("Exporting \"{0}\"..."), selection[photo_index].Name); progress_dialog.Fraction = photo_index / (double)selection.Count; gallery.ProcessImage(photo_index, filter_set); progress_dialog.ProgressText = System.String.Format(Catalog.GetString("{0} of {1}"), (photo_index + 1), selection.Count); } catch (Exception e) { Log.Error(e.ToString()); progress_dialog.Message = String.Format(Catalog.GetString("Error Copying \"{0}\" to Gallery:{2}{1}"), selection[photo_index].Name, e.Message, Environment.NewLine); progress_dialog.ProgressText = Catalog.GetString("Error"); if (progress_dialog.PerformRetrySkip()) { photo_index--; } } } // create the zip tarballs for original if (gallery is OriginalGallery) { bool include_tarballs; try { include_tarballs = Preferences.Get <bool> (INCLUDE_TARBALLS_KEY); } catch (NullReferenceException) { include_tarballs = true; Preferences.Set(INCLUDE_TARBALLS_KEY, true); } if (include_tarballs) { (gallery as OriginalGallery).CreateZip(); } } // we've created the structure, now if the destination was local (native) we are done // otherwise we xfer if (!dest.IsNative) { Log.DebugFormat("Transferring \"{0}\" to \"{1}\"", source.Path, target.Path); progress_dialog.Message = String.Format(Catalog.GetString("Transferring to \"{0}\""), target.Path); progress_dialog.ProgressText = Catalog.GetString("Transferring..."); source.CopyRecursive(target, GLib.FileCopyFlags.Overwrite, new GLib.Cancellable(), Progress); } // No need to check result here as if result is not true, an Exception will be thrown before progress_dialog.Message = Catalog.GetString("Export Complete."); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Exporting Photos Completed."); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open) { Log.DebugFormat(String.Format("Open URI \"{0}\"", target.Uri.ToString())); ThreadAssist.ProxyToMain(() => { GtkBeans.Global.ShowUri(Dialog.Screen, target.Uri.ToString()); }); } // Save these settings for next time Preferences.Set(SCALE_KEY, scale); Preferences.Set(SIZE_KEY, size); Preferences.Set(OPEN_KEY, open); Preferences.Set(EXPORT_TAGS_KEY, exportTags); Preferences.Set(EXPORT_TAG_ICONS_KEY, exportTagIcons); Preferences.Set(METHOD_KEY, static_radio.Active ? "static" : original_radio.Active ? "original" : "folder"); Preferences.Set(URI_KEY, uri_chooser.Uri); } catch (System.Exception e) { Log.Error(e.ToString()); progress_dialog.Message = e.ToString(); progress_dialog.ProgressText = Catalog.GetString("Error Transferring"); } finally { // if the destination isn't local then we want to remove the temp directory we // created. if (!dest.IsNative) { System.IO.Directory.Delete(gallery_path, true); } ThreadAssist.ProxyToMain(() => { Dialog.Destroy(); }); } }
public FilteredListSourceContents(string name) { this.name = name; InitializeViews(); string position = ForcePosition == null?BrowserPosition.Get() : ForcePosition; if (position == "top") { LayoutTop(); } else { LayoutLeft(); } if (ForcePosition != null) { return; } if (ServiceManager.Contains("InterfaceActionService")) { action_service = ServiceManager.Get <InterfaceActionService> (); if (action_service.FindActionGroup("BrowserView") == null) { browser_view_actions = new ActionGroup("BrowserView"); browser_view_actions.Add(new RadioActionEntry [] { new RadioActionEntry("BrowserLeftAction", null, Catalog.GetString("Browser on Left"), null, Catalog.GetString("Show the artist/album browser to the left of the track list"), 0), new RadioActionEntry("BrowserTopAction", null, Catalog.GetString("Browser on Top"), null, Catalog.GetString("Show the artist/album browser above the track list"), 1), }, position == "top" ? 1 : 0, null); browser_view_actions.Add(new ToggleActionEntry [] { new ToggleActionEntry("BrowserVisibleAction", null, Catalog.GetString("Show Browser"), "<control>B", Catalog.GetString("Show or hide the artist/album browser"), null, BrowserVisible.Get()) }); action_service.AddActionGroup(browser_view_actions); //action_merge_id = action_service.UIManager.NewMergeId (); action_service.UIManager.AddUiFromString(menu_xml); } (action_service.FindAction("BrowserView.BrowserLeftAction") as RadioAction).Changed += OnViewModeChanged; (action_service.FindAction("BrowserView.BrowserTopAction") as RadioAction).Changed += OnViewModeChanged; action_service.FindAction("BrowserView.BrowserVisibleAction").Activated += OnToggleBrowser; } ServiceManager.SourceManager.ActiveSourceChanged += delegate { ThreadAssist.ProxyToMain(delegate { browser_container.Visible = ActiveSourceCanHasBrowser ? BrowserVisible.Get() : false; }); }; NoShowAll = true; }
private void OnModelChanged(object o, EventArgs a) { ThreadAssist.ProxyToMain(EmitModelChanged); }
public FileSystemQueueSource() : base(Catalog.GetString("File System Queue"), Catalog.GetString("File System Queue"), "file-system-queue", 30) { TypeUniqueId = "file-system-queue"; Properties.SetStringList("Icon.Name", "system-file-manager"); Properties.Set <bool> ("AutoAddSource", false); IsLocal = true; ServiceManager.Get <DBusCommandService> ().ArgumentPushed += OnCommandLineArgument; AfterInitialized(); InterfaceActionService uia_service = ServiceManager.Get <InterfaceActionService> (); uia_service.GlobalActions.AddImportant( new ActionEntry("ClearFileSystemQueueAction", Stock.Clear, Catalog.GetString("Clear"), null, Catalog.GetString("Remove all tracks from the file system queue"), OnClearFileSystemQueue) ); uia_service.GlobalActions.Add(new ToggleActionEntry [] { new ToggleActionEntry("ClearFileSystemQueueOnQuitAction", null, Catalog.GetString("Clear on Quit"), null, Catalog.GetString("Clear the file system queue when quitting"), OnClearFileSystemQueueOnQuit, ClearOnQuitSchema.Get()) }); uia_service.UIManager.AddUiFromResource("GlobalUI.xml"); Properties.SetString("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.SetString("GtkActionPath", "/FileSystemQueueContextMenu"); actions_loaded = true; UpdateActions(); ServiceManager.SourceManager.ActiveSourceChanged += delegate { if (ServiceManager.SourceManager.ActiveSource is FileSystemQueueSource) { ThreadAssist.ProxyToMain(UpdateActions); } }; TrackModel.Reloaded += OnTrackModelReloaded; Reload(); play_enqueued = ApplicationContext.CommandLine.Contains("play-enqueued"); foreach (string path in ApplicationContext.CommandLine.Files) { // If it looks like a URI with a protocol, leave it as is if (System.Text.RegularExpressions.Regex.IsMatch(path, "^\\w+\\:\\/")) { Log.DebugFormat("URI file : {0}", path); Enqueue(path); } else { Log.DebugFormat("Relative file : {0} -> {1}", path, Path.GetFullPath(path)); Enqueue(Path.GetFullPath(path)); } } StorageName = null; // MusicLibrary source is initialized before extension sources ServiceManager.SourceManager.MusicLibrary.TracksAdded += OnTracksImported; }
public void Enqueue(string path) { try { SafeUri uri = new SafeUri(path); if (uri.IsLocalPath && !String.IsNullOrEmpty(uri.LocalPath)) { path = uri.LocalPath; } } catch { } lock (this) { if (importer == null) { importer = new DatabaseImportManager(this); importer.KeepUserJobHidden = true; importer.ImportResult += delegate(object o, DatabaseImportResultArgs args) { Banshee.ServiceStack.Application.Invoke(delegate { if (args.Error != null || path_to_play != null) { return; } path_to_play = args.Path; if (args.Track == null) { // Play immediately if the track is already in the source, // otherwise the call will be deferred until the track has // been imported and loaded into the cache PlayEnqueued(); } }); }; importer.Finished += delegate { if (visible) { ThreadAssist.ProxyToMain(delegate { TrackInfo current_track = ServiceManager.PlaybackController.CurrentTrack; // Don't switch to FSQ if the current item is a video if (current_track == null || !current_track.HasAttribute(TrackMediaAttributes.VideoStream)) { ServiceManager.SourceManager.SetActiveSource(this); } }); } }; } if (PlaylistFileUtil.PathHasPlaylistExtension(path)) { Banshee.Kernel.Scheduler.Schedule(new DelegateJob(delegate { // If it's in /tmp it probably came from Firefox - just play it if (path.StartsWith(Paths.SystemTempDir)) { Banshee.Streaming.RadioTrackInfo.OpenPlay(path); } else { PlaylistFileUtil.ImportPlaylistToLibrary(path, this, importer); } })); } else { importer.Enqueue(path); } } }
public void Teardown() { ThreadAssist.ProxyToMain(Application.Shutdown); main_thread.Join(); main_thread = null; }
public void PushLevels(double [] levels) { ThreadAssist.ProxyToMain(delegate { PushLevelsSafe(levels); }); }
private static void OnDownloadCompletedHandler(object sender, DownloadCompletedEventArgs args) { DownloadInfo dif = args.DownloadInfo; SafeUri local_uri = new SafeUri(args.LocalUri); if (dif == null || local_uri == null) { return; } PodcastInfo pi = null; lock (downloads.SyncRoot) { if (downloads.Contains(dif)) { pi = downloads [args.DownloadInfo] as PodcastInfo; } } if (pi != null) { TrackInfo ti = null; try { try { ti = new LibraryTrackInfo(local_uri.LocalPath); } catch (ApplicationException) { ti = Globals.Library.TracksFnKeyed [PathUtil.MakeFileNameKey(local_uri)] as TrackInfo; } } catch (Exception e) { PodcastErrorsSource.Instance.AddError( local_uri.ToString(), Catalog.GetString("Unable to add file to library"), e ); } pi.IsDownloaded = true; if (ti != null) { pi.Track = ti; } else { pi.DownloadFailed = true; PodcastDBManager.Commit(pi); return; } pi.LocalPath = local_uri.ToString(); PodcastDBManager.Commit(pi); pi.Feed.UpdateCounts(); ThreadAssist.ProxyToMain(delegate { Library.AddTrack(ti, pi, true); }); } source.Update(); }
private void HandleTrackModelReloaded(object sender, EventArgs args) { ThreadAssist.ProxyToMain(UpdateSourceInformation); }
private void OnReloaded(object sender, EventArgs args) { ThreadAssist.ProxyToMain(delegate { UpdateActions(); }); }
public void RemoveSource(Source source, bool recursivelyDispose) { if (source == null || !ContainsSource(source)) { return; } if (source == default_source) { default_source = null; } source.Updated -= OnSourceUpdated; source.ChildSourceAdded -= OnChildSourceAdded; source.ChildSourceRemoved -= OnChildSourceRemoved; sources.Remove(source); GroupSource associated_groupsource = FindAssociatedGroupSource(source.Order); if (!GroupSourceHasMembers(associated_groupsource)) { RemoveSource(associated_groupsource, recursivelyDispose); } foreach (Source child_source in source.Children) { RemoveSource(child_source, recursivelyDispose); } IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.UnregisterObject(exportable); } if (recursivelyDispose) { IDisposable disposable = source as IDisposable; if (disposable != null) { disposable.Dispose(); } } ThreadAssist.ProxyToMain(delegate { if (source == active_source) { if (source.Parent != null && source.Parent.CanActivate) { SetActiveSource(source.Parent); } else { SetActiveSource(default_source); } } SourceEventHandler handler = SourceRemoved; if (handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = source; handler(args); } }); }
public void ShowRecommendations(string artist) { if (current_artist == artist) { Visible = true; return; } // FIXME: Error handling ThreadAssist.Spawn(delegate { // Fetch data for "similar" artists. XmlDocument artists_xml_data = new XmlDocument(); artists_xml_data.LoadXml(RequestContent(String.Format(AUDIOSCROBBLER_SIMILAR_URL, artist))); XmlNodeList artists_xml_list = artists_xml_data.SelectNodes("/similarartists/artist"); // Cache artists images (here in the spawned thread) for (int i = 0; i < artists_xml_list.Count && i < NUM_MAX_ARTISTS; i++) { string url = artists_xml_list [i].SelectSingleNode("image_small").InnerText; DownloadContent(url, GetCachedPathFromUrl(url), true); } // Fetch data for top tracks XmlDocument tracks_xml_data = new XmlDocument(); tracks_xml_data.LoadXml(RequestContent(String.Format(AUDIOSCROBBLER_TOP_TRACKS_URL, artist))); XmlNodeList tracks_xml_list = tracks_xml_data.SelectNodes("/mostknowntracks/track"); // Try to match top tracks with the users's library for (int i = 0; i < tracks_xml_list.Count && i < NUM_TRACKS; i++) { string track_name = tracks_xml_list [i].SelectSingleNode("name").InnerText; int track_id = GetTrackId(artist, track_name); if (track_id == -1) { continue; } XmlNode track_id_node = tracks_xml_list [i].OwnerDocument.CreateNode(XmlNodeType.Element, "track_id", null); track_id_node.InnerText = track_id.ToString(); tracks_xml_list [i].AppendChild(track_id_node); } // Fetch data for top albums XmlDocument albums_xml_data = new XmlDocument(); albums_xml_data.LoadXml(RequestContent(String.Format(AUDIOSCROBBLER_TOP_ALBUMS_URL, artist))); XmlNodeList albums_xml_list = albums_xml_data.SelectNodes("/topalbums/album"); if (artists_xml_list.Count < 1 && tracks_xml_list.Count < 1 && albums_xml_list.Count < 1) { return; } ThreadAssist.ProxyToMain(delegate { // Wipe the old recommendations here, we keep them around in case // where the the artist is the same as the last song. foreach (Widget child in similar_items_table.Children) { similar_items_table.Remove(child); } foreach (Widget child in tracks_items_box.Children) { tracks_items_box.Remove(child); } foreach (Widget child in albums_items_box.Children) { albums_items_box.Remove(child); } // Display recommendations and artist information current_artist = artist; tracks_header.Markup = String.Format("<b>{0} {1}</b>", Catalog.GetString("Top Tracks by"), artist); albums_header.Markup = String.Format("<b>{0} {1}</b>", Catalog.GetString("Top Albums by"), artist); artists_widgets_list.Clear(); if (artists_xml_list != null) { for (int i = 0; i < artists_xml_list.Count && i < NUM_MAX_ARTISTS; i++) { artists_widgets_list.Add(RenderSimilarArtist(artists_xml_list [i])); } RenderSimilarArtists(); } if (tracks_xml_list != null) { for (int i = 0; i < tracks_xml_list.Count && i < NUM_TRACKS; i++) { tracks_items_box.PackStart(RenderTrack(tracks_xml_list [i], i + 1), false, true, 0); } } if (albums_xml_list != null) { for (int i = 0; i < albums_xml_list.Count && i < NUM_ALBUMS; i++) { albums_items_box.PackStart(RenderAlbum(albums_xml_list [i], i + 1), false, true, 0); } } Visible = true; ShowAll(); }); }); }
private void HandleActiveSourceUpdated(object o, EventArgs args) { ThreadAssist.ProxyToMain(() => { UpdateActions(true); }); }
private void OnSourceAdded(SourceAddedArgs args) { ThreadAssist.ProxyToMain(delegate { AddSource(args.Source); }); }
protected override void OnReloaded() { ThreadAssist.ProxyToMain(base.OnReloaded); }
private void OnSourceChildSourceAdded(SourceEventArgs args) { ThreadAssist.ProxyToMain(delegate { AddSource(args.Source, FindSource(args.Source.Parent)); }); }
protected void ScanPhotoDirectory(bool recurseSubdirectories, bool mergeRawAndJpeg, SafeUri uri) { var enumerator = (new RecursiveFileEnumerator(uri) { Recurse = recurseSubdirectories, CatchErrors = true, IgnoreSymlinks = true }).GetEnumerator(); SafeUri file = null; while (true) { if (file == null) { file = NextImageFileOrNull(enumerator); if (file == null) { break; } } // peek the next file to see if we have a RAW+JPEG combination // skip any non-image files SafeUri nextFile = NextImageFileOrNull(enumerator); SafeUri original; SafeUri version = null; if (mergeRawAndJpeg && nextFile != null && IsJpegRawPair(file, nextFile)) { // RAW+JPEG: import as one photo with versions original = ImageFile.IsRaw(file) ? file : nextFile; version = ImageFile.IsRaw(file) ? nextFile : file; // current and next files consumed in this iteration, // prepare to get next file on next iteration file = null; } else { // import current file as single photo original = file; // forward peeked file to next iteration of loop file = nextFile; } FileImportInfo info; if (version == null) { info = new FileImportInfo(original, Catalog.GetString("Original")); } else { info = new FileImportInfo(original, Catalog.GetString("Original RAW")); info.AddVersion(version, Catalog.GetString("Original JPEG")); } ThreadAssist.ProxyToMain(() => { if (PhotoFoundEvent != null) { PhotoFoundEvent.Invoke(this, new PhotoFoundEventArgs { FileImportInfo = info }); } }); if (!run_photoscanner) { return; } } }
private void OnSourceChildSourceRemoved(SourceEventArgs args) { ThreadAssist.ProxyToMain(delegate { RemoveSource(args.Source); }); }
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; }); } }); } }
internal void OnHaveResult(MetadataServiceJob job) { ThreadAssist.ProxyToMain(delegate { OnHaveResult(job.Track, job.ResultTags); }); }
protected virtual void DeleteTrackList(CachedList <DatabaseTrackInfo> list) { is_deleting = true; DeleteTrackJob.Total += (int)list.Count; List <DatabaseTrackInfo> skip_deletion = null; // Remove from file system foreach (DatabaseTrackInfo track in list) { if (track == null) { DeleteTrackJob.Completed++; continue; } try { DeleteTrackJob.Status = String.Format("{0} - {1}", track.ArtistName, track.TrackTitle); if (!DeleteTrack(track)) { if (skip_deletion == null) { skip_deletion = new List <DatabaseTrackInfo> (); } skip_deletion.Add(track); } } catch (Exception e) { Log.Exception(e); ErrorSource.AddMessage(e.Message, track.Uri.ToString()); } DeleteTrackJob.Completed++; if (DeleteTrackJob.Completed % 10 == 0 && !DeleteTrackJob.IsFinished) { OnTracksDeleted(); } } is_deleting = false; if (DeleteTrackJob.Total == DeleteTrackJob.Completed) { delete_track_job.Finish(); delete_track_job = null; } if (skip_deletion != null) { list.Remove(skip_deletion); skip_deletion.Clear(); skip_deletion = null; } // Remove from database if (list.Count > 0) { ServiceManager.DbConnection.Execute(remove_list_command, DateTime.Now, list.CacheId, list.CacheId); } ThreadAssist.ProxyToMain(delegate { OnTracksDeleted(); OnUserNotifyUpdated(); OnUpdated(); }); }
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); }