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" | 10 #include "base/run_loop.h" |
11 #include "base/stl_util.h" | |
12 #include "base/strings/nullable_string16.h" | 11 #include "base/strings/nullable_string16.h" |
13 #include "base/strings/string_number_conversions.h" | 12 #include "base/strings/string_number_conversions.h" |
14 #include "base/strings/string_util.h" | 13 #include "base/strings/string_util.h" |
15 #include "base/strings/utf_string_conversions.h" | 14 #include "base/strings/utf_string_conversions.h" |
15 #include "base/synchronization/lock.h" | |
16 #include "base/task_scheduler/post_task.h" | 16 #include "base/task_scheduler/post_task.h" |
17 #include "chrome/browser/browser_process.h" | 17 #include "chrome/browser/browser_process.h" |
18 #include "chrome/browser/chrome_notification_types.h" | 18 #include "chrome/browser/chrome_notification_types.h" |
19 #include "chrome/browser/notifications/native_notification_display_service.h" | 19 #include "chrome/browser/notifications/native_notification_display_service.h" |
20 #include "chrome/browser/notifications/notification.h" | 20 #include "chrome/browser/notifications/notification.h" |
21 #include "chrome/browser/notifications/notification_display_service_factory.h" | 21 #include "chrome/browser/notifications/notification_display_service_factory.h" |
22 #include "chrome/browser/profiles/profile_manager.h" | 22 #include "chrome/browser/profiles/profile_manager.h" |
23 #include "chrome/browser/shell_integration_linux.h" | 23 #include "chrome/browser/shell_integration_linux.h" |
24 #include "content/public/browser/browser_thread.h" | |
24 #include "content/public/browser/notification_service.h" | 25 #include "content/public/browser/notification_service.h" |
26 #include "dbus/bus.h" | |
27 #include "dbus/message.h" | |
28 #include "dbus/object_proxy.h" | |
29 #include "ui/gfx/image/image_skia.h" | |
25 | 30 |
26 namespace { | 31 namespace { |
27 | 32 |
28 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications"; | 33 const char kFreedesktopNotificationsName[] = "org.freedesktop.Notifications"; |
29 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications"; | 34 const char kFreedesktopNotificationsPath[] = "/org/freedesktop/Notifications"; |
30 | 35 |
31 void AddActionToNotification(GVariantBuilder* actions_builder, | 36 gfx::Image DeepCopyImage(const gfx::Image& image) { |
32 const char* action_id, | 37 std::unique_ptr<gfx::ImageSkia> image_skia(image.CopyImageSkia()); |
33 const char* button_label) { | 38 return gfx::Image(*image_skia); |
34 g_variant_builder_add(actions_builder, "s", action_id); | |
35 g_variant_builder_add(actions_builder, "s", button_label); | |
36 } | 39 } |
37 | 40 |
38 int NotificationPriorityToFdoUrgency(int priority) { | 41 int NotificationPriorityToFdoUrgency(int priority) { |
39 enum FdoUrgency { | 42 enum FdoUrgency { |
40 LOW = 0, | 43 LOW = 0, |
41 NORMAL = 1, | 44 NORMAL = 1, |
42 CRITICAL = 2, | 45 CRITICAL = 2, |
43 }; | 46 }; |
44 switch (priority) { | 47 switch (priority) { |
45 case message_center::MIN_PRIORITY: | 48 case message_center::MIN_PRIORITY: |
46 case message_center::LOW_PRIORITY: | 49 case message_center::LOW_PRIORITY: |
47 return LOW; | 50 return LOW; |
48 case message_center::HIGH_PRIORITY: | 51 case message_center::HIGH_PRIORITY: |
49 case message_center::MAX_PRIORITY: | 52 case message_center::MAX_PRIORITY: |
50 return CRITICAL; | 53 return CRITICAL; |
51 default: | 54 default: |
52 NOTREACHED(); | 55 NOTREACHED(); |
53 // fallthrough | |
54 case message_center::DEFAULT_PRIORITY: | 56 case message_center::DEFAULT_PRIORITY: |
55 return NORMAL; | 57 return NORMAL; |
56 } | 58 } |
57 } | 59 } |
58 | 60 |
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 | 61 // Runs once the profile has been loaded in order to perform a given |
77 // |operation| on a notification. | 62 // |operation| on a notification. |
78 void ProfileLoadedCallback(NotificationCommon::Operation operation, | 63 void ProfileLoadedCallback(NotificationCommon::Operation operation, |
79 NotificationCommon::Type notification_type, | 64 NotificationCommon::Type notification_type, |
80 const std::string& origin, | 65 const std::string& origin, |
81 const std::string& notification_id, | 66 const std::string& notification_id, |
82 int action_index, | 67 int action_index, |
83 const base::NullableString16& reply, | 68 const base::NullableString16& reply, |
84 Profile* profile) { | 69 Profile* profile) { |
85 if (!profile) | 70 if (!profile) |
(...skipping 18 matching lines...) Expand all Loading... | |
104 if (!base::CreateTemporaryFile(&file_path)) | 89 if (!base::CreateTemporaryFile(&file_path)) |
105 return base::FilePath(); | 90 return base::FilePath(); |
106 if (base::WriteFile(file_path, data->front_as<char>(), data_len) != | 91 if (base::WriteFile(file_path, data->front_as<char>(), data_len) != |
107 data_len) { | 92 data_len) { |
108 base::DeleteFile(file_path, false); | 93 base::DeleteFile(file_path, false); |
109 return base::FilePath(); | 94 return base::FilePath(); |
110 } | 95 } |
111 return file_path; | 96 return file_path; |
112 } | 97 } |
113 | 98 |
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::BindOnce(base::IgnoreResult(base::DeleteFile), file_path, false)); | |
124 } | |
125 | |
126 } // namespace | 99 } // namespace |
127 | 100 |
128 // static | 101 // static |
129 NotificationPlatformBridge* NotificationPlatformBridge::Create() { | 102 NotificationPlatformBridge* NotificationPlatformBridge::Create() { |
130 GDBusProxy* notification_proxy = g_dbus_proxy_new_for_bus_sync( | 103 return new NotificationPlatformBridgeLinux(); |
131 G_BUS_TYPE_SESSION, | 104 } |
132 static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | | 105 |
133 G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START), | 106 class NotificationPlatformBridgeLinuxImpl |
134 nullptr, kFreedesktopNotificationsName, kFreedesktopNotificationsPath, | 107 : public NotificationPlatformBridge, |
135 kFreedesktopNotificationsName, nullptr, nullptr); | 108 public content::NotificationObserver, |
136 if (!notification_proxy) | 109 public base::RefCountedThreadSafe<NotificationPlatformBridgeLinuxImpl> { |
110 public: | |
111 NotificationPlatformBridgeLinuxImpl() | |
112 : task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( | |
113 base::TaskTraits().MayBlock().WithPriority( | |
114 base::TaskPriority::USER_BLOCKING))) { | |
115 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, | |
116 content::NotificationService::AllSources()); | |
117 PostTaskToTaskRunnerThread( | |
118 base::BindOnce(&NotificationPlatformBridgeLinuxImpl::Init, this)); | |
119 } | |
120 | |
121 void Display(NotificationCommon::Type notification_type, | |
122 const std::string& notification_id, | |
123 const std::string& profile_id, | |
124 bool is_incognito, | |
125 const Notification& notification) override { | |
126 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
127 auto notification_copy = base::MakeUnique<Notification>(notification); | |
128 notification_copy->set_icon(DeepCopyImage(notification_copy->icon())); | |
Peter Beverloo
2017/04/25 15:16:55
nit: add a comment about why we do this
Tom (Use chromium acct)
2017/04/25 18:35:21
Done.
| |
129 notification_copy->set_image(gfx::Image()); | |
130 notification_copy->set_small_image(gfx::Image()); | |
131 for (size_t i = 0; i < notification_copy->buttons().size(); i++) | |
132 notification_copy->SetButtonIcon(i, gfx::Image()); | |
133 | |
134 PostTaskToTaskRunnerThread( | |
135 base::Bind(&NotificationPlatformBridgeLinuxImpl::DisplayNow, this, | |
Peter Beverloo
2017/04/25 15:16:55
optional: "Now" doesn't convey the same meaning th
Tom (Use chromium acct)
2017/04/25 18:35:21
Done.
| |
136 notification_type, notification_id, profile_id, is_incognito, | |
137 base::Passed(¬ification_copy))); | |
138 } | |
139 | |
140 void Close(const std::string& profile_id, | |
141 const std::string& notification_id) override { | |
142 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
143 PostTaskToTaskRunnerThread( | |
144 base::Bind(&NotificationPlatformBridgeLinuxImpl::CloseNow, this, | |
145 profile_id, notification_id)); | |
146 } | |
147 | |
148 void GetDisplayed( | |
149 const std::string& profile_id, | |
150 bool incognito, | |
151 const GetDisplayedNotificationsCallback& callback) const override { | |
152 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
153 PostTaskToTaskRunnerThread( | |
154 base::Bind(&NotificationPlatformBridgeLinuxImpl::GetDisplayedNow, this, | |
155 profile_id, incognito, callback)); | |
156 } | |
157 | |
158 void CheckConnection(base::OnceCallback<void(bool)> callback) { | |
159 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
160 base::AutoLock lock(connected_lock_); | |
161 if (connected_.has_value()) { | |
162 content::BrowserThread::PostTask( | |
163 content::BrowserThread::UI, FROM_HERE, | |
164 base::BindOnce(std::move(callback), connected_.value())); | |
165 } else { | |
166 on_connected_callbacks_.push_back(std::move(callback)); | |
167 } | |
168 } | |
169 | |
170 private: | |
171 friend class base::RefCountedThreadSafe<NotificationPlatformBridgeLinuxImpl>; | |
172 | |
173 struct ResourceFile { | |
174 explicit ResourceFile(const base::FilePath& file_path) | |
175 : file_path(file_path) {} | |
176 ~ResourceFile() { base::DeleteFile(file_path, false); } | |
177 const base::FilePath file_path; | |
178 }; | |
179 | |
180 struct NotificationData { | |
181 NotificationData(NotificationCommon::Type notification_type, | |
182 const std::string& notification_id, | |
183 const std::string& profile_id, | |
184 bool is_incognito, | |
185 const GURL& origin_url) | |
186 : notification_type(notification_type), | |
187 notification_id(notification_id), | |
188 profile_id(profile_id), | |
189 is_incognito(is_incognito), | |
190 origin_url(origin_url) {} | |
191 | |
192 // The ID used by the notification server. Will be 0 until the | |
193 // first "Notify" message completes. | |
194 uint32_t dbus_id = 0; | |
195 | |
196 // Same parameters used by NotificationPlatformBridge::Display(). | |
197 NotificationCommon::Type notification_type; | |
198 const std::string notification_id; | |
199 const std::string profile_id; | |
200 const bool is_incognito; | |
201 | |
202 // A copy of the origin_url from the underlying | |
203 // message_center::Notification. Used to pass back to | |
204 // NativeNotificationDisplayService. | |
205 const GURL origin_url; | |
206 | |
207 // Used to keep track of the IDs of the buttons currently displayed | |
208 // on this notification. The valid range of action IDs is | |
209 // [action_start, action_end). | |
210 size_t action_start = 0; | |
211 size_t action_end = 0; | |
212 | |
213 // Temporary resource files associated with the notification that | |
214 // should be cleaned up when the notification is closed or on | |
215 // shutdown. | |
216 std::vector<std::unique_ptr<ResourceFile>> resource_files; | |
217 }; | |
218 | |
219 ~NotificationPlatformBridgeLinuxImpl() override { | |
220 DCHECK(!bus_); | |
221 DCHECK(notifications_.empty()); | |
222 } | |
223 | |
224 void Observe(int type, | |
225 const content::NotificationSource& source, | |
226 const content::NotificationDetails& details) override { | |
227 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
228 DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type); | |
229 // The browser process is about to exit. Post the CleanUp() task | |
230 // while we still can. | |
231 CleanUp(); | |
232 } | |
233 | |
234 void PostTaskToTaskRunnerThread(base::OnceClosure closure) const { | |
235 DCHECK(task_runner_); | |
236 bool success = task_runner_->PostTask(FROM_HERE, std::move(closure)); | |
237 DCHECK(success); | |
238 } | |
239 | |
240 // Sets up the D-Bus connection. | |
241 void Init() { | |
242 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
243 dbus::Bus::Options bus_options; | |
244 bus_options.bus_type = dbus::Bus::SESSION; | |
245 bus_options.connection_type = dbus::Bus::PRIVATE; | |
246 bus_options.dbus_task_runner = task_runner_; | |
247 bus_ = make_scoped_refptr(new dbus::Bus(bus_options)); | |
248 | |
249 notification_proxy_ = | |
250 bus_->GetObjectProxy(kFreedesktopNotificationsName, | |
251 dbus::ObjectPath(kFreedesktopNotificationsPath)); | |
252 if (!notification_proxy_) { | |
253 OnConnectionInitializationFinished(false); | |
254 return; | |
255 } | |
256 | |
257 notification_proxy_->ConnectToSignal( | |
258 kFreedesktopNotificationsName, "ActionInvoked", | |
259 base::Bind(&NotificationPlatformBridgeLinuxImpl::OnActionInvoked, this), | |
260 base::Bind(&NotificationPlatformBridgeLinuxImpl::OnSignalConnected, | |
261 this)); | |
262 notification_proxy_->ConnectToSignal( | |
263 kFreedesktopNotificationsName, "NotificationClosed", | |
264 base::Bind(&NotificationPlatformBridgeLinuxImpl::OnNotificationClosed, | |
265 this), | |
266 base::Bind(&NotificationPlatformBridgeLinuxImpl::OnSignalConnected, | |
267 this)); | |
268 } | |
269 | |
270 void CleanUp() { | |
271 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
272 PostTaskToTaskRunnerThread(base::BindOnce( | |
273 &NotificationPlatformBridgeLinuxImpl::CleanUpOnTaskRunnerThread, this)); | |
274 } | |
275 | |
276 void CleanUpOnTaskRunnerThread() { | |
277 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
278 bus_->ShutdownAndBlock(); | |
279 bus_ = nullptr; | |
280 notification_proxy_ = nullptr; | |
281 notifications_.clear(); | |
282 } | |
283 | |
284 // Makes the "Notify" call to D-Bus. | |
285 void DisplayNow(NotificationCommon::Type notification_type, | |
286 const std::string& notification_id, | |
287 const std::string& profile_id, | |
288 bool is_incognito, | |
289 std::unique_ptr<Notification> notification) { | |
290 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
291 NotificationData* data = | |
292 FindNotificationData(notification_id, profile_id, is_incognito); | |
293 if (data) { | |
294 // Update an existing notification. | |
295 data->notification_type = notification_type; | |
296 data->resource_files.clear(); | |
297 } else { | |
298 // Send the notification for the first time. | |
299 data = | |
300 new NotificationData(notification_type, notification_id, profile_id, | |
301 is_incognito, notification->origin_url()); | |
302 notifications_.emplace(data, base::WrapUnique(data)); | |
303 } | |
304 | |
305 dbus::MethodCall method_call(kFreedesktopNotificationsName, "Notify"); | |
306 dbus::MessageWriter writer(&method_call); | |
307 | |
308 // app_name passed implicitly via desktop-entry. | |
309 writer.AppendString(""); | |
310 | |
311 writer.AppendUint32(data->dbus_id); | |
312 | |
313 // app_icon passed implicitly via desktop-entry. | |
314 writer.AppendString(""); | |
315 | |
316 const std::string title = base::UTF16ToUTF8(notification->title()); | |
317 writer.AppendString(title); | |
318 | |
319 const std::string message = base::UTF16ToUTF8(notification->message()); | |
320 writer.AppendString(message); | |
321 | |
322 // Even-indexed elements in this vector are action IDs passed back to | |
323 // us in OnActionInvoked(). Odd-indexed ones contain the button text. | |
324 std::vector<std::string> actions; | |
325 data->action_start = data->action_end; | |
326 for (const auto& button_info : notification->buttons()) { | |
327 // FDO notification buttons can contain either an icon or a label, | |
328 // but not both, and the type of all buttons must be the same (all | |
329 // labels or all icons), so always use labels. | |
330 const std::string id = base::SizeTToString(data->action_end++); | |
331 const std::string label = base::UTF16ToUTF8(button_info.title); | |
332 actions.push_back(id); | |
333 actions.push_back(label); | |
334 } | |
335 if (notification->clickable()) { | |
336 // Special case: the pair ("default", "") will not add a button, | |
337 // but instead makes the entire notification clickable. | |
338 actions.push_back("default"); | |
339 actions.push_back(""); | |
340 } | |
341 // Always add a settings button. | |
342 actions.push_back("settings"); | |
343 actions.push_back("Settings"); | |
344 writer.AppendArrayOfStrings(actions); | |
345 | |
346 dbus::MessageWriter hints_writer(nullptr); | |
347 writer.OpenArray("{sv}", &hints_writer); | |
348 dbus::MessageWriter urgency_writer(nullptr); | |
349 hints_writer.OpenDictEntry(&urgency_writer); | |
350 urgency_writer.AppendString("urgency"); | |
351 urgency_writer.AppendVariantOfUint32( | |
352 NotificationPriorityToFdoUrgency(notification->priority())); | |
353 hints_writer.CloseContainer(&urgency_writer); | |
354 | |
355 std::unique_ptr<base::Environment> env = base::Environment::Create(); | |
356 base::FilePath desktop_file( | |
357 shell_integration_linux::GetDesktopName(env.get())); | |
358 const char kDesktopFileSuffix[] = ".desktop"; | |
359 DCHECK(base::EndsWith(desktop_file.value(), kDesktopFileSuffix, | |
360 base::CompareCase::SENSITIVE)); | |
361 desktop_file = desktop_file.RemoveFinalExtension(); | |
362 dbus::MessageWriter desktop_entry_writer(nullptr); | |
363 hints_writer.OpenDictEntry(&desktop_entry_writer); | |
364 desktop_entry_writer.AppendString("desktop-entry"); | |
365 desktop_entry_writer.AppendVariantOfString(desktop_file.value()); | |
366 hints_writer.CloseContainer(&desktop_entry_writer); | |
367 | |
368 base::FilePath icon_file = | |
369 WriteDataToTmpFile(notification->icon().As1xPNGBytes()); | |
370 if (!icon_file.empty()) { | |
371 dbus::MessageWriter image_path_writer(nullptr); | |
372 hints_writer.OpenDictEntry(&image_path_writer); | |
373 image_path_writer.AppendString("image-path"); | |
374 image_path_writer.AppendVariantOfString(icon_file.value()); | |
375 hints_writer.CloseContainer(&image_path_writer); | |
376 data->resource_files.push_back(base::MakeUnique<ResourceFile>(icon_file)); | |
377 } | |
378 | |
379 writer.CloseContainer(&hints_writer); | |
380 | |
381 const int32_t kExpireTimeoutDefault = -1; | |
382 writer.AppendInt32(kExpireTimeoutDefault); | |
383 | |
384 std::unique_ptr<dbus::Response> response = | |
385 notification_proxy_->CallMethodAndBlock( | |
386 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); | |
387 if (response) { | |
388 dbus::MessageReader reader(response.get()); | |
389 reader.PopUint32(&data->dbus_id); | |
390 } | |
391 if (!data->dbus_id) { | |
392 // There was some sort of error with creating the notification. | |
393 notifications_.erase(data); | |
394 } | |
395 } | |
396 | |
397 // Makes the "CloseNotification" call to D-Bus. | |
398 void CloseNow(const std::string& profile_id, | |
399 const std::string& notification_id) { | |
400 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
401 std::vector<NotificationData*> to_erase; | |
402 for (const auto& pair : notifications_) { | |
403 NotificationData* data = pair.first; | |
404 if (data->notification_id == notification_id && | |
405 data->profile_id == profile_id) { | |
406 dbus::MethodCall method_call(kFreedesktopNotificationsName, | |
407 "CloseNotification"); | |
408 dbus::MessageWriter writer(&method_call); | |
409 writer.AppendUint32(data->dbus_id); | |
410 notification_proxy_->CallMethodAndBlock( | |
411 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); | |
412 } | |
413 } | |
414 for (NotificationData* data : to_erase) | |
415 notifications_.erase(data); | |
416 } | |
417 | |
418 void GetDisplayedNow( | |
419 const std::string& profile_id, | |
420 bool incognito, | |
421 const GetDisplayedNotificationsCallback& callback) const { | |
422 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
423 // TODO(thomasanderson): Implement. | |
424 content::BrowserThread::PostTask( | |
425 content::BrowserThread::UI, FROM_HERE, | |
426 base::Bind(callback, | |
427 base::Passed(base::MakeUnique<std::set<std::string>>()), | |
428 false)); | |
429 } | |
430 | |
431 NotificationData* FindNotificationData(const std::string& notification_id, | |
432 const std::string& profile_id, | |
433 bool is_incognito) { | |
434 for (const auto& pair : notifications_) { | |
435 NotificationData* data = pair.first; | |
436 if (data->notification_id == notification_id && | |
437 data->profile_id == profile_id && | |
438 data->is_incognito == is_incognito) { | |
439 return data; | |
440 } | |
441 } | |
442 | |
137 return nullptr; | 443 return nullptr; |
138 return new NotificationPlatformBridgeLinux(notification_proxy); | 444 } |
139 } | 445 |
140 | 446 NotificationData* FindNotificationData(uint32_t dbus_id) { |
141 struct NotificationPlatformBridgeLinux::NotificationData { | 447 for (const auto& pair : notifications_) { |
142 NotificationData(NotificationCommon::Type notification_type, | 448 NotificationData* data = pair.first; |
143 const std::string& notification_id, | 449 if (data->dbus_id == dbus_id) |
144 const std::string& profile_id, | 450 return data; |
145 bool is_incognito, | 451 } |
146 const GURL& origin_url) | 452 |
147 : notification_type(notification_type), | 453 return nullptr; |
148 notification_id(notification_id), | 454 } |
149 profile_id(profile_id), | 455 |
150 is_incognito(is_incognito), | 456 void ForwardNotificationOperation(NotificationData* data, |
151 origin_url(origin_url), | 457 NotificationCommon::Operation operation, |
152 weak_factory(this) {} | 458 int action_index) { |
153 | 459 DCHECK(task_runner_->RunsTasksOnCurrentThread()); |
154 ~NotificationData() { | 460 content::BrowserThread::PostTask( |
155 if (cancellable) | 461 content::BrowserThread::UI, FROM_HERE, |
156 g_cancellable_cancel(cancellable); | 462 base::Bind( |
157 ResetResourceFiles(); | 463 [](NotificationCommon::Operation operation, |
158 } | 464 NotificationCommon::Type notification_type, |
159 | 465 const std::string& origin, const std::string& notification_id, |
160 void ResetResourceFiles() { | 466 int action_index, const std::string& profile_id, |
161 for (const base::FilePath& file : resource_files) | 467 bool is_incognito) { |
162 DeleteNotificationResourceFile(file); | 468 ProfileManager* profile_manager = |
163 resource_files.clear(); | 469 g_browser_process->profile_manager(); |
164 } | 470 DCHECK(profile_manager); |
165 | 471 |
166 // The ID used by the notification server. Will be 0 until the | 472 profile_manager->LoadProfile( |
167 // first "Notify" message completes. | 473 profile_id, is_incognito, |
168 uint32_t dbus_id = 0; | 474 base::Bind(&ProfileLoadedCallback, operation, |
169 | 475 notification_type, origin, notification_id, |
170 // Same parameters used by NotificationPlatformBridge::Display(). | 476 action_index, base::NullableString16())); |
171 NotificationCommon::Type notification_type; | 477 }, |
172 const std::string notification_id; | 478 operation, data->notification_type, data->origin_url.spec(), |
173 const std::string profile_id; | 479 data->notification_id, action_index, data->profile_id, |
174 const bool is_incognito; | 480 data->is_incognito)); |
175 | 481 } |
176 // A copy of the origin_url from the underlying | 482 |
177 // message_center::Notification. Used to pass back to | 483 void OnActionInvoked(dbus::Signal* signal) { |
178 // NativeNotificationDisplayService. | 484 DCHECK(task_runner_->RunsTasksOnCurrentThread()); |
179 const GURL origin_url; | 485 dbus::MessageReader reader(signal); |
180 | 486 uint32_t dbus_id; |
181 // Used to keep track of the IDs of the buttons currently displayed | 487 if (!reader.PopUint32(&dbus_id)) |
182 // on this notification. The valid range of action IDs is | 488 return; |
183 // [action_start, action_end). | 489 std::string action; |
184 size_t action_start = 0; | 490 if (!reader.PopString(&action)) |
185 size_t action_end = 0; | 491 return; |
186 | 492 |
187 // Temporary resource files associated with the notification that | 493 NotificationData* data = FindNotificationData(dbus_id); |
188 // should be cleaned up when the notification is closed or on | 494 if (!data) |
189 // shutdown. | 495 return; |
190 std::vector<base::FilePath> resource_files; | 496 |
191 | 497 if (action == "default") { |
192 // Used to cancel the initial "Notify" message so we don't call | 498 ForwardNotificationOperation(data, NotificationCommon::CLICK, -1); |
193 // NotificationPlatformBridgeLinux::NotifyCompleteInternal() with a | 499 } else if (action == "settings") { |
194 // destroyed Notification. | 500 ForwardNotificationOperation(data, NotificationCommon::SETTINGS, -1); |
195 ScopedGObject<GCancellable> cancellable; | 501 } else { |
196 | 502 size_t id; |
197 // If not null, the data to update the notification with once | 503 if (!base::StringToSizeT(action, &id)) |
198 // |dbus_id| becomes available. | 504 return; |
199 std::unique_ptr<Notification> update_data; | 505 size_t n_buttons = data->action_end - data->action_start; |
200 NotificationCommon::Type update_notification_type = | 506 size_t id_zero_based = id - data->action_start; |
201 NotificationCommon::TYPE_MAX; | 507 if (id_zero_based >= n_buttons) |
202 | 508 return; |
203 // If true, indicates the notification should be closed once | 509 ForwardNotificationOperation(data, NotificationCommon::CLICK, |
204 // |dbus_id| becomes available. | 510 id_zero_based); |
205 bool should_close = false; | 511 } |
206 | 512 } |
207 base::WeakPtrFactory<NotificationData> weak_factory; | 513 |
514 void OnNotificationClosed(dbus::Signal* signal) { | |
515 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
516 dbus::MessageReader reader(signal); | |
517 uint32_t dbus_id; | |
518 if (!reader.PopUint32(&dbus_id)) | |
519 return; | |
520 | |
521 NotificationData* data = FindNotificationData(dbus_id); | |
522 if (!data) | |
523 return; | |
524 | |
525 ForwardNotificationOperation(data, NotificationCommon::CLOSE, -1); | |
526 notifications_.erase(data); | |
527 } | |
528 | |
529 // Called once the connection has been set up (or not). |success| | |
530 // indicates the connection is ready to use. | |
531 void OnConnectionInitializationFinished(bool success) { | |
532 DCHECK(task_runner_->RunsTasksOnCurrentThread()); | |
533 { | |
534 base::AutoLock lock(connected_lock_); | |
535 connected_ = success; | |
536 for (auto& callback : on_connected_callbacks_) { | |
537 content::BrowserThread::PostTask( | |
538 content::BrowserThread::UI, FROM_HERE, | |
539 base::BindOnce(std::move(callback), success)); | |
540 } | |
541 on_connected_callbacks_.clear(); | |
542 } | |
543 if (!success) | |
544 CleanUpOnTaskRunnerThread(); | |
545 } | |
546 | |
547 void OnSignalConnected(const std::string& interface_name, | |
548 const std::string& signal_name, | |
549 bool success) { | |
550 if (!success) | |
551 OnConnectionInitializationFinished(false); | |
552 else if (++connected_signals == 2) | |
Peter Beverloo
2017/04/25 15:16:55
base::BarrierClosure solves this in a very nice wa
Tom (Use chromium acct)
2017/04/25 18:35:21
Done. Cool trick!
| |
553 OnConnectionInitializationFinished(true); | |
554 } | |
555 | |
556 // State necessary for OnConnectionInitializationFinished() and | |
557 // CheckConnection(). | |
558 base::Optional<bool> connected_; | |
559 std::vector<base::OnceCallback<void(bool)>> on_connected_callbacks_; | |
560 // Protects both |connected_| and |on_connected_callbacks_|. | |
561 base::Lock connected_lock_; | |
562 | |
563 scoped_refptr<base::SequencedTaskRunner> task_runner_; | |
564 | |
565 scoped_refptr<dbus::Bus> bus_; | |
566 | |
567 int connected_signals = 0; | |
568 | |
569 dbus::ObjectProxy* notification_proxy_ = nullptr; | |
570 | |
571 // A std::set<std::unique_ptr<T>> doesn't work well because | |
572 // eg. std::set::erase(T) would require a std::unique_ptr<T> | |
573 // argument, so the data would get double-destructed. | |
574 template <typename T> | |
575 using UnorderedUniqueSet = std::unordered_map<T*, std::unique_ptr<T>>; | |
576 | |
577 UnorderedUniqueSet<NotificationData> notifications_; | |
578 | |
579 content::NotificationRegistrar registrar_; | |
580 | |
581 DISALLOW_COPY_AND_ASSIGN(NotificationPlatformBridgeLinuxImpl); | |
208 }; | 582 }; |
209 | 583 |
210 struct NotificationPlatformBridgeLinux::ResourceFiles { | 584 NotificationPlatformBridgeLinux::NotificationPlatformBridgeLinux() |
211 explicit ResourceFiles(const base::FilePath& icon_file) | 585 : impl_(new NotificationPlatformBridgeLinuxImpl()) {} |
212 : icon_file(icon_file) {} | 586 |
213 ~ResourceFiles() { DeleteNotificationResourceFile(icon_file); } | 587 NotificationPlatformBridgeLinux::~NotificationPlatformBridgeLinux() = default; |
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 | 588 |
231 void NotificationPlatformBridgeLinux::Display( | 589 void NotificationPlatformBridgeLinux::Display( |
232 NotificationCommon::Type notification_type, | 590 NotificationCommon::Type notification_type, |
233 const std::string& notification_id, | 591 const std::string& notification_id, |
234 const std::string& profile_id, | 592 const std::string& profile_id, |
235 bool is_incognito, | 593 bool is_incognito, |
236 const Notification& notification) { | 594 const Notification& notification) { |
237 NotificationData* data = | 595 impl_->Display(notification_type, notification_id, profile_id, is_incognito, |
238 FindNotificationData(notification_id, profile_id, is_incognito); | 596 notification); |
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 } | 597 } |
257 | 598 |
258 void NotificationPlatformBridgeLinux::Close( | 599 void NotificationPlatformBridgeLinux::Close( |
259 const std::string& profile_id, | 600 const std::string& profile_id, |
260 const std::string& notification_id) { | 601 const std::string& notification_id) { |
261 std::vector<NotificationData*> to_erase; | 602 impl_->Close(profile_id, notification_id); |
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 } | 603 } |
277 | 604 |
278 void NotificationPlatformBridgeLinux::GetDisplayed( | 605 void NotificationPlatformBridgeLinux::GetDisplayed( |
279 const std::string& profile_id, | 606 const std::string& profile_id, |
280 bool incognito, | 607 bool incognito, |
281 const GetDisplayedNotificationsCallback& callback) const { | 608 const GetDisplayedNotificationsCallback& callback) const { |
282 // TODO(thomasanderson): implement. | 609 impl_->GetDisplayed(profile_id, incognito, callback); |
283 callback.Run(base::MakeUnique<std::set<std::string>>(), false); | |
284 } | 610 } |
285 | 611 |
286 void NotificationPlatformBridgeLinux::NotifyCompleteInternal(gpointer user_data, | 612 void NotificationPlatformBridgeLinux::CheckConnection( |
287 GVariant* value) { | 613 base::OnceCallback<void(bool)> callback) { |
288 NotificationData* data = reinterpret_cast<NotificationData*>(user_data); | 614 impl_->CheckConnection(std::move(callback)); |
289 if (!base::ContainsKey(notifications_, data)) | |
290 return; | |
291 data->cancellable.reset(); | |
292 if (value && g_variant_is_of_type(value, G_VARIANT_TYPE("(u)"))) | |
293 g_variant_get(value, "(u)", &data->dbus_id); | |
294 | |
295 if (!data->dbus_id) { | |
296 // There was some sort of error with creating the notification. | |
297 notifications_.erase(data); | |
298 } else if (data->should_close) { | |
299 CloseNow(data->dbus_id); | |
300 notifications_.erase(data); | |
301 } else if (data->update_data) { | |
302 data->notification_type = data->update_notification_type; | |
303 Notify(*data->update_data, data, nullptr, nullptr); | |
304 data->update_data.reset(); | |
305 } | |
306 } | 615 } |
307 | |
308 void NotificationPlatformBridgeLinux::Observe( | |
309 int type, | |
310 const content::NotificationSource& source, | |
311 const content::NotificationDetails& details) { | |
312 DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type); | |
313 // The browser process is about to exit. Clean up all notification | |
314 // resource files. | |
315 notifications_.clear(); | |
316 } | |
317 | |
318 void NotificationPlatformBridgeLinux::Notify(const Notification& notification, | |
319 NotificationData* data, | |
320 GAsyncReadyCallback callback, | |
321 gpointer user_data) { | |
322 const scoped_refptr<base::RefCountedMemory> icon_data = | |
323 notification.icon().As1xPNGBytes(); | |
324 if (!icon_data->size()) { | |
325 NotifyNow(notification, data->weak_factory.GetWeakPtr(), callback, | |
326 user_data, base::MakeUnique<ResourceFiles>(base::FilePath())); | |
327 } else { | |
328 base::PostTaskWithTraitsAndReplyWithResult( | |
329 FROM_HERE, | |
330 base::TaskTraits() | |
331 .MayBlock() | |
332 .WithPriority(base::TaskPriority::USER_BLOCKING) | |
333 .WithShutdownBehavior(base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN), | |
334 base::Bind( | |
335 [](scoped_refptr<base::RefCountedMemory> icon) { | |
336 return base::MakeUnique<ResourceFiles>(WriteDataToTmpFile(icon)); | |
337 }, | |
338 icon_data), | |
339 base::Bind(&NotificationPlatformBridgeLinux::NotifyNow, | |
340 weak_factory_.GetWeakPtr(), notification, | |
341 data->weak_factory.GetWeakPtr(), callback, user_data)); | |
342 } | |
343 } | |
344 | |
345 void NotificationPlatformBridgeLinux::NotifyNow( | |
346 const Notification& notification, | |
347 base::WeakPtr<NotificationData> data, | |
348 GAsyncReadyCallback callback, | |
349 gpointer user_data, | |
350 std::unique_ptr<ResourceFiles> resource_files) { | |
351 if (!data) | |
352 return; | |
353 | |
354 if (data->dbus_id) | |
355 DCHECK(!data->cancellable); | |
356 | |
357 data->ResetResourceFiles(); | |
358 | |
359 GVariantBuilder actions_builder; | |
360 // Even-indexed elements in this array are action IDs passed back to | |
361 // us in GSignalReceiver. Odd-indexed ones contain the button text. | |
362 g_variant_builder_init(&actions_builder, G_VARIANT_TYPE("as")); | |
363 data->action_start = data->action_end; | |
364 for (const auto& button_info : notification.buttons()) { | |
365 // FDO notification buttons can contain either an icon or a label, | |
366 // but not both, and the type of all buttons must be the same (all | |
367 // labels or all icons), so always use labels. | |
368 std::string id = base::SizeTToString(data->action_end++); | |
369 const std::string label = base::UTF16ToUTF8(button_info.title); | |
370 AddActionToNotification(&actions_builder, id.c_str(), label.c_str()); | |
371 } | |
372 if (notification.clickable()) { | |
373 // Special case: the pair ("default", "") will not add a button, | |
374 // but instead makes the entire notification clickable. | |
375 AddActionToNotification(&actions_builder, "default", ""); | |
376 } | |
377 // Always add a settings button. | |
378 AddActionToNotification(&actions_builder, "settings", "Settings"); | |
379 | |
380 GVariantBuilder hints_builder; | |
381 g_variant_builder_init(&hints_builder, G_VARIANT_TYPE("a{sv}")); | |
382 | |
383 g_variant_builder_add(&hints_builder, "{sv}", "urgency", | |
384 g_variant_new_byte(NotificationPriorityToFdoUrgency( | |
385 notification.priority()))); | |
386 | |
387 std::unique_ptr<base::Environment> env = base::Environment::Create(); | |
388 base::FilePath desktop_file( | |
389 shell_integration_linux::GetDesktopName(env.get())); | |
390 const char kDesktopFileSuffix[] = ".desktop"; | |
391 DCHECK(base::EndsWith(desktop_file.value(), kDesktopFileSuffix, | |
392 base::CompareCase::SENSITIVE)); | |
393 | |
394 desktop_file = desktop_file.RemoveFinalExtension(); | |
395 g_variant_builder_add(&hints_builder, "{sv}", "desktop-entry", | |
396 g_variant_new_string(desktop_file.value().c_str())); | |
397 | |
398 if (!resource_files->icon_file.empty()) { | |
399 g_variant_builder_add( | |
400 &hints_builder, "{sv}", "image-path", | |
401 g_variant_new_string(resource_files->icon_file.value().c_str())); | |
402 data->resource_files.push_back(resource_files->icon_file); | |
403 resource_files->icon_file.clear(); | |
404 } | |
405 | |
406 const std::string title = base::UTF16ToUTF8(notification.title()); | |
407 const std::string message = base::UTF16ToUTF8(notification.message()); | |
408 | |
409 GVariant* parameters = g_variant_new( | |
410 "(susssasa{sv}i)", "" /* app_name passed implicitly via desktop-entry */, | |
411 data->dbus_id, "" /* app_icon passed implicitly via desktop-entry */, | |
412 title.c_str(), message.c_str(), &actions_builder, &hints_builder, -1); | |
413 g_dbus_proxy_call(notification_proxy_, "Notify", parameters, | |
414 G_DBUS_CALL_FLAGS_NONE, -1, data->cancellable, callback, | |
415 user_data); | |
416 } | |
417 | |
418 void NotificationPlatformBridgeLinux::CloseNow(uint32_t dbus_id) { | |
419 g_dbus_proxy_call(notification_proxy_, "CloseNotification", | |
420 g_variant_new("(u)", dbus_id), G_DBUS_CALL_FLAGS_NONE, -1, | |
421 nullptr, nullptr, nullptr); | |
422 } | |
423 | |
424 NotificationPlatformBridgeLinux::NotificationData* | |
425 NotificationPlatformBridgeLinux::FindNotificationData( | |
426 const std::string& notification_id, | |
427 const std::string& profile_id, | |
428 bool is_incognito) { | |
429 for (const auto& pair : notifications_) { | |
430 NotificationData* data = pair.first; | |
431 if (data->notification_id == notification_id && | |
432 data->profile_id == profile_id && data->is_incognito == is_incognito) { | |
433 return data; | |
434 } | |
435 } | |
436 | |
437 return nullptr; | |
438 } | |
439 | |
440 NotificationPlatformBridgeLinux::NotificationData* | |
441 NotificationPlatformBridgeLinux::FindNotificationData(uint32_t dbus_id) { | |
442 for (const auto& pair : notifications_) { | |
443 NotificationData* data = pair.first; | |
444 if (data->dbus_id == dbus_id) | |
445 return data; | |
446 } | |
447 | |
448 return nullptr; | |
449 } | |
450 | |
451 void NotificationPlatformBridgeLinux::ForwardNotificationOperation( | |
452 uint32_t dbus_id, | |
453 NotificationCommon::Operation operation, | |
454 int action_index) { | |
455 NotificationData* data = FindNotificationData(dbus_id); | |
456 if (!data) { | |
457 // This notification either belongs to a different app or we | |
458 // already removed the NotificationData after sending a | |
459 // "CloseNotification" message. | |
460 return; | |
461 } | |
462 | |
463 ProfileManager* profile_manager = g_browser_process->profile_manager(); | |
464 DCHECK(profile_manager); | |
465 | |
466 profile_manager->LoadProfile( | |
467 data->profile_id, data->is_incognito, | |
468 base::Bind(&ProfileLoadedCallback, operation, data->notification_type, | |
469 data->origin_url.spec(), data->notification_id, action_index, | |
470 base::NullableString16())); | |
471 } | |
472 | |
473 void NotificationPlatformBridgeLinux::GSignalReceiver(GDBusProxy* proxy, | |
474 const char* sender_name, | |
475 const char* sender_signal, | |
476 GVariant* parameters) { | |
477 uint32_t dbus_id = 0; | |
478 if (strcmp("NotificationClosed", sender_signal) == 0 && | |
479 g_variant_is_of_type(parameters, G_VARIANT_TYPE("(uu)"))) { | |
480 uint32_t reason; | |
481 g_variant_get(parameters, "(uu)", &dbus_id, &reason); | |
482 ForwardNotificationOperation(dbus_id, NotificationCommon::CLOSE, -1); | |
483 // std::unordered_map::erase(nullptr) is safe here. | |
484 notifications_.erase(FindNotificationData(dbus_id)); | |
485 } else if (strcmp("ActionInvoked", sender_signal) == 0 && | |
486 g_variant_is_of_type(parameters, G_VARIANT_TYPE("(us)"))) { | |
487 const gchar* action = nullptr; | |
488 g_variant_get(parameters, "(u&s)", &dbus_id, &action); | |
489 DCHECK(action); | |
490 | |
491 if (strcmp(action, "default") == 0) { | |
492 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, -1); | |
493 } else if (strcmp(action, "settings") == 0) { | |
494 ForwardNotificationOperation(dbus_id, NotificationCommon::SETTINGS, -1); | |
495 } else { | |
496 size_t id; | |
497 if (!base::StringToSizeT(action, &id)) | |
498 return; | |
499 NotificationData* data = FindNotificationData(dbus_id); | |
500 if (!data) | |
501 return; | |
502 size_t n_buttons = data->action_end - data->action_start; | |
503 size_t id_zero_based = id - data->action_start; | |
504 if (id_zero_based >= n_buttons) | |
505 return; | |
506 ForwardNotificationOperation(dbus_id, NotificationCommon::CLICK, | |
507 id_zero_based); | |
508 } | |
509 } | |
510 } | |
OLD | NEW |