├── .gitmodules
├── QuickLook.Plugin.Metadata.Base.config
├── Scripts
├── pack-zip.ps1
└── update-version.ps1
├── LICENSE.txt
├── Plugin.cs
├── README.md
├── Extensions.cs
├── Properties
└── AssemblyInfo.cs
├── QuickLook.Plugin.TorrentViewer.sln
├── TorrentFileListView.xaml.cs
├── TorrentFileEntry.cs
├── TorrentInfoPanel.xaml
├── QuickLook.Plugin.TorrentViewer.csproj
├── Converters.cs
├── .gitignore
├── TorrentInfoPanel.xaml.cs
├── TorrentFileListView.xaml
└── IconManager.cs
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "QuickLook.Common"]
2 | path = QuickLook.Common
3 | url = https://github.com/QL-Win/QuickLook.Common.git
4 |
--------------------------------------------------------------------------------
/QuickLook.Plugin.Metadata.Base.config:
--------------------------------------------------------------------------------
1 |
2 |
3 | QuickLook.Plugin.TorrentViewer
4 | 0
5 | Enable preview for torrent file.
6 |
--------------------------------------------------------------------------------
/Scripts/pack-zip.ps1:
--------------------------------------------------------------------------------
1 | Remove-Item ..\QuickLook.Plugin.TorrentViewer.qlplugin -ErrorAction SilentlyContinue
2 |
3 | $files = Get-ChildItem -Path ..\bin\Release\ -Exclude *.pdb,*.xml
4 | Compress-Archive $files ..\QuickLook.Plugin.TorrentViewer.zip
5 | Move-Item ..\QuickLook.Plugin.TorrentViewer.zip ..\QuickLook.Plugin.TorrentViewer.qlplugin
--------------------------------------------------------------------------------
/Scripts/update-version.ps1:
--------------------------------------------------------------------------------
1 | $tag = git describe --always --tags "--abbrev=0"
2 | $revision = git describe --always --tags
3 |
4 | $text = @"
5 | // This file is generated by update-version.ps1
6 |
7 | using System.Reflection;
8 |
9 | [assembly: AssemblyVersion("$tag")]
10 | [assembly: AssemblyInformationalVersion("$revision")]
11 | "@
12 |
13 | $text | Out-File $PSScriptRoot\..\GitVersion.cs -Encoding utf8
14 |
15 |
16 | $xml = [xml](Get-Content $PSScriptRoot\..\QuickLook.Plugin.Metadata.Base.config)
17 | $xml.Metadata.Version="$revision"
18 | $xml.Save("$PSScriptRoot\..\QuickLook.Plugin.Metadata.config")
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Paddy Xu
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/Plugin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using QuickLook.Common.Plugin;
6 |
7 | namespace QuickLook.Plugin.TorrentViewer
8 | {
9 | public class Plugin : IViewer
10 | {
11 | private TorrentInfoPanel _panel;
12 |
13 | public int Priority => 0;
14 |
15 | public void Init()
16 | {
17 | }
18 |
19 | public bool CanHandle(string path)
20 | {
21 | return File.Exists(path) && path.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase);
22 | }
23 |
24 | public void Prepare(string path, ContextObject context)
25 | {
26 | context.PreferredSize = new Size {Width = 800, Height = 400};
27 | }
28 |
29 | public void View(string path, ContextObject context)
30 | {
31 | _panel = new TorrentInfoPanel(path);
32 |
33 | context.ViewerContent = _panel;
34 | context.Title = $"{Path.GetFileName(path)}";
35 |
36 | context.IsBusy = false;
37 | }
38 |
39 | public void Cleanup()
40 | {
41 | _panel?.Dispose();
42 | _panel = null;
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # QuickLook.Plugin.TorrentViewer
4 |
5 | ## How-To-Use
6 |
7 | 1. Install plugin.
8 | 2. Modify `QuickLook.exe.config` and add the following lines into `configuration/runtime` section:
9 |
10 | ``` xml
11 |
12 |
13 |
14 | ...
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | ...
24 |
25 |
26 |
27 | ```
28 |
29 | Restart `QuickLook.exe`, it should support to preview torrent file now.
30 |
31 | ### Why the modify is necessary?
32 |
33 | Because of the `BencodeNET` is target to the `.Net Standard 2.0` (with `System.Buffers 4.0.2.0`),
34 | but the `QuickLook` is target to the `.Net Framework 4.6.2` (with `System.Buffers 4.0.3.0`);
35 |
36 | Also see:
37 |
38 | - https://github.com/dotnet/runtime/issues/1830
39 | - https://github.com/dotnet/runtime/issues/27774
40 |
41 | ### Where is the `QuickLook.exe.config`?
42 |
43 | It should nearby your `QuickLook.exe` file.
44 |
45 | ### Unable to modify the Microsoft store version of `QuickLook.exe.config`
46 |
47 | https://github.com/Cologler/QuickLook.Plugin.TorrentViewer/issues/3 reported this,
48 | but I have no idea how to solve it. ¯\\_(ツ)_/¯
49 |
50 |
--------------------------------------------------------------------------------
/Extensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Collections.Generic;
20 | using System.Windows;
21 | using System.Windows.Media;
22 |
23 | namespace QuickLook.Plugin.TorrentViewer
24 | {
25 | public static class Extensions
26 | {
27 | public static void ForEach(this IEnumerable enumeration, Action action)
28 | {
29 | foreach (var item in enumeration)
30 | action(item);
31 | }
32 |
33 | public static T GetDescendantByType(this Visual element) where T : class
34 | {
35 | if (element == null)
36 | return default;
37 | if (element.GetType() == typeof(T))
38 | return element as T;
39 |
40 | T foundElement = null;
41 | (element as FrameworkElement)?.ApplyTemplate();
42 |
43 | for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
44 | {
45 | var visual = VisualTreeHelper.GetChild(element, i) as Visual;
46 | foundElement = visual.GetDescendantByType();
47 | if (foundElement != null)
48 | break;
49 | }
50 |
51 | return foundElement;
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 | using System.Windows;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("QuickLook.Plugin.TorrentViewer")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("pooi.moe")]
12 | [assembly: AssemblyProduct("QuickLook.Plugin.TorrentViewer")]
13 | [assembly: AssemblyCopyright("Copyright © Paddy Xu 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | //In order to begin building localizable applications, set
23 | //CultureYouAreCodingWith in your .csproj file
24 | //inside a . For example, if you are using US english
25 | //in your source files, set the to en-US. Then uncomment
26 | //the NeutralResourceLanguage attribute below. Update the "en-US" in
27 | //the line below to match the UICulture setting in the project file.
28 |
29 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
30 |
31 |
32 | [assembly: ThemeInfo(
33 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
34 | //(used if a resource is not found in the page,
35 | // or application resource dictionaries)
36 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
37 | //(used if a resource is not found in the page,
38 | // app, or any theme specific resource dictionaries)
39 | )]
40 |
41 |
42 | // Version information for an assembly consists of the following four values:
43 | //
44 | // Major Version
45 | // Minor Version
46 | // Build Number
47 | // Revision
48 | //
49 | // You can specify all the values or you can default the Build and Revision Numbers
50 | // by using the '*' as shown below:
51 | //[assembly: AssemblyVersion("1.0.*")]
--------------------------------------------------------------------------------
/QuickLook.Plugin.TorrentViewer.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28010.2003
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickLook.Plugin.TorrentViewer", "QuickLook.Plugin.TorrentViewer.csproj", "{863ECAAC-18D9-4256-A27D-0F308089FB47}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickLook.Common", "QuickLook.Common\QuickLook.Common.csproj", "{85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Debug|x86 = Debug|x86
14 | Release|Any CPU = Release|Any CPU
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Debug|x86.ActiveCfg = Debug|x86
21 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Debug|x86.Build.0 = Debug|x86
22 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Release|x86.ActiveCfg = Release|x86
25 | {863ECAAC-18D9-4256-A27D-0F308089FB47}.Release|x86.Build.0 = Release|x86
26 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Debug|x86.ActiveCfg = Debug|Any CPU
29 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Debug|x86.Build.0 = Debug|Any CPU
30 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Release|x86.ActiveCfg = Release|Any CPU
33 | {85FDD6BA-871D-46C8-BD64-F6BB0CB5EA95}.Release|x86.Build.0 = Release|Any CPU
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | GlobalSection(ExtensibilityGlobals) = postSolution
39 | SolutionGuid = {D545EDE6-0533-4E3F-BB67-308B17E4EDAC}
40 | EndGlobalSection
41 | EndGlobal
42 |
--------------------------------------------------------------------------------
/TorrentFileListView.xaml.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Windows;
20 | using System.Windows.Controls;
21 |
22 | namespace QuickLook.Plugin.TorrentViewer
23 | {
24 | ///
25 | /// Interaction logic for ArchiveFileListView.xaml
26 | ///
27 | public partial class TorrentFileListView : UserControl, IDisposable
28 | {
29 | public TorrentFileListView()
30 | {
31 | InitializeComponent();
32 | }
33 |
34 | public void Dispose()
35 | {
36 | GC.SuppressFinalize(this);
37 |
38 | IconManager.ClearCache();
39 | }
40 |
41 | public void SetDataContext(object context)
42 | {
43 | treeGrid.DataContext = context;
44 |
45 | treeView.LayoutUpdated += (sender, e) =>
46 | {
47 | // return when empty
48 | if (treeView.Items.Count == 0)
49 | return;
50 |
51 | // return when there are more than one root nodes
52 | if (treeView.Items.Count > 1)
53 | return;
54 |
55 | var root = (TreeViewItem) treeView.ItemContainerGenerator.ContainerFromItem(treeView.Items[0]);
56 | if (root == null)
57 | return;
58 |
59 | root.IsExpanded = true;
60 | };
61 | }
62 |
63 | private void CopyMd5SumLower_Click(object sender, RoutedEventArgs e)
64 | {
65 | if ((sender as FrameworkElement)?.DataContext is TorrentFileEntry fileEntry && fileEntry.Md5Sum?.Length > 0)
66 | {
67 | try
68 | {
69 | Clipboard.SetText(fileEntry.Md5Sum.ToLower());
70 | return;
71 | }
72 | catch (Exception) { }
73 |
74 | MessageBox.Show("Failed to copy Md5Sum.");
75 | }
76 | }
77 |
78 | private void CopyMd5SumUpper_Click(object sender, RoutedEventArgs e)
79 | {
80 | if ((sender as FrameworkElement)?.DataContext is TorrentFileEntry fileEntry && fileEntry.Md5Sum?.Length > 0)
81 | {
82 | try
83 | {
84 | Clipboard.SetText(fileEntry.Md5Sum.ToUpper());
85 | return;
86 | }
87 | catch (Exception) { }
88 |
89 | MessageBox.Show("Failed to copy Md5Sum.");
90 | }
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/TorrentFileEntry.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Collections.Generic;
20 | using System.Linq;
21 |
22 | namespace QuickLook.Plugin.TorrentViewer
23 | {
24 | public class TorrentFileEntry : IComparable
25 | {
26 | private readonly TorrentFileEntry _parent;
27 | private int _cachedDepth = -1;
28 | private int _cachedLevel = -1;
29 |
30 | public TorrentFileEntry(string name, bool isFolder, TorrentFileEntry parent = null, string md5Sum = null)
31 | {
32 | Name = name;
33 | IsFolder = isFolder;
34 |
35 | _parent = parent;
36 | _parent?.Children.Add(this);
37 | this.Md5Sum = md5Sum ?? string.Empty;
38 | }
39 |
40 | public List Children { get; } = new List();
41 |
42 | public IList VisibileChildren => this.Children.Where(x => !x.IsPaddingFile).ToList();
43 |
44 | public string Name { get; set; }
45 |
46 | public bool Encrypted { get; set; }
47 |
48 | public bool IsFolder { get; set; }
49 |
50 | public bool IsPaddingFile
51 | {
52 | get
53 | {
54 | return this.Name is string name && name.StartsWith("_____padding_file_");
55 | }
56 | }
57 |
58 | public ulong Size { get; set; }
59 |
60 | public string Md5Sum { get; }
61 |
62 | public DateTime ModifiedDate { get; set; }
63 |
64 | ///
65 | /// Returns the maximum depth of all siblings
66 | ///
67 | public int Level
68 | {
69 | get
70 | {
71 | if (_cachedLevel != -1)
72 | return _cachedLevel;
73 |
74 | if (_parent == null)
75 | _cachedLevel = GetDepth();
76 | else
77 | _cachedLevel = _parent.Level - 1;
78 |
79 | return _cachedLevel;
80 | }
81 | }
82 |
83 | public int CompareTo(TorrentFileEntry other)
84 | {
85 | if (IsFolder == other.IsFolder)
86 | return string.Compare(Name, other.Name, StringComparison.CurrentCulture);
87 |
88 | if (IsFolder)
89 | return -1;
90 |
91 | return 1;
92 | }
93 |
94 | ///
95 | /// Returns the number of nodes in the longest path to a leaf
96 | ///
97 | private int GetDepth()
98 | {
99 | if (_cachedDepth != -1)
100 | return _cachedDepth;
101 |
102 | var max = Children.Count == 0 ? 0 : Children.Max(r => r.GetDepth());
103 | _cachedDepth = max + 1;
104 | return _cachedDepth;
105 | }
106 |
107 | public override string ToString()
108 | {
109 | if (IsFolder)
110 | return $"{Name}";
111 |
112 | var en = Encrypted ? "*" : "";
113 | return $"{Name}{en},{IsFolder},{Size},{ModifiedDate}";
114 | }
115 | }
116 | }
--------------------------------------------------------------------------------
/TorrentInfoPanel.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
24 |
26 |
30 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
60 |
61 |
63 |
64 |
71 |
72 |
73 |
74 |
78 |
80 |
81 |
82 |
83 |
84 |
86 |
88 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/QuickLook.Plugin.TorrentViewer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {863ECAAC-18D9-4256-A27D-0F308089FB47}
8 | library
9 | QuickLook.Plugin.TorrentViewer
10 | QuickLook.Plugin.TorrentViewer
11 | v4.6.2
12 | 512
13 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
14 | 4
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | pdbonly
27 | true
28 | bin\Release\
29 | TRACE
30 | prompt
31 | 4
32 |
33 |
34 | true
35 | Debug\
36 | DEBUG;TRACE
37 | full
38 | x86
39 | prompt
40 | MinimumRecommendedRules.ruleset
41 |
42 |
43 | Release\
44 | TRACE
45 | true
46 | pdbonly
47 | x86
48 | prompt
49 | MinimumRecommendedRules.ruleset
50 |
51 |
52 | false
53 |
54 |
55 |
56 |
57 |
58 |
59 | true
60 |
61 |
62 |
63 |
64 |
65 |
66 | 4.0
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 | Always
87 |
88 |
89 |
90 |
91 | {85fdd6ba-871d-46c8-bd64-f6bb0cb5ea95}
92 | QuickLook.Common
93 |
94 |
95 |
96 |
97 | 4.0.0
98 |
99 |
100 |
101 |
102 | MSBuild:Compile
103 | Designer
104 |
105 |
106 | MSBuild:Compile
107 | Designer
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/Converters.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Globalization;
20 | using System.Windows;
21 | using System.Windows.Data;
22 |
23 | using QuickLook.Common.ExtensionMethods;
24 |
25 | namespace QuickLook.Plugin.TorrentViewer
26 | {
27 | public class Percent100ToVisibilityVisibleConverter : DependencyObject, IValueConverter
28 | {
29 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
30 | {
31 | if (value == null)
32 | value = 0;
33 |
34 | var percent = (double)value;
35 | return Math.Abs(percent - 100) < 0.00001 ? Visibility.Visible : Visibility.Collapsed;
36 | }
37 |
38 | public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
39 | {
40 | throw new NotImplementedException();
41 | }
42 | }
43 |
44 | public class Percent100ToVisibilityCollapsedConverter : DependencyObject, IValueConverter
45 | {
46 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
47 | {
48 | if (value == null)
49 | value = 0;
50 |
51 | var percent = (double)value;
52 | return Math.Abs(percent - 100) < 0.00001 ? Visibility.Collapsed : Visibility.Visible;
53 | }
54 |
55 | public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
56 | {
57 | throw new NotImplementedException();
58 | }
59 | }
60 |
61 | public class LevelToIndentConverter : DependencyObject, IMultiValueConverter
62 | {
63 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
64 | {
65 | if (values[0] == DependencyProperty.UnsetValue)
66 | values[0] = 1;
67 |
68 | var level = (int)values[0];
69 | var indent = (double)values[1];
70 | return indent * level;
71 | }
72 |
73 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
74 | {
75 | throw new NotImplementedException();
76 | }
77 | }
78 |
79 | public class LevelToBooleanConverter : DependencyObject, IValueConverter
80 | {
81 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
82 | {
83 | var level = (int)value;
84 |
85 | return level < 2;
86 | }
87 |
88 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
89 | {
90 | throw new NotImplementedException();
91 | }
92 | }
93 |
94 | public class BooleanToAsteriskConverter : DependencyObject, IValueConverter
95 | {
96 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
97 | {
98 | var b = (bool)value;
99 |
100 | return b ? "*" : "";
101 | }
102 |
103 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
104 | {
105 | throw new NotImplementedException();
106 | }
107 | }
108 |
109 | public class SizePrettyPrintConverter : DependencyObject, IMultiValueConverter
110 | {
111 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
112 | {
113 | var size = (ulong)values[0];
114 | var isFolder = (bool)values[1];
115 |
116 | return isFolder ? "" : ((long)size).ToPrettySize(2);
117 | }
118 |
119 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
120 | {
121 | throw new NotImplementedException();
122 | }
123 | }
124 |
125 | public class DatePrintConverter : DependencyObject, IMultiValueConverter
126 | {
127 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
128 | {
129 | var date = (DateTime)values[0];
130 | var isFolder = (bool)values[1];
131 |
132 | return isFolder ? "" : date.ToString(CultureInfo.CurrentCulture);
133 | }
134 |
135 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
136 | {
137 | throw new NotImplementedException();
138 | }
139 | }
140 |
141 | public class FileExtToIconConverter : DependencyObject, IMultiValueConverter
142 | {
143 | public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
144 | {
145 | var name = (string)values[0];
146 | var isFolder = (bool)values[1];
147 |
148 | if (isFolder)
149 | return IconManager.FindIconForDir(false);
150 |
151 | return IconManager.FindIconForFilename(name, false);
152 | }
153 |
154 | public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
155 | {
156 | throw new NotImplementedException();
157 | }
158 | }
159 |
160 | public class EmptyToCollapsedValueConverter : IValueConverter
161 | {
162 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
163 | {
164 | if (value is null)
165 | return Visibility.Collapsed;
166 |
167 | if (value is string s && string.IsNullOrEmpty(s))
168 | return Visibility.Collapsed;
169 |
170 | return Visibility.Visible;
171 | }
172 |
173 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
174 | }
175 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 | /*.qlplugin
332 | /GitVersion.cs
333 | /QuickLook.Plugin.Metadata.config
334 |
--------------------------------------------------------------------------------
/TorrentInfoPanel.xaml.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Collections.Generic;
20 | using System.ComponentModel;
21 | using System.IO;
22 | using System.Linq;
23 | using System.Runtime.CompilerServices;
24 | using System.Threading.Tasks;
25 | using System.Windows;
26 | using System.Windows.Controls;
27 |
28 | using BencodeNET.IO;
29 | using BencodeNET.Torrents;
30 |
31 | using QuickLook.Common.Annotations;
32 | using QuickLook.Common.ExtensionMethods;
33 | using QuickLook.Common.Helpers;
34 |
35 | namespace QuickLook.Plugin.TorrentViewer
36 | {
37 | ///
38 | /// Interaction logic for ArchiveInfoPanel.xaml
39 | ///
40 | public partial class TorrentInfoPanel : UserControl, IDisposable, INotifyPropertyChanged
41 | {
42 | private bool _disposed;
43 | private double _loadPercent;
44 | private string _magnetUri;
45 |
46 | public TorrentInfoPanel(string path)
47 | {
48 | InitializeComponent();
49 |
50 | // design-time only
51 | Resources.MergedDictionaries.Clear();
52 |
53 | BeginLoadArchive(path);
54 | }
55 |
56 | public double LoadPercent
57 | {
58 | get => _loadPercent;
59 | private set
60 | {
61 | if (value == _loadPercent)
62 | return;
63 | _loadPercent = value;
64 | OnPropertyChanged();
65 | }
66 | }
67 |
68 | public void Dispose()
69 | {
70 | GC.SuppressFinalize(this);
71 |
72 | _disposed = true;
73 |
74 | fileListView.Dispose();
75 | }
76 |
77 | public event PropertyChangedEventHandler PropertyChanged;
78 |
79 | private void BeginLoadArchive(string path)
80 | {
81 | Task.Run(() =>
82 | {
83 | Dictionary nodeEntires;
84 | try
85 | {
86 | nodeEntires = LoadFromTorrent(path);
87 | }
88 | catch (Exception e)
89 | {
90 | ProcessHelper.WriteLog(e.ToString());
91 | Dispatcher.Invoke(() => lblLoading.Content = $"Preview failed:\n{e.Message}");
92 | return;
93 | }
94 |
95 | var root = nodeEntires[string.Empty];
96 |
97 | var files = nodeEntires
98 | .Where(z => !z.Value.IsFolder)
99 | .Select(z => z.Value)
100 | .ToList();
101 |
102 | var paddingFilesCount = files.Count(z => z.IsPaddingFile);
103 | var totalFilesCount = $"Total {files.Count} files";
104 | if (paddingFilesCount > 0)
105 | {
106 | totalFilesCount += $" (with hided {paddingFilesCount} padding files)";
107 | }
108 |
109 | var totalSize = files.Sum(z => (long)z.Size).ToPrettySize(2);
110 |
111 | Dispatcher.Invoke(() =>
112 | {
113 | if (_disposed)
114 | return;
115 |
116 | fileListView.SetDataContext(root.VisibileChildren);
117 |
118 | TotalFilesCount.Content = totalFilesCount;
119 |
120 | TotalSize.Content = $"Total size: {totalSize}";
121 | });
122 |
123 | LoadPercent = 100d;
124 | });
125 | }
126 |
127 | private Dictionary LoadFromTorrent(string torrentPath)
128 | {
129 | var nodeEntries = new Dictionary();
130 |
131 | var root = new TorrentFileEntry(Path.GetFileName(torrentPath), true);
132 | nodeEntries.Add(string.Empty, root);
133 |
134 | using (var stream = File.OpenRead(torrentPath))
135 | using (var reader = new BencodeReader(stream))
136 | {
137 | var parser = new TorrentParser();
138 | var torrent = parser.Parse(reader);
139 |
140 | switch (torrent.FileMode)
141 | {
142 | case TorrentFileMode.Single:
143 | ProcessFile(
144 | new[] { torrent.File.FileNameUtf8 ?? torrent.File.FileName },
145 | torrent.File.FileSize, torrent.File.Md5Sum);
146 | break;
147 |
148 |
149 | case TorrentFileMode.Multi:
150 | foreach (var item in torrent.Files)
151 | {
152 | ProcessFile(item.PathUtf8 ?? item.Path, item.FileSize, item.Md5Sum);
153 | }
154 | break;
155 | }
156 |
157 | var infohash = torrent.OriginalInfoHash.ToLower();
158 |
159 | // must use original infohash, BencodeNET ignore some fields from the torrent
160 | // see: https://github.com/Krusen/BencodeNET/issues/62
161 | this._magnetUri = TorrentUtil.CreateMagnetLink(
162 | infohash,
163 | torrent.DisplayName,
164 | torrent.Trackers.SelectMany(x => x),
165 | MagnetLinkOptions.IncludeTrackers);
166 |
167 | var torrentName = torrent.DisplayNameUtf8 ?? torrent.DisplayName ?? string.Empty;
168 |
169 | this.Dispatcher.Invoke(() =>
170 | {
171 | if (this._disposed)
172 | return;
173 |
174 | this.TorrentName.Content = $"Name: {torrentName}";
175 | this.TorrentBtih.Content = $"BTIH: {infohash}";
176 | });
177 | }
178 |
179 | void ProcessFile(IList pathList, long fileSize, string md5Sum)
180 | {
181 | // process folders. When entry is a directory, all fragments are folders.
182 | var parts = new List();
183 |
184 | for (var i = 0; i < pathList.Count; i++)
185 | {
186 | var isFolder = i < pathList.Count - 1;
187 | var namePart = pathList[i];
188 | parts.Add(namePart);
189 | var path = Path.Combine(parts.ToArray());
190 | if (!nodeEntries.ContainsKey(path))
191 | {
192 | nodeEntries.TryGetValue(Path.GetDirectoryName(path) ?? "", out var parent);
193 | var entry = new TorrentFileEntry(namePart, isFolder, parent, md5Sum);
194 | nodeEntries.Add(path, entry);
195 | if (!isFolder)
196 | {
197 | entry.Size = (ulong)Math.Max(0, fileSize);
198 | }
199 | }
200 | }
201 | }
202 |
203 | return nodeEntries;
204 | }
205 |
206 | [NotifyPropertyChangedInvocator]
207 | protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
208 | {
209 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
210 | }
211 |
212 | private void CopyMagnetUriButton_Click(object sender, System.Windows.RoutedEventArgs e)
213 | {
214 | if (this._magnetUri is string uri)
215 | {
216 | try
217 | {
218 | Clipboard.SetText(uri);
219 | return;
220 | }
221 | catch (Exception) { }
222 | }
223 |
224 | MessageBox.Show("Failed to copy magnet uri.");
225 | }
226 | }
227 | }
--------------------------------------------------------------------------------
/TorrentFileListView.xaml:
--------------------------------------------------------------------------------
1 |
10 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
33 |
34 |
35 |
37 |
38 |
41 |
42 |
44 |
46 |
47 |
48 |
50 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
69 |
70 |
71 |
72 |
73 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
88 |
89 |
90 |
92 |
94 |
95 |
96 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
111 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
123 |
124 |
125 |
127 |
128 |
129 |
131 |
132 |
133 |
134 |
136 |
137 |
138 |
139 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
154 |
155 |
159 |
160 |
161 |
162 |
--------------------------------------------------------------------------------
/IconManager.cs:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 Paddy Xu
2 | //
3 | // This file is part of QuickLook program.
4 | //
5 | // This program is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see .
17 |
18 | using System;
19 | using System.Collections.Generic;
20 | using System.Drawing;
21 | using System.IO;
22 | using System.Runtime.InteropServices;
23 | using System.Windows;
24 | using System.Windows.Interop;
25 | using System.Windows.Media;
26 | using System.Windows.Media.Imaging;
27 |
28 | namespace QuickLook.Plugin.TorrentViewer
29 | {
30 | ///
31 | /// Internals are mostly from here:
32 | /// http://www.codeproject.com/Articles/2532/Obtaining-and-managing-file-and-folder-icons-using
33 | /// Caches all results.
34 | ///
35 | public static class IconManager
36 | {
37 | private static ImageSource SmallDirIcon;
38 | private static ImageSource LargeDirIcon;
39 | private static readonly Dictionary SmallIconCache = new Dictionary();
40 | private static readonly Dictionary LargeIconCache = new Dictionary();
41 |
42 | public static void ClearCache()
43 | {
44 | SmallDirIcon = LargeDirIcon = null;
45 |
46 | SmallIconCache.Clear();
47 | LargeIconCache.Clear();
48 | }
49 |
50 | ///
51 | /// Get the icon of a directory
52 | ///
53 | /// 16x16 or 32x32 icon
54 | /// an icon
55 | public static ImageSource FindIconForDir(bool large)
56 | {
57 | var icon = large ? LargeDirIcon : SmallDirIcon;
58 | if (icon != null)
59 | return icon;
60 | icon = IconReader.GetFolderIcon(large ? IconReader.IconSize.Large : IconReader.IconSize.Small,
61 | false)
62 | .ToImageSource();
63 | if (large)
64 | LargeDirIcon = icon;
65 | else
66 | SmallDirIcon = icon;
67 | return icon;
68 | }
69 |
70 | ///
71 | /// Get an icon for a given filename
72 | ///
73 | /// any filename
74 | /// 16x16 or 32x32 icon
75 | /// null if path is null, otherwise - an icon
76 | public static ImageSource FindIconForFilename(string fileName, bool large)
77 | {
78 | var extension = Path.GetExtension(fileName);
79 | if (extension == null)
80 | return null;
81 | var cache = large ? LargeIconCache : SmallIconCache;
82 | ImageSource icon;
83 | if (cache.TryGetValue(extension, out icon))
84 | return icon;
85 | icon = IconReader.GetFileIcon(fileName, large ? IconReader.IconSize.Large : IconReader.IconSize.Small,
86 | false)
87 | .ToImageSource();
88 | cache.Add(extension, icon);
89 | return icon;
90 | }
91 |
92 | ///
93 | /// http://stackoverflow.com/a/6580799/1943849
94 | ///
95 | private static ImageSource ToImageSource(this Icon icon)
96 | {
97 | var imageSource = Imaging.CreateBitmapSourceFromHIcon(
98 | icon.Handle,
99 | Int32Rect.Empty,
100 | BitmapSizeOptions.FromEmptyOptions());
101 | return imageSource;
102 | }
103 |
104 | ///
105 | /// Provides static methods to read system icons for both folders and files.
106 | ///
107 | ///
108 | /// IconReader.GetFileIcon("c:\\general.xls");
109 | ///
110 | private static class IconReader
111 | {
112 | ///
113 | /// Options to specify the size of icons to return.
114 | ///
115 | public enum IconSize
116 | {
117 | ///
118 | /// Specify large icon - 32 pixels by 32 pixels.
119 | ///
120 | Large = 0,
121 | ///
122 | /// Specify small icon - 16 pixels by 16 pixels.
123 | ///
124 | Small = 1
125 | }
126 |
127 | ///
128 | /// Returns the icon of a folder.
129 | ///
130 | /// Large or small
131 | /// Whether to include the link icon
132 | /// System.Drawing.Icon
133 | public static Icon GetFolderIcon(IconSize size, bool linkOverlay)
134 | {
135 | var shfi = new Shell32.Shfileinfo();
136 | var flags = Shell32.ShgfiIcon | Shell32.ShgfiUsefileattributes;
137 | if (linkOverlay)
138 | flags += Shell32.ShgfiLinkoverlay;
139 | /* Check the size specified for return. */
140 | if (IconSize.Small == size)
141 | flags += Shell32.ShgfiSmallicon;
142 | else
143 | flags += Shell32.ShgfiLargeicon;
144 | Shell32.SHGetFileInfo("placeholder",
145 | Shell32.FileAttributeDirectory,
146 | ref shfi,
147 | (uint)Marshal.SizeOf(shfi),
148 | flags);
149 | // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
150 | var icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
151 | User32.DestroyIcon(shfi.hIcon); // Cleanup
152 | return icon;
153 | }
154 |
155 | ///
156 | /// Returns an icon for a given file - indicated by the name parameter.
157 | ///
158 | /// Pathname for file.
159 | /// Large or small
160 | /// Whether to include the link icon
161 | /// System.Drawing.Icon
162 | public static Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
163 | {
164 | var shfi = new Shell32.Shfileinfo();
165 | var flags = Shell32.ShgfiIcon | Shell32.ShgfiUsefileattributes;
166 | if (linkOverlay)
167 | flags += Shell32.ShgfiLinkoverlay;
168 | /* Check the size specified for return. */
169 | if (IconSize.Small == size)
170 | flags += Shell32.ShgfiSmallicon;
171 | else
172 | flags += Shell32.ShgfiLargeicon;
173 | Shell32.SHGetFileInfo(name,
174 | Shell32.FileAttributeNormal,
175 | ref shfi,
176 | (uint)Marshal.SizeOf(shfi),
177 | flags);
178 | // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
179 | var icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
180 | User32.DestroyIcon(shfi.hIcon); // Cleanup
181 | return icon;
182 | }
183 | }
184 |
185 | ///
186 | /// Wraps necessary Shell32.dll structures and functions required to retrieve Icon Handles using SHGetFileInfo. Code
187 | /// courtesy of MSDN Cold Rooster Consulting case study.
188 | ///
189 | private static class Shell32
190 | {
191 | private const int MaxPath = 256;
192 | public const uint ShgfiIcon = 0x000000100; // get icon
193 | public const uint ShgfiLinkoverlay = 0x000008000; // put a link overlay on icon
194 | public const uint ShgfiLargeicon = 0x000000000; // get large icon
195 | public const uint ShgfiSmallicon = 0x000000001; // get small icon
196 | public const uint ShgfiUsefileattributes = 0x000000010; // use passed dwFileAttribute
197 | public const uint FileAttributeNormal = 0x00000080;
198 | public const uint FileAttributeDirectory = 0x00000010;
199 |
200 | [DllImport("Shell32.dll")]
201 | public static extern IntPtr SHGetFileInfo(
202 | string pszPath,
203 | uint dwFileAttributes,
204 | ref Shfileinfo psfi,
205 | uint cbFileInfo,
206 | uint uFlags
207 | );
208 |
209 | [StructLayout(LayoutKind.Sequential)]
210 | public struct Shfileinfo
211 | {
212 | private const int Namesize = 80;
213 | public readonly IntPtr hIcon;
214 | private readonly int iIcon;
215 | private readonly uint dwAttributes;
216 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MaxPath)]
217 | private readonly string szDisplayName;
218 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Namesize)]
219 | private readonly string szTypeName;
220 | }
221 | }
222 |
223 | ///
224 | /// Wraps necessary functions imported from User32.dll. Code courtesy of MSDN Cold Rooster Consulting example.
225 | ///
226 | private static class User32
227 | {
228 | ///
229 | /// Provides access to function required to delete handle. This method is used internally
230 | /// and is not required to be called separately.
231 | ///
232 | /// Pointer to icon handle.
233 | /// N/A
234 | [DllImport("User32.dll")]
235 | public static extern int DestroyIcon(IntPtr hIcon);
236 | }
237 | }
238 | }
--------------------------------------------------------------------------------