OLD | NEW |
---|---|
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/files/file_util.h" |
10 #include "base/memory/ptr_util.h" | |
11 #include "base/stl_util.h" | |
12 #include "base/strings/nullable_string16.h" | 10 #include "base/strings/nullable_string16.h" |
13 #include "base/strings/string_number_conversions.h" | 11 #include "base/strings/string_number_conversions.h" |
14 #include "base/strings/string_util.h" | 12 #include "base/strings/string_util.h" |
15 #include "base/strings/utf_string_conversions.h" | 13 #include "base/strings/utf_string_conversions.h" |
14 #include "base/synchronization/waitable_event.h" | |
16 #include "base/task_scheduler/post_task.h" | 15 #include "base/task_scheduler/post_task.h" |
17 #include "chrome/browser/browser_process.h" | 16 #include "chrome/browser/browser_process.h" |
18 #include "chrome/browser/chrome_notification_types.h" | |
19 #include "chrome/browser/notifications/native_notification_display_service.h" | 17 #include "chrome/browser/notifications/native_notification_display_service.h" |
20 #include "chrome/browser/notifications/notification.h" | 18 #include "chrome/browser/notifications/notification.h" |
21 #include "chrome/browser/notifications/notification_display_service_factory.h" | 19 #include "chrome/browser/notifications/notification_display_service_factory.h" |
22 #include "chrome/browser/profiles/profile_manager.h" | 20 #include "chrome/browser/profiles/profile_manager.h" |
23 #include "chrome/browser/shell_integration_linux.h" | 21 #include "chrome/browser/shell_integration_linux.h" |
24 #include "content/public/browser/notification_service.h" | 22 #include "content/public/browser/browser_thread.h" |
23 #include "dbus/bus.h" | |
24 #include "dbus/message.h" | |
25 #include "dbus/object_proxy.h" | |
25 | 26 |
26 namespace { | 27 namespace { |
27 | 28 |
28 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications"; | 29 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications"; |
29 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications"; | 30 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications"; |
30 | 31 |
31 void AddActionToNotification(GVariantBuilder* actions_builder, | |
32 const char* action_id, | |
33 const char* button_label) { | |
34 g_variant_builder_add(actions_builder, "s", action_id); | |
35 g_variant_builder_add(actions_builder, "s", button_label); | |
36 } | |
37 | |
38 int NotificationPriorityToFdoUrgency(int priority) { | 32 int NotificationPriorityToFdoUrgency(int priority) { |
39 enum FdoUrgency { | 33 enum FdoUrgency { |
40 LOW = 0, | 34 LOW = 0, |
41 NORMAL = 1, | 35 NORMAL = 1, |
42 CRITICAL = 2, | 36 CRITICAL = 2, |
43 }; | 37 }; |
44 switch (priority) { | 38 switch (priority) { |
45 case message_center::MIN_PRIORITY: | 39 case message_center::MIN_PRIORITY: |
46 case message_center::LOW_PRIORITY: | 40 case message_center::LOW_PRIORITY: |
47 return LOW; | 41 return LOW; |
48 case message_center::HIGH_PRIORITY: | 42 case message_center::HIGH_PRIORITY: |
49 case message_center::MAX_PRIORITY: | 43 case message_center::MAX_PRIORITY: |
50 return CRITICAL; | 44 return CRITICAL; |
51 default: | 45 default: |
52 NOTREACHED(); | 46 NOTREACHED(); |
53 // fallthrough | |
54 case message_center::DEFAULT_PRIORITY: | 47 case message_center::DEFAULT_PRIORITY: |
55 return NORMAL; | 48 return NORMAL; |
56 } | 49 } |
57 } | 50 } |
58 | 51 |
59 // Callback used by GLib when the "Notify" message completes for the | |
60 // first time. | |
61 void NotifyCompleteReceiver(GObject* source_object, | |
62 GAsyncResult* result, | |
63 gpointer user_data) { | |
64 GDBusProxy* proxy = G_DBUS_PROXY(source_object); | |
65 GVariant* value = g_dbus_proxy_call_finish(proxy, result, nullptr); | |
66 if (!value) { | |
67 // The message might have been cancelled, in which case | |
68 // |user_data| points to a destroyed NotificationData. | |
69 return; | |
70 } | |
71 auto* platform_bridge_linux = static_cast<NotificationPlatformBridgeLinux*>( | |
72 g_browser_process->notification_platform_bridge()); | |
73 platform_bridge_linux->NotifyCompleteInternal(user_data, value); | |
74 } | |
75 | |
76 // Runs once the profile has been loaded in order to perform a given | 52 // Runs once the profile has been loaded in order to perform a given |
77 // |operation| on a notification. | 53 // |operation| on a notification. |
78 void ProfileLoadedCallback(NotificationCommon::Operation operation, | 54 void ProfileLoadedCallback(NotificationCommon::Operation operation, |
79 NotificationCommon::Type notification_type, | 55 NotificationCommon::Type notification_type, |
80 const std::string& origin, | 56 const std::string& origin, |
81 const std::string& notification_id, | 57 const std::string& notification_id, |
82 int action_index, | 58 int action_index, |
83 const base::NullableString16& reply, | 59 const base::NullableString16& reply, |
84 Profile* profile) { | 60 Profile* profile) { |
85 if (!profile) | 61 if (!profile) |
(...skipping 18 matching lines...) Expand all Loading... | |
104 if (!base::CreateTemporaryFile(&file_path)) | 80 if (!base::CreateTemporaryFile(&file_path)) |
105 return base::FilePath(); | 81 return base::FilePath(); |
106 if (base::WriteFile(file_path, data->front_as<char>(), data_len) != | 82 if (base::WriteFile(file_path, data->front_as<char>(), data_len) != |
107 data_len) { | 83 data_len) { |
108 base::DeleteFile(file_path, false); | 84 base::DeleteFile(file_path, false); |
109 return base::FilePath(); | 85 return base::FilePath(); |
110 } | 86 } |
111 return file_path; | 87 return file_path; |
112 } | 88 } |
113 | 89 |
114 void DeleteNotificationResourceFile(const base::FilePath& file_path) { | |
115 if (file_path.empty()) | |
116 return; | |
117 base::PostTaskWithTraits( | |
118 FROM_HERE, | |
119 base::TaskTraits() | |
120 .MayBlock() | |
121 .WithPriority(base::TaskPriority::BACKGROUND) | |
122 .WithShutdownBehavior(base::TaskShutdownBehavior::BLOCK_SHUTDOWN), | |
123 base::Bind(base::IgnoreResult(base::DeleteFile), file_path, false)); | |
124 } | |
125 | |
126 } // namespace | 90 } // namespace |
127 | 91 |
128 // static | 92 // static |
129 NotificationPlatformBridge* NotificationPlatformBridge::Create() { | 93 NotificationPlatformBridge* NotificationPlatformBridge::Create() { |
130 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync( | 94 NotificationPlatformBridgeLinux* npbl = new NotificationPlatformBridgeLinux(); |
131 G_BUS_TYPE_SESSION, | 95 if (npbl->BlockUntilReady()) |
132 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | | 96 return npbl; |
133 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START), | 97 delete npbl; |
134 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath, | |
135 kFreedesktopNotificationsName, nullptr, nullptr); | |
136 if (!notification_proxy) | |
137 return nullptr; | |
138 return new NotificationPlatformBridgeLinux(notification_proxy); | |
139 } | |
140 | |
141 struct NotificationPlatformBridgeLinux::NotificationData { | |
142 NotificationData(NotificationCommon::Type notification_type, | |
143 const std::string& notification_id, | |
144 const std::string& profile_id, | |
145 bool is_incognito, | |
146 const GURL& origin_url) | |
147 : notification_type(notification_type), | |
148 notification_id(notification_id), | |
149 profile_id(profile_id), | |
150 is_incognito(is_incognito), | |
151 origin_url(origin_url), | |
152 weak_factory(this) {} | |
153 | |
154 ~NotificationData() { | |
155 if (cancellable) | |
156 g_cancellable_cancel(cancellable); | |
157 ResetResourceFiles(); | |
158 } | |
159 | |
160 void ResetResourceFiles() { | |
161 for (const base::FilePath& file : resource_files) | |
162 DeleteNotificationResourceFile(file); | |
163 resource_files.clear(); | |
164 } | |
165 | |
166 // The ID used by the notification server. Will be 0 until the | |
167 // first "Notify" message completes. | |
168 uint32_t dbus_id = 0; | |
169 | |
170 // Same parameters used by NotificationPlatformBridge::Display(). | |
171 NotificationCommon::Type notification_type; | |
172 const std::string notification_id; | |
173 const std::string profile_id; | |
174 const bool is_incognito; | |
175 | |
176 // A copy of the origin_url from the underlying | |
177 // message_center::Notification. Used to pass back to | |
178 // NativeNotificationDisplayService. | |
179 const GURL origin_url; | |
180 | |
181 // Used to keep track of the IDs of the buttons currently displayed | |
182 // on this notification. The valid range of action IDs is | |
183 // [action_start, action_end). | |
184 size_t action_start = 0; | |
185 size_t action_end = 0; | |
186 | |
187 // Temporary resource files associated with the notification that | |
188 // should be cleaned up when the notification is closed or on | |
189 // shutdown. | |
190 std::vector<base::FilePath> resource_files; | |
191 | |
192 // Used to cancel the initial "Notify" message so we don't call | |
193 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a | |
194 // destroyed Notification. | |
195 ScopedGObject<GCancellable> cancellable; | |
196 | |
197 // If not null, the data to update the notification with once | |
198 // |dbus_id| becomes available. | |
199 std::unique_ptr<Notification> update_data; | |
200 NotificationCommon::Type update_notification_type = | |
201 NotificationCommon::TYPE_MAX; | |
202 | |
203 // If true, indicates the notification should be closed once | |
204 // |dbus_id| becomes available. | |
205 bool should_close = false; | |
206 | |
207 base::WeakPtrFactory<NotificationData> weak_factory; | |
208 }; | |
209 | |
210 struct NotificationPlatformBridgeLinux::ResourceFiles { | |
211 explicit ResourceFiles(const base::FilePath& icon_file) | |
212 : icon_file(icon_file) {} | |
213 ~ResourceFiles() { DeleteNotificationResourceFile(icon_file); } | |
214 base::FilePath icon_file; | |
215 }; | |
216 | |
217 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux( | |
218 GDBusProxy* notification_proxy) | |
219 : notification_proxy_(notification_proxy), weak_factory_(this) { | |
220 proxy_signal_handler_ = g_signal_connect( | |
221 notification_proxy_, "g-signal", G_CALLBACK(GSignalReceiverThunk), this); | |
222 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, | |
223 content::NotificationService::AllSources()); | |
224 } | |
225 | |
226 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() { | |
227 if (proxy_signal_handler_) | |
228 g_signal_handler_disconnect(notification_proxy_, proxy_signal_handler_); | |
229 } | |
230 | |
231 void NotificationPlatformBridgeLinux::Display( | |
232 NotificationCommon::Type notification_type, | |
233 const std::string& notification_id, | |
234 const std::string& profile_id, | |
235 bool is_incognito, | |
236 const Notification& notification) { | |
237 NotificationData* data = | |
238 FindNotificationData(notification_id, profile_id, is_incognito); | |
239 if (data) { | |
240 // Update an existing notification. | |
241 if (data->dbus_id) { | |
242 data->notification_type = notification_type; | |
243 Notify(notification, data, nullptr, nullptr); | |
244 } else { | |
245 data->update_notification_type = notification_type; | |
246 data->update_data = base::MakeUnique<Notification>(notification); | |
247 } | |
248 } else { | |
249 // Send the notification for the first time. | |
250 data = new NotificationData(notification_type, notification_id, profile_id, | |
251 is_incognito, notification.origin_url()); | |
252 data->cancellable.reset(g_cancellable_new()); | |
253 notifications_.emplace(data, base::WrapUnique(data)); | |
254 Notify(notification, data, NotifyCompleteReceiver, data); | |
255 } | |
256 } | |
257 | |
258 void NotificationPlatformBridgeLinux::Close( | |
259 const std::string& profile_id, | |
260 const std::string& notification_id) { | |
261 std::vector<NotificationData*> to_erase; | |
262 for (const auto& pair : notifications_) { | |
263 NotificationData* data = pair.first; | |
264 if (data->notification_id == notification_id && | |
265 data->profile_id == profile_id) { | |
266 if (data->dbus_id) { | |
267 CloseNow(data->dbus_id); | |
268 to_erase.push_back(data); | |
269 } else { | |
270 data->should_close = true; | |
271 } | |
272 } | |
273 } | |
274 for (NotificationData* data : to_erase) | |
275 notifications_.erase(data); | |
276 } | |
277 | |
278 void NotificationPlatformBridgeLinux::GetDisplayed( | |
279 const std::string& profile_id, | |
280 bool incognito, | |
281 const DisplayedNotificationsCallback& callback) const { | |
282 callback.Run(base::MakeUnique<std::set<std::string>>(), false); | |
283 } | |
284 | |
285 void NotificationPlatformBridgeLinux::NotifyCompleteInternal(gpointer user_data, | |
286 GVariant* value) { | |
287 NotificationData* data = reinterpret_cast<NotificationData*>(user_data); | |
288 if (!base::ContainsKey(notifications_, data)) | |
289 return; | |
290 data->cancellable.reset(); | |
291 if (value && g_variant_is_of_type(value, G_VARIANT_TYPE("(u)"))) | |
292 g_variant_get(value, "(u)", &data->dbus_id); | |
293 | |
294 if (!data->dbus_id) { | |
295 // There was some sort of error with creating the notification. | |
296 notifications_.erase(data); | |
297 } else if (data->should_close) { | |
298 CloseNow(data->dbus_id); | |
299 notifications_.erase(data); | |
300 } else if (data->update_data) { | |
301 data->notification_type = data->update_notification_type; | |
302 Notify(*data->update_data, data, nullptr, nullptr); | |
303 data->update_data.reset(); | |
304 } | |
305 } | |
306 | |
307 void NotificationPlatformBridgeLinux::Observe( | |
308 int type, | |
309 const content::NotificationSource& source, | |
310 const content::NotificationDetails& details) { | |
311 DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type); | |
312 // The browser process is about to exit. Clean up all notification | |
313 // resource files. | |
314 notifications_.clear(); | |
315 } | |
316 | |
317 void NotificationPlatformBridgeLinux::Notify(const Notification& notification, | |
318 NotificationData* data, | |
319 GAsyncReadyCallback callback, | |
320 gpointer user_data) { | |
321 const scoped_refptr<base::RefCountedMemory> icon_data = | |
322 notification.icon().As1xPNGBytes(); | |
323 if (!icon_data->size()) { | |
324 NotifyNow(notification, data->weak_factory.GetWeakPtr(), callback, | |
325 user_data, base::MakeUnique<ResourceFiles>(base::FilePath())); | |
326 } else { | |
327 base::PostTaskWithTraitsAndReplyWithResult( | |
328 FROM_HERE, | |
329 base::TaskTraits() | |
330 .MayBlock() | |
331 .WithPriority(base::TaskPriority::USER_BLOCKING) | |
332 .WithShutdownBehavior(base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN), | |
333 base::Bind( | |
334 [](scoped_refptr<base::RefCountedMemory> icon) { | |
335 return base::MakeUnique<ResourceFiles>(WriteDataToTmpFile(icon)); | |
336 }, | |
337 icon_data), | |
338 base::Bind(&NotificationPlatformBridgeLinux::NotifyNow, | |
339 weak_factory_.GetWeakPtr(), notification, | |
340 data->weak_factory.GetWeakPtr(), callback, user_data)); | |
341 } | |
342 } | |
343 | |
344 void NotificationPlatformBridgeLinux::NotifyNow( | |
345 const Notification& notification, | |
346 base::WeakPtr<NotificationData> data, | |
347 GAsyncReadyCallback callback, | |
348 gpointer user_data, | |
349 std::unique_ptr<ResourceFiles> resource_files) { | |
350 if (!data) | |
351 return; | |
352 | |
353 if (data->dbus_id) | |
354 DCHECK(!data->cancellable); | |
355 | |
356 data->ResetResourceFiles(); | |
357 | |
358 GVariantBuilder actions_builder; | |
359 // Even-indexed elements in this array are action IDs passed back to | |
360 // us in GSignalReceiver. Odd-indexed ones contain the button text. | |
361 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as")); | |
362 data->action_start = data->action_end; | |
363 for (const auto& button_info : notification.buttons()) { | |
364 // FDO notification buttons can contain either an icon or a label, | |
365 // but not both, and the type of all buttons must be the same (all | |
366 // labels or all icons), so always use labels. | |
367 std::string id = base::SizeTToString(data->action_end++); | |
368 const std::string label = base::UTF16ToUTF8(button_info.title); | |
369 AddActionToNotification(&actions_builder, id.c_str(), label.c_str()); | |
370 } | |
371 if (notification.clickable()) { | |
372 // Special case: the pair ("default", "") will not add a button, | |
373 // but instead makes the entire notification clickable. | |
374 AddActionToNotification(&actions_builder, "default", ""); | |
375 } | |
376 // Always add a settings button. | |
377 AddActionToNotification(&actions_builder, "settings", "Settings"); | |
378 | |
379 GVariantBuilder hints_builder; | |
380 g_variant_builder_init(&hints_builder, G_VARIANT_TYPE("a{sv}")); | |
381 | |
382 g_variant_builder_add(&hints_builder, "{sv}", "urgency", | |
383 g_variant_new_byte(NotificationPriorityToFdoUrgency( | |
384 notification.priority()))); | |
385 | |
386 std::unique_ptr<base::Environment> env = base::Environment::Create(); | |
387 std::string desktop_file = shell_integration_linux::GetDesktopName(env.get()); | |
388 const char kDesktopFileSuffix[] = ".desktop"; | |
389 DCHECK(base::EndsWith(desktop_file, kDesktopFileSuffix, | |
390 base::CompareCase::SENSITIVE)); | |
391 desktop_file = | |
392 desktop_file.substr(0, desktop_file.size() - strlen(kDesktopFileSuffix)); | |
393 g_variant_builder_add(&hints_builder, "{sv}", "desktop-entry", | |
394 g_variant_new_string(desktop_file.c_str())); | |
395 | |
396 if (!resource_files->icon_file.empty()) { | |
397 g_variant_builder_add( | |
398 &hints_builder, "{sv}", "image-path", | |
399 g_variant_new_string(resource_files->icon_file.value().c_str())); | |
400 data->resource_files.push_back(resource_files->icon_file); | |
401 resource_files->icon_file.clear(); | |
402 } | |
403 | |
404 const std::string title = base::UTF16ToUTF8(notification.title()); | |
405 const std::string message = base::UTF16ToUTF8(notification.message()); | |
406 | |
407 GVariant* parameters = g_variant_new( | |
408 "(susssasa{sv}i)", "" /* app_name passed implicitly via desktop-entry */, | |
409 data->dbus_id, "" /* app_icon passed implicitly via desktop-entry */, | |
410 title.c_str(), message.c_str(), &actions_builder, &hints_builder, -1); | |
411 g_dbus_proxy_call(notification_proxy_, "Notify", parameters, | |
412 G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, callback, | |
413 user_data); | |
414 } | |
415 | |
416 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) { | |
417 g_dbus_proxy_call(notification_proxy_, "CloseNotification", | |
418 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1, | |
419 nullptr, nullptr, nullptr); | |
420 } | |
421 | |
422 NotificationPlatformBridgeLinux::NotificationData* | |
423 NotificationPlatformBridgeLinux::FindNotificationData( | |
424 const std::string& notification_id, | |
425 const std::string& profile_id, | |
426 bool is_incognito) { | |
427 for (const auto& pair : notifications_) { | |
428 NotificationData* data = pair.first; | |
429 if (data->notification_id == notification_id && | |
430 data->profile_id == profile_id && data->is_incognito == is_incognito) { | |
431 return data; | |
432 } | |
433 } | |
434 | |
435 return nullptr; | 98 return nullptr; |
436 } | 99 } |
437 | 100 |
438 NotificationPlatformBridgeLinux::NotificationData* | 101 class NotificationPlatformBridgeLinux::NativeNotificationThread |
439 NotificationPlatformBridgeLinux::FindNotificationData(uint32_t dbus_id) { | 102 : public base::Thread { |
440 for (const auto& pair : notifications_) { | 103 public: |
441 NotificationData* data = pair.first; | 104 NativeNotificationThread() |
442 if (data->dbus_id == dbus_id) | 105 : base::Thread("FDO Notifications D-Bus thread"), |
443 return data; | 106 event_(base::WaitableEvent::ResetPolicy::MANUAL, |
444 } | 107 base::WaitableEvent::InitialState::NOT_SIGNALED) { |
445 | 108 base::Thread::Options thread_options(base::MessageLoop::TYPE_IO, 0); |
446 return nullptr; | 109 if (!StartWithOptions(thread_options)) |
447 } | 110 event_.Signal(); |
448 | 111 } |
449 void NotificationPlatformBridgeLinux::ForwardNotificationOperation( | 112 |
450 uint32_t dbus_id, | 113 ~NativeNotificationThread() override { Stop(); } |
451 NotificationCommon::Operation operation, | 114 |
452 int action_index) { | 115 void Display(NotificationCommon::Type notification_type, |
453 NotificationData* data = FindNotificationData(dbus_id); | 116 const std::string& notification_id, |
454 if (!data) { | 117 const std::string& profile_id, |
455 // This notification either belongs to a different app or we | 118 bool is_incognito, |
456 // already removed the NotificationData after sending a | 119 const Notification& notification) { |
457 // "CloseNotification" message. | 120 NotificationData* data = |
458 return; | 121 FindNotificationData(notification_id, profile_id, is_incognito); |
459 } | 122 if (data) { |
460 | 123 // Update an existing notification. |
461 ProfileManager* profile_manager = g_browser_process->profile_manager(); | 124 data->notification_type = notification_type; |
462 DCHECK(profile_manager); | 125 data->resource_files.clear(); |
463 | 126 } else { |
464 profile_manager->LoadProfile( | 127 // Send the notification for the first time. |
465 data->profile_id, data->is_incognito, | 128 data = |
466 base::Bind(&ProfileLoadedCallback, operation, data->notification_type, | 129 new NotificationData(notification_type, notification_id, profile_id, |
467 data->origin_url.spec(), data->notification_id, action_index, | 130 is_incognito, notification.origin_url()); |
468 base::NullableString16())); | 131 notifications_.emplace(data, base::WrapUnique(data)); |
469 } | 132 } |
470 | 133 |
471 void NotificationPlatformBridgeLinux::GSignalReceiver(GDBusProxy* proxy, | 134 dbus::MethodCall method_call(kFreedesktopNotificationsName, "Notify"); |
472 const char* sender_name, | 135 dbus::MessageWriter writer(&method_call); |
473 const char* sender_signal, | 136 |
474 GVariant* parameters) { | 137 // app_name passed implicitly via desktop-entry. |
475 uint32_t dbus_id = 0; | 138 writer.AppendString(""); |
476 if (strcmp("NotificationClosed", sender_signal) == 0 && | 139 |
477 g_variant_is_of_type(parameters, G_VARIANT_TYPE("(uu)"))) { | 140 writer.AppendUint32(data->dbus_id); |
478 uint32_t reason; | 141 |
479 g_variant_get(parameters, "(uu)", &dbus_id, &reason); | 142 // app_icon passed implicitly via desktop-entry. |
480 ForwardNotificationOperation(dbus_id, NotificationCommon::CLOSE, -1); | 143 writer.AppendString(""); |
481 // std::unordered_map::erase(nullptr) is safe here. | 144 |
482 notifications_.erase(FindNotificationData(dbus_id)); | 145 const std::string title = base::UTF16ToUTF8(notification.title()); |
483 } else if (strcmp("ActionInvoked", sender_signal) == 0 && | 146 writer.AppendString(title); |
484 g_variant_is_of_type(parameters, G_VARIANT_TYPE("(us)"))) { | 147 |
485 const gchar* action = nullptr; | 148 const std::string message = base::UTF16ToUTF8(notification.message()); |
486 g_variant_get(parameters, "(u&s)", &dbus_id, &action); | 149 writer.AppendString(message); |
487 DCHECK(action); | 150 |
488 | 151 // Even-indexed elements in this vector are action IDs passed back to |
489 if (strcmp(action, "default") == 0) { | 152 // us in GSignalReceiver. Odd-indexed ones contain the button text. |
hashimoto
2017/04/17 03:17:58
GSignalReceiver is no longer used.
Tom (Use chromium acct)
2017/04/17 18:07:13
Changed to OnActionInvoked()
| |
153 std::vector<std::string> actions; | |
154 data->action_start = data->action_end; | |
155 for (const auto& button_info : notification.buttons()) { | |
156 // FDO notification buttons can contain either an icon or a label, | |
157 // but not both, and the type of all buttons must be the same (all | |
158 // labels or all icons), so always use labels. | |
159 std::string id = base::SizeTToString(data->action_end++); | |
160 const std::string label = base::UTF16ToUTF8(button_info.title); | |
161 actions.push_back(id); | |
162 actions.push_back(label); | |
163 } | |
164 if (notification.clickable()) { | |
165 // Special case: the pair ("default", "") will not add a button, | |
166 // but instead makes the entire notification clickable. | |
167 actions.push_back("default"); | |
168 actions.push_back(""); | |
169 } | |
170 // Always add a settings button. | |
171 actions.push_back("settings"); | |
172 actions.push_back("Settings"); | |
173 writer.AppendArrayOfStrings(actions); | |
174 | |
175 dbus::MessageWriter hints_writer(nullptr); | |
176 writer.OpenArray("{sv}", &hints_writer); | |
177 dbus::MessageWriter urgency_writer(nullptr); | |
178 hints_writer.OpenDictEntry(&urgency_writer); | |
179 urgency_writer.AppendString("urgency"); | |
180 urgency_writer.AppendVariantOfUint32( | |
181 NotificationPriorityToFdoUrgency(notification.priority())); | |
182 hints_writer.CloseContainer(&urgency_writer); | |
183 | |
184 std::unique_ptr<base::Environment> env = base::Environment::Create(); | |
185 std::string desktop_file = | |
186 shell_integration_linux::GetDesktopName(env.get()); | |
187 const char kDesktopFileSuffix[] = ".desktop"; | |
188 DCHECK(base::EndsWith(desktop_file, kDesktopFileSuffix, | |
189 base::CompareCase::SENSITIVE)); | |
190 desktop_file = desktop_file.substr( | |
191 0, desktop_file.size() - strlen(kDesktopFileSuffix)); | |
192 dbus::MessageWriter desktop_entry_writer(nullptr); | |
193 hints_writer.OpenDictEntry(&desktop_entry_writer); | |
194 desktop_entry_writer.AppendString("desktop-entry"); | |
195 desktop_entry_writer.AppendVariantOfString(desktop_file); | |
196 hints_writer.CloseContainer(&desktop_entry_writer); | |
197 | |
198 base::FilePath icon_file = | |
199 WriteDataToTmpFile(notification.icon().As1xPNGBytes()); | |
200 if (!icon_file.empty()) { | |
201 dbus::MessageWriter image_path_writer(nullptr); | |
202 hints_writer.OpenDictEntry(&image_path_writer); | |
203 image_path_writer.AppendString("image-path"); | |
204 image_path_writer.AppendVariantOfString(icon_file.value()); | |
205 hints_writer.CloseContainer(&image_path_writer); | |
206 data->resource_files.push_back(ResourceFile(icon_file)); | |
207 } | |
208 | |
209 writer.CloseContainer(&hints_writer); | |
210 | |
211 int32_t expire_timeout = -1; | |
212 writer.AppendInt32(expire_timeout); | |
213 | |
214 if (data->dbus_id) { | |
215 notification_proxy_->CallMethod(&method_call, -1, | |
hashimoto
2017/04/17 03:17:58
Please use dbus::ObjectProxy::TIMEOUT_USE_DEFAULT
Tom (Use chromium acct)
2017/04/17 18:07:13
Done.
| |
216 base::Bind([](dbus::Response*) {})); | |
217 } else { | |
218 std::unique_ptr<dbus::Response> response = | |
219 notification_proxy_->CallMethodAndBlock(&method_call, -1); | |
220 if (response) { | |
221 dbus::MessageReader reader(response.get()); | |
222 reader.PopUint32(&data->dbus_id); | |
223 } | |
224 if (!data->dbus_id) { | |
225 // There was some sort of error with creating the notification. | |
226 notifications_.erase(data); | |
227 } | |
228 } | |
229 } | |
230 | |
231 void Close(const std::string& profile_id, | |
232 const std::string& notification_id) { | |
233 std::vector<NotificationData*> to_erase; | |
234 for (const auto& pair : notifications_) { | |
235 NotificationData* data = pair.first; | |
236 if (data->notification_id == notification_id && | |
237 data->profile_id == profile_id) { | |
238 dbus::MethodCall method_call(kFreedesktopNotificationsName, | |
239 "CloseNotification"); | |
240 dbus::MessageWriter writer(&method_call); | |
241 writer.AppendUint32(data->dbus_id); | |
242 notification_proxy_->CallMethod(&method_call, -1, | |
243 base::Bind([](dbus::Response*) {})); | |
244 } | |
245 } | |
246 for (NotificationData* data : to_erase) | |
247 notifications_.erase(data); | |
248 } | |
249 | |
250 void GetDisplayed(const std::string& profile_id, | |
251 bool incognito, | |
252 const DisplayedNotificationsCallback& callback) const { | |
253 content::BrowserThread::PostTask( | |
254 content::BrowserThread::UI, FROM_HERE, | |
255 base::Bind(callback, | |
256 base::Passed(base::MakeUnique<std::set<std::string>>()), | |
257 false)); | |
258 } | |
259 | |
260 bool BlockUntilReady() { | |
261 event_.Wait(); | |
262 return notification_proxy_initialized_.IsSet(); | |
263 } | |
264 | |
265 private: | |
266 struct ResourceFile { | |
267 explicit ResourceFile(const base::FilePath& file_path) | |
268 : file_path(file_path) {} | |
269 ~ResourceFile() { base::DeleteFile(file_path, false); } | |
270 base::FilePath file_path; | |
271 }; | |
272 | |
273 struct NotificationData { | |
274 NotificationData(NotificationCommon::Type notification_type, | |
275 const std::string& notification_id, | |
276 const std::string& profile_id, | |
277 bool is_incognito, | |
278 const GURL& origin_url) | |
279 : notification_type(notification_type), | |
280 notification_id(notification_id), | |
281 profile_id(profile_id), | |
282 is_incognito(is_incognito), | |
283 origin_url(origin_url) {} | |
284 | |
285 // The ID used by the notification server. Will be 0 until the | |
286 // first "Notify" message completes. | |
287 uint32_t dbus_id = 0; | |
288 | |
289 // Same parameters used by NotificationPlatformBridge::Display(). | |
290 NotificationCommon::Type notification_type; | |
291 const std::string notification_id; | |
292 const std::string profile_id; | |
293 const bool is_incognito; | |
294 | |
295 // A copy of the origin_url from the underlying | |
296 // message_center::Notification. Used to pass back to | |
297 // NativeNotificationDisplayService. | |
298 const GURL origin_url; | |
299 | |
300 // Used to keep track of the IDs of the buttons currently displayed | |
301 // on this notification. The valid range of action IDs is | |
302 // [action_start, action_end). | |
303 size_t action_start = 0; | |
304 size_t action_end = 0; | |
305 | |
306 // Temporary resource files associated with the notification that | |
307 // should be cleaned up when the notification is closed or on | |
308 // shutdown. | |
309 std::vector<ResourceFile> resource_files; | |
310 }; | |
311 | |
312 void Init() override { | |
313 dbus::Bus::Options bus_options; | |
314 bus_options.bus_type = dbus::Bus::SESSION; | |
315 bus_options.connection_type = dbus::Bus::PRIVATE; | |
316 bus_options.dbus_task_runner = task_runner(); | |
hashimoto
2017/04/17 03:17:58
You don't need to fill dbus_task_runner here.
dbus
Tom (Use chromium acct)
2017/04/17 18:07:13
Done.
| |
317 bus_ = new dbus::Bus(bus_options); | |
318 | |
319 notification_proxy_ = | |
320 bus_->GetObjectProxy(kFreedesktopNotificationsName, | |
321 dbus::ObjectPath(kFreedesktopNotificationsPath)); | |
322 if (notification_proxy_) | |
323 notification_proxy_initialized_.Set(); | |
324 event_.Signal(); | |
325 if (!notification_proxy_) | |
326 return; | |
327 | |
328 auto on_signal_connected = [](const std::string&, const std::string&, | |
329 bool success) { DCHECK(success); }; | |
330 notification_proxy_->ConnectToSignal( | |
331 kFreedesktopNotificationsName, "ActionInvoked", | |
332 base::Bind(&NativeNotificationThread::OnActionInvoked, | |
333 base::Unretained(this)), | |
334 base::Bind(on_signal_connected)); | |
335 notification_proxy_->ConnectToSignal( | |
336 kFreedesktopNotificationsName, "NotificationClosed", | |
337 base::Bind(&NativeNotificationThread::OnNotificationClosed, | |
338 base::Unretained(this)), | |
339 base::Bind(on_signal_connected)); | |
340 } | |
341 | |
342 void CleanUp() override { | |
343 bus_->ShutdownAndBlock(); | |
344 notifications_.clear(); | |
345 } | |
346 | |
347 NotificationData* FindNotificationData(const std::string& notification_id, | |
348 const std::string& profile_id, | |
349 bool is_incognito) { | |
350 for (const auto& pair : notifications_) { | |
351 NotificationData* data = pair.first; | |
352 if (data->notification_id == notification_id && | |
353 data->profile_id == profile_id && | |
354 data->is_incognito == is_incognito) { | |
355 return data; | |
356 } | |
357 } | |
358 | |
359 return nullptr; | |
360 } | |
361 | |
362 NotificationData* FindNotificationData(uint32_t dbus_id) { | |
363 for (const auto& pair : notifications_) { | |
364 NotificationData* data = pair.first; | |
365 if (data->dbus_id == dbus_id) | |
366 return data; | |
367 } | |
368 | |
369 return nullptr; | |
370 } | |
371 | |
372 void ForwardNotificationOperation(uint32_t dbus_id, | |
373 NotificationCommon::Operation operation, | |
374 int action_index) { | |
375 NotificationData* data = FindNotificationData(dbus_id); | |
376 if (!data) { | |
377 // This notification either belongs to a different app or we | |
378 // already removed the NotificationData after sending a | |
379 // "CloseNotification" message. | |
380 return; | |
381 } | |
382 | |
383 content::BrowserThread::PostTask( | |
384 content::BrowserThread::UI, FROM_HERE, | |
385 base::Bind( | |
386 [](NotificationCommon::Operation operation, | |
387 NotificationCommon::Type notification_type, | |
388 const std::string& origin, const std::string& notification_id, | |
389 int action_index, const std::string& profile_id, | |
390 bool is_incognito) { | |
391 ProfileManager* profile_manager = | |
392 g_browser_process->profile_manager(); | |
393 DCHECK(profile_manager); | |
394 | |
395 profile_manager->LoadProfile( | |
396 profile_id, is_incognito, | |
397 base::Bind(&ProfileLoadedCallback, operation, | |
398 notification_type, origin, notification_id, | |
399 action_index, base::NullableString16())); | |
400 }, | |
401 operation, data->notification_type, data->origin_url.spec(), | |
402 data->notification_id, action_index, data->profile_id, | |
403 data->is_incognito)); | |
404 } | |
405 | |
406 void OnActionInvoked(dbus::Signal* signal) { | |
407 dbus::MessageReader reader(signal); | |
408 uint32_t dbus_id; | |
409 if (!reader.PopUint32(&dbus_id)) | |
410 return; | |
411 std::string action; | |
412 if (!reader.PopString(&action)) | |
413 return; | |
414 | |
415 if (action == "default") { | |
490 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, -1); | 416 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, -1); |
491 } else if (strcmp(action, "settings") == 0) { | 417 } else if (action == "settings") { |
492 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1); | 418 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1); |
493 } else { | 419 } else { |
494 size_t id; | 420 size_t id; |
495 if (!base::StringToSizeT(action, &id)) | 421 if (!base::StringToSizeT(action, &id)) |
496 return; | 422 return; |
497 NotificationData* data = FindNotificationData(dbus_id); | 423 NotificationData* data = FindNotificationData(dbus_id); |
498 if (!data) | 424 if (!data) |
499 return; | 425 return; |
500 size_t n_buttons = data->action_end - data->action_start; | 426 size_t n_buttons = data->action_end - data->action_start; |
501 size_t id_zero_based = id - data->action_start; | 427 size_t id_zero_based = id - data->action_start; |
502 if (id_zero_based >= n_buttons) | 428 if (id_zero_based >= n_buttons) |
503 return; | 429 return; |
504 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, | 430 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, |
505 id_zero_based); | 431 id_zero_based); |
506 } | 432 } |
507 } | 433 } |
434 | |
435 void OnNotificationClosed(dbus::Signal* signal) { | |
436 dbus::MessageReader reader(signal); | |
437 uint32_t dbus_id; | |
438 if (!reader.PopUint32(&dbus_id)) | |
439 return; | |
440 ForwardNotificationOperation(dbus_id, NotificationCommon::CLOSE, -1); | |
441 // std::unordered_map::erase(nullptr) is safe here. | |
442 notifications_.erase(FindNotificationData(dbus_id)); | |
443 } | |
444 | |
445 scoped_refptr<dbus::Bus> bus_; | |
446 | |
447 dbus::ObjectProxy* notification_proxy_ = nullptr; | |
448 // Event that will be signaled once |notification_proxy_| is done | |
449 // connecting, or has failed to connect. | |
450 base::WaitableEvent event_; | |
451 | |
452 base::AtomicFlag notification_proxy_initialized_; | |
453 | |
454 // A std::set<std::unique_ptr<T>> doesn't work well because | |
455 // eg. std::set::erase(T) would require a std::unique_ptr<T> | |
456 // argument, so the data would get double-destructed. | |
457 template <typename T> | |
458 using UnorderedUniqueSet = std::unordered_map<T*, std::unique_ptr<T>>; | |
459 | |
460 UnorderedUniqueSet<NotificationData> notifications_; | |
461 }; | |
462 | |
463 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux() | |
464 : thread_(new NativeNotificationThread()) {} | |
465 | |
466 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() {} | |
467 | |
468 void NotificationPlatformBridgeLinux::Display( | |
469 NotificationCommon::Type notification_type, | |
470 const std::string& notification_id, | |
471 const std::string& profile_id, | |
472 bool is_incognito, | |
473 const Notification& notification) { | |
474 // TODO(thomasanderson): Subclass Notification and add pass it | |
475 // thread-safe style to the other thread. | |
476 thread_->task_runner()->PostTask( | |
477 FROM_HERE, | |
478 base::Bind(&NativeNotificationThread::Display, | |
479 base::Unretained(thread_.get()), notification_type, | |
480 notification_id, profile_id, is_incognito, notification)); | |
508 } | 481 } |
482 | |
483 void NotificationPlatformBridgeLinux::Close( | |
484 const std::string& profile_id, | |
485 const std::string& notification_id) { | |
486 thread_->task_runner()->PostTask( | |
487 FROM_HERE, | |
488 base::Bind(&NativeNotificationThread::Close, | |
489 base::Unretained(thread_.get()), profile_id, notification_id)); | |
490 } | |
491 | |
492 void NotificationPlatformBridgeLinux::GetDisplayed( | |
493 const std::string& profile_id, | |
494 bool incognito, | |
495 const DisplayedNotificationsCallback& callback) const { | |
496 thread_->task_runner()->PostTask( | |
497 FROM_HERE, base::Bind(&NativeNotificationThread::GetDisplayed, | |
498 base::Unretained(thread_.get()), profile_id, | |
499 incognito, callback)); | |
500 } | |
501 | |
502 bool NotificationPlatformBridgeLinux::BlockUntilReady() { | |
503 return thread_->BlockUntilReady(); | |
504 } | |
OLD | NEW |