Code cleanup

This commit is contained in:
Samuel Attard 2017-04-24 13:07:42 +10:00
parent 03688b9415
commit c6196810a6
No known key found for this signature in database
GPG key ID: 273DC1869D8F13EF
11 changed files with 758 additions and 614 deletions

View file

@ -4,6 +4,7 @@
#include "atom/browser/api/atom_api_notification.h"
#include <map>
#include <string>
#include "atom/browser/api/atom_api_menu.h"
@ -25,7 +26,9 @@ namespace api {
int id_counter = 1;
std::map<int, Notification*> notifications_;
Notification::Notification(v8::Isolate* isolate, v8::Local<v8::Object> wrapper, mate::Arguments* args) {
Notification::Notification(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Arguments* args) {
InitWith(isolate, wrapper);
mate::Dictionary opts;
@ -65,19 +68,46 @@ Notification* Notification::FromID(int id) {
}
// Getters
int Notification::GetID() { return id_; }
base::string16 Notification::GetTitle() { return title_; }
base::string16 Notification::GetBody() { return body_; }
bool Notification::GetSilent() { return silent_; }
base::string16 Notification::GetReplyPlaceholder() { return reply_placeholder_; }
bool Notification::GetHasReply() { return has_reply_; }
int Notification::GetID() {
return id_;
}
base::string16 Notification::GetTitle() {
return title_;
}
base::string16 Notification::GetBody() {
return body_;
}
bool Notification::GetSilent() {
return silent_;
}
base::string16 Notification::GetReplyPlaceholder() {
return reply_placeholder_;
}
bool Notification::GetHasReply() {
return has_reply_;
}
// Setters
void Notification::SetTitle(base::string16 new_title) { title_ = new_title; NotifyPropsUpdated(); }
void Notification::SetBody(base::string16 new_body) { body_ = new_body; NotifyPropsUpdated(); }
void Notification::SetSilent(bool new_silent) { silent_ = new_silent; NotifyPropsUpdated(); }
void Notification::SetReplyPlaceholder(base::string16 new_reply_placeholder) { reply_placeholder_ = new_reply_placeholder; NotifyPropsUpdated(); }
void Notification::SetHasReply(bool new_has_reply) { has_reply_ = new_has_reply; NotifyPropsUpdated(); }
void Notification::SetTitle(base::string16 new_title) {
title_ = new_title;
NotifyPropsUpdated();
}
void Notification::SetBody(base::string16 new_body) {
body_ = new_body;
NotifyPropsUpdated();
}
void Notification::SetSilent(bool new_silent) {
silent_ = new_silent;
NotifyPropsUpdated();
}
void Notification::SetReplyPlaceholder(base::string16 new_reply_placeholder) {
reply_placeholder_ = new_reply_placeholder;
NotifyPropsUpdated();
}
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
NotifyPropsUpdated();
}
void Notification::OnClicked() {
Emit("click");
@ -102,26 +132,30 @@ void Notification::BuildPrototype(v8::Isolate* isolate,
.SetProperty("title", &Notification::GetTitle, &Notification::SetTitle)
.SetProperty("body", &Notification::GetBody, &Notification::SetBody)
.SetProperty("silent", &Notification::GetSilent, &Notification::SetSilent)
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder, &Notification::SetReplyPlaceholder)
.SetProperty("hasReply", &Notification::GetHasReply, &Notification::SetHasReply);
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder,
&Notification::SetReplyPlaceholder)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Notification;
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Notification::SetConstructor(isolate, base::Bind(&Notification::New));
mate::Dictionary dict(isolate, exports);
dict.Set("Notification", Notification::GetConstructor(isolate)->GetFunction());
dict.Set("Notification",
Notification::GetConstructor(isolate)->GetFunction());
}
} // namespace

View file

@ -35,7 +35,9 @@ class Notification : public mate::TrackableObject<Notification>,
void OnShown() override;
protected:
Notification(v8::Isolate* isolate, v8::Local<v8::Object> wrapper, mate::Arguments* args);
Notification(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Arguments* args);
~Notification() override;
void OnInitialProps();

View file

