sky_surface.mm 7.7 KB
Newer Older
C
Chinmay Garde 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "sky_surface.h"

#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>

11 12 13
#include "base/time/time.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "sky/services/engine/input_event.mojom.h"
14
#include "sky/shell/mac/platform_view_mac.h"
15
#include "sky/shell/shell_view.h"
16
#include "sky/shell/shell.h"
17
#include "sky/shell/ui_delegate.h"
18
#include <strings.h>
C
Chinmay Garde 已提交
19

20 21 22 23 24 25 26 27 28
enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

using EventTypeMapperPhase = std::pair<sky::EventType, MapperPhase>;
static inline EventTypeMapperPhase EventTypePhaseFromUITouchPhase(
    UITouchPhase phase) {
C
Chinmay Garde 已提交
29 30
  switch (phase) {
    case UITouchPhaseBegan:
31
      return EventTypeMapperPhase(sky::EventType::POINTER_DOWN,
32
                                  MapperPhase::Added);
C
Chinmay Garde 已提交
33 34 35 36
    case UITouchPhaseMoved:
    case UITouchPhaseStationary:
      // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
      // with the same coordinates
37
      return EventTypeMapperPhase(sky::EventType::POINTER_MOVE,
38
                                  MapperPhase::Accessed);
C
Chinmay Garde 已提交
39
    case UITouchPhaseEnded:
40
      return EventTypeMapperPhase(sky::EventType::POINTER_UP,
41
                                  MapperPhase::Removed);
42
    case UITouchPhaseCancelled:
43
      return EventTypeMapperPhase(sky::EventType::POINTER_CANCEL,
44
                                  MapperPhase::Removed);
C
Chinmay Garde 已提交
45 46
  }

47
  return EventTypeMapperPhase(sky::EventType::UNKNOWN, MapperPhase::Accessed);
C
Chinmay Garde 已提交
48 49
}

50 51 52 53 54
static inline int64 InputEventTimestampFromNSTimeInterval(
    NSTimeInterval interval) {
  return base::TimeDelta::FromSecondsD(interval).InMilliseconds();
}

55 56 57 58 59 60 61 62 63 64 65 66 67 68
// UITouch pointers cannot be used as touch ids (even though they remain
// constant throughout the multitouch sequence) because internal components
// assume that ids are < 16. This class maps touch pointers to ids
class TouchMapper {
 public:
  TouchMapper() : free_spots_(~0) {}

  int registerTouch(uintptr_t touch) {
    int freeSpot = ffsll(free_spots_);
    touch_map_[touch] = freeSpot;
    free_spots_ &= ~(1 << (freeSpot - 1));
    return freeSpot;
  }

69
  int unregisterTouch(uintptr_t touch) {
70 71 72
    auto index = touch_map_[touch];
    free_spots_ |= 1 << (index - 1);
    touch_map_.erase(touch);
73
    return index;
74 75 76 77 78 79 80 81 82 83
  }

  int identifierOf(uintptr_t touch) { return touch_map_[touch]; }

 private:
  using BitSet = long long int;
  BitSet free_spots_;
  std::map<uintptr_t, int> touch_map_;
};

C
Chinmay Garde 已提交
84 85
@implementation SkySurface {
  BOOL _platformViewInitialized;
86
  CGPoint _lastScrollTranslation;
C
Chinmay Garde 已提交
87

88
  sky::SkyEnginePtr _sky_engine;
89
  scoped_ptr<sky::shell::ShellView> _shell_view;
90
  TouchMapper _touch_mapper;
91 92
}

93 94 95
static std::string SkPictureTracingPath() {
  NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask, YES);
96
  return [paths.firstObject UTF8String];
97 98
}

99
- (instancetype)initWithShellView:(sky::shell::ShellView*)shellView {
100
  self = [super init];
101
  if (self) {
102 103 104 105 106
    base::FilePath pictureTracingPath =
        base::FilePath::FromUTF8Unsafe(SkPictureTracingPath());
    sky::shell::Shell::Shared()
        .tracing_controller()
        .set_picture_tracing_base_path(pictureTracingPath);
107

108
    _shell_view.reset(shellView);
109
    self.multipleTouchEnabled = YES;
110
  }
111
  return self;
C
Chinmay Garde 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
}

- (gfx::AcceleratedWidget)acceleratedWidget {
  return (gfx::AcceleratedWidget)self.layer;
}

