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

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

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

Powered by Google App Engine
This is Rietveld 408576698