@ -48,7 +48,8 @@ void Notification::Show() {
if (can_toast_) {
atom::AtomToastHandler* handler = new atom::AtomToastHandler(this);
WinToastLib::WinToastTemplate::WinToastTemplateType toastType = WinToastLib::WinToastTemplate::TextOneLine;
WinToastLib::WinToastTemplate::WinToastTemplateType toastType =
WinToastLib::WinToastTemplate::TextOneLine;
if (!has_icon_) {
if (body_ != L"") {
toastType = WinToastLib::WinToastTemplate::TextTwoLines;
@ -62,40 +63,41 @@ void Notification::Show() {
toastType = WinToastLib::WinToastTemplate::ImageWithOneLine;
}
}
WinToastLib::WinToastTemplate toast = WinToastLib::WinToastTemplate(toastType);
WinToastLib::WinToastTemplate toast =
WinToastLib::WinToastTemplate(toastType);
std::string filename = base::MD5String(base::UTF16ToUTF8(icon_path_)) + ".png";
base::FilePath savePath = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
std::string filename =
base::MD5String(base::UTF16ToUTF8(icon_path_)) + ".png";
base::FilePath savePath =
temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
if (has_icon_ && SaveIconToPath(image, savePath)) {
toast.setImagePath(savePath.value());
}
toast.setTextField(title_, WinToastLib::WinToastTemplate::TextField::FirstLine);
toast.setTextField(body_, WinToastLib::WinToastTemplate::TextField::SecondLine);
toast.setTextField(title_,
WinToastLib::WinToastTemplate::TextField::FirstLine);
toast.setTextField(body_,
WinToastLib::WinToastTemplate::TextField::SecondLine);
toast.setSilent(silent_);
WinToastLib::WinToast::instance()->showToast(toast, handler);
OnShown();
} else {
AtomNotificationDelegateAdapter* adapter = new AtomNotificationDelegateAdapter(this);
AtomNotificationDelegateAdapter* adapter =
new AtomNotificationDelegateAdapter(this);
auto notif = presenter->CreateNotification(adapter);
GURL nullUrl = *(new GURL);
notif->Show(
title_,
body_,
"",
nullUrl,
image,
silent_
);
notif->Show(title_, body_, "", nullUrl, image, silent_);
}
}
void Notification::OnInitialProps() {
if (!initialized_) {
Browser* browser = Browser::Get();
WinToastLib::WinToast::instance()->setAppName(base::UTF8ToUTF16(browser->GetName()));
WinToastLib::WinToast::instance()->setAppUserModelId(browser->GetAppUserModelID());
WinToastLib::WinToast::instance()->setAppName(
base::UTF8ToUTF16(browser->GetName()));
WinToastLib::WinToast::instance()->setAppUserModelId(
browser->GetAppUserModelID());
can_toast_ = WinToastLib::WinToast::instance()->initialize();
temp_dir_.CreateUniqueTempDir();
}
@ -104,10 +106,6 @@ void Notification::OnInitialProps() {
}
}
void Notification::NotifyPropsUpdated() {
}
}
}
void Notification::NotifyPropsUpdated() {}
} // namespace api
} // namespace atom

View file

