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

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

Issue 2806203003: Linux native notifications: Support icons (Closed)
Patch Set: Address thestig'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 int data_len = data->size();
98 if (data_len == 0)
Lei Zhang 2017/04/13 20:29:47 But this can't happen now, right? DCHECK(data_len)
Tom (Use chromium acct) 2017/04/13 20:38:40 Not now, but when there's an icon and an image, we
Lei Zhang 2017/04/14 01:00:53 Ah, ok. You have a better mental picture of where
99 return base::FilePath();
100 base::FilePath file_path;
101 if (!base::CreateTemporaryFile(&file_path))
102 return base::FilePath();
103 if (base::WriteFile(file_path, data->front_as<char>(), data_len) !=
104 data_len) {
105 base::DeleteFile(file_path, false);
106 return base::FilePath();
107 }
108 return file_path;
109 }
110
111 void DeleteNotificationResourceFile(const base::FilePath& file_path) {
112 if (file_path.empty())
113 return;
114 base::PostTaskWithTraits(
115 FROM_HERE,
116 base::TaskTraits()
117 .MayBlock()
118 .WithPriority(base::TaskPriority::BACKGROUND)
119 .WithShutdownBehavior(base::TaskShutdownBehavior::BLOCK_SHUTDOWN),
120 base::Bind(base::IgnoreResult(base::DeleteFile), file_path, false));
121 }
122
68 } // namespace 123 } // namespace
69 124
70 // static 125 // static
71 NotificationPlatformBridge* NotificationPlatformBridge::Create() { 126 NotificationPlatformBridge* NotificationPlatformBridge::Create() {
72 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync( 127 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync(
73 G_BUS_TYPE_SESSION, 128 G_BUS_TYPE_SESSION,
74 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | 129 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
75 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START), 130 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START),
76 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath, 131 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath,
77 kFreedesktopNotificationsName, nullptr, nullptr); 132 kFreedesktopNotificationsName, nullptr, nullptr);
78 if (!notification_proxy) 133 if (!notification_proxy)
79 return nullptr; 134 return nullptr;
80 return new NotificationPlatformBridgeLinux(notification_proxy); 135 return new NotificationPlatformBridgeLinux(notification_proxy);
81 } 136 }
82 137
83 struct NotificationPlatformBridgeLinux::NotificationData { 138 struct NotificationPlatformBridgeLinux::NotificationData {
84 NotificationData(NotificationCommon::Type notification_type, 139 NotificationData(NotificationCommon::Type notification_type,
85 const std::string& notification_id, 140 const std::string& notification_id,
86 const std::string& profile_id, 141 const std::string& profile_id,
87 bool is_incognito, 142 bool is_incognito,
88 const GURL& origin_url) 143 const GURL& origin_url)
89 : notification_type(notification_type), 144 : notification_type(notification_type),
90 notification_id(notification_id), 145 notification_id(notification_id),
91 profile_id(profile_id), 146 profile_id(profile_id),
92 is_incognito(is_incognito), 147 is_incognito(is_incognito),
93 origin_url(origin_url) {} 148 origin_url(origin_url),
149 weak_factory(this) {}
94 150
95 ~NotificationData() { 151 ~NotificationData() {
96 if (cancellable) 152 if (cancellable)
97 g_cancellable_cancel(cancellable); 153 g_cancellable_cancel(cancellable);
154 ResetResourceFiles();
155 }
156
157 void ResetResourceFiles() {
158 for (const base::FilePath& file : resource_files)
159 DeleteNotificationResourceFile(file);
160 resource_files.clear();
98 } 161 }
99 162
100 // The ID used by the notification server. Will be 0 until the 163 // The ID used by the notification server. Will be 0 until the
101 // first "Notify" message completes. 164 // first "Notify" message completes.
102 uint32_t dbus_id = 0; 165 uint32_t dbus_id = 0;
103 166
104 // Same parameters used by NotificationPlatformBridge::Display(). 167 // Same parameters used by NotificationPlatformBridge::Display().
105 const NotificationCommon::Type notification_type; 168 NotificationCommon::Type notification_type;
106 const std::string notification_id; 169 const std::string notification_id;
107 const std::string profile_id; 170 const std::string profile_id;
108 const bool is_incognito; 171 const bool is_incognito;
109 172
110 // A copy of the origin_url from the underlying 173 // A copy of the origin_url from the underlying
111 // message_center::Notification. Used to pass back to 174 // message_center::Notification. Used to pass back to
112 // NativeNotificationDisplayService. 175 // NativeNotificationDisplayService.
113 const GURL origin_url; 176 const GURL origin_url;
114 177
178 // Temporary resource files associated with the notification that
179 // should be cleaned up when the notification is closed or on
180 // shutdown.
181 std::vector<base::FilePath> resource_files;
182
115 // Used to cancel the initial "Notify" message so we don't call 183 // Used to cancel the initial "Notify" message so we don't call
116 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a 184 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a
117 // destroyed Notification. 185 // destroyed Notification.
118 ScopedGObject<GCancellable> cancellable; 186 ScopedGObject<GCancellable> cancellable;
119 187
120 // If not null, the data to update the notification with once 188 // If not null, the data to update the notification with once
121 // |dbus_id| becomes available. 189 // |dbus_id| becomes available.
122 std::unique_ptr<Notification> update_data; 190 std::unique_ptr<Notification> update_data;
191 NotificationCommon::Type update_notification_type =
192 NotificationCommon::TYPE_MAX;
123 193
124 // If true, indicates the notification should be closed once 194 // If true, indicates the notification should be closed once
125 // |dbus_id| becomes available. 195 // |dbus_id| becomes available.
126 bool should_close = false; 196 bool should_close = false;
197
198 base::WeakPtrFactory<NotificationData> weak_factory;
199 };
200
201 struct NotificationPlatformBridgeLinux::ResourceFiles {
202 explicit ResourceFiles(const base::FilePath& icon_file)
203 : icon_file(icon_file) {}
204 ~ResourceFiles() { DeleteNotificationResourceFile(icon_file); }
205 base::FilePath icon_file;
127 }; 206 };
128 207
129 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux( 208 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux(
130 GDBusProxy* notification_proxy) 209 GDBusProxy* notification_proxy)
131 : notification_proxy_(notification_proxy) { 210 : notification_proxy_(notification_proxy), weak_factory_(this) {
132 proxy_signal_handler_ = g_signal_connect( 211 proxy_signal_handler_ = g_signal_connect(
133 notification_proxy_, "g-signal", G_CALLBACK(GSignalReceiverThunk), this); 212 notification_proxy_, "g-signal", G_CALLBACK(GSignalReceiverThunk), this);
213 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
214 content::NotificationService::AllSources());
134 } 215 }
135 216
136 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() { 217 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() {
137 if (proxy_signal_handler_) 218 if (proxy_signal_handler_)
138 g_signal_handler_disconnect(notification_proxy_, proxy_signal_handler_); 219 g_signal_handler_disconnect(notification_proxy_, proxy_signal_handler_);
139 } 220 }
140 221
141 void NotificationPlatformBridgeLinux::Display( 222 void NotificationPlatformBridgeLinux::Display(
142 NotificationCommon::Type notification_type, 223 NotificationCommon::Type notification_type,
143 const std::string& notification_id, 224 const std::string& notification_id,
144 const std::string& profile_id, 225 const std::string& profile_id,
145 bool is_incognito, 226 bool is_incognito,
146 const Notification& notification) { 227 const Notification& notification) {
147 NotificationData* data = 228 NotificationData* data =
148 FindNotificationData(notification_id, profile_id, is_incognito); 229 FindNotificationData(notification_id, profile_id, is_incognito);
149 if (data) { 230 if (data) {
150 // Update an existing notification. 231 // Update an existing notification.
151 DCHECK_EQ(data->notification_type, notification_type);
152 if (data->dbus_id) { 232 if (data->dbus_id) {
153 NotifyNow(data->dbus_id, notification_type, notification, nullptr, 233 data->notification_type = notification_type;
154 nullptr, nullptr); 234 Notify(notification, data, nullptr, nullptr);
155 } else { 235 } else {
236 data->update_notification_type = notification_type;
156 data->update_data = base::MakeUnique<Notification>(notification); 237 data->update_data = base::MakeUnique<Notification>(notification);
157 } 238 }
158 } else { 239 } else {
159 // Send the notification for the first time. 240 // Send the notification for the first time.
160 data = new NotificationData(notification_type, notification_id, profile_id, 241 data = new NotificationData(notification_type, notification_id, profile_id,
161 is_incognito, notification.origin_url()); 242 is_incognito, notification.origin_url());
162 data->cancellable.reset(g_cancellable_new()); 243 data->cancellable.reset(g_cancellable_new());
163 notifications_.emplace(data, base::WrapUnique(data)); 244 notifications_.emplace(data, base::WrapUnique(data));
164 NotifyNow(0, notification_type, notification, data->cancellable, 245 Notify(notification, data, NotifyCompleteReceiver, data);
165 NotifyCompleteReceiver, data);
166 } 246 }
167 } 247 }
168 248
169 void NotificationPlatformBridgeLinux::Close( 249 void NotificationPlatformBridgeLinux::Close(
170 const std::string& profile_id, 250 const std::string& profile_id,
171 const std::string& notification_id) { 251 const std::string& notification_id) {
172 std::vector<NotificationData*> to_erase; 252 std::vector<NotificationData*> to_erase;
173 for (const auto& pair : notifications_) { 253 for (const auto& pair : notifications_) {
174 NotificationData* data = pair.first; 254 NotificationData* data = pair.first;
175 if (data->notification_id == notification_id && 255 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)"))) 282 if (value && g_variant_is_of_type(value, G_VARIANT_TYPE("(u)")))
203 g_variant_get(value, "(u)", &data->dbus_id); 283 g_variant_get(value, "(u)", &data->dbus_id);
204 284
205 if (!data->dbus_id) { 285 if (!data->dbus_id) {
206 // There was some sort of error with creating the notification. 286 // There was some sort of error with creating the notification.
207 notifications_.erase(data); 287 notifications_.erase(data);
208 } else if (data->should_close) { 288 } else if (data->should_close) {
209 CloseNow(data->dbus_id); 289 CloseNow(data->dbus_id);
210 notifications_.erase(data); 290 notifications_.erase(data);
211 } else if (data->update_data) { 291 } else if (data->update_data) {
212 NotifyNow(data->dbus_id, data->notification_type, *data->update_data, 292 data->notification_type = data->update_notification_type;
213 nullptr, nullptr, nullptr); 293 Notify(*data->update_data, data, nullptr, nullptr);
214 data->update_data.reset(); 294 data->update_data.reset();
215 } 295 }
216 } 296 }
217 297
298 void NotificationPlatformBridgeLinux::Observe(
299 int type,
300 const content::NotificationSource& source,
301 const content::NotificationDetails& details) {
302 DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type);
303 // The browser process is about to exit. Clean up all notification
304 // resource files.
305 notifications_.clear();
306 }
307
308 void NotificationPlatformBridgeLinux::Notify(const Notification& notification,
309 NotificationData* data,
310 GAsyncReadyCallback callback,
311 gpointer user_data) {
312 const scoped_refptr<base::RefCountedMemory> icon_data =
313 notification.icon().As1xPNGBytes();
314 if (!icon_data->size()) {
315 NotifyNow(notification, data->weak_factory.GetWeakPtr(), callback,
316 user_data, base::MakeUnique<ResourceFiles>(base::FilePath()));
317 } else {
318 base::PostTaskWithTraitsAndReplyWithResult(
319 FROM_HERE,
320 base::TaskTraits()
321 .MayBlock()
322 .WithPriority(base::TaskPriority::USER_BLOCKING)
323 .WithShutdownBehavior(base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN),
324 base::Bind(
325 [](scoped_refptr<base::RefCountedMemory> icon) {
326 return base::MakeUnique<ResourceFiles>(WriteDataToTmpFile(icon));
327 },
328 icon_data),
329 base::Bind(&NotificationPlatformBridgeLinux::NotifyNow,
330 weak_factory_.GetWeakPtr(), notification,
331 data->weak_factory.GetWeakPtr(), callback, user_data));
332 }
333 }
334
218 void NotificationPlatformBridgeLinux::NotifyNow( 335 void NotificationPlatformBridgeLinux::NotifyNow(
219 uint32_t dbus_id,
220 NotificationCommon::Type notification_type,
221 const Notification& notification, 336 const Notification& notification,
222 GCancellable* cancellable, 337 base::WeakPtr<NotificationData> data,
223 GAsyncReadyCallback callback, 338 GAsyncReadyCallback callback,
224 gpointer user_data) { 339 gpointer user_data,
225 // TODO(thomasanderson): Add a complete implementation. 340 std::unique_ptr<ResourceFiles> resource_files) {
341 if (!data)
342 return;
343
344 if (data->dbus_id)
345 DCHECK(!data->cancellable);
346
347 data->ResetResourceFiles();
226 348
227 GVariantBuilder actions_builder; 349 GVariantBuilder actions_builder;
228 // Even-indexed elements in this array are action IDs passed back to 350 // Even-indexed elements in this array are action IDs passed back to
229 // us in GSignalReceiver. Odd-indexed ones contain the button text. 351 // us in GSignalReceiver. Odd-indexed ones contain the button text.
230 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as")); 352 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as"));
231 if (notification.clickable()) { 353 if (notification.clickable()) {
232 // Special case: the pair ("default", "") will not add a button, 354 // Special case: the pair ("default", "") will not add a button,
233 // but instead makes the entire notification clickable. 355 // but instead makes the entire notification clickable.
234 AddActionToNotification(&actions_builder, "default", ""); 356 AddActionToNotification(&actions_builder, "default", "");
235 } 357 }
236 // Always add a settings button. 358 // Always add a settings button.
237 AddActionToNotification(&actions_builder, "settings", "Settings"); 359 AddActionToNotification(&actions_builder, "settings", "Settings");
238 360
361 GVariantBuilder hints_builder;
362 g_variant_builder_init(&hints_builder, G_VARIANT_TYPE("a{sv}"));
363 g_variant_builder_add(&hints_builder, "{sv}", "urgency",
364 g_variant_new_byte(NotificationPriorityToFdoUrgency(
365 notification.priority())));
366
367 if (!resource_files->icon_file.empty()) {
368 g_variant_builder_add(
369 &hints_builder, "{sv}", "image-path",
370 g_variant_new_string(resource_files->icon_file.value().c_str()));
371 data->resource_files.push_back(resource_files->icon_file);
372 resource_files->icon_file.clear();
373 }
374
239 const std::string title = base::UTF16ToUTF8(notification.title()); 375 const std::string title = base::UTF16ToUTF8(notification.title());
240 const std::string message = base::UTF16ToUTF8(notification.message()); 376 const std::string message = base::UTF16ToUTF8(notification.message());
241 377
242 GVariant* parameters = 378 GVariant* parameters =
243 g_variant_new("(susssasa{sv}i)", "", dbus_id, "", title.c_str(), 379 g_variant_new("(susssasa{sv}i)", "", data->dbus_id, "", title.c_str(),
244 message.c_str(), &actions_builder, nullptr, -1); 380 message.c_str(), &actions_builder, &hints_builder, -1);
245 g_dbus_proxy_call(notification_proxy_, "Notify", parameters, 381 g_dbus_proxy_call(notification_proxy_, "Notify", parameters,
246 G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, 382 G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, callback,
247 user_data); 383 user_data);
248 } 384 }
249 385
250 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) { 386 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) {
251 g_dbus_proxy_call(notification_proxy_, "CloseNotification", 387 g_dbus_proxy_call(notification_proxy_, "CloseNotification",
252 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1, 388 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1,
253 nullptr, nullptr, nullptr); 389 nullptr, nullptr, nullptr);
254 } 390 }
255 391
256 NotificationPlatformBridgeLinux::NotificationData* 392 NotificationPlatformBridgeLinux::NotificationData*
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
322 458
323 if (strcmp(action, "default") == 0) { 459 if (strcmp(action, "default") == 0) {
324 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, 0); 460 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, 0);
325 } else if (strcmp(action, "settings") == 0) { 461 } else if (strcmp(action, "settings") == 0) {
326 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1); 462 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1);
327 } else { 463 } else {
328 NOTIMPLEMENTED() << "No custom buttons just yet!"; 464 NOTIMPLEMENTED() << "No custom buttons just yet!";
329 } 465 }
330 } 466 }
331 } 467 }
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