ns_view_ids.mm 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/remote_cocoa/app_shim/ns_view_ids.h"
  5. #import <Cocoa/Cocoa.h>
  6. #include <map>
  7. #include <utility>
  8. #include "base/check.h"
  9. #include "base/no_destructor.h"
  10. namespace remote_cocoa {
  11. std::map<uint64_t, NSView*>& GetIdToNSViewMap() {
  12. static base::NoDestructor<std::map<uint64_t, NSView*>> instance;
  13. return *instance;
  14. }
  15. std::map<NSView*, uint64_t>& GetNSViewToIdMap() {
  16. static base::NoDestructor<std::map<NSView*, uint64_t>> instance;
  17. return *instance;
  18. }
  19. NSView* GetNSViewFromId(uint64_t ns_view_id) {
  20. auto& id_to_view_map = GetIdToNSViewMap();
  21. auto found = id_to_view_map.find(ns_view_id);
  22. if (found == id_to_view_map.end())
  23. return nil;
  24. return found->second;
  25. }
  26. uint64_t GetIdFromNSView(NSView* ns_view) {
  27. auto& view_to_id_map = GetNSViewToIdMap();
  28. auto found = view_to_id_map.find(ns_view);
  29. if (found == view_to_id_map.end())
  30. return 0;
  31. return found->second;
  32. }
  33. ScopedNSViewIdMapping::ScopedNSViewIdMapping(uint64_t ns_view_id, NSView* view)
  34. : ns_view_(view), ns_view_id_(ns_view_id) {
  35. DCHECK(ns_view_id_);
  36. {
  37. auto result = GetIdToNSViewMap().insert(std::make_pair(ns_view_id, view));
  38. DCHECK(result.second);
  39. }
  40. {
  41. auto result = GetNSViewToIdMap().insert(std::make_pair(view, ns_view_id));
  42. DCHECK(result.second);
  43. }
  44. }
  45. ScopedNSViewIdMapping::~ScopedNSViewIdMapping() {
  46. {
  47. auto found = GetIdToNSViewMap().find(ns_view_id_);
  48. DCHECK(found != GetIdToNSViewMap().end());
  49. GetIdToNSViewMap().erase(found);
  50. }
  51. {
  52. auto found = GetNSViewToIdMap().find(ns_view_);
  53. DCHECK(found != GetNSViewToIdMap().end());
  54. GetNSViewToIdMap().erase(found);
  55. }
  56. }
  57. } // namespace remote_cocoa