@ -1,3 +1,7 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/notification_delegate_adapter.h"
#include "atom/browser/api/atom_api_notification.h"
@ -5,7 +9,8 @@
namespace atom {
AtomNotificationDelegateAdapter::AtomNotificationDelegateAdapter(atom::api::Notification* target) {
AtomNotificationDelegateAdapter::AtomNotificationDelegateAdapter(
atom::api::Notification* target) {
observer_ = target;
}
void AtomNotificationDelegateAdapter::NotificationDisplayed() {
@ -18,4 +23,4 @@ void AtomNotificationDelegateAdapter::NotificationClick() {
void AtomNotificationDelegateAdapter::NotificationDestroyed() {}
void AtomNotificationDelegateAdapter::NotificationFailed() {}
}
} // namespace atom

View file

@ -14,7 +14,7 @@ namespace atom {
class AtomNotificationDelegateAdapter : public brightray::NotificationDelegate {
public:
atom::api::Notification* observer_;
AtomNotificationDelegateAdapter(atom::api::Notification* target);
explicit AtomNotificationDelegateAdapter(atom::api::Notification* target);
void NotificationDisplayed();
void NotificationClosed();
@ -23,6 +23,6 @@ class AtomNotificationDelegateAdapter : public brightray::NotificationDelegate {
void NotificationFailed();
};
}
} // namespace atom
#endif // ATOM_BROWSER_UI_NOTIFICATION_DELEGATE_ADAPTER_H_

View file

@ -5,6 +5,8 @@
#ifndef ATOM_BROWSER_UI_NOTIFICATION_OBSERVER_H_
#define ATOM_BROWSER_UI_NOTIFICATION_OBSERVER_H_
#include <string>
namespace atom {
class NotifictionObserver {

View file

@ -15,14 +15,15 @@ AtomToastHandler::AtomToastHandler(atom::api::Notification* target) {
void AtomToastHandler::toastActivated() {
observer_->OnClicked();
};
}
void AtomToastHandler::toastDismissed(WinToastLib::WinToastHandler::WinToastDismissalReason state) {
void AtomToastHandler::toastDismissed(
WinToastLib::WinToastHandler::WinToastDismissalReason state) {
// observer_->OnDismissed();
};
}
void AtomToastHandler::toastFailed() {
// observer_->OnErrored();
};
}
} // namespace atom

View file

@ -5,21 +5,22 @@
#include "atom/browser/ui/win/toast_lib.h"
#include "atom/browser/api/atom_api_notification.h"
#ifndef ATOM_BROWSER_UI_TOAST_HANDLER_H_
#define ATOM_BROWSER_UI_TOAST_HANDLER_H_
#ifndef ATOM_BROWSER_UI_WIN_TOAST_HANDLER_H_
#define ATOM_BROWSER_UI_WIN_TOAST_HANDLER_H_
namespace atom {
class AtomToastHandler : public WinToastLib::WinToastHandler {
public:
atom::api::Notification* observer_;
AtomToastHandler(atom::api::Notification* target);
explicit AtomToastHandler(atom::api::Notification* target);
void toastActivated() override;
void toastDismissed(WinToastLib::WinToastHandler::WinToastDismissalReason state);
void toastDismissed(
WinToastLib::WinToastHandler::WinToastDismissalReason state);
void toastFailed();
};
}
} // namespace atom
#endif // ATOM_BROWSER_UI_TOAST_HANDLER_H_
#endif // ATOM_BROWSER_UI_WIN_TOAST_HANDLER_H_

View file

@ -9,8 +9,8 @@
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@ -20,17 +20,27 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "toast_lib.h"
#include "atom/browser/ui/win/toast_lib.h"
#include <string>
#include "browser/win/scoped_hstring.h"
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")
using namespace WinToastLib;
using WinToastLib::WinToast;
using WinToastLib::WinToastHandler;
using WinToastLib::WinToastStringWrapper;
using WinToastLib::WinToastTemplate;
namespace DllImporter {
// Function load a function from library
template <typename Function>
HRESULT loadFunctionFromLibrary(HINSTANCE library, LPCSTR name, Function &func) {
HRESULT loadFunctionFromLibrary(HINSTANCE library,
LPCSTR name,
Function& func) { // NOLINT
if (!library)
return false;
@ -38,54 +48,82 @@ namespace DllImporter {
return (func != nullptr) ? S_OK : E_FAIL;
}
typedef HRESULT(FAR STDAPICALLTYPE *f_SetCurrentProcessExplicitAppUserModelID)(__in PCWSTR AppID);
typedef HRESULT(FAR STDAPICALLTYPE *f_PropVariantToString)(_In_ REFPROPVARIANT propvar, _Out_writes_(cch) PWSTR psz, _In_ UINT cch);
typedef HRESULT(FAR STDAPICALLTYPE *f_RoGetActivationFactory)(_In_ HSTRING activatableClassId, _In_ REFIID iid, _COM_Outptr_ void ** factory);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsCreateStringReference)(_In_reads_opt_(length + 1) PCWSTR sourceString, UINT32 length, _Out_ HSTRING_HEADER * hstringHeader, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string);
typedef HRESULT(FAR STDAPICALLTYPE *f_WindowsDeleteString)(_In_opt_ HSTRING string);
typedef HRESULT(FAR STDAPICALLTYPE* f_SetCurrentProcessExplicitAppUserModelID)(
__in PCWSTR AppID);
typedef HRESULT(FAR STDAPICALLTYPE* f_PropVariantToString)(
_In_ REFPROPVARIANT propvar,
_Out_writes_(cch) PWSTR psz,
_In_ UINT cch);
typedef HRESULT(FAR STDAPICALLTYPE* f_RoGetActivationFactory)(
_In_ HSTRING activatableClassId,
_In_ REFIID iid,
_COM_Outptr_ void** factory);
typedef HRESULT(FAR STDAPICALLTYPE* f_WindowsCreateStringReference)(
_In_reads_opt_(length + 1) PCWSTR sourceString,
UINT32 length,
_Out_ HSTRING_HEADER* hstringHeader,
_Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING* string);
typedef HRESULT(FAR STDAPICALLTYPE* f_WindowsDeleteString)(
_In_opt_ HSTRING string);
f_SetCurrentProcessExplicitAppUserModelID SetCurrentProcessExplicitAppUserModelID;
f_SetCurrentProcessExplicitAppUserModelID
SetCurrentProcessExplicitAppUserModelID;
f_PropVariantToString PropVariantToString;
f_RoGetActivationFactory RoGetActivationFactory;
f_WindowsCreateStringReference WindowsCreateStringReference;
f_WindowsDeleteString WindowsDeleteString;
template <class T>
_Check_return_ __inline HRESULT _1_GetActivationFactory(_In_ HSTRING activatableClassId, _COM_Outptr_ T** factory) {
_Check_return_ __inline HRESULT _1_GetActivationFactory(
_In_ HSTRING activatableClassId,
_COM_Outptr_ T** factory) {
return RoGetActivationFactory(activatableClassId, IID_INS_ARGS(factory));
}
template <typename T>
inline HRESULT Wrap_GetActivationFactory(_In_ HSTRING activatableClassId, _Inout_ Details::ComPtrRef<T> factory) throw() {
return _1_GetActivationFactory(activatableClassId, factory.ReleaseAndGetAddressOf());
inline HRESULT Wrap_GetActivationFactory(
_In_ HSTRING activatableClassId,
_Inout_ ComPtrRef<T> factory) throw() {
return _1_GetActivationFactory(activatableClassId,
factory.ReleaseAndGetAddressOf());
}
inline HRESULT initialize() {
HINSTANCE LibShell32 = LoadLibrary(L"SHELL32.DLL");
HRESULT hr = loadFunctionFromLibrary(LibShell32, "SetCurrentProcessExplicitAppUserModelID", SetCurrentProcessExplicitAppUserModelID);
HRESULT hr = loadFunctionFromLibrary(
LibShell32, "SetCurrentProcessExplicitAppUserModelID",
SetCurrentProcessExplicitAppUserModelID);
if (SUCCEEDED(hr)) {
HINSTANCE LibPropSys = LoadLibrary(L"PROPSYS.DLL");
hr = loadFunctionFromLibrary(LibPropSys, "PropVariantToString", PropVariantToString);
hr = loadFunctionFromLibrary(LibPropSys, "PropVariantToString",
PropVariantToString);
if (SUCCEEDED(hr)) {
HINSTANCE LibComBase = LoadLibrary(L"COMBASE.DLL");
return SUCCEEDED(loadFunctionFromLibrary(LibComBase, "RoGetActivationFactory", RoGetActivationFactory))
&& SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsCreateStringReference", WindowsCreateStringReference))
&& SUCCEEDED(loadFunctionFromLibrary(LibComBase, "WindowsDeleteString", WindowsDeleteString));
return SUCCEEDED(loadFunctionFromLibrary(LibComBase,
"RoGetActivationFactory",
RoGetActivationFactory)) &&
SUCCEEDED(loadFunctionFromLibrary(LibComBase,
"WindowsCreateStringReference",
WindowsCreateStringReference)) &&
SUCCEEDED(loadFunctionFromLibrary(
LibComBase, "WindowsDeleteString", WindowsDeleteString));
}
}
return hr;
}
}
} // namespace DllImporter
namespace Util {
inline HRESULT defaultExecutablePath(_In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
DWORD written = GetModuleFileNameEx(GetCurrentProcess(), nullptr, path, nSize);
inline HRESULT defaultExecutablePath(_In_ WCHAR* path,
_In_ DWORD nSize = MAX_PATH) {
DWORD written =
GetModuleFileNameEx(GetCurrentProcess(), nullptr, path, nSize);
return (written > 0) ? S_OK : E_FAIL;
}
inline HRESULT defaultShellLinksDirectory(_In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
inline HRESULT defaultShellLinksDirectory(_In_ WCHAR* path,
_In_ DWORD nSize = MAX_PATH) {
DWORD written = GetEnvironmentVariable(L"APPDATA", path, nSize);
HRESULT hr = written > 0 ? S_OK : E_INVALIDARG;
if (SUCCEEDED(hr)) {
@ -95,7 +133,9 @@ namespace Util {
return hr;
}
inline HRESULT defaultShellLinkPath(const std::wstring& appname, _In_ WCHAR* path, _In_ DWORD nSize = MAX_PATH) {
inline HRESULT defaultShellLinkPath(const std::wstring& appname,
_In_ WCHAR* path,
_In_ DWORD nSize = MAX_PATH) {
HRESULT hr = defaultShellLinksDirectory(path, nSize);
if (SUCCEEDED(hr)) {
const std::wstring appLink(appname + DEFAULT_LINK_FORMAT);
@ -105,10 +145,12 @@ namespace Util {
return hr;
}
inline HRESULT setNodeStringValue(const std::wstring& string, IXmlNode *node, IXmlDocument *xml) {
inline HRESULT setNodeStringValue(const std::wstring& string,
IXmlNode* node,
IXmlDocument* xml) {
ComPtr<IXmlText> textNode;
HRESULT hr = xml->CreateTextNode( WinToastStringWrapper(string).Get(), &textNode);
HRESULT hr =
xml->CreateTextNode(WinToastStringWrapper(string).Get(), &textNode);
if (SUCCEEDED(hr)) {
ComPtr<IXmlNode> stringNode;
hr = textNode.As(&stringNode);
@ -120,42 +162,53 @@ namespace Util {
return hr;
}
inline HRESULT setEventHandlers(_In_ IToastNotification* notification, _In_ WinToastHandler* eventHandler) {
inline HRESULT setEventHandlers(_In_ IToastNotification* notification,
_In_ WinToastHandler* eventHandler) {
EventRegistrationToken activatedToken, dismissedToken, failedToken;
HRESULT hr = notification->add_Activated(
Callback < Implements < RuntimeClassFlags<ClassicCom>,
Callback<
Implements<RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, IInspectable*>>>(
[eventHandler](IToastNotification*, IInspectable*)
{
[eventHandler](IToastNotification*, IInspectable*) {
eventHandler->toastActivated();
return S_OK;
}).Get(), &activatedToken);
})
.Get(),
&activatedToken);
if (SUCCEEDED(hr)) {
hr = notification->add_Dismissed(Callback < Implements < RuntimeClassFlags<ClassicCom>,
hr = notification->add_Dismissed(
Callback<Implements<
RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, ToastDismissedEventArgs*>>>(
[eventHandler](IToastNotification*, IToastDismissedEventArgs* e)
{
[eventHandler](IToastNotification*, IToastDismissedEventArgs* e) {
ToastDismissalReason reason;
if (SUCCEEDED(e->get_Reason(&reason)))
{
eventHandler->toastDismissed(static_cast<WinToastHandler::WinToastDismissalReason>(reason));
if (SUCCEEDED(e->get_Reason(&reason))) {
eventHandler->toastDismissed(
static_cast<WinToastHandler::WinToastDismissalReason>(
reason));
}
return S_OK;
}).Get(), &dismissedToken);
})
.Get(),
&dismissedToken);
if (SUCCEEDED(hr)) {
hr = notification->add_Failed(Callback < Implements < RuntimeClassFlags<ClassicCom>,
hr = notification->add_Failed(
Callback<Implements<
RuntimeClassFlags<ClassicCom>,
ITypedEventHandler<ToastNotification*, ToastFailedEventArgs*>>>(
[eventHandler](IToastNotification*, IToastFailedEventArgs*)
{
[eventHandler](IToastNotification*, IToastFailedEventArgs*) {
eventHandler->toastFailed();
return S_OK;
}).Get(), &failedToken);
})
.Get(),
&failedToken);
}
}
return hr;
}
}
} // namespace Util
WinToast* WinToast::_instance = nullptr;
WinToast* WinToast::instance() {
@ -165,8 +218,7 @@ WinToast* WinToast::instance() {
return _instance;
}
WinToast::WinToast() : _isInitialized(false)
{
WinToast::WinToast() : _isInitialized(false) {
DllImporter::initialize();
}
@ -186,18 +238,17 @@ void WinToast::setAppUserModelId(_In_ const std::wstring& aumi) {
}
bool WinToast::isCompatible() {
return !((DllImporter::SetCurrentProcessExplicitAppUserModelID == nullptr)
|| (DllImporter::PropVariantToString == nullptr)
|| (DllImporter::RoGetActivationFactory == nullptr)
|| (DllImporter::WindowsCreateStringReference == nullptr)
|| (DllImporter::WindowsDeleteString == nullptr));
return !((DllImporter::SetCurrentProcessExplicitAppUserModelID == nullptr) ||
(DllImporter::PropVariantToString == nullptr) ||
(DllImporter::RoGetActivationFactory == nullptr) ||
(DllImporter::WindowsCreateStringReference == nullptr) ||
(DllImporter::WindowsDeleteString == nullptr));
}
std::wstring WinToast::configureAUMI(_In_ const std::wstring& company,
_In_ const std::wstring& name,
_In_ const std::wstring& surname,
_In_ const std::wstring &versionInfo)
{
_In_ const std::wstring& versionInfo) {
std::wstring aumi = company;
aumi += L"." + name;
aumi += L"." + surname;
@ -215,22 +266,31 @@ bool WinToast::initialize() {
return _isInitialized = false;
}
if (FAILED(DllImporter::SetCurrentProcessExplicitAppUserModelID(_aumi.c_str()))) {
if (FAILED(DllImporter::SetCurrentProcessExplicitAppUserModelID(
_aumi.c_str()))) {
return _isInitialized = false;
}
HRESULT hr = validateShellLink();
if (FAILED(hr)) {
hr = createShellLink();
}
if (SUCCEEDED(hr)) {
hr = DllImporter::Wrap_GetActivationFactory(WinToastStringWrapper(RuntimeClass_Windows_UI_Notifications_ToastNotificationManager).Get(), &_notificationManager);
hr = DllImporter::Wrap_GetActivationFactory(
WinToastStringWrapper(
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager)
.Get(),
&_notificationManager);
if (SUCCEEDED(hr)) {
hr = notificationManager()->CreateToastNotifierWithId(WinToastStringWrapper(_aumi).Get(), &_notifier);
hr = notificationManager()->CreateToastNotifierWithId(
WinToastStringWrapper(_aumi).Get(), &_notifier);
if (SUCCEEDED(hr)) {
hr = DllImporter::Wrap_GetActivationFactory(WinToastStringWrapper(RuntimeClass_Windows_UI_Notifications_ToastNotification).Get(), &_notificationFactory);
hr = DllImporter::Wrap_GetActivationFactory(
WinToastStringWrapper(
RuntimeClass_Windows_UI_Notifications_ToastNotification)
.Get(),
&_notificationFactory);
}
}
}
@ -239,13 +299,13 @@ bool WinToast::initialize() {
}
HRESULT WinToast::validateShellLink() {
WCHAR _path[MAX_PATH];
Util::defaultShellLinkPath(_appName, _path);
// Check if the file exist
DWORD attr = GetFileAttributes(_path);
if (attr >= 0xFFFFFFF) {
std::wcout << "Error, shell link not found. Try to create a new one in: " << _path << std::endl;
std::wcout << "Error, shell link not found. Try to create a new one in: "
<< _path << std::endl;
return E_FAIL;
}
@ -256,7 +316,8 @@ HRESULT WinToast::validateShellLink() {
// - Read the property AUMI and validate with the current
// - Review if AUMI is equal.
ComPtr<IShellLink> shellLink;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&shellLink));
if (SUCCEEDED(hr)) {
ComPtr<IPersistFile> persistFile;
hr = shellLink.As(&persistFile);
@ -273,11 +334,13 @@ HRESULT WinToast::validateShellLink() {
hr = DllImporter::PropVariantToString(appIdPropVar, AUMI, MAX_PATH);
if (SUCCEEDED(hr)) {
hr = (_aumi == AUMI) ? S_OK : E_FAIL;
} else { // AUMI Changed for the same app, let's update the current value! =)
} else { // AUMI Changed for the same app, let's update the current
// value! =)
PropVariantClear(&appIdPropVar);
hr = InitPropVariantFromString(_aumi.c_str(), &appIdPropVar);
if (SUCCEEDED(hr)) {
hr = propertyStore->SetValue(PKEY_AppUserModel_ID, appIdPropVar);
hr =
propertyStore->SetValue(PKEY_AppUserModel_ID, appIdPropVar);
if (SUCCEEDED(hr)) {
hr = propertyStore->Commit();
if (SUCCEEDED(hr) && SUCCEEDED(persistFile->IsDirty())) {
@ -295,15 +358,14 @@ HRESULT WinToast::validateShellLink() {
return hr;
}
HRESULT WinToast::createShellLink() {
WCHAR exePath[MAX_PATH];
WCHAR slPath[MAX_PATH];
Util::defaultShellLinkPath(_appName, slPath);
Util::defaultExecutablePath(exePath);
ComPtr<IShellLink> shellLink;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&shellLink));
if (SUCCEEDED(hr)) {
hr = shellLink->SetPath(exePath);
if (SUCCEEDED(hr)) {
@ -340,14 +402,14 @@ HRESULT WinToast::createShellLink() {
return hr;
}
bool WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ WinToastHandler* handler) {
bool WinToast::showToast(_In_ const WinToastTemplate& toast,
_In_ WinToastHandler* handler) {
if (!isInitialized()) {
return _isInitialized;
}
HRESULT hr = _notificationManager->GetTemplateContent(ToastTemplateType(toast.type()), &_xmlDocument);
HRESULT hr = _notificationManager->GetTemplateContent(
ToastTemplateType(toast.type()), &_xmlDocument);
if (SUCCEEDED(hr)) {
const int fieldsCount = toast.textFieldsCount();
for (int i = 0; i < fieldsCount && SUCCEEDED(hr); i++) {
@ -358,7 +420,8 @@ bool WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ WinToastHandle
if (SUCCEEDED(hr)) {
hr = toast.hasImage() ? setImageField(toast.imagePath()) : hr;
if (SUCCEEDED(hr)) {
hr = _notificationFactory->CreateToastNotification(xmlDocument(), &_notification);
hr = _notificationFactory->CreateToastNotification(xmlDocument(),
&_notification);
if (SUCCEEDED(hr)) {
hr = Util::setEventHandlers(notification(), handler);
if (SUCCEEDED(hr)) {
@ -376,10 +439,10 @@ bool WinToast::showToast(_In_ const WinToastTemplate& toast, _In_ WinToastHandle
return SUCCEEDED(hr);
}
HRESULT WinToast::setTextField(_In_ const std::wstring& text, _In_ int pos) {
ComPtr<IXmlNodeList> nodeList;
HRESULT hr = _xmlDocument->GetElementsByTagName(WinToastStringWrapper(L"text").Get(), &nodeList);
HRESULT hr = _xmlDocument->GetElementsByTagName(
WinToastStringWrapper(L"text").Get(), &nodeList);
if (SUCCEEDED(hr)) {
ComPtr<IXmlNode> node;
hr = nodeList->Item(pos, &node);
@ -391,7 +454,8 @@ HRESULT WinToast::setTextField(_In_ const std::wstring& text, _In_ int pos) {
}
bool WinToast::makeSilent(bool is_silent) {
if (!is_silent) return true;
if (!is_silent)
return true;
ScopedHString tag(L"toast");
if (!tag.success())
return false;
@ -455,13 +519,13 @@ bool WinToast::makeSilent(bool is_silent) {
&silent_attribute_pnode));
}
HRESULT WinToast::setImageField(_In_ const std::wstring& path) {
wchar_t imagePath[MAX_PATH] = L"file:///";
HRESULT hr = StringCchCat(imagePath, MAX_PATH, path.c_str());
if (SUCCEEDED(hr)) {
ComPtr<IXmlNodeList> nodeList;
hr = _xmlDocument->GetElementsByTagName(WinToastStringWrapper(L"image").Get(), &nodeList);
hr = _xmlDocument->GetElementsByTagName(
WinToastStringWrapper(L"image").Get(), &nodeList);
if (SUCCEEDED(hr)) {
ComPtr<IXmlNode> node;
hr = nodeList->Item(0, &node);
@ -470,9 +534,11 @@ HRESULT WinToast::setImageField(_In_ const std::wstring& path) {
hr = node->get_Attributes(&attributes);
if (SUCCEEDED(hr)) {
ComPtr<IXmlNode> editedNode;
hr = attributes->GetNamedItem(WinToastStringWrapper(L"src").Get(), &editedNode);
hr = attributes->GetNamedItem(WinToastStringWrapper(L"src").Get(),
&editedNode);
if (SUCCEEDED(hr)) {
Util::setNodeStringValue(imagePath, editedNode.Get(), xmlDocument());
Util::setNodeStringValue(imagePath, editedNode.Get(),
xmlDocument());
}
}
}
@ -481,19 +547,18 @@ HRESULT WinToast::setImageField(_In_ const std::wstring& path) {
return hr;
}
WinToastTemplate::WinToastTemplate(const WinToastTemplateType& type) :
_type(type)
{
WinToastTemplate::WinToastTemplate(const WinToastTemplateType& type)
: _type(type) {
initComponentsFromType();
}
WinToastTemplate::~WinToastTemplate()
{
WinToastTemplate::~WinToastTemplate() {
_textFields.clear();
}
void WinToastTemplate::setTextField(_In_ const std::wstring& txt, _In_ const WinToastTemplate::TextField& pos) {
void WinToastTemplate::setTextField(
_In_ const std::wstring& txt,
_In_ const WinToastTemplate::TextField& pos) {
_textFields[pos] = txt;
}
void WinToastTemplate::setImagePath(_In_ const std::wstring& imgPath) {
@ -506,25 +571,31 @@ void WinToastTemplate::setSilent(bool is_silent) {
_silent = is_silent;
}
int WinToastTemplate::TextFieldsCount[WinToastTemplateTypeCount] = { 1, 2, 2, 3, 1, 2, 2, 3};
int WinToastTemplate::TextFieldsCount[WinToastTemplateTypeCount] = {1, 2, 2, 3,
1, 2, 2, 3};
void WinToastTemplate::initComponentsFromType() {
_hasImage = _type < ToastTemplateType_ToastText01;
_textFields = std::vector<std::wstring>(TextFieldsCount[_type], L"");
}
WinToastStringWrapper::WinToastStringWrapper(_In_reads_(length) PCWSTR stringRef, _In_ UINT32 length) throw() {
HRESULT hr = DllImporter::WindowsCreateStringReference(stringRef, length, &_header, &_hstring);
WinToastStringWrapper::WinToastStringWrapper(_In_reads_(length)
PCWSTR stringRef,
_In_ UINT32 length) throw() {
HRESULT hr = DllImporter::WindowsCreateStringReference(stringRef, length,
&_header, &_hstring);
if (!SUCCEEDED(hr)) {
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr);
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER),
EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
}
WinToastStringWrapper::WinToastStringWrapper(const std::wstring &stringRef)
{
HRESULT hr = DllImporter::WindowsCreateStringReference(stringRef.c_str(), static_cast<UINT32>(stringRef.length()), &_header, &_hstring);
WinToastStringWrapper::WinToastStringWrapper(const std::wstring& stringRef) {
HRESULT hr = DllImporter::WindowsCreateStringReference(
stringRef.c_str(), static_cast<UINT32>(stringRef.length()), &_header,
&_hstring);
if (FAILED(hr)) {
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr);
RaiseException(static_cast<DWORD>(STATUS_INVALID_PARAMETER),
EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
}

View file

@ -9,8 +9,8 @@
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@ -20,30 +20,56 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef WINTOASTLIB_H
#define WINTOASTLIB_H
#include <windows.h>
#include <SDKDDKVer.h>
#include <WinUser.h>
#include <Shobjidl.h>
#include <wrl/implements.h>
#include <wrl/event.h>
#include <windows.ui.notifications.h>
#include <strsafe.h>
#include <Psapi.h>
#include <shlobj.h>
#include <roapi.h>
#include <propvarutil.h>
#include <functiondiscoverykeys.h>
#include <iostream>
#include <winstring.h>
#ifndef ATOM_BROWSER_UI_WIN_TOAST_LIB_H_
#define ATOM_BROWSER_UI_WIN_TOAST_LIB_H_
#include <string.h>
#include <winstring.h>
#include <SDKDDKVer.h>
#include <Shobjidl.h>
#include <WinUser.h>
#include <functiondiscoverykeys.h>
#include <propvarutil.h>
#include <roapi.h>
#include <shlobj.h>
#include <strsafe.h>
#include <windows.h>
#include <windows.ui.notifications.h>
#include <wrl/event.h>
#include <wrl/implements.h>
#include <Psapi.h>
#include <iostream>
#include <vector>
using namespace Microsoft::WRL;
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::UI::Notifications;
using namespace Windows::Foundation;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::Details::ComPtrRef;
using Microsoft::WRL::Callback;
using Microsoft::WRL::Implements;
using Microsoft::WRL::RuntimeClassFlags;
using Microsoft::WRL::ClassicCom;
using ABI::Windows::Data::Xml::Dom::IXmlAttribute;
using ABI::Windows::Data::Xml::Dom::IXmlDocument;
using ABI::Windows::Data::Xml::Dom::IXmlElement;
using ABI::Windows::Data::Xml::Dom::IXmlNamedNodeMap;
using ABI::Windows::Data::Xml::Dom::IXmlNode;
using ABI::Windows::Data::Xml::Dom::IXmlNodeList;
using ABI::Windows::Data::Xml::Dom::IXmlText;
using ABI::Windows::UI::Notifications::ToastDismissalReason;
using ABI::Windows::UI::Notifications::ToastTemplateType;
using ABI::Windows::UI::Notifications::IToastNotificationManagerStatics;
using ABI::Windows::UI::Notifications::IToastNotifier;
using ABI::Windows::UI::Notifications::IToastNotificationFactory;
using ABI::Windows::UI::Notifications::IToastNotification;
using ABI::Windows::UI::Notifications::ToastNotification;
using ABI::Windows::UI::Notifications::ToastDismissedEventArgs;
using ABI::Windows::UI::Notifications::IToastDismissedEventArgs;
using ABI::Windows::UI::Notifications::ToastFailedEventArgs;
using ABI::Windows::UI::Notifications::IToastFailedEventArgs;
using ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01;
using ABI::Windows::Foundation::ITypedEventHandler;
#define DEFAULT_SHELL_LINKS_PATH L"\\Microsoft\\Windows\\Start Menu\\Programs\\"
#define DEFAULT_LINK_FORMAT L".lnk"
@ -51,45 +77,43 @@ using namespace Windows::Foundation;
namespace WinToastLib {
class WinToastStringWrapper {
public:
WinToastStringWrapper(_In_reads_(length) PCWSTR stringRef, _In_ UINT32 length) throw();
WinToastStringWrapper(_In_ const std::wstring &stringRef) throw();
WinToastStringWrapper(_In_reads_(length) PCWSTR stringRef,
_In_ UINT32 length) throw();
explicit WinToastStringWrapper(_In_ const std::wstring& stringRef) throw();
~WinToastStringWrapper();
HSTRING Get() const throw();
private:
HSTRING _hstring;
HSTRING_HEADER _header;
};
class WinToastHandler {
public:
enum WinToastDismissalReason {
UserCanceled = ToastDismissalReason::ToastDismissalReason_UserCanceled,
ApplicationHidden = ToastDismissalReason::ToastDismissalReason_ApplicationHidden,
ApplicationHidden =
ToastDismissalReason::ToastDismissalReason_ApplicationHidden,
TimedOut = ToastDismissalReason::ToastDismissalReason_TimedOut
};
virtual void toastActivated() {};
virtual void toastDismissed(WinToastDismissalReason state) {};
virtual void toastFailed() {};
virtual void toastActivated() {}
virtual void toastDismissed(WinToastDismissalReason state) {}
virtual void toastFailed() {}
};
class WinToastTemplate
{
class WinToastTemplate {
public:
enum TextField {
FirstLine = 0,
SecondLine,
ThirdLine,
LineCount
};
enum TextField { FirstLine = 0, SecondLine, ThirdLine, LineCount };
enum WinToastTemplateType {
ImageWithOneLine = ToastTemplateType::ToastTemplateType_ToastImageAndText01,
ImageWithTwoLines = ToastTemplateType::ToastTemplateType_ToastImageAndText02,
ImageWithThreeLines = ToastTemplateType::ToastTemplateType_ToastImageAndText03,
ImageWithFourLines = ToastTemplateType::ToastTemplateType_ToastImageAndText04,
ImageWithTwoLines =
ToastTemplateType::ToastTemplateType_ToastImageAndText02,
ImageWithThreeLines =
ToastTemplateType::ToastTemplateType_ToastImageAndText03,
ImageWithFourLines =
ToastTemplateType::ToastTemplateType_ToastImageAndText04,
TextOneLine = ToastTemplateType::ToastTemplateType_ToastText01,
TextTwoLines = ToastTemplateType::ToastTemplateType_ToastText02,
TextThreeLines = ToastTemplateType::ToastTemplateType_ToastText03,
@ -97,19 +121,23 @@ namespace WinToastLib {
WinToastTemplateTypeCount
};
WinToastTemplate(_In_ const WinToastTemplateType& type = ImageWithTwoLines);
explicit WinToastTemplate(
_In_ const WinToastTemplateType& type = ImageWithTwoLines);
~WinToastTemplate();
int textFieldsCount() const { return _textFields.size(); }
bool hasImage() const { return _hasImage; }
std::vector<std::wstring> textFields() const { return _textFields; }
std::wstring textField(_In_ const TextField& pos) const { return _textFields[pos]; }
std::wstring textField(_In_ const TextField& pos) const {
return _textFields[pos];
}
std::wstring imagePath() const { return _imagePath; }
WinToastTemplateType type() const { return _type; }
void setTextField(_In_ const std::wstring& txt, _In_ const TextField& pos);
void setImagePath(_In_ const std::wstring& imgPath);
void setSilent(bool is_silent);
bool isSilent() const { return _silent; }
private:
static int TextFieldsCount[WinToastTemplateTypeCount];
bool _hasImage;
@ -127,15 +155,16 @@ namespace WinToastLib {
static std::wstring configureAUMI(_In_ const std::wstring& company,
_In_ const std::wstring& name,
_In_ const std::wstring& surname,
_In_ const std::wstring& versionInfo
);
_In_ const std::wstring& versionInfo);
bool initialize();
bool isInitialized() const { return _isInitialized; }
bool showToast(_In_ const WinToastTemplate& toast, _In_ WinToastHandler* handler);
bool showToast(_In_ const WinToastTemplate& toast,
_In_ WinToastHandler* handler);
std::wstring appName() const;
std::wstring appUserModelId() const;
void setAppUserModelId(_In_ const std::wstring& appName);
void setAppName(_In_ const std::wstring& appName);
private:
bool _isInitialized;
std::wstring _appName;
@ -150,8 +179,12 @@ namespace WinToastLib {
WinToast(void);
IXmlDocument* xmlDocument() const { return _xmlDocument.Get(); }
IToastNotifier* notifier() const { return _notifier.Get(); }
IToastNotificationFactory* notificationFactory() const { return _notificationFactory.Get(); }
IToastNotificationManagerStatics* notificationManager() const { return _notificationManager.Get(); }
IToastNotificationFactory* notificationFactory() const {
return _notificationFactory.Get();
}
IToastNotificationManagerStatics* notificationManager() const {
return _notificationManager.Get();
}
IToastNotification* notification() const { return _notification.Get(); }
HRESULT validateShellLink();
@ -160,9 +193,6 @@ namespace WinToastLib {
HRESULT setTextField(_In_ const std::wstring& text, _In_ int pos);
bool makeSilent(bool is_silent);
};
} // namespace WinToastLib
}
#endif // WINTOASTLIB_H
#endif // ATOM_BROWSER_UI_WIN_TOAST_LIB_H_

View file

@ -32,14 +32,14 @@ exports.load = (appUrl) => {
title: 'Hello World',
body: 'This is the long and complicated body for this notification that just goes on and on and on and never really seems to stop',
silent: true,
icon: '/Users/samuel/Downloads/ninja.png',
icon: path.resolve('C:\\Users\\Samuel\\Downloads\\icon.png'),
hasReply: true,
replyPlaceholder: 'Type Here!!'
});
n.on('show', () => console.log('showed'));
n.on('click', () => console.info('clicked!!'));
n.on('reply', (e, reply) => console.log('Replied:', reply));
})
n.on('show', () => console.log('showed'))
n.on('click', () => console.info('clicked!!'))
n.on('reply', (e, reply) => console.log('Replied:', reply))
n.show();
n.show()
})
}