Skip to content

Commit 8178ee7

Browse files
committed
Optimizations & improvements
1 parent 4864270 commit 8178ee7

File tree

9 files changed

+139
-57
lines changed

9 files changed

+139
-57
lines changed

SmartImage.Lib/SearchClient.cs

Lines changed: 28 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ public SearchClient(SearchConfig config)
4343
DetailedResults = new List<ImageResult>();
4444
ContinueTasks = new List<Task>();
4545

46+
m_w = new AutoResetEvent(false);
4647

4748
Reload();
4849
}
@@ -95,7 +96,8 @@ public SearchClient(SearchConfig config)
9596

9697
public bool IsContinueComplete { get; private set; }
9798

98-
private List<Task> ContinueTasks { get; }
99+
public List<Task<SearchResult>> Tasks { get; private set; }
100+
private List<Task> ContinueTasks { get; }
99101

100102

101103
/// <summary>
@@ -128,6 +130,7 @@ public void Reset()
128130
PendingCount = 0;
129131
IsComplete = false;
130132
IsContinueComplete = false;
133+
m_w = new AutoResetEvent(false);
131134

132135
Reload();
133136
}
@@ -141,6 +144,7 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
141144
Reset();
142145
}
143146

147+
144148
cts ??= CancellationToken.None;
145149

