blob: be91cddfdd09a825d829a59d3c7bfeb429eec261 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017#include <stdlib.h>
18#include <stdio.h>
19#include <stdint.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <errno.h>
23#include <math.h>
Jean-Baptiste Queru20763732009-01-26 11:51:12 -080024#include <limits.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/ioctl.h>
28
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
32#include <utils/IPCThreadState.h>
33#include <utils/IServiceManager.h>
34#include <utils/MemoryDealer.h>
35#include <utils/MemoryBase.h>
36#include <utils/String8.h>
37#include <utils/String16.h>
38#include <utils/StopWatch.h>
39
40#include <ui/PixelFormat.h>
41#include <ui/DisplayInfo.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43#include <pixelflinger/pixelflinger.h>
44#include <GLES/gl.h>
45
46#include "clz.h"
Mathias Agopian1473f462009-04-10 14:24:30 -070047#include "BufferAllocator.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048#include "Layer.h"
49#include "LayerBlur.h"
50#include "LayerBuffer.h"
51#include "LayerDim.h"
52#include "LayerBitmap.h"
53#include "LayerOrientationAnim.h"
54#include "OrientationAnimation.h"
55#include "SurfaceFlinger.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059#define DISPLAY_COUNT 1
60
61namespace android {
62
63// ---------------------------------------------------------------------------
64
65void SurfaceFlinger::instantiate() {
66 defaultServiceManager()->addService(
67 String16("SurfaceFlinger"), new SurfaceFlinger());
68}
69
70void SurfaceFlinger::shutdown() {
71 // we should unregister here, but not really because
72 // when (if) the service manager goes away, all the services
73 // it has a reference to will leave too.
74}
75
76// ---------------------------------------------------------------------------
77
78SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
79 : lookup(rhs.lookup), layers(rhs.layers)
80{
81}
82
83ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian1473f462009-04-10 14:24:30 -070084 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085{
86 if (guess<size() && lookup.keyAt(guess) == key)
87 return guess;
88 const ssize_t i = lookup.indexOfKey(key);
89 if (i>=0) {
90 const size_t idx = lookup.valueAt(i);
Mathias Agopian1473f462009-04-10 14:24:30 -070091 LOGE_IF(layers[idx]!=key,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian1473f462009-04-10 14:24:30 -070093 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 return idx;
95 }
96 return i;
97}
98
99ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian1473f462009-04-10 14:24:30 -0700100 const sp<LayerBase>& layer,
101 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102{
103 size_t count = layers.size();
104 ssize_t l = 0;
105 ssize_t h = count-1;
106 ssize_t mid;
Mathias Agopian1473f462009-04-10 14:24:30 -0700107 sp<LayerBase> const* a = layers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 while (l <= h) {
109 mid = l + (h - l)/2;
110 const int c = cmp(a+mid, &layer);
111 if (c == 0) { l = mid; break; }
112 else if (c<0) { l = mid+1; }
113 else { h = mid-1; }
114 }
115 size_t order = l;
116 while (order<count && !cmp(&layer, a+order)) {
117 order++;
118 }
119 count = lookup.size();
120 for (size_t i=0 ; i<count ; i++) {
121 if (lookup.valueAt(i) >= order) {
122 lookup.editValueAt(i)++;
123 }
124 }
125 layers.insertAt(layer, order);
126 lookup.add(layer, order);
127 return order;
128}
129
Mathias Agopian1473f462009-04-10 14:24:30 -0700130ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131{
132 const ssize_t keyIndex = lookup.indexOfKey(layer);
133 if (keyIndex >= 0) {
134 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian1473f462009-04-10 14:24:30 -0700135 LOGE_IF(layers[index]!=layer,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian1473f462009-04-10 14:24:30 -0700137 this, int(index), layers[index].get(), layer.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 layers.removeItemsAt(index);
139 lookup.removeItemsAt(keyIndex);
140 const size_t count = lookup.size();
141 for (size_t i=0 ; i<count ; i++) {
142 if (lookup.valueAt(i) >= size_t(index)) {
143 lookup.editValueAt(i)--;
144 }
145 }
146 return index;
147 }
148 return NAME_NOT_FOUND;
149}
150
151ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian1473f462009-04-10 14:24:30 -0700152 const sp<LayerBase>& layer,
153 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154{
155 // XXX: it's a little lame. but oh well...
156 ssize_t err = remove(layer);
157 if (err >=0)
158 err = add(layer, cmp);
159 return err;
160}
161
162// ---------------------------------------------------------------------------
163#if 0
164#pragma mark -
165#endif
166
167SurfaceFlinger::SurfaceFlinger()
168 : BnSurfaceComposer(), Thread(false),
169 mTransactionFlags(0),
170 mTransactionCount(0),
Mathias Agopian1473f462009-04-10 14:24:30 -0700171 mLayersRemoved(false),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 mBootTime(systemTime()),
173 mLastScheduledBroadcast(NULL),
174 mVisibleRegionsDirty(false),
175 mDeferReleaseConsole(false),
176 mFreezeDisplay(false),
177 mFreezeCount(0),
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700178 mFreezeDisplayTime(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 mDebugRegion(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 mDebugBackground(0),
181 mDebugNoBootAnimation(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 mConsoleSignals(0),
183 mSecureFrameBuffer(0)
184{
185 init();
186}
187
188void SurfaceFlinger::init()
189{
190 LOGI("SurfaceFlinger is starting");
191
192 // debugging stuff...
193 char value[PROPERTY_VALUE_MAX];
194 property_get("debug.sf.showupdates", value, "0");
195 mDebugRegion = atoi(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 property_get("debug.sf.showbackground", value, "0");
197 mDebugBackground = atoi(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 property_get("debug.sf.nobootanimation", value, "0");
199 mDebugNoBootAnimation = atoi(value);
200
201 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
204}
205
206SurfaceFlinger::~SurfaceFlinger()
207{
208 glDeleteTextures(1, &mWormholeTexName);
209 delete mOrientationAnimation;
210}
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
213{
214 return graphicPlane(0).displayHardware().getOverlayEngine();
215}
216
217sp<IMemory> SurfaceFlinger::getCblk() const
218{
219 return mServerCblkMemory;
220}
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
223{
224 Mutex::Autolock _l(mStateLock);
225 uint32_t token = mTokens.acquire();
226
227 Client* client = new Client(token, this);
228 if ((client == 0) || (client->ctrlblk == 0)) {
229 mTokens.release(token);
230 return 0;
231 }
232 status_t err = mClientsMap.add(token, client);
233 if (err < 0) {
234 delete client;
235 mTokens.release(token);
236 return 0;
237 }
238 sp<BClient> bclient =
239 new BClient(this, token, client->controlBlockMemory());
240 return bclient;
241}
242
243void SurfaceFlinger::destroyConnection(ClientID cid)
244{
245 Mutex::Autolock _l(mStateLock);
246 Client* const client = mClientsMap.valueFor(cid);
247 if (client) {
248 // free all the layers this client owns
Mathias Agopian1473f462009-04-10 14:24:30 -0700249 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 const size_t count = layers.size();
251 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700252 sp<LayerBaseClient> layer(layers[i].promote());
253 if (layer != 0) {
254 removeLayer_l(layer);
255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 }
257
258 // the resources associated with this client will be freed
259 // during the next transaction, after these surfaces have been
260 // properly removed from the screen
261
262 // remove this client from our ClientID->Client mapping.
263 mClientsMap.removeItem(cid);
264
265 // and add it to the list of disconnected clients
266 mDisconnectedClients.add(client);
267
268 // request a transaction
269 setTransactionFlags(eTransactionNeeded);
270 }
271}
272
273const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
274{
275 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
276 const GraphicPlane& plane(mGraphicPlanes[dpy]);
277 return plane;
278}
279
280GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
281{
282 return const_cast<GraphicPlane&>(
283 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
284}
285
286void SurfaceFlinger::bootFinished()
287{
288 const nsecs_t now = systemTime();
289 const nsecs_t duration = now - mBootTime;
290 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
291 if (mBootAnimation != 0) {
292 mBootAnimation->requestExit();
293 mBootAnimation.clear();
294 }
295}
296
297void SurfaceFlinger::onFirstRef()
298{
299 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
300
301 // Wait for the main thread to be done with its initialization
302 mReadyToRunBarrier.wait();
303}
304
305
306static inline uint16_t pack565(int r, int g, int b) {
307 return (r<<11)|(g<<5)|b;
308}
309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310status_t SurfaceFlinger::readyToRun()
311{
312 LOGI( "SurfaceFlinger's main thread ready to run. "
313 "Initializing graphics H/W...");
314
315 // create the shared control-block
316 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
317 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
318
319 mServerCblkMemory = mServerHeap->allocate(4096);
320 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
321
322 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
323 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
324 new(mServerCblk) surface_flinger_cblk_t;
325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 // we only support one display currently
327 int dpy = 0;
328
329 {
330 // initialize the main display
331 GraphicPlane& plane(graphicPlane(dpy));
332 DisplayHardware* const hw = new DisplayHardware(this, dpy);
333 plane.setDisplayHardware(hw);
334 }
335
336 // initialize primary screen
337 // (other display should be initialized in the same manner, but
338 // asynchronously, as they could come and go. None of this is supported
339 // yet).
340 const GraphicPlane& plane(graphicPlane(dpy));
341 const DisplayHardware& hw = plane.displayHardware();
342 const uint32_t w = hw.getWidth();
343 const uint32_t h = hw.getHeight();
344 const uint32_t f = hw.getFormat();
345 hw.makeCurrent();
346
347 // initialize the shared control block
348 mServerCblk->connected |= 1<<dpy;
349 display_cblk_t* dcblk = mServerCblk->displays + dpy;
350 memset(dcblk, 0, sizeof(display_cblk_t));
351 dcblk->w = w;
352 dcblk->h = h;
353 dcblk->format = f;
354 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
355 dcblk->xdpi = hw.getDpiX();
356 dcblk->ydpi = hw.getDpiY();
357 dcblk->fps = hw.getRefreshRate();
358 dcblk->density = hw.getDensity();
359 asm volatile ("":::"memory");
360
361 // Initialize OpenGL|ES
362 glActiveTexture(GL_TEXTURE0);
363 glBindTexture(GL_TEXTURE_2D, 0);
364 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
365 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
366 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
367 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
368 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
369 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
370 glPixelStorei(GL_PACK_ALIGNMENT, 4);
371 glEnableClientState(GL_VERTEX_ARRAY);
372 glEnable(GL_SCISSOR_TEST);
373 glShadeModel(GL_FLAT);
374 glDisable(GL_DITHER);
375 glDisable(GL_CULL_FACE);
376
377 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
378 const uint16_t g1 = pack565(0x17,0x2f,0x17);
379 const uint16_t textureData[4] = { g0, g1, g1, g0 };
380 glGenTextures(1, &mWormholeTexName);
381 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
382 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
383 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
384 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
385 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
386 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
387 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
388
389 glViewport(0, 0, w, h);
390 glMatrixMode(GL_PROJECTION);
391 glLoadIdentity();
392 glOrthof(0, w, h, 0, 0, 1);
393
394 LayerDim::initDimmer(this, w, h);
395
396 mReadyToRunBarrier.open();
397
398 /*
399 * We're now ready to accept clients...
400 */
401
402 mOrientationAnimation = new OrientationAnimation(this);
403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 // the boot animation!
405 if (mDebugNoBootAnimation == false)
406 mBootAnimation = new BootAnimation(this);
407
408 return NO_ERROR;
409}
410
411// ----------------------------------------------------------------------------
412#if 0
413#pragma mark -
414#pragma mark Events Handler
415#endif
416
417void SurfaceFlinger::waitForEvent()
418{
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700419 while (true) {
420 nsecs_t timeout = -1;
421 if (UNLIKELY(isFrozen())) {
422 // wait 5 seconds
423 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
424 const nsecs_t now = systemTime();
425 if (mFreezeDisplayTime == 0) {
426 mFreezeDisplayTime = now;
427 }
428 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
429 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700430 }
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700431
432 MessageList::NODE_PTR msg = mEventQueue.waitMessage(timeout);
433 if (msg != 0) {
434 mFreezeDisplayTime = 0;
435 switch (msg->what) {
436 case MessageQueue::INVALIDATE:
437 // invalidate message, just return to the main loop
438 return;
439 }
440 } else {
441 // we timed out
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 if (isFrozen()) {
443 // we timed out and are still frozen
444 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
445 mFreezeDisplay, mFreezeCount);
446 mFreezeCount = 0;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700447 mFreezeDisplay = false;
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700448 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452}
453
454void SurfaceFlinger::signalEvent() {
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700455 mEventQueue.invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456}
457
458void SurfaceFlinger::signal() const {
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700459 // this is the IPC call
460 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461}
462
463void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
464{
Mathias Agopian6ead5d92009-04-20 19:39:12 -0700465 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466}
467
468// ----------------------------------------------------------------------------
469#if 0
470#pragma mark -
471#pragma mark Main loop
472#endif
473
474bool SurfaceFlinger::threadLoop()
475{
476 waitForEvent();
477
478 // check for transactions
479 if (UNLIKELY(mConsoleSignals)) {
480 handleConsoleEvents();
481 }
482
483 if (LIKELY(mTransactionCount == 0)) {
484 // if we're in a global transaction, don't do anything.
485 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
486 uint32_t transactionFlags = getTransactionFlags(mask);
487 if (LIKELY(transactionFlags)) {
488 handleTransaction(transactionFlags);
489 }
490 }
491
492 // post surfaces (if needed)
493 handlePageFlip();
494
495 const DisplayHardware& hw(graphicPlane(0).displayHardware());
496 if (LIKELY(hw.canDraw())) {
497 // repaint the framebuffer (if needed)
498 handleRepaint();
499
500 // release the clients before we flip ('cause flip might block)
501 unlockClients();
502 executeScheduledBroadcasts();
503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 postFramebuffer();
505 } else {
506 // pretend we did the post
507 unlockClients();
508 executeScheduledBroadcasts();
509 usleep(16667); // 60 fps period
510 }
511 return true;
512}
513
514void SurfaceFlinger::postFramebuffer()
515{
516 const bool skip = mOrientationAnimation->run();
517 if (UNLIKELY(skip)) {
518 return;
519 }
520
521 if (!mInvalidRegion.isEmpty()) {
522 const DisplayHardware& hw(graphicPlane(0).displayHardware());
523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 hw.flip(mInvalidRegion);
525
526 mInvalidRegion.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 }
528}
529
530void SurfaceFlinger::handleConsoleEvents()
531{
532 // something to do with the console
533 const DisplayHardware& hw = graphicPlane(0).displayHardware();
534
535 int what = android_atomic_and(0, &mConsoleSignals);
536 if (what & eConsoleAcquired) {
537 hw.acquireScreen();
538 }
539
540 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopianed81f222009-04-14 23:02:51 -0700541 // We got the release signal before the acquire signal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 mDeferReleaseConsole = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 hw.releaseScreen();
544 }
545
546 if (what & eConsoleReleased) {
547 if (hw.canDraw()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 hw.releaseScreen();
549 } else {
550 mDeferReleaseConsole = true;
551 }
552 }
553
554 mDirtyRegion.set(hw.bounds());
555}
556
557void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
558{
559 Mutex::Autolock _l(mStateLock);
560
561 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
562 const size_t count = currentLayers.size();
563
564 /*
565 * Traversal of the children
566 * (perform the transaction for each of them if needed)
567 */
568
569 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
570 if (layersNeedTransaction) {
571 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700572 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
574 if (!trFlags) continue;
575
576 const uint32_t flags = layer->doTransaction(0);
577 if (flags & Layer::eVisibleRegion)
578 mVisibleRegionsDirty = true;
579
580 if (flags & Layer::eRestartTransaction) {
581 // restart the transaction, but back-off a little
582 layer->setTransactionFlags(eTransactionNeeded);
583 setTransactionFlags(eTraversalNeeded, ms2ns(8));
584 }
585 }
586 }
587
588 /*
589 * Perform our own transaction if needed
590 */
591
592 if (transactionFlags & eTransactionNeeded) {
593 if (mCurrentState.orientation != mDrawingState.orientation) {
594 // the orientation has changed, recompute all visible regions
595 // and invalidate everything.
596
597 const int dpy = 0;
598 const int orientation = mCurrentState.orientation;
Mathias Agopianeb0c86e2009-03-27 18:11:38 -0700599 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 GraphicPlane& plane(graphicPlane(dpy));
601 plane.setOrientation(orientation);
602
603 // update the shared control block
604 const DisplayHardware& hw(plane.displayHardware());
605 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
606 dcblk->orientation = orientation;
607 if (orientation & eOrientationSwapMask) {
608 // 90 or 270 degrees orientation
609 dcblk->w = hw.getHeight();
610 dcblk->h = hw.getWidth();
611 } else {
612 dcblk->w = hw.getWidth();
613 dcblk->h = hw.getHeight();
614 }
615
616 mVisibleRegionsDirty = true;
617 mDirtyRegion.set(hw.bounds());
Mathias Agopianeb0c86e2009-03-27 18:11:38 -0700618 mFreezeDisplayTime = 0;
619 mOrientationAnimation->onOrientationChanged(type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 }
621
622 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
623 // freezing or unfreezing the display -> trigger animation if needed
624 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626
Mathias Agopiana3aa6c92009-04-22 15:23:34 -0700627 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
628 // layers have been added
629 mVisibleRegionsDirty = true;
630 }
631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 // some layers might have been removed, so
633 // we need to update the regions they're exposing.
Mathias Agopian1473f462009-04-10 14:24:30 -0700634 if (mLayersRemoved) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 mVisibleRegionsDirty = true;
Mathias Agopiana3aa6c92009-04-22 15:23:34 -0700636 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
637 const ssize_t count = previousLayers.size();
638 for (ssize_t i=0 ; i<count ; i++) {
639 const sp<LayerBase>& layer(previousLayers[i]);
640 if (currentLayers.indexOf( layer ) < 0) {
641 // this layer is not visible anymore
642 // FIXME: would be better to call without the lock held
643 //LOGD("ditching layer %p", layer.get());
644 layer->ditch();
645 }
646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 }
648
649 // get rid of all resources we don't need anymore
650 // (layers and clients)
651 free_resources_l();
652 }
653
654 commitTransaction();
655}
656
657sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
658{
659 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
660}
661
662void SurfaceFlinger::computeVisibleRegions(
663 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
664{
665 const GraphicPlane& plane(graphicPlane(0));
666 const Transform& planeTransform(plane.transform());
667
668 Region aboveOpaqueLayers;
669 Region aboveCoveredLayers;
670 Region dirty;
671
672 bool secureFrameBuffer = false;
673
674 size_t i = currentLayers.size();
675 while (i--) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700676 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 layer->validateVisibility(planeTransform);
678
679 // start with the whole surface at its current location
680 const Layer::State& s = layer->drawingState();
681 const Rect bounds(layer->visibleBounds());
682
683 // handle hidden surfaces by setting the visible region to empty
684 Region opaqueRegion;
685 Region visibleRegion;
686 Region coveredRegion;
687 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
688 visibleRegion.clear();
689 } else {
690 const bool translucent = layer->needsBlending();
691 visibleRegion.set(bounds);
692 coveredRegion = visibleRegion;
693
694 // Remove the transparent area from the visible region
695 if (translucent) {
696 visibleRegion.subtractSelf(layer->transparentRegionScreen);
697 }
698
699 // compute the opaque region
700 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
701 // the opaque region is the visible region
702 opaqueRegion = visibleRegion;
703 }
704 }
705
706 // subtract the opaque region covered by the layers above us
707 visibleRegion.subtractSelf(aboveOpaqueLayers);
708 coveredRegion.andSelf(aboveCoveredLayers);
709
710 // compute this layer's dirty region
711 if (layer->contentDirty) {
712 // we need to invalidate the whole region
713 dirty = visibleRegion;
714 // as well, as the old visible region
715 dirty.orSelf(layer->visibleRegionScreen);
716 layer->contentDirty = false;
717 } else {
718 // compute the exposed region
719 // dirty = what's visible now - what's wasn't covered before
720 // = what's visible now & what's was covered before
721 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
722 }
723 dirty.subtractSelf(aboveOpaqueLayers);
724
725 // accumulate to the screen dirty region
726 dirtyRegion.orSelf(dirty);
727
Mathias Agopianed81f222009-04-14 23:02:51 -0700728 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 aboveOpaqueLayers.orSelf(opaqueRegion);
730 aboveCoveredLayers.orSelf(bounds);
731
732 // Store the visible region is screen space
733 layer->setVisibleRegion(visibleRegion);
734 layer->setCoveredRegion(coveredRegion);
735
Mathias Agopianed81f222009-04-14 23:02:51 -0700736 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 if (layer->isSecure() && !visibleRegion.isEmpty()) {
738 secureFrameBuffer = true;
739 }
740 }
741
742 mSecureFrameBuffer = secureFrameBuffer;
743 opaqueRegion = aboveOpaqueLayers;
744}
745
746
747void SurfaceFlinger::commitTransaction()
748{
749 mDrawingState = mCurrentState;
750 mTransactionCV.signal();
751}
752
753void SurfaceFlinger::handlePageFlip()
754{
755 bool visibleRegions = mVisibleRegionsDirty;
756 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
757 visibleRegions |= lockPageFlip(currentLayers);
758
759 const DisplayHardware& hw = graphicPlane(0).displayHardware();
760 const Region screenRegion(hw.bounds());
761 if (visibleRegions) {
762 Region opaqueRegion;
763 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
764 mWormholeRegion = screenRegion.subtract(opaqueRegion);
765 mVisibleRegionsDirty = false;
766 }
767
768 unlockPageFlip(currentLayers);
769 mDirtyRegion.andSelf(screenRegion);
770}
771
772bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
773{
774 bool recomputeVisibleRegions = false;
775 size_t count = currentLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700776 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700778 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 layer->lockPageFlip(recomputeVisibleRegions);
780 }
781 return recomputeVisibleRegions;
782}
783
784void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
785{
786 const GraphicPlane& plane(graphicPlane(0));
787 const Transform& planeTransform(plane.transform());
788 size_t count = currentLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700789 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700791 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 layer->unlockPageFlip(planeTransform, mDirtyRegion);
793 }
794}
795
796void SurfaceFlinger::handleRepaint()
797{
798 // set the frame buffer
799 const DisplayHardware& hw(graphicPlane(0).displayHardware());
800 glMatrixMode(GL_MODELVIEW);
801 glLoadIdentity();
802
803 if (UNLIKELY(mDebugRegion)) {
804 debugFlashRegions();
805 }
806
807 // compute the invalid region
808 mInvalidRegion.orSelf(mDirtyRegion);
809
810 uint32_t flags = hw.getFlags();
811 if (flags & DisplayHardware::BUFFER_PRESERVED) {
812 // here we assume DisplayHardware::flip()'s implementation
813 // performs the copy-back optimization.
814 } else {
815 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
816 // we need to fully redraw the part that will be updated
817 mDirtyRegion.set(mInvalidRegion.bounds());
818 } else {
819 // we need to redraw everything
820 mDirtyRegion.set(hw.bounds());
821 mInvalidRegion = mDirtyRegion;
822 }
823 }
824
825 // compose all surfaces
826 composeSurfaces(mDirtyRegion);
827
828 // clear the dirty regions
829 mDirtyRegion.clear();
830}
831
832void SurfaceFlinger::composeSurfaces(const Region& dirty)
833{
834 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
835 // should never happen unless the window manager has a bug
836 // draw something...
837 drawWormhole();
838 }
839 const SurfaceFlinger& flinger(*this);
840 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
841 const size_t count = drawingLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700842 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700844 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 const Region& visibleRegion(layer->visibleRegionScreen);
846 if (!visibleRegion.isEmpty()) {
847 const Region clip(dirty.intersect(visibleRegion));
848 if (!clip.isEmpty()) {
849 layer->draw(clip);
850 }
851 }
852 }
853}
854
855void SurfaceFlinger::unlockClients()
856{
857 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
858 const size_t count = drawingLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700859 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700861 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 layer->finishPageFlip();
863 }
864}
865
866void SurfaceFlinger::scheduleBroadcast(Client* client)
867{
868 if (mLastScheduledBroadcast != client) {
869 mLastScheduledBroadcast = client;
870 mScheduledBroadcasts.add(client);
871 }
872}
873
874void SurfaceFlinger::executeScheduledBroadcasts()
875{
876 SortedVector<Client*>& list = mScheduledBroadcasts;
877 size_t count = list.size();
878 while (count--) {
879 per_client_cblk_t* const cblk = list[count]->ctrlblk;
880 if (cblk->lock.tryLock() == NO_ERROR) {
881 cblk->cv.broadcast();
882 list.removeAt(count);
883 cblk->lock.unlock();
884 } else {
885 // schedule another round
886 LOGW("executeScheduledBroadcasts() skipped, "
887 "contention on the client. We'll try again later...");
888 signalDelayedEvent(ms2ns(4));
889 }
890 }
891 mLastScheduledBroadcast = 0;
892}
893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894void SurfaceFlinger::debugFlashRegions()
895{
896 if (UNLIKELY(!mDirtyRegion.isRect())) {
897 // TODO: do this only if we don't have preserving
898 // swapBuffer. If we don't have update-on-demand,
899 // redraw everything.
900 composeSurfaces(Region(mDirtyRegion.bounds()));
901 }
902
903 glDisable(GL_TEXTURE_2D);
904 glDisable(GL_BLEND);
905 glDisable(GL_DITHER);
906 glDisable(GL_SCISSOR_TEST);
907
908 glColor4x(0x10000, 0, 0x10000, 0x10000);
909
910 Rect r;
911 Region::iterator iterator(mDirtyRegion);
912 while (iterator.iterate(&r)) {
913 GLfloat vertices[][2] = {
914 { r.left, r.top },
915 { r.left, r.bottom },
916 { r.right, r.bottom },
917 { r.right, r.top }
918 };
919 glVertexPointer(2, GL_FLOAT, 0, vertices);
920 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
921 }
922
923 const DisplayHardware& hw(graphicPlane(0).displayHardware());
924 hw.flip(mDirtyRegion.merge(mInvalidRegion));
925 mInvalidRegion.clear();
926
927 if (mDebugRegion > 1)
928 usleep(mDebugRegion * 1000);
929
930 glEnable(GL_SCISSOR_TEST);
931 //mDirtyRegion.dump("mDirtyRegion");
932}
933
934void SurfaceFlinger::drawWormhole() const
935{
936 const Region region(mWormholeRegion.intersect(mDirtyRegion));
937 if (region.isEmpty())
938 return;
939
940 const DisplayHardware& hw(graphicPlane(0).displayHardware());
941 const int32_t width = hw.getWidth();
942 const int32_t height = hw.getHeight();
943
944 glDisable(GL_BLEND);
945 glDisable(GL_DITHER);
946
947 if (LIKELY(!mDebugBackground)) {
948 glClearColorx(0,0,0,0);
949 Rect r;
950 Region::iterator iterator(region);
951 while (iterator.iterate(&r)) {
952 const GLint sy = height - (r.top + r.height());
953 glScissor(r.left, sy, r.width(), r.height());
954 glClear(GL_COLOR_BUFFER_BIT);
955 }
956 } else {
957 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
958 { width, height }, { 0, height } };
959 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
960 glVertexPointer(2, GL_SHORT, 0, vertices);
961 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
962 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
963 glEnable(GL_TEXTURE_2D);
964 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
965 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
966 glMatrixMode(GL_TEXTURE);
967 glLoadIdentity();
968 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
969 Rect r;
970 Region::iterator iterator(region);
971 while (iterator.iterate(&r)) {
972 const GLint sy = height - (r.top + r.height());
973 glScissor(r.left, sy, r.width(), r.height());
974 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
975 }
976 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
977 }
978}
979
980void SurfaceFlinger::debugShowFPS() const
981{
982 static int mFrameCount;
983 static int mLastFrameCount = 0;
984 static nsecs_t mLastFpsTime = 0;
985 static float mFps = 0;
986 mFrameCount++;
987 nsecs_t now = systemTime();
988 nsecs_t diff = now - mLastFpsTime;
989 if (diff > ms2ns(250)) {
990 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
991 mLastFpsTime = now;
992 mLastFrameCount = mFrameCount;
993 }
994 // XXX: mFPS has the value we want
995 }
996
Mathias Agopian1473f462009-04-10 14:24:30 -0700997status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998{
999 Mutex::Autolock _l(mStateLock);
1000 addLayer_l(layer);
1001 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1002 return NO_ERROR;
1003}
1004
Mathias Agopian1473f462009-04-10 14:24:30 -07001005status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006{
1007 Mutex::Autolock _l(mStateLock);
1008 removeLayer_l(layer);
1009 setTransactionFlags(eTransactionNeeded);
1010 return NO_ERROR;
1011}
1012
Mathias Agopian1473f462009-04-10 14:24:30 -07001013status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014{
1015 layer->forceVisibilityTransaction();
1016 setTransactionFlags(eTraversalNeeded);
1017 return NO_ERROR;
1018}
1019
Mathias Agopian1473f462009-04-10 14:24:30 -07001020status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021{
1022 ssize_t i = mCurrentState.layersSortedByZ.add(
1023 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian1473f462009-04-10 14:24:30 -07001024 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1025 if (lbc != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 mLayerMap.add(lbc->serverIndex(), lbc);
1027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 return NO_ERROR;
1029}
1030
Mathias Agopian1473f462009-04-10 14:24:30 -07001031status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032{
1033 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1034 if (index >= 0) {
Mathias Agopian1473f462009-04-10 14:24:30 -07001035 mLayersRemoved = true;
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001036 sp<LayerBaseClient> layer =
1037 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian1473f462009-04-10 14:24:30 -07001038 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 mLayerMap.removeItem(layer->serverIndex());
1040 }
1041 return NO_ERROR;
1042 }
1043 // it's possible that we don't find a layer, because it might
1044 // have been destroyed already -- this is not technically an error
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001045 // from the user because there is a race between BClient::destroySurface(),
1046 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1048}
1049
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001050status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1051{
1052 // First add the layer to the purgatory list, which makes sure it won't
1053 // go away, then remove it from the main list (through a transaction).
1054 ssize_t err = removeLayer_l(layerBase);
1055 if (err >= 0) {
1056 mLayerPurgatory.add(layerBase);
1057 }
1058 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1059}
1060
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062void SurfaceFlinger::free_resources_l()
1063{
1064 // Destroy layers that were removed
Mathias Agopian1473f462009-04-10 14:24:30 -07001065 mLayersRemoved = false;
1066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 // free resources associated with disconnected clients
1068 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1069 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1070 const size_t count = disconnectedClients.size();
1071 for (size_t i=0 ; i<count ; i++) {
1072 Client* client = disconnectedClients[i];
1073 // if this client is the scheduled broadcast list,
1074 // remove it from there (and we don't need to signal it
1075 // since it is dead).
1076 int32_t index = scheduledBroadcasts.indexOf(client);
1077 if (index >= 0) {
1078 scheduledBroadcasts.removeItemsAt(index);
1079 }
1080 mTokens.release(client->cid);
1081 delete client;
1082 }
1083 disconnectedClients.clear();
1084}
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1087{
1088 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1089}
1090
1091uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1092{
1093 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1094 if ((old & flags)==0) { // wake the server up
1095 if (delay > 0) {
1096 signalDelayedEvent(delay);
1097 } else {
1098 signalEvent();
1099 }
1100 }
1101 return old;
1102}
1103
1104void SurfaceFlinger::openGlobalTransaction()
1105{
1106 android_atomic_inc(&mTransactionCount);
1107}
1108
1109void SurfaceFlinger::closeGlobalTransaction()
1110{
1111 if (android_atomic_dec(&mTransactionCount) == 1) {
1112 signalEvent();
1113 }
1114}
1115
1116status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1117{
1118 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1119 return BAD_VALUE;
1120
1121 Mutex::Autolock _l(mStateLock);
1122 mCurrentState.freezeDisplay = 1;
1123 setTransactionFlags(eTransactionNeeded);
1124
1125 // flags is intended to communicate some sort of animation behavior
Mathias Agopianed81f222009-04-14 23:02:51 -07001126 // (for instance fading)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 return NO_ERROR;
1128}
1129
1130status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1131{
1132 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1133 return BAD_VALUE;
1134
1135 Mutex::Autolock _l(mStateLock);
1136 mCurrentState.freezeDisplay = 0;
1137 setTransactionFlags(eTransactionNeeded);
1138
1139 // flags is intended to communicate some sort of animation behavior
Mathias Agopianed81f222009-04-14 23:02:51 -07001140 // (for instance fading)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 return NO_ERROR;
1142}
1143
Mathias Agopianeb0c86e2009-03-27 18:11:38 -07001144int SurfaceFlinger::setOrientation(DisplayID dpy,
1145 int orientation, uint32_t flags)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146{
1147 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1148 return BAD_VALUE;
1149
1150 Mutex::Autolock _l(mStateLock);
1151 if (mCurrentState.orientation != orientation) {
1152 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianeb0c86e2009-03-27 18:11:38 -07001153 mCurrentState.orientationType = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 mCurrentState.orientation = orientation;
1155 setTransactionFlags(eTransactionNeeded);
1156 mTransactionCV.wait(mStateLock);
1157 } else {
1158 orientation = BAD_VALUE;
1159 }
1160 }
1161 return orientation;
1162}
1163
1164sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1165 ISurfaceFlingerClient::surface_data_t* params,
1166 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1167 uint32_t flags)
1168{
Mathias Agopian1473f462009-04-10 14:24:30 -07001169 sp<LayerBaseClient> layer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 sp<LayerBaseClient::Surface> surfaceHandle;
1171 Mutex::Autolock _l(mStateLock);
1172 Client* const c = mClientsMap.valueFor(clientId);
1173 if (UNLIKELY(!c)) {
1174 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1175 return surfaceHandle;
1176 }
1177
1178 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1179 int32_t id = c->generateId(pid);
1180 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1181 LOGE("createSurface() failed, generateId = %d", id);
1182 return surfaceHandle;
1183 }
1184
1185 switch (flags & eFXSurfaceMask) {
1186 case eFXSurfaceNormal:
1187 if (UNLIKELY(flags & ePushBuffers)) {
1188 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1189 } else {
1190 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1191 }
1192 break;
1193 case eFXSurfaceBlur:
1194 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1195 break;
1196 case eFXSurfaceDim:
1197 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1198 break;
1199 }
1200
Mathias Agopian1473f462009-04-10 14:24:30 -07001201 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 setTransactionFlags(eTransactionNeeded);
1203 surfaceHandle = layer->getSurface();
1204 if (surfaceHandle != 0)
1205 surfaceHandle->getSurfaceData(params);
1206 }
1207
1208 return surfaceHandle;
1209}
1210
Mathias Agopian1473f462009-04-10 14:24:30 -07001211sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 Client* client, DisplayID display,
1213 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1214{
1215 // initialize the surfaces
1216 switch (format) { // TODO: take h/w into account
1217 case PIXEL_FORMAT_TRANSPARENT:
1218 case PIXEL_FORMAT_TRANSLUCENT:
1219 format = PIXEL_FORMAT_RGBA_8888;
1220 break;
1221 case PIXEL_FORMAT_OPAQUE:
1222 format = PIXEL_FORMAT_RGB_565;
1223 break;
1224 }
1225
Mathias Agopian1473f462009-04-10 14:24:30 -07001226 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 status_t err = layer->setBuffers(client, w, h, format, flags);
1228 if (LIKELY(err == NO_ERROR)) {
1229 layer->initStates(w, h, flags);
1230 addLayer_l(layer);
1231 } else {
1232 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian1473f462009-04-10 14:24:30 -07001233 layer.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235 return layer;
1236}
1237
Mathias Agopian1473f462009-04-10 14:24:30 -07001238sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 Client* client, DisplayID display,
1240 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1241{
Mathias Agopian1473f462009-04-10 14:24:30 -07001242 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 layer->initStates(w, h, flags);
1244 addLayer_l(layer);
1245 return layer;
1246}
1247
Mathias Agopian1473f462009-04-10 14:24:30 -07001248sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 Client* client, DisplayID display,
1250 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1251{
Mathias Agopian1473f462009-04-10 14:24:30 -07001252 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 layer->initStates(w, h, flags);
1254 addLayer_l(layer);
1255 return layer;
1256}
1257
Mathias Agopian1473f462009-04-10 14:24:30 -07001258sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 Client* client, DisplayID display,
1260 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1261{
Mathias Agopian1473f462009-04-10 14:24:30 -07001262 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 layer->initStates(w, h, flags);
1264 addLayer_l(layer);
1265 return layer;
1266}
1267
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001268status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269{
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001270 /*
1271 * called by the window manager, when a surface should be marked for
1272 * destruction.
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001273 *
1274 * The surface is removed from the current and drawing lists, but placed
1275 * in the purgatory queue, so it's not destroyed right-away (we need
1276 * to wait for all client's references to go away first).
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001277 */
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001278
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001279 Mutex::Autolock _l(mStateLock);
1280 sp<LayerBaseClient> layer = getLayerUser_l(index);
1281 status_t err = purgatorizeLayer_l(layer);
1282 if (err == NO_ERROR) {
1283 setTransactionFlags(eTransactionNeeded);
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001284 }
1285 return err;
1286}
1287
1288status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1289{
1290 /*
1291 * called by ~ISurface() when all references are gone
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001292 *
1293 * the surface must be removed from purgatory from the main thread
1294 * since its dtor must run from there (b/c of OpenGL ES).
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001295 */
1296
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001297 class MessageDestroySurface : public MessageBase {
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001298 SurfaceFlinger* flinger;
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001299 sp<LayerBaseClient> layer;
1300 public:
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001301 MessageDestroySurface(
1302 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1303 : flinger(flinger), layer(layer) { }
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001304 virtual bool handler() {
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001305 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001306 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1307 LOGE_IF(idx<0, "layer=%p is not in the purgatory list", layer.get());
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001308 return true;
1309 }
1310 };
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001311 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 return NO_ERROR;
1313}
1314
1315status_t SurfaceFlinger::setClientState(
1316 ClientID cid,
1317 int32_t count,
1318 const layer_state_t* states)
1319{
1320 Mutex::Autolock _l(mStateLock);
1321 uint32_t flags = 0;
1322 cid <<= 16;
1323 for (int i=0 ; i<count ; i++) {
1324 const layer_state_t& s = states[i];
Mathias Agopian1473f462009-04-10 14:24:30 -07001325 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1326 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 const uint32_t what = s.what;
1328 // check if it has been destroyed first
1329 if (what & eDestroyed) {
1330 if (removeLayer_l(layer) == NO_ERROR) {
1331 flags |= eTransactionNeeded;
1332 // we skip everything else... well, no, not really
1333 // we skip ONLY that transaction.
1334 continue;
1335 }
1336 }
1337 if (what & ePositionChanged) {
1338 if (layer->setPosition(s.x, s.y))
1339 flags |= eTraversalNeeded;
1340 }
1341 if (what & eLayerChanged) {
1342 if (layer->setLayer(s.z)) {
1343 mCurrentState.layersSortedByZ.reorder(
1344 layer, &Layer::compareCurrentStateZ);
1345 // we need traversal (state changed)
1346 // AND transaction (list changed)
1347 flags |= eTransactionNeeded|eTraversalNeeded;
1348 }
1349 }
1350 if (what & eSizeChanged) {
1351 if (layer->setSize(s.w, s.h))
1352 flags |= eTraversalNeeded;
1353 }
1354 if (what & eAlphaChanged) {
1355 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1356 flags |= eTraversalNeeded;
1357 }
1358 if (what & eMatrixChanged) {
1359 if (layer->setMatrix(s.matrix))
1360 flags |= eTraversalNeeded;
1361 }
1362 if (what & eTransparentRegionChanged) {
1363 if (layer->setTransparentRegionHint(s.transparentRegion))
1364 flags |= eTraversalNeeded;
1365 }
1366 if (what & eVisibilityChanged) {
1367 if (layer->setFlags(s.flags, s.mask))
1368 flags |= eTraversalNeeded;
1369 }
1370 }
1371 }
1372 if (flags) {
1373 setTransactionFlags(flags);
1374 }
1375 return NO_ERROR;
1376}
1377
Mathias Agopian1473f462009-04-10 14:24:30 -07001378sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379{
Mathias Agopian1473f462009-04-10 14:24:30 -07001380 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1381 return layer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382}
1383
1384void SurfaceFlinger::screenReleased(int dpy)
1385{
1386 // this may be called by a signal handler, we can't do too much in here
1387 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1388 signalEvent();
1389}
1390
1391void SurfaceFlinger::screenAcquired(int dpy)
1392{
1393 // this may be called by a signal handler, we can't do too much in here
1394 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1395 signalEvent();
1396}
1397
1398status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1399{
1400 const size_t SIZE = 1024;
1401 char buffer[SIZE];
1402 String8 result;
1403 if (checkCallingPermission(
1404 String16("android.permission.DUMP")) == false)
1405 { // not allowed
1406 snprintf(buffer, SIZE, "Permission Denial: "
1407 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1408 IPCThreadState::self()->getCallingPid(),
1409 IPCThreadState::self()->getCallingUid());
1410 result.append(buffer);
1411 } else {
1412 Mutex::Autolock _l(mStateLock);
1413 size_t s = mClientsMap.size();
1414 char name[64];
1415 for (size_t i=0 ; i<s ; i++) {
1416 Client* client = mClientsMap.valueAt(i);
1417 sprintf(name, " Client (id=0x%08x)", client->cid);
1418 client->dump(name);
1419 }
1420 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1421 const size_t count = currentLayers.size();
1422 for (size_t i=0 ; i<count ; i++) {
1423 /*** LayerBase ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001424 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 const Layer::State& s = layer->drawingState();
1426 snprintf(buffer, SIZE,
1427 "+ %s %p\n"
1428 " "
1429 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1430 "needsBlending=%1d, invalidate=%1d, "
1431 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian1473f462009-04-10 14:24:30 -07001432 layer->getTypeID(), layer.get(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 s.z, layer->tx(), layer->ty(), s.w, s.h,
1434 layer->needsBlending(), layer->contentDirty,
1435 s.alpha, s.flags,
1436 s.transform[0], s.transform[1],
1437 s.transform[2], s.transform[3]);
1438 result.append(buffer);
1439 buffer[0] = 0;
1440 /*** LayerBaseClient ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001441 sp<LayerBaseClient> lbc =
1442 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1443 if (lbc != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 snprintf(buffer, SIZE,
1445 " "
1446 "id=0x%08x, client=0x%08x, identity=%u\n",
1447 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1448 lbc->getIdentity());
1449 }
1450 result.append(buffer);
1451 buffer[0] = 0;
1452 /*** Layer ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001453 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1454 if (l != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 const LayerBitmap& buf0(l->getBuffer(0));
1456 const LayerBitmap& buf1(l->getBuffer(1));
1457 snprintf(buffer, SIZE,
1458 " "
Mathias Agopian1473f462009-04-10 14:24:30 -07001459 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 " freezeLock=%p, swapState=0x%08x\n",
1461 l->pixelFormat(),
Mathias Agopian1473f462009-04-10 14:24:30 -07001462 buf0.getWidth(), buf0.getHeight(),
1463 buf0.getBuffer()->getStride(),
1464 buf1.getWidth(), buf1.getHeight(),
1465 buf1.getBuffer()->getStride(),
1466 l->getFreezeLock().get(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 l->lcblk->swapState);
1468 }
1469 result.append(buffer);
1470 buffer[0] = 0;
1471 s.transparentRegion.dump(result, "transparentRegion");
1472 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1473 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1474 }
1475 mWormholeRegion.dump(result, "WormholeRegion");
1476 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1477 snprintf(buffer, SIZE,
1478 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1479 mFreezeDisplay?"yes":"no", mFreezeCount,
1480 mCurrentState.orientation, hw.canDraw());
1481 result.append(buffer);
1482
Mathias Agopian1473f462009-04-10 14:24:30 -07001483 const BufferAllocator& alloc(BufferAllocator::get());
1484 alloc.dump(result);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
1486 write(fd, result.string(), result.size());
1487 return NO_ERROR;
1488}
1489
1490status_t SurfaceFlinger::onTransact(
1491 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1492{
1493 switch (code) {
1494 case CREATE_CONNECTION:
1495 case OPEN_GLOBAL_TRANSACTION:
1496 case CLOSE_GLOBAL_TRANSACTION:
1497 case SET_ORIENTATION:
1498 case FREEZE_DISPLAY:
1499 case UNFREEZE_DISPLAY:
1500 case BOOT_FINISHED:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 {
1502 // codes that require permission check
1503 IPCThreadState* ipc = IPCThreadState::self();
1504 const int pid = ipc->getCallingPid();
1505 const int self_pid = getpid();
1506 if (UNLIKELY(pid != self_pid)) {
1507 // we're called from a different process, do the real check
1508 if (!checkCallingPermission(
1509 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1510 {
1511 const int uid = ipc->getCallingUid();
1512 LOGE("Permission Denial: "
1513 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1514 return PERMISSION_DENIED;
1515 }
1516 }
1517 }
1518 }
1519
1520 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1521 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1522 // HARDWARE_TEST stuff...
1523 if (UNLIKELY(checkCallingPermission(
1524 String16("android.permission.HARDWARE_TEST")) == false))
1525 { // not allowed
1526 LOGE("Permission Denial: pid=%d, uid=%d\n",
1527 IPCThreadState::self()->getCallingPid(),
1528 IPCThreadState::self()->getCallingUid());
1529 return PERMISSION_DENIED;
1530 }
1531 int n;
1532 switch (code) {
Mathias Agopian17f638b2009-04-16 20:04:08 -07001533 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 return NO_ERROR;
Mathias Agopianef07dda2009-04-21 18:28:33 -07001535 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 return NO_ERROR;
1537 case 1002: // SHOW_UPDATES
1538 n = data.readInt32();
1539 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1540 return NO_ERROR;
1541 case 1003: // SHOW_BACKGROUND
1542 n = data.readInt32();
1543 mDebugBackground = n ? 1 : 0;
1544 return NO_ERROR;
1545 case 1004:{ // repaint everything
1546 Mutex::Autolock _l(mStateLock);
1547 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1548 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1549 signalEvent();
1550 }
1551 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 case 1007: // set mFreezeCount
1553 mFreezeCount = data.readInt32();
1554 return NO_ERROR;
1555 case 1010: // interrogate.
Mathias Agopian17f638b2009-04-16 20:04:08 -07001556 reply->writeInt32(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 reply->writeInt32(0);
1558 reply->writeInt32(mDebugRegion);
1559 reply->writeInt32(mDebugBackground);
1560 return NO_ERROR;
1561 case 1013: {
1562 Mutex::Autolock _l(mStateLock);
1563 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1564 reply->writeInt32(hw.getPageFlipCount());
1565 }
1566 return NO_ERROR;
1567 }
1568 }
1569 return err;
1570}
1571
1572// ---------------------------------------------------------------------------
1573#if 0
1574#pragma mark -
1575#endif
1576
1577Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1578 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1579{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 const int pgsize = getpagesize();
1581 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1582 mCblkHeap = new MemoryDealer(cblksize);
1583 mCblkMemory = mCblkHeap->allocate(cblksize);
1584 if (mCblkMemory != 0) {
1585 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1586 if (ctrlblk) { // construct the shared structure in-place.
1587 new(ctrlblk) per_client_cblk_t;
1588 }
1589 }
1590}
1591
1592Client::~Client() {
1593 if (ctrlblk) {
1594 const int pgsize = getpagesize();
1595 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1596 }
1597}
1598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599int32_t Client::generateId(int pid)
1600{
1601 const uint32_t i = clz( ~mBitmap );
1602 if (i >= NUM_LAYERS_MAX) {
1603 return NO_MEMORY;
1604 }
1605 mPid = pid;
1606 mInUse.add(uint8_t(i));
1607 mBitmap |= 1<<(31-i);
1608 return i;
1609}
Mathias Agopian1473f462009-04-10 14:24:30 -07001610
1611status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612{
1613 ssize_t idx = mInUse.indexOf(id);
1614 if (idx < 0)
1615 return NAME_NOT_FOUND;
1616 return mLayers.insertAt(layer, idx);
1617}
Mathias Agopian1473f462009-04-10 14:24:30 -07001618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619void Client::free(int32_t id)
1620{
1621 ssize_t idx = mInUse.remove(uint8_t(id));
1622 if (idx >= 0) {
1623 mBitmap &= ~(1<<(31-id));
1624 mLayers.removeItemsAt(idx);
1625 }
1626}
1627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628bool Client::isValid(int32_t i) const {
1629 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1630}
Mathias Agopian1473f462009-04-10 14:24:30 -07001631
1632sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1633 sp<LayerBaseClient> lbc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian1473f462009-04-10 14:24:30 -07001635 if (idx >= 0) {
1636 lbc = mLayers[idx].promote();
1637 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1638 }
1639 return lbc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640}
1641
1642void Client::dump(const char* what)
1643{
1644}
1645
1646// ---------------------------------------------------------------------------
1647#if 0
1648#pragma mark -
1649#endif
1650
1651BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1652 : mId(cid), mFlinger(flinger), mCblk(cblk)
1653{
1654}
1655
1656BClient::~BClient() {
1657 // destroy all resources attached to this client
1658 mFlinger->destroyConnection(mId);
1659}
1660
1661void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1662 *ctrl = mCblk;
1663}
1664
1665sp<ISurface> BClient::createSurface(
1666 ISurfaceFlingerClient::surface_data_t* params, int pid,
1667 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1668 uint32_t flags)
1669{
1670 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1671}
1672
1673status_t BClient::destroySurface(SurfaceID sid)
1674{
1675 sid |= (mId << 16); // add the client-part to id
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001676 return mFlinger->removeSurface(sid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677}
1678
1679status_t BClient::setState(int32_t count, const layer_state_t* states)
1680{
1681 return mFlinger->setClientState(mId, count, states);
1682}
1683
1684// ---------------------------------------------------------------------------
1685
1686GraphicPlane::GraphicPlane()
1687 : mHw(0)
1688{
1689}
1690
1691GraphicPlane::~GraphicPlane() {
1692 delete mHw;
1693}
1694
1695bool GraphicPlane::initialized() const {
1696 return mHw ? true : false;
1697}
1698
1699void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1700 mHw = hw;
1701}
1702
1703void GraphicPlane::setTransform(const Transform& tr) {
1704 mTransform = tr;
1705 mGlobalTransform = mOrientationTransform * mTransform;
1706}
1707
1708status_t GraphicPlane::orientationToTransfrom(
1709 int orientation, int w, int h, Transform* tr)
1710{
1711 float a, b, c, d, x, y;
1712 switch (orientation) {
1713 case ISurfaceComposer::eOrientationDefault:
1714 a=1; b=0; c=0; d=1; x=0; y=0;
1715 break;
1716 case ISurfaceComposer::eOrientation90:
1717 a=0; b=-1; c=1; d=0; x=w; y=0;
1718 break;
1719 case ISurfaceComposer::eOrientation180:
1720 a=-1; b=0; c=0; d=-1; x=w; y=h;
1721 break;
1722 case ISurfaceComposer::eOrientation270:
1723 a=0; b=1; c=-1; d=0; x=0; y=h;
1724 break;
1725 default:
1726 return BAD_VALUE;
1727 }
1728 tr->set(a, b, c, d);
1729 tr->set(x, y);
1730 return NO_ERROR;
1731}
1732
1733status_t GraphicPlane::setOrientation(int orientation)
1734{
1735 const DisplayHardware& hw(displayHardware());
1736 const float w = hw.getWidth();
1737 const float h = hw.getHeight();
1738
1739 if (orientation == ISurfaceComposer::eOrientationDefault) {
1740 // make sure the default orientation is optimal
1741 mOrientationTransform.reset();
Mathias Agopian3552f532009-03-27 17:58:20 -07001742 mOrientation = orientation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 mGlobalTransform = mTransform;
1744 return NO_ERROR;
1745 }
1746
1747 // If the rotation can be handled in hardware, this is where
1748 // the magic should happen.
1749 if (UNLIKELY(orientation == 42)) {
1750 float a, b, c, d, x, y;
1751 const float r = (3.14159265f / 180.0f) * 42.0f;
1752 const float si = sinf(r);
1753 const float co = cosf(r);
1754 a=co; b=-si; c=si; d=co;
1755 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1756 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1757 mOrientationTransform.set(a, b, c, d);
1758 mOrientationTransform.set(x, y);
1759 } else {
1760 GraphicPlane::orientationToTransfrom(orientation, w, h,
1761 &mOrientationTransform);
1762 }
Mathias Agopian3552f532009-03-27 17:58:20 -07001763 mOrientation = orientation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 mGlobalTransform = mOrientationTransform * mTransform;
1765 return NO_ERROR;
1766}
1767
1768const DisplayHardware& GraphicPlane::displayHardware() const {
1769 return *mHw;
1770}
1771
1772const Transform& GraphicPlane::transform() const {
1773 return mGlobalTransform;
1774}
1775
Mathias Agopian1473f462009-04-10 14:24:30 -07001776EGLDisplay GraphicPlane::getEGLDisplay() const {
1777 return mHw->getEGLDisplay();
1778}
1779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780// ---------------------------------------------------------------------------
1781
1782}; // namespace android