Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(35)

Side by Side Diff: chrome/browser/notifications/notification_platform_bridge_linux.cc

Issue 2806203003: Linux native notifications: Support icons (Closed)
Patch Set: Address thestig and peter's comments Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « chrome/browser/notifications/notification_platform_bridge_linux.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2017 The Chromium Authors. All rights reserved. 1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/notifications/notification_platform_bridge_linux.h" 5 #include "chrome/browser/notifications/notification_platform_bridge_linux.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 8
9 #include "base/files/file_util.h"
9 #include "base/memory/ptr_util.h" 10 #include "base/memory/ptr_util.h"
10 #include "base/stl_util.h" 11 #include "base/stl_util.h"
11 #include "base/strings/nullable_string16.h" 12 #include "base/strings/nullable_string16.h"
12 #include "base/strings/utf_string_conversions.h" 13 #include "base/strings/utf_string_conversions.h"
14 #include "base/task_scheduler/post_task.h"
13 #include "chrome/browser/browser_process.h" 15 #include "chrome/browser/browser_process.h"
16 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/notifications/native_notification_display_service.h" 17 #include "chrome/browser/notifications/native_notification_display_service.h"
15 #include "chrome/browser/notifications/notification.h" 18 #include "chrome/browser/notifications/notification.h"
16 #include "chrome/browser/notifications/notification_display_service_factory.h" 19 #include "chrome/browser/notifications/notification_display_service_factory.h"
17 #include "chrome/browser/profiles/profile_manager.h" 20 #include "chrome/browser/profiles/profile_manager.h"
21 #include "content/public/browser/notification_service.h"
18 22
19 namespace { 23 namespace {
20 24
21 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications"; 25 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications";
22 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications"; 26 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications";
23 27
24 void AddActionToNotification(GVariantBuilder* actions_builder, 28 void AddActionToNotification(GVariantBuilder* actions_builder,
25 const char* action_id, 29 const char* action_id,
26 const char* button_label) { 30 const char* button_label) {
27 g_variant_builder_add(actions_builder, "s", action_id); 31 g_variant_builder_add(actions_builder, "s", action_id);
28 g_variant_builder_add(actions_builder, "s", button_label); 32 g_variant_builder_add(actions_builder, "s", button_label);
29 } 33 }
30 34
35 int NotificationPriorityToFdoUrgency(int priority) {
36 enum FdoUrgency {
37 LOW = 0,
38 NORMAL = 1,
39 CRITICAL = 2,
40 };
41 switch (priority) {
42 case message_center::MIN_PRIORITY:
43 case message_center::LOW_PRIORITY:
44 return LOW;
45 case message_center::HIGH_PRIORITY:
46 case message_center::MAX_PRIORITY:
47 return CRITICAL;
48 default:
49 NOTREACHED();
50 // fallthrough
51 case message_center::DEFAULT_PRIORITY:
52 return NORMAL;
53 }
54 }
55
31 // Callback used by GLib when the "Notify" message completes for the 56 // Callback used by GLib when the "Notify" message completes for the
32 // first time. 57 // first time.
33 void NotifyCompleteReceiver(GObject* source_object, 58 void NotifyCompleteReceiver(GObject* source_object,
34 GAsyncResult* result, 59 GAsyncResult* result,
35 gpointer user_data) { 60 gpointer user_data) {
36 GDBusProxy* proxy = G_DBUS_PROXY(source_object); 61 GDBusProxy* proxy = G_DBUS_PROXY(source_object);
37 GVariant* value = g_dbus_proxy_call_finish(proxy, result, nullptr); 62 GVariant* value = g_dbus_proxy_call_finish(proxy, result, nullptr);
38 if (!value) { 63 if (!value) {
39 // The message might have been cancelled, in which case 64 // The message might have been cancelled, in which case
40 // |user_data| points to a destroyed NotificationData. 65 // |user_data| points to a destroyed NotificationData.
(...skipping 17 matching lines...) Expand all
58 return; 83 return;
59 84
60 NotificationDisplayService* display_service = 85 NotificationDisplayService* display_service =
61 NotificationDisplayServiceFactory::GetForProfile(profile); 86 NotificationDisplayServiceFactory::GetForProfile(profile);
62 87
63 static_cast<NativeNotificationDisplayService*>(display_service) 88 static_cast<NativeNotificationDisplayService*>(display_service)
64 ->ProcessNotificationOperation(operation, notification_type, origin, 89 ->ProcessNotificationOperation(operation, notification_type, origin,
65 notification_id, action_index, reply); 90 notification_id, action_index, reply);
66 } 91 }
67 92
93 // Writes |data| to a new temporary file and returns its path.
94 // Returns base::FilePath() on failure.
95 base::FilePath WriteDataToTmpFile(
96 const scoped_refptr<base::RefCountedMemory>& data) {
97 base::FilePath file_path;
98 if (!base::CreateTemporaryFile(&file_path))
99 return base::FilePath();
100 int data_len = data->size();
Lei Zhang 2017/04/13 04:44:35 Can we check the data size first and fail early wi
Tom (Use chromium acct) 2017/04/13 20:19:26 Done.
101 if (data_len == 0 || base::WriteFile(file_path, data->front_as<char>(),
102 data_len) != data_len) {
103 base::DeleteFile(file_path, false);
104 return base::FilePath();
105 }
106 return file_path;
107 }
108
109 void DeleteNotificationResourceFile(const base::FilePath& file_path) {
110 if (file_path.empty())
111 return;
112 base::PostTaskWithTraits(
113 FROM_HERE,
114 base::TaskTraits()
115 .MayBlock()
116 .WithPriority(base::TaskPriority::BACKGROUND)
117 .WithShutdownBehavior(base::TaskShutdownBehavior::BLOCK_SHUTDOWN),
118 base::Bind(base::IgnoreResult(base::DeleteFile), file_path, false));
119 }
120
68 } // namespace 121 } // namespace
69 122
70 // static 123 // static
71 NotificationPlatformBridge* NotificationPlatformBridge::Create() { 124 NotificationPlatformBridge* NotificationPlatformBridge::Create() {
72 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync( 125 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync(
73 G_BUS_TYPE_SESSION, 126 G_BUS_TYPE_SESSION,
74 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | 127 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
75 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START), 128 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START),
76 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath, 129 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath,
77 kFreedesktopNotificationsName, nullptr, nullptr); 130 kFreedesktopNotificationsName, nullptr, nullptr);
78 if (!notification_proxy) 131 if (!notification_proxy)
79 return nullptr; 132 return nullptr;
80 return new NotificationPlatformBridgeLinux(notification_proxy); 133 return new NotificationPlatformBridgeLinux(notification_proxy);
81 } 134 }
82 135
83 struct NotificationPlatformBridgeLinux::NotificationData { 136 struct NotificationPlatformBridgeLinux::NotificationData {
84 NotificationData(NotificationCommon::Type notification_type, 137 NotificationData(NotificationCommon::Type notification_type,
85 const std::string& notification_id, 138 const std::string& notification_id,
86 const std::string& profile_id, 139 const std::string& profile_id,
87 bool is_incognito, 140 bool is_incognito,
88 const GURL& origin_url) 141 const GURL& origin_url)
89 : notification_type(notification_type), 142 : notification_type(notification_type),
90 notification_id(notification_id), 143 notification_id(notification_id),
91 profile_id(profile_id), 144 profile_id(profile_id),
92 is_incognito(is_incognito), 145 is_incognito(is_incognito),
93 origin_url(origin_url) {} 146 origin_url(origin_url),
147 weak_factory(this) {}
94 148
95 ~NotificationData() { 149 ~NotificationData() {
96 if (cancellable) 150 if (cancellable)
97 g_cancellable_cancel(cancellable); 151 g_cancellable_cancel(cancellable);
152 ResetResourceFiles();
153 }
154
155 void ResetResourceFiles() {
156 for (const base::FilePath& file : resource_files)
157 DeleteNotificationResourceFile(file);
158 resource_files.clear();
98 } 159 }
99 160
100 // The ID used by the notification server. Will be 0 until the 161 // The ID used by the notification server. Will be 0 until the
101 // first "Notify" message completes. 162 // first "Notify" message completes.
102 uint32_t dbus_id = 0; 163 uint32_t dbus_id = 0;
103 164
104 // Same parameters used by NotificationPlatformBridge::Display(). 165 // Same parameters used by NotificationPlatformBridge::Display().
105 const NotificationCommon::Type notification_type; 166 NotificationCommon::Type notification_type;
106 const std::string notification_id; 167 const std::string notification_id;
107 const std::string profile_id; 168 const std::string profile_id;
108 const bool is_incognito; 169 const bool is_incognito;
109 170
110 // A copy of the origin_url from the underlying 171 // A copy of the origin_url from the underlying
111 // message_center::Notification. Used to pass back to 172 // message_center::Notification. Used to pass back to
112 // NativeNotificationDisplayService. 173 // NativeNotificationDisplayService.
113 const GURL origin_url; 174 const GURL origin_url;
114 175
176 // Temporary resource files associated with the notification that
177 // should be cleaned up when the notification is closed.
Lei Zhang 2017/04/13 04:44:35 Or on shut down.
Tom (Use chromium acct) 2017/04/13 20:19:26 Done.
178 std::vector<base::FilePath> resource_files;
179
115 // Used to cancel the initial "Notify" message so we don't call 180 // Used to cancel the initial "Notify" message so we don't call
116 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a 181 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a
117 // destroyed Notification. 182 // destroyed Notification.
118 ScopedGObject<GCancellable> cancellable; 183 ScopedGObject<GCancellable> cancellable;
119 184
120 // If not null, the data to update the notification with once 185 // If not null, the data to update the notification with once
121 // |dbus_id| becomes available. 186 // |dbus_id| becomes available.
122 std::unique_ptr<Notification> update_data; 187 std::unique_ptr<Notification> update_data;
188 NotificationCommon::Type update_notification_type =
189 NotificationCommon::TYPE_MAX;
123 190
124 // If true, indicates the notification should be closed once 191 // If true, indicates the notification should be closed once
125 // |dbus_id| becomes available. 192 // |dbus_id| becomes available.
126 bool should_close = false; 193 bool should_close = false;
194
195 base::WeakPtrFactory<NotificationData> weak_factory;
196 };
197
198 struct NotificationPlatformBridgeLinux::ResourceFiles {
199 explicit ResourceFiles(const base::FilePath& icon_file)
200 : icon_file(icon_file) {}
201 ~ResourceFiles() { DeleteNotificationResourceFile(icon_file); }
202 base::FilePath icon_file;
127 }; 203 };
128 204
129 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux( 205 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux(
130 GDBusProxy* notification_proxy) 206 GDBusProxy* notification_proxy)
131 : notification_proxy_(notification_proxy) { 207 : notification_proxy_(notification_proxy), weak_factory_(this) {
132 proxy_signal_handler_ = g_signal_connect( 208 proxy_signal_handler_ = g_signal_connect(
133 notification_proxy_, "g-signal", G_CALLBACK(GSignalReceiverThunk), this); 209 notification_proxy_, "g-signal", G_CALLBACK(GSignalReceiverThunk), this);
210 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
211 content::NotificationService::AllSources());
134 } 212 }
135 213
136 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() { 214 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() {
137 if (proxy_signal_handler_) 215 if (proxy_signal_handler_)
138 g_signal_handler_disconnect(notification_proxy_, proxy_signal_handler_); 216 g_signal_handler_disconnect(notification_proxy_, proxy_signal_handler_);
139 } 217 }
140 218
141 void NotificationPlatformBridgeLinux::Display( 219 void NotificationPlatformBridgeLinux::Display(
142 NotificationCommon::Type notification_type, 220 NotificationCommon::Type notification_type,
143 const std::string& notification_id, 221 const std::string& notification_id,
144 const std::string& profile_id, 222 const std::string& profile_id,
145 bool is_incognito, 223 bool is_incognito,
146 const Notification& notification) { 224 const Notification& notification) {
147 NotificationData* data = 225 NotificationData* data =
148 FindNotificationData(notification_id, profile_id, is_incognito); 226 FindNotificationData(notification_id, profile_id, is_incognito);
149 if (data) { 227 if (data) {
150 // Update an existing notification. 228 // Update an existing notification.
151 DCHECK_EQ(data->notification_type, notification_type);
152 if (data->dbus_id) { 229 if (data->dbus_id) {
153 NotifyNow(data->dbus_id, notification_type, notification, nullptr, 230 data->notification_type = notification_type;
154 nullptr, nullptr); 231 Notify(notification, data, nullptr, nullptr);
155 } else { 232 } else {
233 data->update_notification_type = notification_type;
156 data->update_data = base::MakeUnique<Notification>(notification); 234 data->update_data = base::MakeUnique<Notification>(notification);
157 } 235 }
158 } else { 236 } else {
159 // Send the notification for the first time. 237 // Send the notification for the first time.
160 data = new NotificationData(notification_type, notification_id, profile_id, 238 data = new NotificationData(notification_type, notification_id, profile_id,
161 is_incognito, notification.origin_url()); 239 is_incognito, notification.origin_url());
162 data->cancellable.reset(g_cancellable_new()); 240 data->cancellable.reset(g_cancellable_new());
163 notifications_.emplace(data, base::WrapUnique(data)); 241 notifications_.emplace(data, base::WrapUnique(data));
164 NotifyNow(0, notification_type, notification, data->cancellable, 242 Notify(notification, data, NotifyCompleteReceiver, data);
165 NotifyCompleteReceiver, data);
166 } 243 }
167 } 244 }
168 245
169 void NotificationPlatformBridgeLinux::Close( 246 void NotificationPlatformBridgeLinux::Close(
170 const std::string& profile_id, 247 const std::string& profile_id,
171 const std::string& notification_id) { 248 const std::string& notification_id) {
172 std::vector<NotificationData*> to_erase; 249 std::vector<NotificationData*> to_erase;
173 for (const auto& pair : notifications_) { 250 for (const auto& pair : notifications_) {
174 NotificationData* data = pair.first; 251 NotificationData* data = pair.first;
175 if (data->notification_id == notification_id && 252 if (data->notification_id == notification_id &&
(...skipping 26 matching lines...) Expand all
202 if (value && g_variant_is_of_type(value, G_VARIANT_TYPE("(u)"))) 279 if (value && g_variant_is_of_type(value, G_VARIANT_TYPE("(u)")))
203 g_variant_get(value, "(u)", &data->dbus_id); 280 g_variant_get(value, "(u)", &data->dbus_id);
204 281
205 if (!data->dbus_id) { 282 if (!data->dbus_id) {
206 // There was some sort of error with creating the notification. 283 // There was some sort of error with creating the notification.
207 notifications_.erase(data); 284 notifications_.erase(data);
208 } else if (data->should_close) { 285 } else if (data->should_close) {
209 CloseNow(data->dbus_id); 286 CloseNow(data->dbus_id);
210 notifications_.erase(data); 287 notifications_.erase(data);
211 } else if (data->update_data) { 288 } else if (data->update_data) {
212 NotifyNow(data->dbus_id, data->notification_type, *data->update_data, 289 data->notification_type = data->update_notification_type;
213 nullptr, nullptr, nullptr); 290 Notify(*data->update_data, data, nullptr, nullptr);
214 data->update_data.reset(); 291 data->update_data.reset();
215 } 292 }
216 } 293 }
217 294
295 void NotificationPlatformBridgeLinux::Observe(
296 int type,
297 const content::NotificationSource& source,
298 const content::NotificationDetails& details) {
299 DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type);
300 // The browser process is about to exit. Clean up all notification
301 // resource files.
302 notifications_.clear();
303 }
304
305 void NotificationPlatformBridgeLinux::Notify(const Notification& notification,
306 NotificationData* data,
307 GAsyncReadyCallback callback,
308 gpointer user_data) {
309 base::PostTaskWithTraitsAndReplyWithResult(
310 FROM_HERE,
311 base::TaskTraits()
312 .MayBlock()
313 .WithPriority(base::TaskPriority::USER_BLOCKING)
314 .WithShutdownBehavior(base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN),
315 base::Bind(
316 [](scoped_refptr<base::RefCountedMemory> icon) {
317 return base::MakeUnique<ResourceFiles>(WriteDataToTmpFile(icon));
318 },
319 notification.icon().As1xPNGBytes()),
320 base::Bind(&NotificationPlatformBridgeLinux::NotifyNow,
321 weak_factory_.GetWeakPtr(), notification,
322 data->weak_factory.GetWeakPtr(), callback, user_data));
323 }
324
218 void NotificationPlatformBridgeLinux::NotifyNow( 325 void NotificationPlatformBridgeLinux::NotifyNow(
219 uint32_t dbus_id,
220 NotificationCommon::Type notification_type,
221 const Notification& notification, 326 const Notification& notification,
222 GCancellable* cancellable, 327 base::WeakPtr<NotificationData> data,
223 GAsyncReadyCallback callback, 328 GAsyncReadyCallback callback,
224 gpointer user_data) { 329 gpointer user_data,
225 // TODO(thomasanderson): Add a complete implementation. 330 std::unique_ptr<ResourceFiles> resource_files) {
331 if (!data)
332 return;
333
334 if (data->dbus_id)
335 DCHECK(!data->cancellable);
336
337 data->ResetResourceFiles();
226 338
227 GVariantBuilder actions_builder; 339 GVariantBuilder actions_builder;
228 // Even-indexed elements in this array are action IDs passed back to 340 // Even-indexed elements in this array are action IDs passed back to
229 // us in GSignalReceiver. Odd-indexed ones contain the button text. 341 // us in GSignalReceiver. Odd-indexed ones contain the button text.
230 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as")); 342 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as"));
231 if (notification.clickable()) { 343 if (notification.clickable()) {
232 // Special case: the pair ("default", "") will not add a button, 344 // Special case: the pair ("default", "") will not add a button,
233 // but instead makes the entire notification clickable. 345 // but instead makes the entire notification clickable.
234 AddActionToNotification(&actions_builder, "default", ""); 346 AddActionToNotification(&actions_builder, "default", "");
235 } 347 }
236 // Always add a settings button. 348 // Always add a settings button.
237 AddActionToNotification(&actions_builder, "settings", "Settings"); 349 AddActionToNotification(&actions_builder, "settings", "Settings");
238 350
351 GVariantBuilder hints_builder;
352 g_variant_builder_init(&hints_builder, G_VARIANT_TYPE("a{sv}"));
353 g_variant_builder_add(&hints_builder, "{sv}", "urgency",
354 g_variant_new_byte(NotificationPriorityToFdoUrgency(
355 notification.priority())));
356
357 if (!resource_files->icon_file.empty()) {
358 g_variant_builder_add(
359 &hints_builder, "{sv}", "image-path",
360 g_variant_new_string(resource_files->icon_file.value().c_str()));
361 data->resource_files.push_back(resource_files->icon_file);
362 resource_files->icon_file.clear();
363 }
364
239 const std::string title = base::UTF16ToUTF8(notification.title()); 365 const std::string title = base::UTF16ToUTF8(notification.title());
240 const std::string message = base::UTF16ToUTF8(notification.message()); 366 const std::string message = base::UTF16ToUTF8(notification.message());
241 367
242 GVariant* parameters = 368 GVariant* parameters =
243 g_variant_new("(susssasa{sv}i)", "", dbus_id, "", title.c_str(), 369 g_variant_new("(susssasa{sv}i)", "", data->dbus_id, "", title.c_str(),
244 message.c_str(), &actions_builder, nullptr, -1); 370 message.c_str(), &actions_builder, &hints_builder, -1);
245 g_dbus_proxy_call(notification_proxy_, "Notify", parameters, 371 g_dbus_proxy_call(notification_proxy_, "Notify", parameters,
246 G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, 372 G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, callback,
247 user_data); 373 user_data);
248 } 374 }
249 375
250 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) { 376 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) {
251 g_dbus_proxy_call(notification_proxy_, "CloseNotification", 377 g_dbus_proxy_call(notification_proxy_, "CloseNotification",
252 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1, 378 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1,
253 nullptr, nullptr, nullptr); 379 nullptr, nullptr, nullptr);
254 } 380 }
255 381
256 NotificationPlatformBridgeLinux::NotificationData* 382 NotificationPlatformBridgeLinux::NotificationData*
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
322 448
323 if (strcmp(action, "default") == 0) { 449 if (strcmp(action, "default") == 0) {
324 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, 0); 450 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, 0);
325 } else if (strcmp(action, "settings") == 0) { 451 } else if (strcmp(action, "settings") == 0) {
326 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1); 452 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1);
327 } else { 453 } else {
328 NOTIMPLEMENTED() << "No custom buttons just yet!"; 454 NOTIMPLEMENTED() << "No custom buttons just yet!";
329 } 455 }
330 } 456 }
331 } 457 }
OLDNEW
« no previous file with comments | « chrome/browser/notifications/notification_platform_bridge_linux.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698