146150
Tasks = new List<Task<SearchResult>>(Engines.Select(engine =>
@@ -230,9 +234,10 @@ public async Task RunContinueAsync(CancellationToken? c = null)
230234
{
231235

232236
IsContinueComplete = false;
233-
c??= CancellationToken.None;
234237

235-
while (!IsContinueComplete&&!c.Value.IsCancellationRequested) {
238+
c ??= CancellationToken.None;
239+
240+
while (!IsContinueComplete && !c.Value.IsCancellationRequested) {
236241
var task = await Task.WhenAny(ContinueTasks);
237242
await task;
238243

@@ -241,26 +246,6 @@ public async Task RunContinueAsync(CancellationToken? c = null)
241246
}
242247
}
243248

244-
public WaitHandle GetWaitHandle()
245-
{
246-
// ReSharper disable PossibleNullReferenceException
247-
248-
WaitHandle w = new AutoResetEvent(false);
249-
250-
ThreadPool.QueueUserWorkItem((state) =>
251-
{
252-
//todo
253-
while (!DirectResults.Any()) { }
254-
255-
var resetEvent = (AutoResetEvent) state;
256-
resetEvent.Set();
257-
258-
}, w);
259-
260-
return w;
261-
262-
// ReSharper restore PossibleNullReferenceException
263-
}
264249

265250
private void GetResultContinueCallback(Task<SearchResult> task, object state)
266251
{
@@ -270,21 +255,31 @@ private void GetResultContinueCallback(Task<SearchResult> task, object state)
270255

271256

272257
if (!value.Scanned) {
273-
var task2 = value.FindDirectResultsAsync();
274-
task2.Wait();
275-
var result = task2.Result;
258+
// var task2 = value.FindDirectResultsAsync();
259+
// task2.Wait();
260+
// var result = task2.Result;
261+
262+
var result = value.FindDirectResultsAsync();
276263

264+
if (result.Any()) {
265+
result = result /*.Where(x => x.Direct != null)*/
266+
.ToList();
277267

278-
if (result != null && result.Any()) {
279-
result = result.Where(x => x.Direct != null).ToList();
268+
DirectResults.AddRange(result);
280269

281-
if (result.Any()) {
282-
DirectResults.AddRange(result);
283-
value.Scanned = true;
270+
var autoResetEvent = ((AutoResetEvent) m_w);
284271

285-
ResultUpdated?.Invoke(null, EventArgs.Empty);
272+
if (DirectResults.Count > 0 && !autoResetEvent.SafeWaitHandle.IsClosed) {
273+
Debug.WriteLine("wait handle set");
274+
autoResetEvent.Set();
286275

287276
}
277+
278+
value.Scanned = true;
279+
280+
ResultUpdated?.Invoke(null, EventArgs.Empty);
281+
282+
// if (result.Any()) { }
288283
}
289284
}
290285
}
@@ -380,7 +375,7 @@ public static BaseSearchEngine[] GetAllSearchEngines()
380375

381376
private static readonly SmartImageException SearchException = new("Search must be completed");
382377

383-
public List<Task<SearchResult>> Tasks { get; private set; }
378+
public WaitHandle m_w;
384379

385380

386381
public void Dispose()

SmartImage.Lib/SearchConfig.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Configuration;
34
using System.Linq;
45
using System.Text;
56
using System.Threading;
@@ -17,37 +18,46 @@ namespace SmartImage.Lib;
1718
/// Contains configuration for <see cref="SearchClient"/>
1819
/// </summary>
1920
/// <remarks>Search config is only applicable when used in <see cref="SearchClient"/></remarks>
20-
public sealed class SearchConfig
21+
public sealed class SearchConfig : ConfigurationSection
2122
{
2223
/// <summary>
2324
/// Search query
2425
/// </summary>
2526
public ImageQuery Query { get; set; }
2627

28+
public SearchConfig() { }
29+
2730
/// <summary>
2831
/// Search engines to use
2932
/// </summary>
33+
[ConfigurationProperty("engines", DefaultValue = SearchEngineOptions.All, IsRequired = true, IsKey = true)]
3034
public SearchEngineOptions SearchEngines { get; set; }
3135

3236
/// <summary>
3337
/// Priority engines
3438
/// </summary>
39+
[ConfigurationProperty("priority-engines", DefaultValue = SearchEngineOptions.Auto, IsRequired = true,
40+
IsKey = true)]
3541
public SearchEngineOptions PriorityEngines { get; set; }
3642

3743
/// <summary>
3844
/// Filters any non-primitive results.
3945
/// Filtered results are determined by <see cref="SearchResult.IsNonPrimitive"/>.
4046
/// </summary>
47+
[ConfigurationProperty("filtering", DefaultValue = true, IsRequired = true, IsKey = true)]
4148
public bool Filtering { get; set; } = true;
4249

4350
/// <summary>
4451
/// <see cref="SearchClient.SearchCompleted"/>
4552
/// </summary>
53+
[ConfigurationProperty("notification", DefaultValue = true, IsRequired = true, IsKey = true)]
4654
public bool Notification { get; set; } = true;
4755

4856
/// <summary>
4957
/// <see cref="SearchClient.SearchCompleted"/>
5058
/// </summary>
59+
60+
[ConfigurationProperty("notification-image", DefaultValue = false, IsRequired = true, IsKey = true)]
5161
public bool NotificationImage { get; set; } = false;
5262

5363
public bool OutputOnly { get; set; } = false;
@@ -65,5 +75,4 @@ public override string ToString()
6575

6676
return sb.ToString();
6777
}
68-
6978
}

SmartImage.Lib/Searching/ImageResult.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,11 @@ public void UpdateFrom(ImageResult result)
215215

216216
public async Task<bool> ScanForImagesAsync()
217217
{
218-
if (Url == null || Direct?.Url != null || IsAlreadyDirect()) {
218+
if (Url==null) {
219+
return false;
220+
}
221+
222+
if (Direct is {Url: {}} || IsAlreadyDirect()) {
219223
return true;
220224
}
221225

@@ -248,7 +252,7 @@ public async Task<bool> ScanForImagesAsync()
248252
}
249253

250254

251-
public bool IsAlreadyDirect()
255+
private bool IsAlreadyDirect()
252256
{
253257
if (Url is not { }) {
254258
return false;

SmartImage.Lib/Searching/SearchResult.cs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-

2-
global using ReflectionHelper = Novus.Utilities.ReflectionHelper;
1+
global using ReflectionHelper = Novus.Utilities.ReflectionHelper;
32
using ConsoleProgressIndicator = Kantan.Cli.ConsoleManager.UI.ProgressIndicator;
43
using JetBrains.Annotations;
54
using SmartImage.Lib.Engines;
@@ -144,22 +143,38 @@ public SearchResult(BaseSearchEngine engine)
144143

145144
public bool Scanned { get; internal set; }
146145

147-
public async Task<List<ImageResult>> FindDirectResultsAsync()
146+
public List<ImageResult> FindDirectResultsAsync()
148147
{
149148
Debug.WriteLine($"searching within {Engine.Name}");
150149

151150
var directResults = new List<ImageResult>();
151+
152+
var ll=Parallel.For(0, AllResults.Count, (i, pls) =>
153+
{
154+
var allResult = AllResults[i];
155+
156+
var task = allResult.ScanForImagesAsync();
157+
task.Wait();
158+
var b = task.Result;
159+
160+
if (b && !directResults.Contains(allResult)&& allResult.Direct != null) {
161+
Debug.WriteLine($"{nameof(SearchResult)}: Found direct result {allResult.Direct.Url}");
152162

153-
foreach (ImageResult ir in AllResults) {
163+
directResults.Add(allResult);
164+
PrimaryResult.Direct.Url ??= allResult.Direct.Url;
165+
}
166+
});
167+
/*foreach (ImageResult ir in AllResults) {
154168
var b = await ir.ScanForImagesAsync();
155169
156-
if (b && !directResults.Contains(ir)) {
170+
if (b && !directResults.Contains(ir))
171+
{
172+
// Debug.WriteLine($"{nameof(SearchResult)}: Found direct result {ir.Direct.Url}");
157173
158-
Debug.WriteLine($"{nameof(SearchResult)}: Found direct result {ir.Direct.Url}");
159174
directResults.Add(ir);
160175
PrimaryResult.Direct.Url ??= ir.Direct.Url;
161176
}
162-
}
177+
}*/
163178

164179
Scanned = true;
165180

SmartImage.Lib/SmartImage.Lib.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
<PackageReference Include="Flurl.Http" Version="3.2.0" />
1717
<PackageReference Include="JetBrains.Annotations" Version="2021.3.0" />
1818
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
19+
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
1920
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
2021
<PackageReference Include="System.Json" Version="4.7.1" />
2122
<PackageReference Include="System.Windows.Extensions" Version="6.0.0" />

SmartImage/Core/AppConfig.cs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Configuration;
34
using System.Diagnostics;
45
using System.IO;
56
using Kantan.Collections;
67
using Kantan.Utilities;
8+
using SmartImage.Lib;
79
using SmartImage.Lib.Engines;
810
using SmartImage.Lib.Searching;
911
using static Kantan.Diagnostics.LogCategories;
@@ -12,6 +14,10 @@ namespace SmartImage.Core;
1214

1315
public static class AppConfig
1416
{
17+
/*internal static Configuration Config=> ConfigurationManager.OpenExeConfiguration(
18+
ConfigurationUserLevel.None) as Configuration;
19+
*/
20+
1521
public static FileInfo ConfigFile
1622
{
1723
get
@@ -24,6 +30,8 @@ public static FileInfo ConfigFile
2430
}
2531

2632
return new FileInfo(file);
33+
34+
// return new FileInfo(Config.FilePath);
2735
}
2836
}
2937

@@ -47,6 +55,26 @@ public static Dictionary<string, string> ConfigMap
4755

4856
public static void ReadConfigFile()
4957
{
58+
/*var p=Program.Config;
59+
60+
61+
Console.WriteLine(Config.FilePath);
62+
Console.WriteLine(Config.AppSettings.Settings);
63+
64+
const string s = "SearchConfig";
65+
66+
if (Config.Sections[s] == null)
67+
{
68+
Config.Sections.Add(s, p);
69+
}
70+
71+
p.SectionInformation.ForceSave = true;
72+
73+
Config.Save(ConfigurationSaveMode.Modified);
74+
ConfigurationManager.RefreshSection(s);
75+
Program.Config = Config.GetSection(s) as SearchConfig;
76+
*/
77+
5078
var map = EnumerableHelper.ReadDictionary(ConfigFile.ToString());
5179

5280

@@ -75,8 +103,11 @@ private static void SaveConfigFile()
75103
var map = ConfigMap;
76104

77105
EnumerableHelper.WriteDictionary(map, ConfigFile.ToString());
106+
// Config.Save();
107+
// Config.Save(ConfigurationSaveMode.Modified);
78108

79109
Debug.WriteLine($"Saved to {ConfigFile.Name}", C_INFO);
110+
80111
}
81112

82113
private const string K_ENGINES = "engines";
@@ -92,4 +123,21 @@ public static void UpdateConfig()
92123
Program.Client.Reload();
93124
SaveConfigFile();
94125
}
126+
127+
public static void tmp()
128+
{
129+
var config = ConfigurationManager.OpenExeConfiguration(
130+
ConfigurationUserLevel.None) as Configuration;
131+
132+
// Console.WriteLine(config.FilePath);
133+
// Console.WriteLine(config.AppSettings.Settings);
134+
135+
if (config.Sections["SearchConfig"] == null) {
136+
config.Sections.Add("SearchConfig", Program.Config);
137+
}
138+
139+
Program.Config.SectionInformation.ForceSave = true;
140+
141+
config.Save(ConfigurationSaveMode.Modified);
142+
}
95143
}

SmartImage/Program.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#nullable disable
1414
using SmartImage.Core;
1515
using System.Buffers;
16+
using System.Configuration;
1617
using System.Diagnostics;
1718
using System.Drawing;
1819
using System.Media;
@@ -30,6 +31,7 @@
3031
using SmartImage.Properties;
3132
using SmartImage.UI;
3233
using static SmartImage.UI.AppInterface;
34+
using Configuration = System.Configuration.Configuration;
3335

3436
// ReSharper disable AccessToDisposedClosure
3537
// ReSharper disable SuggestVarOrType_Elsewhere
@@ -54,7 +56,7 @@ public static partial class Program
5456
/// <summary>
5557
/// User search config
5658
/// </summary>
57-
internal static SearchConfig Config { get; private set; } = new();
59+
internal static SearchConfig Config { get; set; } = new();
5860

5961
/// <summary>
6062
/// Search client
@@ -162,7 +164,8 @@ private static async Task Main(string[] args)
162164
* Register events
163165
*/
164166

165-
167+
168+
166169
ToastNotificationManagerCompat.OnActivated += AppToast.OnToastActivated;
167170

168171
Console.OutputEncoding = Encoding.Unicode;

0 commit comments

Comments
 (0)