sky_surface.mm 9.2 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
#include "base/time/time.h"
C
Chinmay Garde 已提交
12
#include "base/trace_event/trace_event.h"
13 14
#include "mojo/public/cpp/bindings/interface_request.h"
#include "sky/services/engine/input_event.mojom.h"
15
#include "sky/services/pointer/pointer.mojom.h"
16
#include "sky/shell/platform/mac/platform_service_provider.h"
17
#include "sky/shell/platform/mac/platform_view_mac.h"
18
#include "sky/shell/shell.h"
19
#include "sky/shell/shell_view.h"
20
#include "sky/shell/ui_delegate.h"
21
#include <strings.h>
C
Chinmay Garde 已提交
22

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

29 30
using PointerTypeMapperPhase = std::pair<pointer::PointerType, MapperPhase>;
static inline PointerTypeMapperPhase PointerTypePhaseFromUITouchPhase(
31
    UITouchPhase phase) {
C
Chinmay Garde 已提交
32 33
  switch (phase) {
    case UITouchPhaseBegan:
34 35
      return PointerTypeMapperPhase(pointer::PointerType::DOWN,
                                    MapperPhase::Added);
C
Chinmay Garde 已提交
36 37 38 39
    case UITouchPhaseMoved:
    case UITouchPhaseStationary:
      // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
      // with the same coordinates
40 41
      return PointerTypeMapperPhase(pointer::PointerType::MOVE,
                                    MapperPhase::Accessed);
C
Chinmay Garde 已提交
42
    case UITouchPhaseEnded:
43 44
      return PointerTypeMapperPhase(pointer::PointerType::UP,
                                    MapperPhase::Removed);
45
    case UITouchPhaseCancelled:
46 47
      return PointerTypeMapperPhase(pointer::PointerType::CANCEL,
                                    MapperPhase::Removed);
C
Chinmay Garde 已提交
48 49
  }

50 51
  return PointerTypeMapperPhase(pointer::PointerType::CANCEL,
                                MapperPhase::Accessed);
C
Chinmay Garde 已提交
52 53
}

54 55
static inline int64 InputEventTimestampFromNSTimeInterval(
    NSTimeInterval interval) {
A
Adam Barth 已提交
56
  return base::TimeDelta::FromSecondsD(interval).InMicroseconds();
57 58
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72
// 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;
  }

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

  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 已提交
88 89
@implementation SkySurface {
  BOOL _platformViewInitialized;
90
  CGPoint _lastScrollTranslation;
C
Chinmay Garde 已提交
91

92
  sky::SkyEnginePtr _sky_engine;
93
  scoped_ptr<sky::shell::ShellView> _shell_view;
94
  TouchMapper _touch_mapper;
95 96
}

97
static std::string TracesBasePath() {
98 99
  NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask, YES);
100
  return [paths.firstObject UTF8String];
101 102
}

103
- (instancetype)initWithShellView:(sky::shell::ShellView*)shellView {
C
Chinmay Garde 已提交
104
  TRACE_EVENT0("flutter", "initWithShellView");
105
  self = [super init];
106
  if (self) {
107 108
    base::FilePath tracesPath =
        base::FilePath::FromUTF8Unsafe(TracesBasePath());
109 110
    sky::shell::Shell::Shared()
        .tracing_controller()
111
        .set_traces_base_path(tracesPath);
112

113
    _shell_view.reset(shellView);
114
    self.multipleTouchEnabled = YES;
115
  }
116
  return self;
C
Chinmay Garde 已提交
117 118 119 120 121 122 123
}

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

- (void)layoutSubviews {
C
Chinmay Garde 已提交
124
  TRACE_EVENT0("flutter", "layoutSubviews");
C
Chinmay Garde 已提交
125 126 127 128 129 130 131 132 133
  [super layoutSubviews];

  [self configureLayerDefaults];

  [self setupPlatformViewIfNecessary];

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

C
Chinmay Garde 已提交
134
  sky::ViewportMetricsPtr metrics = sky::ViewportMetrics::New();
A
Adam Barth 已提交
135 136 137
  metrics->physical_width = size.width * scale;
  metrics->physical_height = size.height * scale;
  metrics->device_pixel_ratio = scale;
138 139 140
  metrics->padding_top =
      [UIApplication sharedApplication].statusBarFrame.size.height;

A
Adam Barth 已提交
141
  _sky_engine->OnViewportMetricsChanged(metrics.Pass());
C
Chinmay Garde 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
}

