// Copyright © 2010-2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace CefSharp
{
///
/// Default implementation of it's used
/// internally for the LoadHtml implementation - basically a resource handler is
/// registered for a specific Url.
///
public class DefaultResourceHandlerFactory : IResourceHandlerFactory
{
///
/// Resource handler thread safe dictionary
///
public ConcurrentDictionary Handlers { get; private set; }
///
/// Create a new instance of DefaultResourceHandlerFactory
///
/// string equality comparer
public DefaultResourceHandlerFactory(IEqualityComparer comparer = null)
{
Handlers = new ConcurrentDictionary(comparer ?? StringComparer.OrdinalIgnoreCase);
}
///
/// Register handler with the specified Url
///
/// url
/// handler
/// returns true if the Url was successfully parsed into a Uri otherwise false
public virtual bool RegisterHandler(string url, IResourceHandler handler)
{
Uri uri;
if (Uri.TryCreate(url, UriKind.Absolute, out uri))
{
Handlers.AddOrUpdate(uri.AbsoluteUri, handler, (k, v) => handler);
return true;
}
return false;
}
///
/// Unregister a handler for the specified Url
///
/// Url
/// returns true if successfully removed
public virtual bool UnregisterHandler(string url)
{
IResourceHandler handler;
return Handlers.TryRemove(url, out handler);
}
///
/// Are there any 's registered?
///
public bool HasHandlers
{
get { return Handlers.Count > 0; }
}
///
/// Called before a resource is loaded. To specify a handler for the resource return a object
///
/// The browser UI control
/// the browser object
/// the frame object
/// the request object - cannot be modified in this callback
/// To allow the resource to load normally return NULL otherwise return an instance of ResourceHandler with a valid stream
public virtual IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
{
try
{
IResourceHandler handler;
Handlers.TryGetValue(request.Url, out handler);
return handler;
}
finally
{
request.Dispose();
}
}
}
}