blob: 993a6ae02a2de3c135d608f6799da1455ed9dfcb [file] [log] [blame]
The Android Open Source Projectedbf3b62009-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 Projectedbf3b62009-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 Querua837ba72009-01-26 11:51:12 -080024#include <limits.h>
The Android Open Source Projectedbf3b62009-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 Projectedbf3b62009-03-03 19:31:44 -080042
43#include <pixelflinger/pixelflinger.h>
44#include <GLES/gl.h>
45
46#include "clz.h"
Mathias Agopian076b1cc2009-04-10 14:24:30 -070047#include "BufferAllocator.h"
The Android Open Source Projectedbf3b62009-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 Projectedbf3b62009-03-03 19:31:44 -080056
57#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -070084 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -070091 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070093 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094 return idx;
95 }
96 return i;
97}
98
99ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700100 const sp<LayerBase>& layer,
101 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -0700107 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -0700130ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -0700135 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700137 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -0700152 const sp<LayerBase>& layer,
153 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-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 Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-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 Projectbcef13b2009-03-11 12:11:56 -0700178 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 mDebugFps(0),
181 mDebugBackground(0),
182 mDebugNoBootAnimation(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 mConsoleSignals(0),
184 mSecureFrameBuffer(0)
185{
186 init();
187}
188
189void SurfaceFlinger::init()
190{
191 LOGI("SurfaceFlinger is starting");
192
193 // debugging stuff...
194 char value[PROPERTY_VALUE_MAX];
195 property_get("debug.sf.showupdates", value, "0");
196 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 property_get("debug.sf.showbackground", value, "0");
198 mDebugBackground = atoi(value);
199 property_get("debug.sf.showfps", value, "0");
200 mDebugFps = atoi(value);
201 property_get("debug.sf.nobootanimation", value, "0");
202 mDebugNoBootAnimation = atoi(value);
203
204 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 LOGI_IF(mDebugBackground, "showbackground enabled");
206 LOGI_IF(mDebugFps, "showfps enabled");
207 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
208}
209
210SurfaceFlinger::~SurfaceFlinger()
211{
212 glDeleteTextures(1, &mWormholeTexName);
213 delete mOrientationAnimation;
214}
215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
217{
218 return graphicPlane(0).displayHardware().getOverlayEngine();
219}
220
221sp<IMemory> SurfaceFlinger::getCblk() const
222{
223 return mServerCblkMemory;
224}
225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
227{
228 Mutex::Autolock _l(mStateLock);
229 uint32_t token = mTokens.acquire();
230
231 Client* client = new Client(token, this);
232 if ((client == 0) || (client->ctrlblk == 0)) {
233 mTokens.release(token);
234 return 0;
235 }
236 status_t err = mClientsMap.add(token, client);
237 if (err < 0) {
238 delete client;
239 mTokens.release(token);
240 return 0;
241 }
242 sp<BClient> bclient =
243 new BClient(this, token, client->controlBlockMemory());
244 return bclient;
245}
246
247void SurfaceFlinger::destroyConnection(ClientID cid)
248{
249 Mutex::Autolock _l(mStateLock);
250 Client* const client = mClientsMap.valueFor(cid);
251 if (client) {
252 // free all the layers this client owns
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700253 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 const size_t count = layers.size();
255 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700256 sp<LayerBaseClient> layer(layers[i].promote());
257 if (layer != 0) {
258 removeLayer_l(layer);
259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 }
261
262 // the resources associated with this client will be freed
263 // during the next transaction, after these surfaces have been
264 // properly removed from the screen
265
266 // remove this client from our ClientID->Client mapping.
267 mClientsMap.removeItem(cid);
268
269 // and add it to the list of disconnected clients
270 mDisconnectedClients.add(client);
271
272 // request a transaction
273 setTransactionFlags(eTransactionNeeded);
274 }
275}
276
277const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
278{
279 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
280 const GraphicPlane& plane(mGraphicPlanes[dpy]);
281 return plane;
282}
283
284GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
285{
286 return const_cast<GraphicPlane&>(
287 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
288}
289
290void SurfaceFlinger::bootFinished()
291{
292 const nsecs_t now = systemTime();
293 const nsecs_t duration = now - mBootTime;
294 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
295 if (mBootAnimation != 0) {
296 mBootAnimation->requestExit();
297 mBootAnimation.clear();
298 }
299}
300
301void SurfaceFlinger::onFirstRef()
302{
303 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
304
305 // Wait for the main thread to be done with its initialization
306 mReadyToRunBarrier.wait();
307}
308
309
310static inline uint16_t pack565(int r, int g, int b) {
311 return (r<<11)|(g<<5)|b;
312}
313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314status_t SurfaceFlinger::readyToRun()
315{
316 LOGI( "SurfaceFlinger's main thread ready to run. "
317 "Initializing graphics H/W...");
318
319 // create the shared control-block
320 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
321 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
322
323 mServerCblkMemory = mServerHeap->allocate(4096);
324 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
325
326 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
327 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
328 new(mServerCblk) surface_flinger_cblk_t;
329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330 // we only support one display currently
331 int dpy = 0;
332
333 {
334 // initialize the main display
335 GraphicPlane& plane(graphicPlane(dpy));
336 DisplayHardware* const hw = new DisplayHardware(this, dpy);
337 plane.setDisplayHardware(hw);
338 }
339
340 // initialize primary screen
341 // (other display should be initialized in the same manner, but
342 // asynchronously, as they could come and go. None of this is supported
343 // yet).
344 const GraphicPlane& plane(graphicPlane(dpy));
345 const DisplayHardware& hw = plane.displayHardware();
346 const uint32_t w = hw.getWidth();
347 const uint32_t h = hw.getHeight();
348 const uint32_t f = hw.getFormat();
349 hw.makeCurrent();
350
351 // initialize the shared control block
352 mServerCblk->connected |= 1<<dpy;
353 display_cblk_t* dcblk = mServerCblk->displays + dpy;
354 memset(dcblk, 0, sizeof(display_cblk_t));
355 dcblk->w = w;
356 dcblk->h = h;
357 dcblk->format = f;
358 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
359 dcblk->xdpi = hw.getDpiX();
360 dcblk->ydpi = hw.getDpiY();
361 dcblk->fps = hw.getRefreshRate();
362 dcblk->density = hw.getDensity();
363 asm volatile ("":::"memory");
364
365 // Initialize OpenGL|ES
366 glActiveTexture(GL_TEXTURE0);
367 glBindTexture(GL_TEXTURE_2D, 0);
368 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
369 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
370 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
371 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
372 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
373 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
374 glPixelStorei(GL_PACK_ALIGNMENT, 4);
375 glEnableClientState(GL_VERTEX_ARRAY);
376 glEnable(GL_SCISSOR_TEST);
377 glShadeModel(GL_FLAT);
378 glDisable(GL_DITHER);
379 glDisable(GL_CULL_FACE);
380
381 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
382 const uint16_t g1 = pack565(0x17,0x2f,0x17);
383 const uint16_t textureData[4] = { g0, g1, g1, g0 };
384 glGenTextures(1, &mWormholeTexName);
385 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
386 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
387 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
388 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
389 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
390 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
391 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
392
393 glViewport(0, 0, w, h);
394 glMatrixMode(GL_PROJECTION);
395 glLoadIdentity();
396 glOrthof(0, w, h, 0, 0, 1);
397
398 LayerDim::initDimmer(this, w, h);
399
400 mReadyToRunBarrier.open();
401
402 /*
403 * We're now ready to accept clients...
404 */
405
406 mOrientationAnimation = new OrientationAnimation(this);
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 // the boot animation!
409 if (mDebugNoBootAnimation == false)
410 mBootAnimation = new BootAnimation(this);
411
412 return NO_ERROR;
413}
414
415// ----------------------------------------------------------------------------
416#if 0
417#pragma mark -
418#pragma mark Events Handler
419#endif
420
421void SurfaceFlinger::waitForEvent()
422{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700423 while (true) {
424 nsecs_t timeout = -1;
425 if (UNLIKELY(isFrozen())) {
426 // wait 5 seconds
427 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
428 const nsecs_t now = systemTime();
429 if (mFreezeDisplayTime == 0) {
430 mFreezeDisplayTime = now;
431 }
432 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
433 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700434 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700435
436 MessageList::NODE_PTR msg = mEventQueue.waitMessage(timeout);
437 if (msg != 0) {
438 mFreezeDisplayTime = 0;
439 switch (msg->what) {
440 case MessageQueue::INVALIDATE:
441 // invalidate message, just return to the main loop
442 return;
443 }
444 } else {
445 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 if (isFrozen()) {
447 // we timed out and are still frozen
448 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
449 mFreezeDisplay, mFreezeCount);
450 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700451 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700452 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 }
454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455 }
456}
457
458void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700459 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460}
461
462void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700463 // this is the IPC call
464 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465}
466
467void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
468{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700469 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470}
471
472// ----------------------------------------------------------------------------
473#if 0
474#pragma mark -
475#pragma mark Main loop
476#endif
477
478bool SurfaceFlinger::threadLoop()
479{
480 waitForEvent();
481
482 // check for transactions
483 if (UNLIKELY(mConsoleSignals)) {
484 handleConsoleEvents();
485 }
486
487 if (LIKELY(mTransactionCount == 0)) {
488 // if we're in a global transaction, don't do anything.
489 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
490 uint32_t transactionFlags = getTransactionFlags(mask);
491 if (LIKELY(transactionFlags)) {
492 handleTransaction(transactionFlags);
493 }
494 }
495
496 // post surfaces (if needed)
497 handlePageFlip();
498
499 const DisplayHardware& hw(graphicPlane(0).displayHardware());
500 if (LIKELY(hw.canDraw())) {
501 // repaint the framebuffer (if needed)
502 handleRepaint();
503
504 // release the clients before we flip ('cause flip might block)
505 unlockClients();
506 executeScheduledBroadcasts();
507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508 postFramebuffer();
509 } else {
510 // pretend we did the post
511 unlockClients();
512 executeScheduledBroadcasts();
513 usleep(16667); // 60 fps period
514 }
515 return true;
516}
517
518void SurfaceFlinger::postFramebuffer()
519{
520 const bool skip = mOrientationAnimation->run();
521 if (UNLIKELY(skip)) {
522 return;
523 }
524
525 if (!mInvalidRegion.isEmpty()) {
526 const DisplayHardware& hw(graphicPlane(0).displayHardware());
527
528 if (UNLIKELY(mDebugFps)) {
529 debugShowFPS();
530 }
531
532 hw.flip(mInvalidRegion);
533
534 mInvalidRegion.clear();
535
536 if (Layer::deletedTextures.size()) {
537 glDeleteTextures(
538 Layer::deletedTextures.size(),
539 Layer::deletedTextures.array());
540 Layer::deletedTextures.clear();
541 }
542 }
543}
544
545void SurfaceFlinger::handleConsoleEvents()
546{
547 // something to do with the console
548 const DisplayHardware& hw = graphicPlane(0).displayHardware();
549
550 int what = android_atomic_and(0, &mConsoleSignals);
551 if (what & eConsoleAcquired) {
552 hw.acquireScreen();
553 }
554
555 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700556 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800557 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558 hw.releaseScreen();
559 }
560
561 if (what & eConsoleReleased) {
562 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800563 hw.releaseScreen();
564 } else {
565 mDeferReleaseConsole = true;
566 }
567 }
568
569 mDirtyRegion.set(hw.bounds());
570}
571
572void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
573{
574 Mutex::Autolock _l(mStateLock);
575
576 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
577 const size_t count = currentLayers.size();
578
579 /*
580 * Traversal of the children
581 * (perform the transaction for each of them if needed)
582 */
583
584 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
585 if (layersNeedTransaction) {
586 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700587 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800588 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
589 if (!trFlags) continue;
590
591 const uint32_t flags = layer->doTransaction(0);
592 if (flags & Layer::eVisibleRegion)
593 mVisibleRegionsDirty = true;
594
595 if (flags & Layer::eRestartTransaction) {
596 // restart the transaction, but back-off a little
597 layer->setTransactionFlags(eTransactionNeeded);
598 setTransactionFlags(eTraversalNeeded, ms2ns(8));
599 }
600 }
601 }
602
603 /*
604 * Perform our own transaction if needed
605 */
606
607 if (transactionFlags & eTransactionNeeded) {
608 if (mCurrentState.orientation != mDrawingState.orientation) {
609 // the orientation has changed, recompute all visible regions
610 // and invalidate everything.
611
612 const int dpy = 0;
613 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700614 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800615 GraphicPlane& plane(graphicPlane(dpy));
616 plane.setOrientation(orientation);
617
618 // update the shared control block
619 const DisplayHardware& hw(plane.displayHardware());
620 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
621 dcblk->orientation = orientation;
622 if (orientation & eOrientationSwapMask) {
623 // 90 or 270 degrees orientation
624 dcblk->w = hw.getHeight();
625 dcblk->h = hw.getWidth();
626 } else {
627 dcblk->w = hw.getWidth();
628 dcblk->h = hw.getHeight();
629 }
630
631 mVisibleRegionsDirty = true;
632 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700633 mFreezeDisplayTime = 0;
634 mOrientationAnimation->onOrientationChanged(type);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635 }
636
637 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
638 // freezing or unfreezing the display -> trigger animation if needed
639 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640 }
641
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700642 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
643 // layers have been added
644 mVisibleRegionsDirty = true;
645 }
646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647 // some layers might have been removed, so
648 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700649 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700651 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
652 const ssize_t count = previousLayers.size();
653 for (ssize_t i=0 ; i<count ; i++) {
654 const sp<LayerBase>& layer(previousLayers[i]);
655 if (currentLayers.indexOf( layer ) < 0) {
656 // this layer is not visible anymore
657 // FIXME: would be better to call without the lock held
658 //LOGD("ditching layer %p", layer.get());
659 layer->ditch();
660 }
661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800662 }
663
664 // get rid of all resources we don't need anymore
665 // (layers and clients)
666 free_resources_l();
667 }
668
669 commitTransaction();
670}
671
672sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
673{
674 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
675}
676
677void SurfaceFlinger::computeVisibleRegions(
678 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
679{
680 const GraphicPlane& plane(graphicPlane(0));
681 const Transform& planeTransform(plane.transform());
682
683 Region aboveOpaqueLayers;
684 Region aboveCoveredLayers;
685 Region dirty;
686
687 bool secureFrameBuffer = false;
688
689 size_t i = currentLayers.size();
690 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700691 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692 layer->validateVisibility(planeTransform);
693
694 // start with the whole surface at its current location
695 const Layer::State& s = layer->drawingState();
696 const Rect bounds(layer->visibleBounds());
697
698 // handle hidden surfaces by setting the visible region to empty
699 Region opaqueRegion;
700 Region visibleRegion;
701 Region coveredRegion;
702 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
703 visibleRegion.clear();
704 } else {
705 const bool translucent = layer->needsBlending();
706 visibleRegion.set(bounds);
707 coveredRegion = visibleRegion;
708
709 // Remove the transparent area from the visible region
710 if (translucent) {
711 visibleRegion.subtractSelf(layer->transparentRegionScreen);
712 }
713
714 // compute the opaque region
715 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
716 // the opaque region is the visible region
717 opaqueRegion = visibleRegion;
718 }
719 }
720
721 // subtract the opaque region covered by the layers above us
722 visibleRegion.subtractSelf(aboveOpaqueLayers);
723 coveredRegion.andSelf(aboveCoveredLayers);
724
725 // compute this layer's dirty region
726 if (layer->contentDirty) {
727 // we need to invalidate the whole region
728 dirty = visibleRegion;
729 // as well, as the old visible region
730 dirty.orSelf(layer->visibleRegionScreen);
731 layer->contentDirty = false;
732 } else {
733 // compute the exposed region
734 // dirty = what's visible now - what's wasn't covered before
735 // = what's visible now & what's was covered before
736 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
737 }
738 dirty.subtractSelf(aboveOpaqueLayers);
739
740 // accumulate to the screen dirty region
741 dirtyRegion.orSelf(dirty);
742
Mathias Agopian62b74442009-04-14 23:02:51 -0700743 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744 aboveOpaqueLayers.orSelf(opaqueRegion);
745 aboveCoveredLayers.orSelf(bounds);
746
747 // Store the visible region is screen space
748 layer->setVisibleRegion(visibleRegion);
749 layer->setCoveredRegion(coveredRegion);
750
Mathias Agopian62b74442009-04-14 23:02:51 -0700751 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752 if (layer->isSecure() && !visibleRegion.isEmpty()) {
753 secureFrameBuffer = true;
754 }
755 }
756
757 mSecureFrameBuffer = secureFrameBuffer;
758 opaqueRegion = aboveOpaqueLayers;
759}
760
761
762void SurfaceFlinger::commitTransaction()
763{
764 mDrawingState = mCurrentState;
765 mTransactionCV.signal();
766}
767
768void SurfaceFlinger::handlePageFlip()
769{
770 bool visibleRegions = mVisibleRegionsDirty;
771 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
772 visibleRegions |= lockPageFlip(currentLayers);
773
774 const DisplayHardware& hw = graphicPlane(0).displayHardware();
775 const Region screenRegion(hw.bounds());
776 if (visibleRegions) {
777 Region opaqueRegion;
778 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
779 mWormholeRegion = screenRegion.subtract(opaqueRegion);
780 mVisibleRegionsDirty = false;
781 }
782
783 unlockPageFlip(currentLayers);
784 mDirtyRegion.andSelf(screenRegion);
785}
786
787bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
788{
789 bool recomputeVisibleRegions = false;
790 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700791 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800792 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700793 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794 layer->lockPageFlip(recomputeVisibleRegions);
795 }
796 return recomputeVisibleRegions;
797}
798
799void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
800{
801 const GraphicPlane& plane(graphicPlane(0));
802 const Transform& planeTransform(plane.transform());
803 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700804 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700806 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800807 layer->unlockPageFlip(planeTransform, mDirtyRegion);
808 }
809}
810
811void SurfaceFlinger::handleRepaint()
812{
813 // set the frame buffer
814 const DisplayHardware& hw(graphicPlane(0).displayHardware());
815 glMatrixMode(GL_MODELVIEW);
816 glLoadIdentity();
817
818 if (UNLIKELY(mDebugRegion)) {
819 debugFlashRegions();
820 }
821
822 // compute the invalid region
823 mInvalidRegion.orSelf(mDirtyRegion);
824
825 uint32_t flags = hw.getFlags();
826 if (flags & DisplayHardware::BUFFER_PRESERVED) {
827 // here we assume DisplayHardware::flip()'s implementation
828 // performs the copy-back optimization.
829 } else {
830 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
831 // we need to fully redraw the part that will be updated
832 mDirtyRegion.set(mInvalidRegion.bounds());
833 } else {
834 // we need to redraw everything
835 mDirtyRegion.set(hw.bounds());
836 mInvalidRegion = mDirtyRegion;
837 }
838 }
839
840 // compose all surfaces
841 composeSurfaces(mDirtyRegion);
842
843 // clear the dirty regions
844 mDirtyRegion.clear();
845}
846
847void SurfaceFlinger::composeSurfaces(const Region& dirty)
848{
849 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
850 // should never happen unless the window manager has a bug
851 // draw something...
852 drawWormhole();
853 }
854 const SurfaceFlinger& flinger(*this);
855 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
856 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700857 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800858 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700859 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800860 const Region& visibleRegion(layer->visibleRegionScreen);
861 if (!visibleRegion.isEmpty()) {
862 const Region clip(dirty.intersect(visibleRegion));
863 if (!clip.isEmpty()) {
864 layer->draw(clip);
865 }
866 }
867 }
868}
869
870void SurfaceFlinger::unlockClients()
871{
872 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
873 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700874 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700876 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800877 layer->finishPageFlip();
878 }
879}
880
881void SurfaceFlinger::scheduleBroadcast(Client* client)
882{
883 if (mLastScheduledBroadcast != client) {
884 mLastScheduledBroadcast = client;
885 mScheduledBroadcasts.add(client);
886 }
887}
888
889void SurfaceFlinger::executeScheduledBroadcasts()
890{
891 SortedVector<Client*>& list = mScheduledBroadcasts;
892 size_t count = list.size();
893 while (count--) {
894 per_client_cblk_t* const cblk = list[count]->ctrlblk;
895 if (cblk->lock.tryLock() == NO_ERROR) {
896 cblk->cv.broadcast();
897 list.removeAt(count);
898 cblk->lock.unlock();
899 } else {
900 // schedule another round
901 LOGW("executeScheduledBroadcasts() skipped, "
902 "contention on the client. We'll try again later...");
903 signalDelayedEvent(ms2ns(4));
904 }
905 }
906 mLastScheduledBroadcast = 0;
907}
908
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800909void SurfaceFlinger::debugFlashRegions()
910{
911 if (UNLIKELY(!mDirtyRegion.isRect())) {
912 // TODO: do this only if we don't have preserving
913 // swapBuffer. If we don't have update-on-demand,
914 // redraw everything.
915 composeSurfaces(Region(mDirtyRegion.bounds()));
916 }
917
918 glDisable(GL_TEXTURE_2D);
919 glDisable(GL_BLEND);
920 glDisable(GL_DITHER);
921 glDisable(GL_SCISSOR_TEST);
922
923 glColor4x(0x10000, 0, 0x10000, 0x10000);
924
925 Rect r;
926 Region::iterator iterator(mDirtyRegion);
927 while (iterator.iterate(&r)) {
928 GLfloat vertices[][2] = {
929 { r.left, r.top },
930 { r.left, r.bottom },
931 { r.right, r.bottom },
932 { r.right, r.top }
933 };
934 glVertexPointer(2, GL_FLOAT, 0, vertices);
935 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
936 }
937
938 const DisplayHardware& hw(graphicPlane(0).displayHardware());
939 hw.flip(mDirtyRegion.merge(mInvalidRegion));
940 mInvalidRegion.clear();
941
942 if (mDebugRegion > 1)
943 usleep(mDebugRegion * 1000);
944
945 glEnable(GL_SCISSOR_TEST);
946 //mDirtyRegion.dump("mDirtyRegion");
947}
948
949void SurfaceFlinger::drawWormhole() const
950{
951 const Region region(mWormholeRegion.intersect(mDirtyRegion));
952 if (region.isEmpty())
953 return;
954
955 const DisplayHardware& hw(graphicPlane(0).displayHardware());
956 const int32_t width = hw.getWidth();
957 const int32_t height = hw.getHeight();
958
959 glDisable(GL_BLEND);
960 glDisable(GL_DITHER);
961
962 if (LIKELY(!mDebugBackground)) {
963 glClearColorx(0,0,0,0);
964 Rect r;
965 Region::iterator iterator(region);
966 while (iterator.iterate(&r)) {
967 const GLint sy = height - (r.top + r.height());
968 glScissor(r.left, sy, r.width(), r.height());
969 glClear(GL_COLOR_BUFFER_BIT);
970 }
971 } else {
972 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
973 { width, height }, { 0, height } };
974 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
975 glVertexPointer(2, GL_SHORT, 0, vertices);
976 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
977 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
978 glEnable(GL_TEXTURE_2D);
979 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
980 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
981 glMatrixMode(GL_TEXTURE);
982 glLoadIdentity();
983 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
984 Rect r;
985 Region::iterator iterator(region);
986 while (iterator.iterate(&r)) {
987 const GLint sy = height - (r.top + r.height());
988 glScissor(r.left, sy, r.width(), r.height());
989 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
990 }
991 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
992 }
993}
994
995void SurfaceFlinger::debugShowFPS() const
996{
997 static int mFrameCount;
998 static int mLastFrameCount = 0;
999 static nsecs_t mLastFpsTime = 0;
1000 static float mFps = 0;
1001 mFrameCount++;
1002 nsecs_t now = systemTime();
1003 nsecs_t diff = now - mLastFpsTime;
1004 if (diff > ms2ns(250)) {
1005 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1006 mLastFpsTime = now;
1007 mLastFrameCount = mFrameCount;
1008 }
1009 // XXX: mFPS has the value we want
1010 }
1011
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001012status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013{
1014 Mutex::Autolock _l(mStateLock);
1015 addLayer_l(layer);
1016 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1017 return NO_ERROR;
1018}
1019
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001020status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
1022 Mutex::Autolock _l(mStateLock);
1023 removeLayer_l(layer);
1024 setTransactionFlags(eTransactionNeeded);
1025 return NO_ERROR;
1026}
1027
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001028status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029{
1030 layer->forceVisibilityTransaction();
1031 setTransactionFlags(eTraversalNeeded);
1032 return NO_ERROR;
1033}
1034
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001035status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036{
1037 ssize_t i = mCurrentState.layersSortedByZ.add(
1038 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001039 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1040 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041 mLayerMap.add(lbc->serverIndex(), lbc);
1042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043 return NO_ERROR;
1044}
1045
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001046status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047{
1048 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1049 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001050 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001051 sp<LayerBaseClient> layer =
1052 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001053 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001054 mLayerMap.removeItem(layer->serverIndex());
1055 }
1056 return NO_ERROR;
1057 }
1058 // it's possible that we don't find a layer, because it might
1059 // have been destroyed already -- this is not technically an error
Mathias Agopian9a112062009-04-17 19:36:26 -07001060 // from the user because there is a race between BClient::destroySurface(),
1061 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1063}
1064
Mathias Agopian9a112062009-04-17 19:36:26 -07001065status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1066{
1067 // First add the layer to the purgatory list, which makes sure it won't
1068 // go away, then remove it from the main list (through a transaction).
1069 ssize_t err = removeLayer_l(layerBase);
1070 if (err >= 0) {
1071 mLayerPurgatory.add(layerBase);
1072 }
1073 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1074}
1075
1076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001077void SurfaceFlinger::free_resources_l()
1078{
1079 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001080 mLayersRemoved = false;
1081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001082 // free resources associated with disconnected clients
1083 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1084 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1085 const size_t count = disconnectedClients.size();
1086 for (size_t i=0 ; i<count ; i++) {
1087 Client* client = disconnectedClients[i];
1088 // if this client is the scheduled broadcast list,
1089 // remove it from there (and we don't need to signal it
1090 // since it is dead).
1091 int32_t index = scheduledBroadcasts.indexOf(client);
1092 if (index >= 0) {
1093 scheduledBroadcasts.removeItemsAt(index);
1094 }
1095 mTokens.release(client->cid);
1096 delete client;
1097 }
1098 disconnectedClients.clear();
1099}
1100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001101uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1102{
1103 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1104}
1105
1106uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1107{
1108 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1109 if ((old & flags)==0) { // wake the server up
1110 if (delay > 0) {
1111 signalDelayedEvent(delay);
1112 } else {
1113 signalEvent();
1114 }
1115 }
1116 return old;
1117}
1118
1119void SurfaceFlinger::openGlobalTransaction()
1120{
1121 android_atomic_inc(&mTransactionCount);
1122}
1123
1124void SurfaceFlinger::closeGlobalTransaction()
1125{
1126 if (android_atomic_dec(&mTransactionCount) == 1) {
1127 signalEvent();
1128 }
1129}
1130
1131status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1132{
1133 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1134 return BAD_VALUE;
1135
1136 Mutex::Autolock _l(mStateLock);
1137 mCurrentState.freezeDisplay = 1;
1138 setTransactionFlags(eTransactionNeeded);
1139
1140 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001141 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142 return NO_ERROR;
1143}
1144
1145status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1146{
1147 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1148 return BAD_VALUE;
1149
1150 Mutex::Autolock _l(mStateLock);
1151 mCurrentState.freezeDisplay = 0;
1152 setTransactionFlags(eTransactionNeeded);
1153
1154 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001155 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001156 return NO_ERROR;
1157}
1158
Mathias Agopianc08731e2009-03-27 18:11:38 -07001159int SurfaceFlinger::setOrientation(DisplayID dpy,
1160 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001161{
1162 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1163 return BAD_VALUE;
1164
1165 Mutex::Autolock _l(mStateLock);
1166 if (mCurrentState.orientation != orientation) {
1167 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001168 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169 mCurrentState.orientation = orientation;
1170 setTransactionFlags(eTransactionNeeded);
1171 mTransactionCV.wait(mStateLock);
1172 } else {
1173 orientation = BAD_VALUE;
1174 }
1175 }
1176 return orientation;
1177}
1178
1179sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1180 ISurfaceFlingerClient::surface_data_t* params,
1181 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1182 uint32_t flags)
1183{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001184 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185 sp<LayerBaseClient::Surface> surfaceHandle;
1186 Mutex::Autolock _l(mStateLock);
1187 Client* const c = mClientsMap.valueFor(clientId);
1188 if (UNLIKELY(!c)) {
1189 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1190 return surfaceHandle;
1191 }
1192
1193 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1194 int32_t id = c->generateId(pid);
1195 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1196 LOGE("createSurface() failed, generateId = %d", id);
1197 return surfaceHandle;
1198 }
1199
1200 switch (flags & eFXSurfaceMask) {
1201 case eFXSurfaceNormal:
1202 if (UNLIKELY(flags & ePushBuffers)) {
1203 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1204 } else {
1205 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1206 }
1207 break;
1208 case eFXSurfaceBlur:
1209 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1210 break;
1211 case eFXSurfaceDim:
1212 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1213 break;
1214 }
1215
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001216 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217 setTransactionFlags(eTransactionNeeded);
1218 surfaceHandle = layer->getSurface();
1219 if (surfaceHandle != 0)
1220 surfaceHandle->getSurfaceData(params);
1221 }
1222
1223 return surfaceHandle;
1224}
1225
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001226sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227 Client* client, DisplayID display,
1228 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1229{
1230 // initialize the surfaces
1231 switch (format) { // TODO: take h/w into account
1232 case PIXEL_FORMAT_TRANSPARENT:
1233 case PIXEL_FORMAT_TRANSLUCENT:
1234 format = PIXEL_FORMAT_RGBA_8888;
1235 break;
1236 case PIXEL_FORMAT_OPAQUE:
1237 format = PIXEL_FORMAT_RGB_565;
1238 break;
1239 }
1240
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001241 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242 status_t err = layer->setBuffers(client, w, h, format, flags);
1243 if (LIKELY(err == NO_ERROR)) {
1244 layer->initStates(w, h, flags);
1245 addLayer_l(layer);
1246 } else {
1247 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001248 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249 }
1250 return layer;
1251}
1252
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001253sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254 Client* client, DisplayID display,
1255 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1256{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001257 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258 layer->initStates(w, h, flags);
1259 addLayer_l(layer);
1260 return layer;
1261}
1262
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001263sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264 Client* client, DisplayID display,
1265 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1266{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001267 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001268 layer->initStates(w, h, flags);
1269 addLayer_l(layer);
1270 return layer;
1271}
1272
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001273sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001274 Client* client, DisplayID display,
1275 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1276{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001277 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001278 layer->initStates(w, h, flags);
1279 addLayer_l(layer);
1280 return layer;
1281}
1282
Mathias Agopian9a112062009-04-17 19:36:26 -07001283status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001284{
Mathias Agopian9a112062009-04-17 19:36:26 -07001285 /*
1286 * called by the window manager, when a surface should be marked for
1287 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001288 *
1289 * The surface is removed from the current and drawing lists, but placed
1290 * in the purgatory queue, so it's not destroyed right-away (we need
1291 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001292 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001293
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001294 Mutex::Autolock _l(mStateLock);
1295 sp<LayerBaseClient> layer = getLayerUser_l(index);
1296 status_t err = purgatorizeLayer_l(layer);
1297 if (err == NO_ERROR) {
1298 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001299 }
1300 return err;
1301}
1302
1303status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1304{
1305 /*
1306 * called by ~ISurface() when all references are gone
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001307 *
1308 * the surface must be removed from purgatory from the main thread
1309 * since its dtor must run from there (b/c of OpenGL ES).
Mathias Agopian9a112062009-04-17 19:36:26 -07001310 */
1311
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001312 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001313 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001314 sp<LayerBaseClient> layer;
1315 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001316 MessageDestroySurface(
1317 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1318 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001319 virtual bool handler() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001320 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001321 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1322 LOGE_IF(idx<0, "layer=%p is not in the purgatory list", layer.get());
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001323 return true;
1324 }
1325 };
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001326 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001327 return NO_ERROR;
1328}
1329
1330status_t SurfaceFlinger::setClientState(
1331 ClientID cid,
1332 int32_t count,
1333 const layer_state_t* states)
1334{
1335 Mutex::Autolock _l(mStateLock);
1336 uint32_t flags = 0;
1337 cid <<= 16;
1338 for (int i=0 ; i<count ; i++) {
1339 const layer_state_t& s = states[i];
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001340 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1341 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001342 const uint32_t what = s.what;
1343 // check if it has been destroyed first
1344 if (what & eDestroyed) {
1345 if (removeLayer_l(layer) == NO_ERROR) {
1346 flags |= eTransactionNeeded;
1347 // we skip everything else... well, no, not really
1348 // we skip ONLY that transaction.
1349 continue;
1350 }
1351 }
1352 if (what & ePositionChanged) {
1353 if (layer->setPosition(s.x, s.y))
1354 flags |= eTraversalNeeded;
1355 }
1356 if (what & eLayerChanged) {
1357 if (layer->setLayer(s.z)) {
1358 mCurrentState.layersSortedByZ.reorder(
1359 layer, &Layer::compareCurrentStateZ);
1360 // we need traversal (state changed)
1361 // AND transaction (list changed)
1362 flags |= eTransactionNeeded|eTraversalNeeded;
1363 }
1364 }
1365 if (what & eSizeChanged) {
1366 if (layer->setSize(s.w, s.h))
1367 flags |= eTraversalNeeded;
1368 }
1369 if (what & eAlphaChanged) {
1370 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1371 flags |= eTraversalNeeded;
1372 }
1373 if (what & eMatrixChanged) {
1374 if (layer->setMatrix(s.matrix))
1375 flags |= eTraversalNeeded;
1376 }
1377 if (what & eTransparentRegionChanged) {
1378 if (layer->setTransparentRegionHint(s.transparentRegion))
1379 flags |= eTraversalNeeded;
1380 }
1381 if (what & eVisibilityChanged) {
1382 if (layer->setFlags(s.flags, s.mask))
1383 flags |= eTraversalNeeded;
1384 }
1385 }
1386 }
1387 if (flags) {
1388 setTransactionFlags(flags);
1389 }
1390 return NO_ERROR;
1391}
1392
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001393sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001394{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001395 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1396 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397}
1398
1399void SurfaceFlinger::screenReleased(int dpy)
1400{
1401 // this may be called by a signal handler, we can't do too much in here
1402 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1403 signalEvent();
1404}
1405
1406void SurfaceFlinger::screenAcquired(int dpy)
1407{
1408 // this may be called by a signal handler, we can't do too much in here
1409 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1410 signalEvent();
1411}
1412
1413status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1414{
1415 const size_t SIZE = 1024;
1416 char buffer[SIZE];
1417 String8 result;
1418 if (checkCallingPermission(
1419 String16("android.permission.DUMP")) == false)
1420 { // not allowed
1421 snprintf(buffer, SIZE, "Permission Denial: "
1422 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1423 IPCThreadState::self()->getCallingPid(),
1424 IPCThreadState::self()->getCallingUid());
1425 result.append(buffer);
1426 } else {
1427 Mutex::Autolock _l(mStateLock);
1428 size_t s = mClientsMap.size();
1429 char name[64];
1430 for (size_t i=0 ; i<s ; i++) {
1431 Client* client = mClientsMap.valueAt(i);
1432 sprintf(name, " Client (id=0x%08x)", client->cid);
1433 client->dump(name);
1434 }
1435 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1436 const size_t count = currentLayers.size();
1437 for (size_t i=0 ; i<count ; i++) {
1438 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001439 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001440 const Layer::State& s = layer->drawingState();
1441 snprintf(buffer, SIZE,
1442 "+ %s %p\n"
1443 " "
1444 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1445 "needsBlending=%1d, invalidate=%1d, "
1446 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001447 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001448 s.z, layer->tx(), layer->ty(), s.w, s.h,
1449 layer->needsBlending(), layer->contentDirty,
1450 s.alpha, s.flags,
1451 s.transform[0], s.transform[1],
1452 s.transform[2], s.transform[3]);
1453 result.append(buffer);
1454 buffer[0] = 0;
1455 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001456 sp<LayerBaseClient> lbc =
1457 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1458 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001459 snprintf(buffer, SIZE,
1460 " "
1461 "id=0x%08x, client=0x%08x, identity=%u\n",
1462 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1463 lbc->getIdentity());
1464 }
1465 result.append(buffer);
1466 buffer[0] = 0;
1467 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001468 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1469 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470 const LayerBitmap& buf0(l->getBuffer(0));
1471 const LayerBitmap& buf1(l->getBuffer(1));
1472 snprintf(buffer, SIZE,
1473 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001474 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001475 " freezeLock=%p, swapState=0x%08x\n",
1476 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001477 buf0.getWidth(), buf0.getHeight(),
1478 buf0.getBuffer()->getStride(),
1479 buf1.getWidth(), buf1.getHeight(),
1480 buf1.getBuffer()->getStride(),
1481 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482 l->lcblk->swapState);
1483 }
1484 result.append(buffer);
1485 buffer[0] = 0;
1486 s.transparentRegion.dump(result, "transparentRegion");
1487 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1488 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1489 }
1490 mWormholeRegion.dump(result, "WormholeRegion");
1491 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1492 snprintf(buffer, SIZE,
1493 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1494 mFreezeDisplay?"yes":"no", mFreezeCount,
1495 mCurrentState.orientation, hw.canDraw());
1496 result.append(buffer);
1497
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001498 const BufferAllocator& alloc(BufferAllocator::get());
1499 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500 }
1501 write(fd, result.string(), result.size());
1502 return NO_ERROR;
1503}
1504
1505status_t SurfaceFlinger::onTransact(
1506 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1507{
1508 switch (code) {
1509 case CREATE_CONNECTION:
1510 case OPEN_GLOBAL_TRANSACTION:
1511 case CLOSE_GLOBAL_TRANSACTION:
1512 case SET_ORIENTATION:
1513 case FREEZE_DISPLAY:
1514 case UNFREEZE_DISPLAY:
1515 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516 {
1517 // codes that require permission check
1518 IPCThreadState* ipc = IPCThreadState::self();
1519 const int pid = ipc->getCallingPid();
1520 const int self_pid = getpid();
1521 if (UNLIKELY(pid != self_pid)) {
1522 // we're called from a different process, do the real check
1523 if (!checkCallingPermission(
1524 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1525 {
1526 const int uid = ipc->getCallingUid();
1527 LOGE("Permission Denial: "
1528 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1529 return PERMISSION_DENIED;
1530 }
1531 }
1532 }
1533 }
1534
1535 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1536 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1537 // HARDWARE_TEST stuff...
1538 if (UNLIKELY(checkCallingPermission(
1539 String16("android.permission.HARDWARE_TEST")) == false))
1540 { // not allowed
1541 LOGE("Permission Denial: pid=%d, uid=%d\n",
1542 IPCThreadState::self()->getCallingPid(),
1543 IPCThreadState::self()->getCallingUid());
1544 return PERMISSION_DENIED;
1545 }
1546 int n;
1547 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001548 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001549 return NO_ERROR;
1550 case 1001: // SHOW_FPS
1551 n = data.readInt32();
1552 mDebugFps = n ? 1 : 0;
1553 return NO_ERROR;
1554 case 1002: // SHOW_UPDATES
1555 n = data.readInt32();
1556 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1557 return NO_ERROR;
1558 case 1003: // SHOW_BACKGROUND
1559 n = data.readInt32();
1560 mDebugBackground = n ? 1 : 0;
1561 return NO_ERROR;
1562 case 1004:{ // repaint everything
1563 Mutex::Autolock _l(mStateLock);
1564 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1565 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1566 signalEvent();
1567 }
1568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001569 case 1007: // set mFreezeCount
1570 mFreezeCount = data.readInt32();
1571 return NO_ERROR;
1572 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001573 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001574 reply->writeInt32(0);
1575 reply->writeInt32(mDebugRegion);
1576 reply->writeInt32(mDebugBackground);
1577 return NO_ERROR;
1578 case 1013: {
1579 Mutex::Autolock _l(mStateLock);
1580 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1581 reply->writeInt32(hw.getPageFlipCount());
1582 }
1583 return NO_ERROR;
1584 }
1585 }
1586 return err;
1587}
1588
1589// ---------------------------------------------------------------------------
1590#if 0
1591#pragma mark -
1592#endif
1593
1594Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1595 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1596{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001597 const int pgsize = getpagesize();
1598 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1599 mCblkHeap = new MemoryDealer(cblksize);
1600 mCblkMemory = mCblkHeap->allocate(cblksize);
1601 if (mCblkMemory != 0) {
1602 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1603 if (ctrlblk) { // construct the shared structure in-place.
1604 new(ctrlblk) per_client_cblk_t;
1605 }
1606 }
1607}
1608
1609Client::~Client() {
1610 if (ctrlblk) {
1611 const int pgsize = getpagesize();
1612 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1613 }
1614}
1615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001616int32_t Client::generateId(int pid)
1617{
1618 const uint32_t i = clz( ~mBitmap );
1619 if (i >= NUM_LAYERS_MAX) {
1620 return NO_MEMORY;
1621 }
1622 mPid = pid;
1623 mInUse.add(uint8_t(i));
1624 mBitmap |= 1<<(31-i);
1625 return i;
1626}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001627
1628status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001629{
1630 ssize_t idx = mInUse.indexOf(id);
1631 if (idx < 0)
1632 return NAME_NOT_FOUND;
1633 return mLayers.insertAt(layer, idx);
1634}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001636void Client::free(int32_t id)
1637{
1638 ssize_t idx = mInUse.remove(uint8_t(id));
1639 if (idx >= 0) {
1640 mBitmap &= ~(1<<(31-id));
1641 mLayers.removeItemsAt(idx);
1642 }
1643}
1644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645bool Client::isValid(int32_t i) const {
1646 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1647}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001648
1649sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1650 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001651 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001652 if (idx >= 0) {
1653 lbc = mLayers[idx].promote();
1654 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1655 }
1656 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001657}
1658
1659void Client::dump(const char* what)
1660{
1661}
1662
1663// ---------------------------------------------------------------------------
1664#if 0
1665#pragma mark -
1666#endif
1667
1668BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1669 : mId(cid), mFlinger(flinger), mCblk(cblk)
1670{
1671}
1672
1673BClient::~BClient() {
1674 // destroy all resources attached to this client
1675 mFlinger->destroyConnection(mId);
1676}
1677
1678void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1679 *ctrl = mCblk;
1680}
1681
1682sp<ISurface> BClient::createSurface(
1683 ISurfaceFlingerClient::surface_data_t* params, int pid,
1684 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1685 uint32_t flags)
1686{
1687 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1688}
1689
1690status_t BClient::destroySurface(SurfaceID sid)
1691{
1692 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001693 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001694}
1695
1696status_t BClient::setState(int32_t count, const layer_state_t* states)
1697{
1698 return mFlinger->setClientState(mId, count, states);
1699}
1700
1701// ---------------------------------------------------------------------------
1702
1703GraphicPlane::GraphicPlane()
1704 : mHw(0)
1705{
1706}
1707
1708GraphicPlane::~GraphicPlane() {
1709 delete mHw;
1710}
1711
1712bool GraphicPlane::initialized() const {
1713 return mHw ? true : false;
1714}
1715
1716void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1717 mHw = hw;
1718}
1719
1720void GraphicPlane::setTransform(const Transform& tr) {
1721 mTransform = tr;
1722 mGlobalTransform = mOrientationTransform * mTransform;
1723}
1724
1725status_t GraphicPlane::orientationToTransfrom(
1726 int orientation, int w, int h, Transform* tr)
1727{
1728 float a, b, c, d, x, y;
1729 switch (orientation) {
1730 case ISurfaceComposer::eOrientationDefault:
1731 a=1; b=0; c=0; d=1; x=0; y=0;
1732 break;
1733 case ISurfaceComposer::eOrientation90:
1734 a=0; b=-1; c=1; d=0; x=w; y=0;
1735 break;
1736 case ISurfaceComposer::eOrientation180:
1737 a=-1; b=0; c=0; d=-1; x=w; y=h;
1738 break;
1739 case ISurfaceComposer::eOrientation270:
1740 a=0; b=1; c=-1; d=0; x=0; y=h;
1741 break;
1742 default:
1743 return BAD_VALUE;
1744 }
1745 tr->set(a, b, c, d);
1746 tr->set(x, y);
1747 return NO_ERROR;
1748}
1749
1750status_t GraphicPlane::setOrientation(int orientation)
1751{
1752 const DisplayHardware& hw(displayHardware());
1753 const float w = hw.getWidth();
1754 const float h = hw.getHeight();
1755
1756 if (orientation == ISurfaceComposer::eOrientationDefault) {
1757 // make sure the default orientation is optimal
1758 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001759 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001760 mGlobalTransform = mTransform;
1761 return NO_ERROR;
1762 }
1763
1764 // If the rotation can be handled in hardware, this is where
1765 // the magic should happen.
1766 if (UNLIKELY(orientation == 42)) {
1767 float a, b, c, d, x, y;
1768 const float r = (3.14159265f / 180.0f) * 42.0f;
1769 const float si = sinf(r);
1770 const float co = cosf(r);
1771 a=co; b=-si; c=si; d=co;
1772 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1773 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1774 mOrientationTransform.set(a, b, c, d);
1775 mOrientationTransform.set(x, y);
1776 } else {
1777 GraphicPlane::orientationToTransfrom(orientation, w, h,
1778 &mOrientationTransform);
1779 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001780 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781 mGlobalTransform = mOrientationTransform * mTransform;
1782 return NO_ERROR;
1783}
1784
1785const DisplayHardware& GraphicPlane::displayHardware() const {
1786 return *mHw;
1787}
1788
1789const Transform& GraphicPlane::transform() const {
1790 return mGlobalTransform;
1791}
1792
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001793EGLDisplay GraphicPlane::getEGLDisplay() const {
1794 return mHw->getEGLDisplay();
1795}
1796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797// ---------------------------------------------------------------------------
1798
1799}; // namespace android