- (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];
162
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
163 164
}

165 166
- (sky::shell::PlatformViewMac*)platformView {
  auto view = static_cast<sky::shell::PlatformViewMac*>(_shell_view->view());
C
Chinmay Garde 已提交
167 168 169 170 171
  DCHECK(view);
  return view;
}

- (void)notifySurfaceCreation {
C
Chinmay Garde 已提交
172
  TRACE_EVENT0("flutter", "notifySurfaceCreation");
C
Chinmay Garde 已提交
173 174 175
  self.platformView->SurfaceCreated(self.acceleratedWidget);
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
-(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;
}

191
- (void)connectToEngineAndLoad {
C
Chinmay Garde 已提交
192
  TRACE_EVENT0("flutter", "connectToEngineAndLoad");
193 194 195 196 197 198 199 200
  self.platformView->ConnectToEngine(mojo::GetProxy(&_sky_engine));

  mojo::ServiceProviderPtr service_provider;
  new sky::shell::PlatformServiceProvider(mojo::GetProxy(&service_provider));
  sky::ServicesDataPtr services = sky::ServicesData::New();
  services->services_provided_by_embedder = service_provider.Pass();
  _sky_engine->SetServices(services.Pass());

201
  mojo::String bundle_path([self flxBundlePath]);
202 203 204 205

#if TARGET_IPHONE_SIMULATOR
  _sky_engine->RunFromBundle(bundle_path);
#else
206
  _sky_engine->RunFromPrecompiledSnapshot(bundle_path);
207
#endif
C
Chinmay Garde 已提交
208 209 210
}

- (void)notifySurfaceDestruction {
C
Chinmay Garde 已提交
211
  TRACE_EVENT0("flutter", "notifySurfaceDestruction");
C
Chinmay Garde 已提交
212 213 214 215 216 217
  self.platformView->SurfaceDestroyed();
}

#pragma mark - UIResponder overrides for raw touches

- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
218
  auto eventTypePhase = PointerTypePhaseFromUITouchPhase(phase);
C
Chinmay Garde 已提交
219
  const CGFloat scale = [UIScreen mainScreen].scale;
220
  auto pointer_packet = pointer::PointerPacket::New();
C
Chinmay Garde 已提交
221 222

  for (UITouch* touch in touches) {
223 224 225 226 227 228 229 230 231 232 233
    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:
234
        touch_identifier = _touch_mapper.unregisterTouch(touch_ptr);
235 236 237
        break;
    }
    DCHECK(touch_identifier != 0);
C
Chinmay Garde 已提交
238
    CGPoint windowCoordinates = [touch locationInView:nil];
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 264 265 266
    auto pointer_time = InputEventTimestampFromNSTimeInterval(touch.timestamp);

    auto pointer_data = pointer::Pointer::New();

    pointer_data->time_stamp = pointer_time;
    pointer_data->type = eventTypePhase.first;
    pointer_data->kind = pointer::PointerKind::TOUCH;
    pointer_data->pointer = touch_identifier;
    pointer_data->x = windowCoordinates.x * scale;
    pointer_data->y = windowCoordinates.y * scale;
    pointer_data->buttons = 0;
    pointer_data->down = false;
    pointer_data->primary = false;
    pointer_data->obscured = false;
    pointer_data->pressure = 1.0;
    pointer_data->pressure_min = 0.0;
    pointer_data->pressure_max = 1.0;
    pointer_data->distance = 0.0;
    pointer_data->distance_min = 0.0;
    pointer_data->distance_max = 0.0;
    pointer_data->radius_major = 0.0;
    pointer_data->radius_minor = 0.0;
    pointer_data->radius_min = 0.0;
    pointer_data->radius_max = 0.0;
    pointer_data->orientation = 0.0;
    pointer_data->tilt = 0.0;

    pointer_packet->pointers.push_back(pointer_data.Pass());
C
Chinmay Garde 已提交
267
  }
268 269

  _sky_engine->OnPointerPacket(pointer_packet.Pass());
C
Chinmay Garde 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
}

- (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