blob: fdfaad3dedf5480b9ac53365b8cb3a8b11e26335 [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();
527
528 if (Layer::deletedTextures.size()) {
529 glDeleteTextures(
530 Layer::deletedTextures.size(),
531 Layer::deletedTextures.array());
532 Layer::deletedTextures.clear();
533 }
534 }
535}
536
537void SurfaceFlinger::handleConsoleEvents()
538{
539 // something to do with the console
540 const DisplayHardware& hw = graphicPlane(0).displayHardware();
541
542 int what = android_atomic_and(0, &mConsoleSignals);
543 if (what & eConsoleAcquired) {
544 hw.acquireScreen();
545 }
546
547 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopianed81f222009-04-14 23:02:51 -0700548 // We got the release signal before the acquire signal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 mDeferReleaseConsole = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 hw.releaseScreen();
551 }
552
553 if (what & eConsoleReleased) {
554 if (hw.canDraw()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 hw.releaseScreen();
556 } else {
557 mDeferReleaseConsole = true;
558 }
559 }
560
561 mDirtyRegion.set(hw.bounds());
562}
563
564void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
565{
566 Mutex::Autolock _l(mStateLock);
567
568 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
569 const size_t count = currentLayers.size();
570
571 /*
572 * Traversal of the children
573 * (perform the transaction for each of them if needed)
574 */
575
576 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
577 if (layersNeedTransaction) {
578 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700579 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
581 if (!trFlags) continue;
582
583 const uint32_t flags = layer->doTransaction(0);
584 if (flags & Layer::eVisibleRegion)
585 mVisibleRegionsDirty = true;
586
587 if (flags & Layer::eRestartTransaction) {
588 // restart the transaction, but back-off a little
589 layer->setTransactionFlags(eTransactionNeeded);
590 setTransactionFlags(eTraversalNeeded, ms2ns(8));
591 }
592 }
593 }
594
595 /*
596 * Perform our own transaction if needed
597 */
598
599 if (transactionFlags & eTransactionNeeded) {
600 if (mCurrentState.orientation != mDrawingState.orientation) {
601 // the orientation has changed, recompute all visible regions
602 // and invalidate everything.
603
604 const int dpy = 0;
605 const int orientation = mCurrentState.orientation;
Mathias Agopianeb0c86e2009-03-27 18:11:38 -0700606 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 GraphicPlane& plane(graphicPlane(dpy));
608 plane.setOrientation(orientation);
609
610 // update the shared control block
611 const DisplayHardware& hw(plane.displayHardware());
612 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
613 dcblk->orientation = orientation;
614 if (orientation & eOrientationSwapMask) {
615 // 90 or 270 degrees orientation
616 dcblk->w = hw.getHeight();
617 dcblk->h = hw.getWidth();
618 } else {
619 dcblk->w = hw.getWidth();
620 dcblk->h = hw.getHeight();
621 }
622
623 mVisibleRegionsDirty = true;
624 mDirtyRegion.set(hw.bounds());
Mathias Agopianeb0c86e2009-03-27 18:11:38 -0700625 mFreezeDisplayTime = 0;
626 mOrientationAnimation->onOrientationChanged(type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 }
628
629 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
630 // freezing or unfreezing the display -> trigger animation if needed
631 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
Mathias Agopiana3aa6c92009-04-22 15:23:34 -0700634 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
635 // layers have been added
636 mVisibleRegionsDirty = true;
637 }
638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 // some layers might have been removed, so
640 // we need to update the regions they're exposing.
Mathias Agopian1473f462009-04-10 14:24:30 -0700641 if (mLayersRemoved) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 mVisibleRegionsDirty = true;
Mathias Agopiana3aa6c92009-04-22 15:23:34 -0700643 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
644 const ssize_t count = previousLayers.size();
645 for (ssize_t i=0 ; i<count ; i++) {
646 const sp<LayerBase>& layer(previousLayers[i]);
647 if (currentLayers.indexOf( layer ) < 0) {
648 // this layer is not visible anymore
649 // FIXME: would be better to call without the lock held
650 //LOGD("ditching layer %p", layer.get());
651 layer->ditch();
652 }
653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655
656 // get rid of all resources we don't need anymore
657 // (layers and clients)
658 free_resources_l();
659 }
660
661 commitTransaction();
662}
663
664sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
665{
666 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
667}
668
669void SurfaceFlinger::computeVisibleRegions(
670 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
671{
672 const GraphicPlane& plane(graphicPlane(0));
673 const Transform& planeTransform(plane.transform());
674
675 Region aboveOpaqueLayers;
676 Region aboveCoveredLayers;
677 Region dirty;
678
679 bool secureFrameBuffer = false;
680
681 size_t i = currentLayers.size();
682 while (i--) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700683 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 layer->validateVisibility(planeTransform);
685
686 // start with the whole surface at its current location
687 const Layer::State& s = layer->drawingState();
688 const Rect bounds(layer->visibleBounds());
689
690 // handle hidden surfaces by setting the visible region to empty
691 Region opaqueRegion;
692 Region visibleRegion;
693 Region coveredRegion;
694 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
695 visibleRegion.clear();
696 } else {
697 const bool translucent = layer->needsBlending();
698 visibleRegion.set(bounds);
699 coveredRegion = visibleRegion;
700
701 // Remove the transparent area from the visible region
702 if (translucent) {
703 visibleRegion.subtractSelf(layer->transparentRegionScreen);
704 }
705
706 // compute the opaque region
707 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
708 // the opaque region is the visible region
709 opaqueRegion = visibleRegion;
710 }
711 }
712
713 // subtract the opaque region covered by the layers above us
714 visibleRegion.subtractSelf(aboveOpaqueLayers);
715 coveredRegion.andSelf(aboveCoveredLayers);
716
717 // compute this layer's dirty region
718 if (layer->contentDirty) {
719 // we need to invalidate the whole region
720 dirty = visibleRegion;
721 // as well, as the old visible region
722 dirty.orSelf(layer->visibleRegionScreen);
723 layer->contentDirty = false;
724 } else {
725 // compute the exposed region
726 // dirty = what's visible now - what's wasn't covered before
727 // = what's visible now & what's was covered before
728 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
729 }
730 dirty.subtractSelf(aboveOpaqueLayers);
731
732 // accumulate to the screen dirty region
733 dirtyRegion.orSelf(dirty);
734
Mathias Agopianed81f222009-04-14 23:02:51 -0700735 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 aboveOpaqueLayers.orSelf(opaqueRegion);
737 aboveCoveredLayers.orSelf(bounds);
738
739 // Store the visible region is screen space
740 layer->setVisibleRegion(visibleRegion);
741 layer->setCoveredRegion(coveredRegion);
742
Mathias Agopianed81f222009-04-14 23:02:51 -0700743 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 if (layer->isSecure() && !visibleRegion.isEmpty()) {
745 secureFrameBuffer = true;
746 }
747 }
748
749 mSecureFrameBuffer = secureFrameBuffer;
750 opaqueRegion = aboveOpaqueLayers;
751}
752
753
754void SurfaceFlinger::commitTransaction()
755{
756 mDrawingState = mCurrentState;
757 mTransactionCV.signal();
758}
759
760void SurfaceFlinger::handlePageFlip()
761{
762 bool visibleRegions = mVisibleRegionsDirty;
763 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
764 visibleRegions |= lockPageFlip(currentLayers);
765
766 const DisplayHardware& hw = graphicPlane(0).displayHardware();
767 const Region screenRegion(hw.bounds());
768 if (visibleRegions) {
769 Region opaqueRegion;
770 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
771 mWormholeRegion = screenRegion.subtract(opaqueRegion);
772 mVisibleRegionsDirty = false;
773 }
774
775 unlockPageFlip(currentLayers);
776 mDirtyRegion.andSelf(screenRegion);
777}
778
779bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
780{
781 bool recomputeVisibleRegions = false;
782 size_t count = currentLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700783 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700785 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 layer->lockPageFlip(recomputeVisibleRegions);
787 }
788 return recomputeVisibleRegions;
789}
790
791void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
792{
793 const GraphicPlane& plane(graphicPlane(0));
794 const Transform& planeTransform(plane.transform());
795 size_t count = currentLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700796 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700798 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 layer->unlockPageFlip(planeTransform, mDirtyRegion);
800 }
801}
802
803void SurfaceFlinger::handleRepaint()
804{
805 // set the frame buffer
806 const DisplayHardware& hw(graphicPlane(0).displayHardware());
807 glMatrixMode(GL_MODELVIEW);
808 glLoadIdentity();
809
810 if (UNLIKELY(mDebugRegion)) {
811 debugFlashRegions();
812 }
813
814 // compute the invalid region
815 mInvalidRegion.orSelf(mDirtyRegion);
816
817 uint32_t flags = hw.getFlags();
818 if (flags & DisplayHardware::BUFFER_PRESERVED) {
819 // here we assume DisplayHardware::flip()'s implementation
820 // performs the copy-back optimization.
821 } else {
822 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
823 // we need to fully redraw the part that will be updated
824 mDirtyRegion.set(mInvalidRegion.bounds());
825 } else {
826 // we need to redraw everything
827 mDirtyRegion.set(hw.bounds());
828 mInvalidRegion = mDirtyRegion;
829 }
830 }
831
832 // compose all surfaces
833 composeSurfaces(mDirtyRegion);
834
835 // clear the dirty regions
836 mDirtyRegion.clear();
837}
838
839void SurfaceFlinger::composeSurfaces(const Region& dirty)
840{
841 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
842 // should never happen unless the window manager has a bug
843 // draw something...
844 drawWormhole();
845 }
846 const SurfaceFlinger& flinger(*this);
847 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
848 const size_t count = drawingLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700849 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700851 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 const Region& visibleRegion(layer->visibleRegionScreen);
853 if (!visibleRegion.isEmpty()) {
854 const Region clip(dirty.intersect(visibleRegion));
855 if (!clip.isEmpty()) {
856 layer->draw(clip);
857 }
858 }
859 }
860}
861
862void SurfaceFlinger::unlockClients()
863{
864 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
865 const size_t count = drawingLayers.size();
Mathias Agopian1473f462009-04-10 14:24:30 -0700866 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian1473f462009-04-10 14:24:30 -0700868 const sp<LayerBase>& layer = layers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 layer->finishPageFlip();
870 }
871}
872
873void SurfaceFlinger::scheduleBroadcast(Client* client)
874{
875 if (mLastScheduledBroadcast != client) {
876 mLastScheduledBroadcast = client;
877 mScheduledBroadcasts.add(client);
878 }
879}
880
881void SurfaceFlinger::executeScheduledBroadcasts()
882{
883 SortedVector<Client*>& list = mScheduledBroadcasts;
884 size_t count = list.size();
885 while (count--) {
886 per_client_cblk_t* const cblk = list[count]->ctrlblk;
887 if (cblk->lock.tryLock() == NO_ERROR) {
888 cblk->cv.broadcast();
889 list.removeAt(count);
890 cblk->lock.unlock();
891 } else {
892 // schedule another round
893 LOGW("executeScheduledBroadcasts() skipped, "
894 "contention on the client. We'll try again later...");
895 signalDelayedEvent(ms2ns(4));
896 }
897 }
898 mLastScheduledBroadcast = 0;
899}
900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901void SurfaceFlinger::debugFlashRegions()
902{
903 if (UNLIKELY(!mDirtyRegion.isRect())) {
904 // TODO: do this only if we don't have preserving
905 // swapBuffer. If we don't have update-on-demand,
906 // redraw everything.
907 composeSurfaces(Region(mDirtyRegion.bounds()));
908 }
909
910 glDisable(GL_TEXTURE_2D);
911 glDisable(GL_BLEND);
912 glDisable(GL_DITHER);
913 glDisable(GL_SCISSOR_TEST);
914
915 glColor4x(0x10000, 0, 0x10000, 0x10000);
916
917 Rect r;
918 Region::iterator iterator(mDirtyRegion);
919 while (iterator.iterate(&r)) {
920 GLfloat vertices[][2] = {
921 { r.left, r.top },
922 { r.left, r.bottom },
923 { r.right, r.bottom },
924 { r.right, r.top }
925 };
926 glVertexPointer(2, GL_FLOAT, 0, vertices);
927 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
928 }
929
930 const DisplayHardware& hw(graphicPlane(0).displayHardware());
931 hw.flip(mDirtyRegion.merge(mInvalidRegion));
932 mInvalidRegion.clear();
933
934 if (mDebugRegion > 1)
935 usleep(mDebugRegion * 1000);
936
937 glEnable(GL_SCISSOR_TEST);
938 //mDirtyRegion.dump("mDirtyRegion");
939}
940
941void SurfaceFlinger::drawWormhole() const
942{
943 const Region region(mWormholeRegion.intersect(mDirtyRegion));
944 if (region.isEmpty())
945 return;
946
947 const DisplayHardware& hw(graphicPlane(0).displayHardware());
948 const int32_t width = hw.getWidth();
949 const int32_t height = hw.getHeight();
950
951 glDisable(GL_BLEND);
952 glDisable(GL_DITHER);
953
954 if (LIKELY(!mDebugBackground)) {
955 glClearColorx(0,0,0,0);
956 Rect r;
957 Region::iterator iterator(region);
958 while (iterator.iterate(&r)) {
959 const GLint sy = height - (r.top + r.height());
960 glScissor(r.left, sy, r.width(), r.height());
961 glClear(GL_COLOR_BUFFER_BIT);
962 }
963 } else {
964 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
965 { width, height }, { 0, height } };
966 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
967 glVertexPointer(2, GL_SHORT, 0, vertices);
968 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
969 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
970 glEnable(GL_TEXTURE_2D);
971 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
972 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
973 glMatrixMode(GL_TEXTURE);
974 glLoadIdentity();
975 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
976 Rect r;
977 Region::iterator iterator(region);
978 while (iterator.iterate(&r)) {
979 const GLint sy = height - (r.top + r.height());
980 glScissor(r.left, sy, r.width(), r.height());
981 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
982 }
983 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
984 }
985}
986
987void SurfaceFlinger::debugShowFPS() const
988{
989 static int mFrameCount;
990 static int mLastFrameCount = 0;
991 static nsecs_t mLastFpsTime = 0;
992 static float mFps = 0;
993 mFrameCount++;
994 nsecs_t now = systemTime();
995 nsecs_t diff = now - mLastFpsTime;
996 if (diff > ms2ns(250)) {
997 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
998 mLastFpsTime = now;
999 mLastFrameCount = mFrameCount;
1000 }
1001 // XXX: mFPS has the value we want
1002 }
1003
Mathias Agopian1473f462009-04-10 14:24:30 -07001004status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005{
1006 Mutex::Autolock _l(mStateLock);
1007 addLayer_l(layer);
1008 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1009 return NO_ERROR;
1010}
1011
Mathias Agopian1473f462009-04-10 14:24:30 -07001012status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013{
1014 Mutex::Autolock _l(mStateLock);
1015 removeLayer_l(layer);
1016 setTransactionFlags(eTransactionNeeded);
1017 return NO_ERROR;
1018}
1019
Mathias Agopian1473f462009-04-10 14:24:30 -07001020status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021{
1022 layer->forceVisibilityTransaction();
1023 setTransactionFlags(eTraversalNeeded);
1024 return NO_ERROR;
1025}
1026
Mathias Agopian1473f462009-04-10 14:24:30 -07001027status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028{
1029 ssize_t i = mCurrentState.layersSortedByZ.add(
1030 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian1473f462009-04-10 14:24:30 -07001031 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1032 if (lbc != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 mLayerMap.add(lbc->serverIndex(), lbc);
1034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 return NO_ERROR;
1036}
1037
Mathias Agopian1473f462009-04-10 14:24:30 -07001038status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039{
1040 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1041 if (index >= 0) {
Mathias Agopian1473f462009-04-10 14:24:30 -07001042 mLayersRemoved = true;
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001043 sp<LayerBaseClient> layer =
1044 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian1473f462009-04-10 14:24:30 -07001045 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 mLayerMap.removeItem(layer->serverIndex());
1047 }
1048 return NO_ERROR;
1049 }
1050 // it's possible that we don't find a layer, because it might
1051 // have been destroyed already -- this is not technically an error
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001052 // from the user because there is a race between BClient::destroySurface(),
1053 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1055}
1056
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001057status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1058{
1059 // First add the layer to the purgatory list, which makes sure it won't
1060 // go away, then remove it from the main list (through a transaction).
1061 ssize_t err = removeLayer_l(layerBase);
1062 if (err >= 0) {
1063 mLayerPurgatory.add(layerBase);
1064 }
1065 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1066}
1067
1068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069void SurfaceFlinger::free_resources_l()
1070{
1071 // Destroy layers that were removed
Mathias Agopian1473f462009-04-10 14:24:30 -07001072 mLayersRemoved = false;
1073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 // free resources associated with disconnected clients
1075 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1076 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1077 const size_t count = disconnectedClients.size();
1078 for (size_t i=0 ; i<count ; i++) {
1079 Client* client = disconnectedClients[i];
1080 // if this client is the scheduled broadcast list,
1081 // remove it from there (and we don't need to signal it
1082 // since it is dead).
1083 int32_t index = scheduledBroadcasts.indexOf(client);
1084 if (index >= 0) {
1085 scheduledBroadcasts.removeItemsAt(index);
1086 }
1087 mTokens.release(client->cid);
1088 delete client;
1089 }
1090 disconnectedClients.clear();
1091}
1092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1094{
1095 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1096}
1097
1098uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1099{
1100 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1101 if ((old & flags)==0) { // wake the server up
1102 if (delay > 0) {
1103 signalDelayedEvent(delay);
1104 } else {
1105 signalEvent();
1106 }
1107 }
1108 return old;
1109}
1110
1111void SurfaceFlinger::openGlobalTransaction()
1112{
1113 android_atomic_inc(&mTransactionCount);
1114}
1115
1116void SurfaceFlinger::closeGlobalTransaction()
1117{
1118 if (android_atomic_dec(&mTransactionCount) == 1) {
1119 signalEvent();
1120 }
1121}
1122
1123status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1124{
1125 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1126 return BAD_VALUE;
1127
1128 Mutex::Autolock _l(mStateLock);
1129 mCurrentState.freezeDisplay = 1;
1130 setTransactionFlags(eTransactionNeeded);
1131
1132 // flags is intended to communicate some sort of animation behavior
Mathias Agopianed81f222009-04-14 23:02:51 -07001133 // (for instance fading)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 return NO_ERROR;
1135}
1136
1137status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1138{
1139 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1140 return BAD_VALUE;
1141
1142 Mutex::Autolock _l(mStateLock);
1143 mCurrentState.freezeDisplay = 0;
1144 setTransactionFlags(eTransactionNeeded);
1145
1146 // flags is intended to communicate some sort of animation behavior
Mathias Agopianed81f222009-04-14 23:02:51 -07001147 // (for instance fading)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 return NO_ERROR;
1149}
1150
Mathias Agopianeb0c86e2009-03-27 18:11:38 -07001151int SurfaceFlinger::setOrientation(DisplayID dpy,
1152 int orientation, uint32_t flags)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153{
1154 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1155 return BAD_VALUE;
1156
1157 Mutex::Autolock _l(mStateLock);
1158 if (mCurrentState.orientation != orientation) {
1159 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianeb0c86e2009-03-27 18:11:38 -07001160 mCurrentState.orientationType = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 mCurrentState.orientation = orientation;
1162 setTransactionFlags(eTransactionNeeded);
1163 mTransactionCV.wait(mStateLock);
1164 } else {
1165 orientation = BAD_VALUE;
1166 }
1167 }
1168 return orientation;
1169}
1170
1171sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1172 ISurfaceFlingerClient::surface_data_t* params,
1173 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1174 uint32_t flags)
1175{
Mathias Agopian1473f462009-04-10 14:24:30 -07001176 sp<LayerBaseClient> layer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 sp<LayerBaseClient::Surface> surfaceHandle;
1178 Mutex::Autolock _l(mStateLock);
1179 Client* const c = mClientsMap.valueFor(clientId);
1180 if (UNLIKELY(!c)) {
1181 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1182 return surfaceHandle;
1183 }
1184
1185 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1186 int32_t id = c->generateId(pid);
1187 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1188 LOGE("createSurface() failed, generateId = %d", id);
1189 return surfaceHandle;
1190 }
1191
1192 switch (flags & eFXSurfaceMask) {
1193 case eFXSurfaceNormal:
1194 if (UNLIKELY(flags & ePushBuffers)) {
1195 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1196 } else {
1197 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1198 }
1199 break;
1200 case eFXSurfaceBlur:
1201 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1202 break;
1203 case eFXSurfaceDim:
1204 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1205 break;
1206 }
1207
Mathias Agopian1473f462009-04-10 14:24:30 -07001208 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 setTransactionFlags(eTransactionNeeded);
1210 surfaceHandle = layer->getSurface();
1211 if (surfaceHandle != 0)
1212 surfaceHandle->getSurfaceData(params);
1213 }
1214
1215 return surfaceHandle;
1216}
1217
Mathias Agopian1473f462009-04-10 14:24:30 -07001218sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 Client* client, DisplayID display,
1220 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1221{
1222 // initialize the surfaces
1223 switch (format) { // TODO: take h/w into account
1224 case PIXEL_FORMAT_TRANSPARENT:
1225 case PIXEL_FORMAT_TRANSLUCENT:
1226 format = PIXEL_FORMAT_RGBA_8888;
1227 break;
1228 case PIXEL_FORMAT_OPAQUE:
1229 format = PIXEL_FORMAT_RGB_565;
1230 break;
1231 }
1232
Mathias Agopian1473f462009-04-10 14:24:30 -07001233 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 status_t err = layer->setBuffers(client, w, h, format, flags);
1235 if (LIKELY(err == NO_ERROR)) {
1236 layer->initStates(w, h, flags);
1237 addLayer_l(layer);
1238 } else {
1239 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian1473f462009-04-10 14:24:30 -07001240 layer.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
1242 return layer;
1243}
1244
Mathias Agopian1473f462009-04-10 14:24:30 -07001245sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 Client* client, DisplayID display,
1247 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1248{
Mathias Agopian1473f462009-04-10 14:24:30 -07001249 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 layer->initStates(w, h, flags);
1251 addLayer_l(layer);
1252 return layer;
1253}
1254
Mathias Agopian1473f462009-04-10 14:24:30 -07001255sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 Client* client, DisplayID display,
1257 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1258{
Mathias Agopian1473f462009-04-10 14:24:30 -07001259 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 layer->initStates(w, h, flags);
1261 addLayer_l(layer);
1262 return layer;
1263}
1264
Mathias Agopian1473f462009-04-10 14:24:30 -07001265sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 Client* client, DisplayID display,
1267 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1268{
Mathias Agopian1473f462009-04-10 14:24:30 -07001269 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 layer->initStates(w, h, flags);
1271 addLayer_l(layer);
1272 return layer;
1273}
1274
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001275status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276{
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001277 /*
1278 * called by the window manager, when a surface should be marked for
1279 * destruction.
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001280 *
1281 * The surface is removed from the current and drawing lists, but placed
1282 * in the purgatory queue, so it's not destroyed right-away (we need
1283 * to wait for all client's references to go away first).
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001284 */
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001285
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001286 Mutex::Autolock _l(mStateLock);
1287 sp<LayerBaseClient> layer = getLayerUser_l(index);
1288 status_t err = purgatorizeLayer_l(layer);
1289 if (err == NO_ERROR) {
1290 setTransactionFlags(eTransactionNeeded);
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001291 }
1292 return err;
1293}
1294
1295status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1296{
1297 /*
1298 * called by ~ISurface() when all references are gone
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001299 *
1300 * the surface must be removed from purgatory from the main thread
1301 * since its dtor must run from there (b/c of OpenGL ES).
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001302 */
1303
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001304 class MessageDestroySurface : public MessageBase {
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001305 SurfaceFlinger* flinger;
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001306 sp<LayerBaseClient> layer;
1307 public:
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001308 MessageDestroySurface(
1309 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1310 : flinger(flinger), layer(layer) { }
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001311 virtual bool handler() {
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001312 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopiana3aa6c92009-04-22 15:23:34 -07001313 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1314 LOGE_IF(idx<0, "layer=%p is not in the purgatory list", layer.get());
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001315 return true;
1316 }
1317 };
Mathias Agopian6ead5d92009-04-20 19:39:12 -07001318 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 return NO_ERROR;
1320}
1321
1322status_t SurfaceFlinger::setClientState(
1323 ClientID cid,
1324 int32_t count,
1325 const layer_state_t* states)
1326{
1327 Mutex::Autolock _l(mStateLock);
1328 uint32_t flags = 0;
1329 cid <<= 16;
1330 for (int i=0 ; i<count ; i++) {
1331 const layer_state_t& s = states[i];
Mathias Agopian1473f462009-04-10 14:24:30 -07001332 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1333 if (layer != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 const uint32_t what = s.what;
1335 // check if it has been destroyed first
1336 if (what & eDestroyed) {
1337 if (removeLayer_l(layer) == NO_ERROR) {
1338 flags |= eTransactionNeeded;
1339 // we skip everything else... well, no, not really
1340 // we skip ONLY that transaction.
1341 continue;
1342 }
1343 }
1344 if (what & ePositionChanged) {
1345 if (layer->setPosition(s.x, s.y))
1346 flags |= eTraversalNeeded;
1347 }
1348 if (what & eLayerChanged) {
1349 if (layer->setLayer(s.z)) {
1350 mCurrentState.layersSortedByZ.reorder(
1351 layer, &Layer::compareCurrentStateZ);
1352 // we need traversal (state changed)
1353 // AND transaction (list changed)
1354 flags |= eTransactionNeeded|eTraversalNeeded;
1355 }
1356 }
1357 if (what & eSizeChanged) {
1358 if (layer->setSize(s.w, s.h))
1359 flags |= eTraversalNeeded;
1360 }
1361 if (what & eAlphaChanged) {
1362 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1363 flags |= eTraversalNeeded;
1364 }
1365 if (what & eMatrixChanged) {
1366 if (layer->setMatrix(s.matrix))
1367 flags |= eTraversalNeeded;
1368 }
1369 if (what & eTransparentRegionChanged) {
1370 if (layer->setTransparentRegionHint(s.transparentRegion))
1371 flags |= eTraversalNeeded;
1372 }
1373 if (what & eVisibilityChanged) {
1374 if (layer->setFlags(s.flags, s.mask))
1375 flags |= eTraversalNeeded;
1376 }
1377 }
1378 }
1379 if (flags) {
1380 setTransactionFlags(flags);
1381 }
1382 return NO_ERROR;
1383}
1384
Mathias Agopian1473f462009-04-10 14:24:30 -07001385sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386{
Mathias Agopian1473f462009-04-10 14:24:30 -07001387 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1388 return layer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389}
1390
1391void SurfaceFlinger::screenReleased(int dpy)
1392{
1393 // this may be called by a signal handler, we can't do too much in here
1394 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1395 signalEvent();
1396}
1397
1398void SurfaceFlinger::screenAcquired(int dpy)
1399{
1400 // this may be called by a signal handler, we can't do too much in here
1401 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1402 signalEvent();
1403}
1404
1405status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1406{
1407 const size_t SIZE = 1024;
1408 char buffer[SIZE];
1409 String8 result;
1410 if (checkCallingPermission(
1411 String16("android.permission.DUMP")) == false)
1412 { // not allowed
1413 snprintf(buffer, SIZE, "Permission Denial: "
1414 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1415 IPCThreadState::self()->getCallingPid(),
1416 IPCThreadState::self()->getCallingUid());
1417 result.append(buffer);
1418 } else {
1419 Mutex::Autolock _l(mStateLock);
1420 size_t s = mClientsMap.size();
1421 char name[64];
1422 for (size_t i=0 ; i<s ; i++) {
1423 Client* client = mClientsMap.valueAt(i);
1424 sprintf(name, " Client (id=0x%08x)", client->cid);
1425 client->dump(name);
1426 }
1427 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1428 const size_t count = currentLayers.size();
1429 for (size_t i=0 ; i<count ; i++) {
1430 /*** LayerBase ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001431 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 const Layer::State& s = layer->drawingState();
1433 snprintf(buffer, SIZE,
1434 "+ %s %p\n"
1435 " "
1436 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1437 "needsBlending=%1d, invalidate=%1d, "
1438 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian1473f462009-04-10 14:24:30 -07001439 layer->getTypeID(), layer.get(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 s.z, layer->tx(), layer->ty(), s.w, s.h,
1441 layer->needsBlending(), layer->contentDirty,
1442 s.alpha, s.flags,
1443 s.transform[0], s.transform[1],
1444 s.transform[2], s.transform[3]);
1445 result.append(buffer);
1446 buffer[0] = 0;
1447 /*** LayerBaseClient ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001448 sp<LayerBaseClient> lbc =
1449 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1450 if (lbc != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 snprintf(buffer, SIZE,
1452 " "
1453 "id=0x%08x, client=0x%08x, identity=%u\n",
1454 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1455 lbc->getIdentity());
1456 }
1457 result.append(buffer);
1458 buffer[0] = 0;
1459 /*** Layer ***/
Mathias Agopian1473f462009-04-10 14:24:30 -07001460 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1461 if (l != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 const LayerBitmap& buf0(l->getBuffer(0));
1463 const LayerBitmap& buf1(l->getBuffer(1));
1464 snprintf(buffer, SIZE,
1465 " "
Mathias Agopian1473f462009-04-10 14:24:30 -07001466 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 " freezeLock=%p, swapState=0x%08x\n",
1468 l->pixelFormat(),
Mathias Agopian1473f462009-04-10 14:24:30 -07001469 buf0.getWidth(), buf0.getHeight(),
1470 buf0.getBuffer()->getStride(),
1471 buf1.getWidth(), buf1.getHeight(),
1472 buf1.getBuffer()->getStride(),
1473 l->getFreezeLock().get(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 l->lcblk->swapState);
1475 }
1476 result.append(buffer);
1477 buffer[0] = 0;
1478 s.transparentRegion.dump(result, "transparentRegion");
1479 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1480 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1481 }
1482 mWormholeRegion.dump(result, "WormholeRegion");
1483 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1484 snprintf(buffer, SIZE,
1485 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1486 mFreezeDisplay?"yes":"no", mFreezeCount,
1487 mCurrentState.orientation, hw.canDraw());
1488 result.append(buffer);
1489
Mathias Agopian1473f462009-04-10 14:24:30 -07001490 const BufferAllocator& alloc(BufferAllocator::get());
1491 alloc.dump(result);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 write(fd, result.string(), result.size());
1494 return NO_ERROR;
1495}
1496
1497status_t SurfaceFlinger::onTransact(
1498 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1499{
1500 switch (code) {
1501 case CREATE_CONNECTION:
1502 case OPEN_GLOBAL_TRANSACTION:
1503 case CLOSE_GLOBAL_TRANSACTION:
1504 case SET_ORIENTATION:
1505 case FREEZE_DISPLAY:
1506 case UNFREEZE_DISPLAY:
1507 case BOOT_FINISHED:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 {
1509 // codes that require permission check
1510 IPCThreadState* ipc = IPCThreadState::self();
1511 const int pid = ipc->getCallingPid();
1512 const int self_pid = getpid();
1513 if (UNLIKELY(pid != self_pid)) {
1514 // we're called from a different process, do the real check
1515 if (!checkCallingPermission(
1516 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1517 {
1518 const int uid = ipc->getCallingUid();
1519 LOGE("Permission Denial: "
1520 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1521 return PERMISSION_DENIED;
1522 }
1523 }
1524 }
1525 }
1526
1527 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1528 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1529 // HARDWARE_TEST stuff...
1530 if (UNLIKELY(checkCallingPermission(
1531 String16("android.permission.HARDWARE_TEST")) == false))
1532 { // not allowed
1533 LOGE("Permission Denial: pid=%d, uid=%d\n",
1534 IPCThreadState::self()->getCallingPid(),
1535 IPCThreadState::self()->getCallingUid());
1536 return PERMISSION_DENIED;
1537 }
1538 int n;
1539 switch (code) {
Mathias Agopian17f638b2009-04-16 20:04:08 -07001540 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 return NO_ERROR;
Mathias Agopianef07dda2009-04-21 18:28:33 -07001542 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 return NO_ERROR;
1544 case 1002: // SHOW_UPDATES
1545 n = data.readInt32();
1546 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1547 return NO_ERROR;
1548 case 1003: // SHOW_BACKGROUND
1549 n = data.readInt32();
1550 mDebugBackground = n ? 1 : 0;
1551 return NO_ERROR;
1552 case 1004:{ // repaint everything
1553 Mutex::Autolock _l(mStateLock);
1554 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1555 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1556 signalEvent();
1557 }
1558 return NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 case 1007: // set mFreezeCount
1560 mFreezeCount = data.readInt32();
1561 return NO_ERROR;
1562 case 1010: // interrogate.
Mathias Agopian17f638b2009-04-16 20:04:08 -07001563 reply->writeInt32(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 reply->writeInt32(0);
1565 reply->writeInt32(mDebugRegion);
1566 reply->writeInt32(mDebugBackground);
1567 return NO_ERROR;
1568 case 1013: {
1569 Mutex::Autolock _l(mStateLock);
1570 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1571 reply->writeInt32(hw.getPageFlipCount());
1572 }
1573 return NO_ERROR;
1574 }
1575 }
1576 return err;
1577}
1578
1579// ---------------------------------------------------------------------------
1580#if 0
1581#pragma mark -
1582#endif
1583
1584Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1585 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1586{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 const int pgsize = getpagesize();
1588 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1589 mCblkHeap = new MemoryDealer(cblksize);
1590 mCblkMemory = mCblkHeap->allocate(cblksize);
1591 if (mCblkMemory != 0) {
1592 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1593 if (ctrlblk) { // construct the shared structure in-place.
1594 new(ctrlblk) per_client_cblk_t;
1595 }
1596 }
1597}
1598
1599Client::~Client() {
1600 if (ctrlblk) {
1601 const int pgsize = getpagesize();
1602 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1603 }
1604}
1605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606int32_t Client::generateId(int pid)
1607{
1608 const uint32_t i = clz( ~mBitmap );
1609 if (i >= NUM_LAYERS_MAX) {
1610 return NO_MEMORY;
1611 }
1612 mPid = pid;
1613 mInUse.add(uint8_t(i));
1614 mBitmap |= 1<<(31-i);
1615 return i;
1616}
Mathias Agopian1473f462009-04-10 14:24:30 -07001617
1618status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619{
1620 ssize_t idx = mInUse.indexOf(id);
1621 if (idx < 0)
1622 return NAME_NOT_FOUND;
1623 return mLayers.insertAt(layer, idx);
1624}
Mathias Agopian1473f462009-04-10 14:24:30 -07001625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626void Client::free(int32_t id)
1627{
1628 ssize_t idx = mInUse.remove(uint8_t(id));
1629 if (idx >= 0) {
1630 mBitmap &= ~(1<<(31-id));
1631 mLayers.removeItemsAt(idx);
1632 }
1633}
1634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635bool Client::isValid(int32_t i) const {
1636 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1637}
Mathias Agopian1473f462009-04-10 14:24:30 -07001638
1639sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1640 sp<LayerBaseClient> lbc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian1473f462009-04-10 14:24:30 -07001642 if (idx >= 0) {
1643 lbc = mLayers[idx].promote();
1644 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1645 }
1646 return lbc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647}
1648
1649void Client::dump(const char* what)
1650{
1651}
1652
1653// ---------------------------------------------------------------------------
1654#if 0
1655#pragma mark -
1656#endif
1657
1658BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1659 : mId(cid), mFlinger(flinger), mCblk(cblk)
1660{
1661}
1662
1663BClient::~BClient() {
1664 // destroy all resources attached to this client
1665 mFlinger->destroyConnection(mId);
1666}
1667
1668void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1669 *ctrl = mCblk;
1670}
1671
1672sp<ISurface> BClient::createSurface(
1673 ISurfaceFlingerClient::surface_data_t* params, int pid,
1674 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1675 uint32_t flags)
1676{
1677 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1678}
1679
1680status_t BClient::destroySurface(SurfaceID sid)
1681{
1682 sid |= (mId << 16); // add the client-part to id
Mathias Agopian6cf0db22009-04-17 19:36:26 -07001683 return mFlinger->removeSurface(sid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684}
1685
1686status_t BClient::setState(int32_t count, const layer_state_t* states)
1687{
1688 return mFlinger->setClientState(mId, count, states);
1689}
1690
1691// ---------------------------------------------------------------------------
1692
1693GraphicPlane::GraphicPlane()
1694 : mHw(0)
1695{
1696}
1697
1698GraphicPlane::~GraphicPlane() {
1699 delete mHw;
1700}
1701
1702bool GraphicPlane::initialized() const {
1703 return mHw ? true : false;
1704}
1705
1706void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1707 mHw = hw;
1708}
1709
1710void GraphicPlane::setTransform(const Transform& tr) {
1711 mTransform = tr;
1712 mGlobalTransform = mOrientationTransform * mTransform;
1713}
1714
1715status_t GraphicPlane::orientationToTransfrom(
1716 int orientation, int w, int h, Transform* tr)
1717{
1718 float a, b, c, d, x, y;
1719 switch (orientation) {
1720 case ISurfaceComposer::eOrientationDefault:
1721 a=1; b=0; c=0; d=1; x=0; y=0;
1722 break;
1723 case ISurfaceComposer::eOrientation90:
1724 a=0; b=-1; c=1; d=0; x=w; y=0;
1725 break;
1726 case ISurfaceComposer::eOrientation180:
1727 a=-1; b=0; c=0; d=-1; x=w; y=h;
1728 break;
1729 case ISurfaceComposer::eOrientation270:
1730 a=0; b=1; c=-1; d=0; x=0; y=h;
1731 break;
1732 default:
1733 return BAD_VALUE;
1734 }
1735 tr->set(a, b, c, d);
1736 tr->set(x, y);
1737 return NO_ERROR;
1738}
1739
1740status_t GraphicPlane::setOrientation(int orientation)
1741{
1742 const DisplayHardware& hw(displayHardware());
1743 const float w = hw.getWidth();
1744 const float h = hw.getHeight();
1745
1746 if (orientation == ISurfaceComposer::eOrientationDefault) {
1747 // make sure the default orientation is optimal
1748 mOrientationTransform.reset();
Mathias Agopian3552f532009-03-27 17:58:20 -07001749 mOrientation = orientation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 mGlobalTransform = mTransform;
1751 return NO_ERROR;
1752 }
1753
1754 // If the rotation can be handled in hardware, this is where
1755 // the magic should happen.
1756 if (UNLIKELY(orientation == 42)) {
1757 float a, b, c, d, x, y;
1758 const float r = (3.14159265f / 180.0f) * 42.0f;
1759 const float si = sinf(r);
1760 const float co = cosf(r);
1761 a=co; b=-si; c=si; d=co;
1762 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1763 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1764 mOrientationTransform.set(a, b, c, d);
1765 mOrientationTransform.set(x, y);
1766 } else {
1767 GraphicPlane::orientationToTransfrom(orientation, w, h,
1768 &mOrientationTransform);
1769 }
Mathias Agopian3552f532009-03-27 17:58:20 -07001770 mOrientation = orientation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 mGlobalTransform = mOrientationTransform * mTransform;
1772 return NO_ERROR;
1773}
1774
1775const DisplayHardware& GraphicPlane::displayHardware() const {
1776 return *mHw;
1777}
1778
1779const Transform& GraphicPlane::transform() const {
1780 return mGlobalTransform;
1781}
1782
Mathias Agopian1473f462009-04-10 14:24:30 -07001783EGLDisplay GraphicPlane::getEGLDisplay() const {
1784 return mHw->getEGLDisplay();
1785}
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787// ---------------------------------------------------------------------------
1788
1789}; // namespace android