- (void)layoutSubviews {
  [super layoutSubviews];

  [self configureLayerDefaults];

  [self setupPlatformViewIfNecessary];

  CGSize size = self.bounds.size;
  CGFloat scale = [UIScreen mainScreen].scale;

C
Chinmay Garde 已提交
128
  sky::ViewportMetricsPtr metrics = sky::ViewportMetrics::New();
A
Adam Barth 已提交
129 130 131
  metrics->physical_width = size.width * scale;
  metrics->physical_height = size.height * scale;
  metrics->device_pixel_ratio = scale;
132 133 134
  metrics->padding_top =
      [UIApplication sharedApplication].statusBarFrame.size.height;

A
Adam Barth 已提交
135
  _sky_engine->OnViewportMetricsChanged(metrics.Pass());
C
Chinmay Garde 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
}

- (void)configureLayerDefaults {
  CAEAGLLayer* layer = reinterpret_cast<CAEAGLLayer*>(self.layer);
  layer.allowsGroupOpacity = YES;
  layer.opaque = YES;
  CGFloat screenScale = [UIScreen mainScreen].scale;
  layer.contentsScale = screenScale;
  // Note: shouldRasterize is still NO. This is just a defensive measure
  layer.rasterizationScale = screenScale;
}

- (void)setupPlatformViewIfNecessary {
  if (_platformViewInitialized) {
    return;
  }

  _platformViewInitialized = YES;

  [self notifySurfaceCreation];
156
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
157 158
}

159 160
- (sky::shell::PlatformViewMac*)platformView {
  auto view = static_cast<sky::shell::PlatformViewMac*>(_shell_view->view());
C
Chinmay Garde 已提交
161 162 163 164 165 166 167 168
  DCHECK(view);
  return view;
}

- (void)notifySurfaceCreation {
  self.platformView->SurfaceCreated(self.acceleratedWidget);
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
-(const char *) flxBundlePath {
  // In case this runner is part of the precompilation SDK, the FLX bundle is
  // present in the application bundle instead of the runner bundle. Attempt
  // to resolve the path there first.
  // TODO: Allow specification of the application bundle identifier
  NSBundle* applicationBundle = [NSBundle
      bundleWithIdentifier:@"io.flutter.aplication.FlutterApplication"];
  NSString* path = [applicationBundle pathForResource:@"app" ofType:@"flx"];
  if (path.length != 0) {
    return path.UTF8String;
  }
  return
      [[NSBundle mainBundle] pathForResource:@"app" ofType:@"flx"].UTF8String;
}

184 185 186
- (void)connectToEngineAndLoad {
  auto interface_request = mojo::GetProxy(&_sky_engine);
  self.platformView->ConnectToEngine(interface_request.Pass());
187
  mojo::String bundle_path([self flxBundlePath]);
188
  _sky_engine->RunFromPrecompiledSnapshot(bundle_path);
C
Chinmay Garde 已提交
189 190 191 192 193 194 195 196 197
}

- (void)notifySurfaceDestruction {
  self.platformView->SurfaceDestroyed();
}

#pragma mark - UIResponder overrides for raw touches

- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
198
  auto eventTypePhase = EventTypePhaseFromUITouchPhase(phase);
C
Chinmay Garde 已提交
199 200 201 202
  const CGFloat scale = [UIScreen mainScreen].scale;

  for (UITouch* touch in touches) {
    auto input = sky::InputEvent::New();
203
    input->type = eventTypePhase.first;
204
    input->time_stamp = InputEventTimestampFromNSTimeInterval(touch.timestamp);
C
Chinmay Garde 已提交
205 206

    input->pointer_data = sky::PointerData::New();
207
    input->pointer_data->kind = sky::PointerKind::TOUCH;
C
Chinmay Garde 已提交
208

209 210 211 212 213 214 215 216 217 218 219
    int touch_identifier = 0;
    uintptr_t touch_ptr = reinterpret_cast<uintptr_t>(touch);

    switch (eventTypePhase.second) {
      case Accessed:
        touch_identifier = _touch_mapper.identifierOf(touch_ptr);
        break;
      case Added:
        touch_identifier = _touch_mapper.registerTouch(touch_ptr);
        break;
      case Removed:
220
        touch_identifier = _touch_mapper.unregisterTouch(touch_ptr);
221 222 223 224 225
        break;
    }

    DCHECK(touch_identifier != 0);
    input->pointer_data->pointer = touch_identifier;
226

C
Chinmay Garde 已提交
227 228 229 230 231
    CGPoint windowCoordinates = [touch locationInView:nil];

    input->pointer_data->x = windowCoordinates.x * scale;
    input->pointer_data->y = windowCoordinates.y * scale;

232
    _sky_engine->OnInputEvent(input.Pass());
C
Chinmay Garde 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  }
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseBegan];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseMoved];
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseEnded];
}

- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseCancelled];
}

#pragma mark - Misc.

+ (Class)layerClass {
  return [CAEAGLLayer class];
}

- (void)dealloc {
  [self notifySurfaceDestruction];
  [super dealloc];
}

@end