blob: e0728ebda33538ec7af1de6d07dc38d51cc235dc [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054
55#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#define DISPLAY_COUNT 1
58
59namespace android {
60
61// ---------------------------------------------------------------------------
62
63void SurfaceFlinger::instantiate() {
64 defaultServiceManager()->addService(
65 String16("SurfaceFlinger"), new SurfaceFlinger());
66}
67
68void SurfaceFlinger::shutdown() {
69 // we should unregister here, but not really because
70 // when (if) the service manager goes away, all the services
71 // it has a reference to will leave too.
72}
73
74// ---------------------------------------------------------------------------
75
76SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
77 : lookup(rhs.lookup), layers(rhs.layers)
78{
79}
80
81ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070082 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083{
84 if (guess<size() && lookup.keyAt(guess) == key)
85 return guess;
86 const ssize_t i = lookup.indexOfKey(key);
87 if (i>=0) {
88 const size_t idx = lookup.valueAt(i);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070089 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070091 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092 return idx;
93 }
94 return i;
95}
96
97ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070098 const sp<LayerBase>& layer,
99 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100{
101 size_t count = layers.size();
102 ssize_t l = 0;
103 ssize_t h = count-1;
104 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700105 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106 while (l <= h) {
107 mid = l + (h - l)/2;
108 const int c = cmp(a+mid, &layer);
109 if (c == 0) { l = mid; break; }
110 else if (c<0) { l = mid+1; }
111 else { h = mid-1; }
112 }
113 size_t order = l;
114 while (order<count && !cmp(&layer, a+order)) {
115 order++;
116 }
117 count = lookup.size();
118 for (size_t i=0 ; i<count ; i++) {
119 if (lookup.valueAt(i) >= order) {
120 lookup.editValueAt(i)++;
121 }
122 }
123 layers.insertAt(layer, order);
124 lookup.add(layer, order);
125 return order;
126}
127
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700128ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129{
130 const ssize_t keyIndex = lookup.indexOfKey(layer);
131 if (keyIndex >= 0) {
132 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700133 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 layers.removeItemsAt(index);
137 lookup.removeItemsAt(keyIndex);
138 const size_t count = lookup.size();
139 for (size_t i=0 ; i<count ; i++) {
140 if (lookup.valueAt(i) >= size_t(index)) {
141 lookup.editValueAt(i)--;
142 }
143 }
144 return index;
145 }
146 return NAME_NOT_FOUND;
147}
148
149ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700150 const sp<LayerBase>& layer,
151 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152{
153 // XXX: it's a little lame. but oh well...
154 ssize_t err = remove(layer);
155 if (err >=0)
156 err = add(layer, cmp);
157 return err;
158}
159
160// ---------------------------------------------------------------------------
161#if 0
162#pragma mark -
163#endif
164
165SurfaceFlinger::SurfaceFlinger()
166 : BnSurfaceComposer(), Thread(false),
167 mTransactionFlags(0),
168 mTransactionCount(0),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700169 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 mBootTime(systemTime()),
171 mLastScheduledBroadcast(NULL),
172 mVisibleRegionsDirty(false),
173 mDeferReleaseConsole(false),
174 mFreezeDisplay(false),
175 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700176 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugBackground(0),
179 mDebugNoBootAnimation(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 mConsoleSignals(0),
181 mSecureFrameBuffer(0)
182{
183 init();
184}
185
186void SurfaceFlinger::init()
187{
188 LOGI("SurfaceFlinger is starting");
189
190 // debugging stuff...
191 char value[PROPERTY_VALUE_MAX];
192 property_get("debug.sf.showupdates", value, "0");
193 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 property_get("debug.sf.showbackground", value, "0");
195 mDebugBackground = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 property_get("debug.sf.nobootanimation", value, "0");
197 mDebugNoBootAnimation = atoi(value);
198
199 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
202}
203
204SurfaceFlinger::~SurfaceFlinger()
205{
206 glDeleteTextures(1, &mWormholeTexName);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207}
208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
210{
211 return graphicPlane(0).displayHardware().getOverlayEngine();
212}
213
214sp<IMemory> SurfaceFlinger::getCblk() const
215{
216 return mServerCblkMemory;
217}
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
220{
221 Mutex::Autolock _l(mStateLock);
222 uint32_t token = mTokens.acquire();
223
224 Client* client = new Client(token, this);
225 if ((client == 0) || (client->ctrlblk == 0)) {
226 mTokens.release(token);
227 return 0;
228 }
229 status_t err = mClientsMap.add(token, client);
230 if (err < 0) {
231 delete client;
232 mTokens.release(token);
233 return 0;
234 }
235 sp<BClient> bclient =
236 new BClient(this, token, client->controlBlockMemory());
237 return bclient;
238}
239
240void SurfaceFlinger::destroyConnection(ClientID cid)
241{
242 Mutex::Autolock _l(mStateLock);
243 Client* const client = mClientsMap.valueFor(cid);
244 if (client) {
245 // free all the layers this client owns
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700246 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 const size_t count = layers.size();
248 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 sp<LayerBaseClient> layer(layers[i].promote());
250 if (layer != 0) {
251 removeLayer_l(layer);
252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 }
254
255 // the resources associated with this client will be freed
256 // during the next transaction, after these surfaces have been
257 // properly removed from the screen
258
259 // remove this client from our ClientID->Client mapping.
260 mClientsMap.removeItem(cid);
261
262 // and add it to the list of disconnected clients
263 mDisconnectedClients.add(client);
264
265 // request a transaction
266 setTransactionFlags(eTransactionNeeded);
267 }
268}
269
270const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
271{
272 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
273 const GraphicPlane& plane(mGraphicPlanes[dpy]);
274 return plane;
275}
276
277GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
278{
279 return const_cast<GraphicPlane&>(
280 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
281}
282
283void SurfaceFlinger::bootFinished()
284{
285 const nsecs_t now = systemTime();
286 const nsecs_t duration = now - mBootTime;
287 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
288 if (mBootAnimation != 0) {
289 mBootAnimation->requestExit();
290 mBootAnimation.clear();
291 }
292}
293
294void SurfaceFlinger::onFirstRef()
295{
296 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
297
298 // Wait for the main thread to be done with its initialization
299 mReadyToRunBarrier.wait();
300}
301
302
303static inline uint16_t pack565(int r, int g, int b) {
304 return (r<<11)|(g<<5)|b;
305}
306
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307status_t SurfaceFlinger::readyToRun()
308{
309 LOGI( "SurfaceFlinger's main thread ready to run. "
310 "Initializing graphics H/W...");
311
312 // create the shared control-block
313 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
314 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
315
316 mServerCblkMemory = mServerHeap->allocate(4096);
317 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
318
319 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
320 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
321 new(mServerCblk) surface_flinger_cblk_t;
322
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 // we only support one display currently
324 int dpy = 0;
325
326 {
327 // initialize the main display
328 GraphicPlane& plane(graphicPlane(dpy));
329 DisplayHardware* const hw = new DisplayHardware(this, dpy);
330 plane.setDisplayHardware(hw);
331 }
332
333 // initialize primary screen
334 // (other display should be initialized in the same manner, but
335 // asynchronously, as they could come and go. None of this is supported
336 // yet).
337 const GraphicPlane& plane(graphicPlane(dpy));
338 const DisplayHardware& hw = plane.displayHardware();
339 const uint32_t w = hw.getWidth();
340 const uint32_t h = hw.getHeight();
341 const uint32_t f = hw.getFormat();
342 hw.makeCurrent();
343
344 // initialize the shared control block
345 mServerCblk->connected |= 1<<dpy;
346 display_cblk_t* dcblk = mServerCblk->displays + dpy;
347 memset(dcblk, 0, sizeof(display_cblk_t));
348 dcblk->w = w;
349 dcblk->h = h;
350 dcblk->format = f;
351 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
352 dcblk->xdpi = hw.getDpiX();
353 dcblk->ydpi = hw.getDpiY();
354 dcblk->fps = hw.getRefreshRate();
355 dcblk->density = hw.getDensity();
356 asm volatile ("":::"memory");
357
358 // Initialize OpenGL|ES
359 glActiveTexture(GL_TEXTURE0);
360 glBindTexture(GL_TEXTURE_2D, 0);
361 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
362 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
363 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
364 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
365 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
366 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
367 glPixelStorei(GL_PACK_ALIGNMENT, 4);
368 glEnableClientState(GL_VERTEX_ARRAY);
369 glEnable(GL_SCISSOR_TEST);
370 glShadeModel(GL_FLAT);
371 glDisable(GL_DITHER);
372 glDisable(GL_CULL_FACE);
373
374 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
375 const uint16_t g1 = pack565(0x17,0x2f,0x17);
376 const uint16_t textureData[4] = { g0, g1, g1, g0 };
377 glGenTextures(1, &mWormholeTexName);
378 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
379 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
380 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
381 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
382 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
383 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
384 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
385
386 glViewport(0, 0, w, h);
387 glMatrixMode(GL_PROJECTION);
388 glLoadIdentity();
389 glOrthof(0, w, h, 0, 0, 1);
390
391 LayerDim::initDimmer(this, w, h);
392
393 mReadyToRunBarrier.open();
394
395 /*
396 * We're now ready to accept clients...
397 */
398
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 // the boot animation!
400 if (mDebugNoBootAnimation == false)
401 mBootAnimation = new BootAnimation(this);
402
403 return NO_ERROR;
404}
405
406// ----------------------------------------------------------------------------
407#if 0
408#pragma mark -
409#pragma mark Events Handler
410#endif
411
412void SurfaceFlinger::waitForEvent()
413{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700414 while (true) {
415 nsecs_t timeout = -1;
416 if (UNLIKELY(isFrozen())) {
417 // wait 5 seconds
418 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
419 const nsecs_t now = systemTime();
420 if (mFreezeDisplayTime == 0) {
421 mFreezeDisplayTime = now;
422 }
423 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
424 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700425 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700426
Mathias Agopianb6683b52009-04-28 03:17:50 -0700427 MessageList::value_type msg = mEventQueue.waitMessage(timeout);
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700428 if (msg != 0) {
429 mFreezeDisplayTime = 0;
430 switch (msg->what) {
431 case MessageQueue::INVALIDATE:
432 // invalidate message, just return to the main loop
433 return;
434 }
435 } else {
436 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 if (isFrozen()) {
438 // we timed out and are still frozen
439 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
440 mFreezeDisplay, mFreezeCount);
441 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700442 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700443 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 }
447}
448
449void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700450 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451}
452
453void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700454 // this is the IPC call
455 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456}
457
458void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
459{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700460 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800461}
462
463// ----------------------------------------------------------------------------
464#if 0
465#pragma mark -
466#pragma mark Main loop
467#endif
468
469bool SurfaceFlinger::threadLoop()
470{
471 waitForEvent();
472
473 // check for transactions
474 if (UNLIKELY(mConsoleSignals)) {
475 handleConsoleEvents();
476 }
477
478 if (LIKELY(mTransactionCount == 0)) {
479 // if we're in a global transaction, don't do anything.
480 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
481 uint32_t transactionFlags = getTransactionFlags(mask);
482 if (LIKELY(transactionFlags)) {
483 handleTransaction(transactionFlags);
484 }
485 }
486
487 // post surfaces (if needed)
488 handlePageFlip();
489
490 const DisplayHardware& hw(graphicPlane(0).displayHardware());
491 if (LIKELY(hw.canDraw())) {
492 // repaint the framebuffer (if needed)
493 handleRepaint();
494
495 // release the clients before we flip ('cause flip might block)
496 unlockClients();
497 executeScheduledBroadcasts();
498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800499 postFramebuffer();
500 } else {
501 // pretend we did the post
502 unlockClients();
503 executeScheduledBroadcasts();
504 usleep(16667); // 60 fps period
505 }
506 return true;
507}
508
509void SurfaceFlinger::postFramebuffer()
510{
Mathias Agopian0926f502009-05-04 14:17:04 -0700511 if (isFrozen()) {
512 // we are not allowed to draw, but pause a bit to make sure
513 // apps don't end up using the whole CPU, if they depend on
514 // surfaceflinger for synchronization.
515 usleep(8333); // 8.3ms ~ 120fps
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 return;
517 }
518
519 if (!mInvalidRegion.isEmpty()) {
520 const DisplayHardware& hw(graphicPlane(0).displayHardware());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522 mInvalidRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 }
524}
525
526void SurfaceFlinger::handleConsoleEvents()
527{
528 // something to do with the console
529 const DisplayHardware& hw = graphicPlane(0).displayHardware();
530
531 int what = android_atomic_and(0, &mConsoleSignals);
532 if (what & eConsoleAcquired) {
533 hw.acquireScreen();
534 }
535
536 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700537 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 hw.releaseScreen();
540 }
541
542 if (what & eConsoleReleased) {
543 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544 hw.releaseScreen();
545 } else {
546 mDeferReleaseConsole = true;
547 }
548 }
549
550 mDirtyRegion.set(hw.bounds());
551}
552
553void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
554{
555 Mutex::Autolock _l(mStateLock);
556
557 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
558 const size_t count = currentLayers.size();
559
560 /*
561 * Traversal of the children
562 * (perform the transaction for each of them if needed)
563 */
564
565 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
566 if (layersNeedTransaction) {
567 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700568 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
570 if (!trFlags) continue;
571
572 const uint32_t flags = layer->doTransaction(0);
573 if (flags & Layer::eVisibleRegion)
574 mVisibleRegionsDirty = true;
575
576 if (flags & Layer::eRestartTransaction) {
577 // restart the transaction, but back-off a little
578 layer->setTransactionFlags(eTransactionNeeded);
579 setTransactionFlags(eTraversalNeeded, ms2ns(8));
580 }
581 }
582 }
583
584 /*
585 * Perform our own transaction if needed
586 */
587
588 if (transactionFlags & eTransactionNeeded) {
589 if (mCurrentState.orientation != mDrawingState.orientation) {
590 // the orientation has changed, recompute all visible regions
591 // and invalidate everything.
592
593 const int dpy = 0;
594 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700595 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596 GraphicPlane& plane(graphicPlane(dpy));
597 plane.setOrientation(orientation);
598
599 // update the shared control block
600 const DisplayHardware& hw(plane.displayHardware());
601 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
602 dcblk->orientation = orientation;
603 if (orientation & eOrientationSwapMask) {
604 // 90 or 270 degrees orientation
605 dcblk->w = hw.getHeight();
606 dcblk->h = hw.getWidth();
607 } else {
608 dcblk->w = hw.getWidth();
609 dcblk->h = hw.getHeight();
610 }
611
612 mVisibleRegionsDirty = true;
613 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700614 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800615 }
616
617 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
618 // freezing or unfreezing the display -> trigger animation if needed
619 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800620 }
621
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700622 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
623 // layers have been added
624 mVisibleRegionsDirty = true;
625 }
626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627 // some layers might have been removed, so
628 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700629 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700631 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
632 const ssize_t count = previousLayers.size();
633 for (ssize_t i=0 ; i<count ; i++) {
634 const sp<LayerBase>& layer(previousLayers[i]);
635 if (currentLayers.indexOf( layer ) < 0) {
636 // this layer is not visible anymore
637 // FIXME: would be better to call without the lock held
638 //LOGD("ditching layer %p", layer.get());
639 layer->ditch();
640 }
641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 }
643
644 // get rid of all resources we don't need anymore
645 // (layers and clients)
646 free_resources_l();
647 }
648
649 commitTransaction();
650}
651
652sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
653{
654 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
655}
656
657void SurfaceFlinger::computeVisibleRegions(
658 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
659{
660 const GraphicPlane& plane(graphicPlane(0));
661 const Transform& planeTransform(plane.transform());
662
663 Region aboveOpaqueLayers;
664 Region aboveCoveredLayers;
665 Region dirty;
666
667 bool secureFrameBuffer = false;
668
669 size_t i = currentLayers.size();
670 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700671 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672 layer->validateVisibility(planeTransform);
673
674 // start with the whole surface at its current location
675 const Layer::State& s = layer->drawingState();
676 const Rect bounds(layer->visibleBounds());
677
678 // handle hidden surfaces by setting the visible region to empty
679 Region opaqueRegion;
680 Region visibleRegion;
681 Region coveredRegion;
682 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
683 visibleRegion.clear();
684 } else {
685 const bool translucent = layer->needsBlending();
686 visibleRegion.set(bounds);
687 coveredRegion = visibleRegion;
688
689 // Remove the transparent area from the visible region
690 if (translucent) {
691 visibleRegion.subtractSelf(layer->transparentRegionScreen);
692 }
693
694 // compute the opaque region
695 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
696 // the opaque region is the visible region
697 opaqueRegion = visibleRegion;
698 }
699 }
700
701 // subtract the opaque region covered by the layers above us
702 visibleRegion.subtractSelf(aboveOpaqueLayers);
703 coveredRegion.andSelf(aboveCoveredLayers);
704
705 // compute this layer's dirty region
706 if (layer->contentDirty) {
707 // we need to invalidate the whole region
708 dirty = visibleRegion;
709 // as well, as the old visible region
710 dirty.orSelf(layer->visibleRegionScreen);
711 layer->contentDirty = false;
712 } else {
713 // compute the exposed region
714 // dirty = what's visible now - what's wasn't covered before
715 // = what's visible now & what's was covered before
716 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
717 }
718 dirty.subtractSelf(aboveOpaqueLayers);
719
720 // accumulate to the screen dirty region
721 dirtyRegion.orSelf(dirty);
722
Mathias Agopian62b74442009-04-14 23:02:51 -0700723 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724 aboveOpaqueLayers.orSelf(opaqueRegion);
725 aboveCoveredLayers.orSelf(bounds);
726
727 // Store the visible region is screen space
728 layer->setVisibleRegion(visibleRegion);
729 layer->setCoveredRegion(coveredRegion);
730
Mathias Agopian62b74442009-04-14 23:02:51 -0700731 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732 if (layer->isSecure() && !visibleRegion.isEmpty()) {
733 secureFrameBuffer = true;
734 }
735 }
736
737 mSecureFrameBuffer = secureFrameBuffer;
738 opaqueRegion = aboveOpaqueLayers;
739}
740
741
742void SurfaceFlinger::commitTransaction()
743{
744 mDrawingState = mCurrentState;
745 mTransactionCV.signal();
746}
747
748void SurfaceFlinger::handlePageFlip()
749{
750 bool visibleRegions = mVisibleRegionsDirty;
751 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
752 visibleRegions |= lockPageFlip(currentLayers);
753
754 const DisplayHardware& hw = graphicPlane(0).displayHardware();
755 const Region screenRegion(hw.bounds());
756 if (visibleRegions) {
757 Region opaqueRegion;
758 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
759 mWormholeRegion = screenRegion.subtract(opaqueRegion);
760 mVisibleRegionsDirty = false;
761 }
762
763 unlockPageFlip(currentLayers);
764 mDirtyRegion.andSelf(screenRegion);
765}
766
767bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
768{
769 bool recomputeVisibleRegions = false;
770 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700771 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700773 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800774 layer->lockPageFlip(recomputeVisibleRegions);
775 }
776 return recomputeVisibleRegions;
777}
778
779void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
780{
781 const GraphicPlane& plane(graphicPlane(0));
782 const Transform& planeTransform(plane.transform());
783 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700784 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700786 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800787 layer->unlockPageFlip(planeTransform, mDirtyRegion);
788 }
789}
790
791void SurfaceFlinger::handleRepaint()
792{
793 // set the frame buffer
794 const DisplayHardware& hw(graphicPlane(0).displayHardware());
795 glMatrixMode(GL_MODELVIEW);
796 glLoadIdentity();
797
798 if (UNLIKELY(mDebugRegion)) {
799 debugFlashRegions();
800 }
801
802 // compute the invalid region
803 mInvalidRegion.orSelf(mDirtyRegion);
804
805 uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700806 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
807 (flags & DisplayHardware::BUFFER_PRESERVED))
808 {
809 // we can redraw only what's dirty
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800810 } else {
811 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700812 // we need to redraw the rectangle that will be updated
813 // (pushed to the framebuffer).
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814 mDirtyRegion.set(mInvalidRegion.bounds());
815 } else {
816 // we need to redraw everything
817 mDirtyRegion.set(hw.bounds());
818 mInvalidRegion = mDirtyRegion;
819 }
820 }
821
822 // compose all surfaces
823 composeSurfaces(mDirtyRegion);
824
825 // clear the dirty regions
826 mDirtyRegion.clear();
827}
828
829void SurfaceFlinger::composeSurfaces(const Region& dirty)
830{
831 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
832 // should never happen unless the window manager has a bug
833 // draw something...
834 drawWormhole();
835 }
836 const SurfaceFlinger& flinger(*this);
837 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
838 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700839 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700841 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842 const Region& visibleRegion(layer->visibleRegionScreen);
843 if (!visibleRegion.isEmpty()) {
844 const Region clip(dirty.intersect(visibleRegion));
845 if (!clip.isEmpty()) {
846 layer->draw(clip);
847 }
848 }
849 }
850}
851
852void SurfaceFlinger::unlockClients()
853{
854 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
855 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700856 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700858 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859 layer->finishPageFlip();
860 }
861}
862
863void SurfaceFlinger::scheduleBroadcast(Client* client)
864{
865 if (mLastScheduledBroadcast != client) {
866 mLastScheduledBroadcast = client;
867 mScheduledBroadcasts.add(client);
868 }
869}
870
871void SurfaceFlinger::executeScheduledBroadcasts()
872{
873 SortedVector<Client*>& list = mScheduledBroadcasts;
874 size_t count = list.size();
875 while (count--) {
876 per_client_cblk_t* const cblk = list[count]->ctrlblk;
877 if (cblk->lock.tryLock() == NO_ERROR) {
878 cblk->cv.broadcast();
879 list.removeAt(count);
880 cblk->lock.unlock();
881 } else {
882 // schedule another round
883 LOGW("executeScheduledBroadcasts() skipped, "
884 "contention on the client. We'll try again later...");
885 signalDelayedEvent(ms2ns(4));
886 }
887 }
888 mLastScheduledBroadcast = 0;
889}
890
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800891void SurfaceFlinger::debugFlashRegions()
892{
Mathias Agopian0926f502009-05-04 14:17:04 -0700893 const DisplayHardware& hw(graphicPlane(0).displayHardware());
894 const uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700895
896 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
897 (flags & DisplayHardware::BUFFER_PRESERVED))) {
Mathias Agopian0926f502009-05-04 14:17:04 -0700898 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
899 mDirtyRegion.bounds() : hw.bounds());
900 composeSurfaces(repaint);
901 }
902
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800903 glDisable(GL_TEXTURE_2D);
904 glDisable(GL_BLEND);
905 glDisable(GL_DITHER);
906 glDisable(GL_SCISSOR_TEST);
907
Mathias Agopian0926f502009-05-04 14:17:04 -0700908 static int toggle = 0;
909 toggle = 1 - toggle;
910 if (toggle) {
911 glColor4x(0x10000, 0, 0x10000, 0x10000);
912 } else {
913 glColor4x(0x10000, 0x10000, 0, 0x10000);
914 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800915
Mathias Agopian20f68782009-05-11 00:03:41 -0700916 Region::const_iterator it = mDirtyRegion.begin();
917 Region::const_iterator const end = mDirtyRegion.end();
918 while (it != end) {
919 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800920 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 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700929
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800930 hw.flip(mDirtyRegion.merge(mInvalidRegion));
931 mInvalidRegion.clear();
932
933 if (mDebugRegion > 1)
934 usleep(mDebugRegion * 1000);
935
936 glEnable(GL_SCISSOR_TEST);
937 //mDirtyRegion.dump("mDirtyRegion");
938}
939
940void SurfaceFlinger::drawWormhole() const
941{
942 const Region region(mWormholeRegion.intersect(mDirtyRegion));
943 if (region.isEmpty())
944 return;
945
946 const DisplayHardware& hw(graphicPlane(0).displayHardware());
947 const int32_t width = hw.getWidth();
948 const int32_t height = hw.getHeight();
949
950 glDisable(GL_BLEND);
951 glDisable(GL_DITHER);
952
953 if (LIKELY(!mDebugBackground)) {
954 glClearColorx(0,0,0,0);
Mathias Agopian20f68782009-05-11 00:03:41 -0700955 Region::const_iterator it = region.begin();
956 Region::const_iterator const end = region.end();
957 while (it != end) {
958 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800959 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);
Mathias Agopian20f68782009-05-11 00:03:41 -0700976 Region::const_iterator it = region.begin();
977 Region::const_iterator const end = region.end();
978 while (it != end) {
979 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800980 const GLint sy = height - (r.top + r.height());
981 glScissor(r.left, sy, r.width(), r.height());
982 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
983 }
984 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
985 }
986}
987
988void SurfaceFlinger::debugShowFPS() const
989{
990 static int mFrameCount;
991 static int mLastFrameCount = 0;
992 static nsecs_t mLastFpsTime = 0;
993 static float mFps = 0;
994 mFrameCount++;
995 nsecs_t now = systemTime();
996 nsecs_t diff = now - mLastFpsTime;
997 if (diff > ms2ns(250)) {
998 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
999 mLastFpsTime = now;
1000 mLastFrameCount = mFrameCount;
1001 }
1002 // XXX: mFPS has the value we want
1003 }
1004
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001005status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001006{
1007 Mutex::Autolock _l(mStateLock);
1008 addLayer_l(layer);
1009 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1010 return NO_ERROR;
1011}
1012
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001013status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001014{
1015 Mutex::Autolock _l(mStateLock);
1016 removeLayer_l(layer);
1017 setTransactionFlags(eTransactionNeeded);
1018 return NO_ERROR;
1019}
1020
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001021status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001022{
1023 layer->forceVisibilityTransaction();
1024 setTransactionFlags(eTraversalNeeded);
1025 return NO_ERROR;
1026}
1027
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001028status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029{
1030 ssize_t i = mCurrentState.layersSortedByZ.add(
1031 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001032 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1033 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001034 mLayerMap.add(lbc->serverIndex(), lbc);
1035 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036 return NO_ERROR;
1037}
1038
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001039status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040{
1041 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1042 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001043 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001044 sp<LayerBaseClient> layer =
1045 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001046 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047 mLayerMap.removeItem(layer->serverIndex());
1048 }
1049 return NO_ERROR;
1050 }
1051 // it's possible that we don't find a layer, because it might
1052 // have been destroyed already -- this is not technically an error
Mathias Agopian9a112062009-04-17 19:36:26 -07001053 // from the user because there is a race between BClient::destroySurface(),
1054 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001055 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1056}
1057
Mathias Agopian9a112062009-04-17 19:36:26 -07001058status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1059{
1060 // First add the layer to the purgatory list, which makes sure it won't
1061 // go away, then remove it from the main list (through a transaction).
1062 ssize_t err = removeLayer_l(layerBase);
1063 if (err >= 0) {
1064 mLayerPurgatory.add(layerBase);
1065 }
1066 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1067}
1068
1069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070void SurfaceFlinger::free_resources_l()
1071{
1072 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001073 mLayersRemoved = false;
1074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075 // free resources associated with disconnected clients
1076 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1077 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1078 const size_t count = disconnectedClients.size();
1079 for (size_t i=0 ; i<count ; i++) {
1080 Client* client = disconnectedClients[i];
1081 // if this client is the scheduled broadcast list,
1082 // remove it from there (and we don't need to signal it
1083 // since it is dead).
1084 int32_t index = scheduledBroadcasts.indexOf(client);
1085 if (index >= 0) {
1086 scheduledBroadcasts.removeItemsAt(index);
1087 }
1088 mTokens.release(client->cid);
1089 delete client;
1090 }
1091 disconnectedClients.clear();
1092}
1093
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001094uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1095{
1096 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1097}
1098
1099uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1100{
1101 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1102 if ((old & flags)==0) { // wake the server up
1103 if (delay > 0) {
1104 signalDelayedEvent(delay);
1105 } else {
1106 signalEvent();
1107 }
1108 }
1109 return old;
1110}
1111
1112void SurfaceFlinger::openGlobalTransaction()
1113{
1114 android_atomic_inc(&mTransactionCount);
1115}
1116
1117void SurfaceFlinger::closeGlobalTransaction()
1118{
1119 if (android_atomic_dec(&mTransactionCount) == 1) {
1120 signalEvent();
1121 }
1122}
1123
1124status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1125{
1126 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1127 return BAD_VALUE;
1128
1129 Mutex::Autolock _l(mStateLock);
1130 mCurrentState.freezeDisplay = 1;
1131 setTransactionFlags(eTransactionNeeded);
1132
1133 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001134 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001135 return NO_ERROR;
1136}
1137
1138status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1139{
1140 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1141 return BAD_VALUE;
1142
1143 Mutex::Autolock _l(mStateLock);
1144 mCurrentState.freezeDisplay = 0;
1145 setTransactionFlags(eTransactionNeeded);
1146
1147 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001148 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001149 return NO_ERROR;
1150}
1151
Mathias Agopianc08731e2009-03-27 18:11:38 -07001152int SurfaceFlinger::setOrientation(DisplayID dpy,
1153 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154{
1155 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1156 return BAD_VALUE;
1157
1158 Mutex::Autolock _l(mStateLock);
1159 if (mCurrentState.orientation != orientation) {
1160 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001161 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162 mCurrentState.orientation = orientation;
1163 setTransactionFlags(eTransactionNeeded);
1164 mTransactionCV.wait(mStateLock);
1165 } else {
1166 orientation = BAD_VALUE;
1167 }
1168 }
1169 return orientation;
1170}
1171
1172sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1173 ISurfaceFlingerClient::surface_data_t* params,
1174 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1175 uint32_t flags)
1176{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001177 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178 sp<LayerBaseClient::Surface> surfaceHandle;
1179 Mutex::Autolock _l(mStateLock);
1180 Client* const c = mClientsMap.valueFor(clientId);
1181 if (UNLIKELY(!c)) {
1182 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1183 return surfaceHandle;
1184 }
1185
1186 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1187 int32_t id = c->generateId(pid);
1188 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1189 LOGE("createSurface() failed, generateId = %d", id);
1190 return surfaceHandle;
1191 }
1192
1193 switch (flags & eFXSurfaceMask) {
1194 case eFXSurfaceNormal:
1195 if (UNLIKELY(flags & ePushBuffers)) {
1196 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1197 } else {
1198 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1199 }
1200 break;
1201 case eFXSurfaceBlur:
1202 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1203 break;
1204 case eFXSurfaceDim:
1205 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1206 break;
1207 }
1208
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001209 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001210 setTransactionFlags(eTransactionNeeded);
1211 surfaceHandle = layer->getSurface();
1212 if (surfaceHandle != 0)
1213 surfaceHandle->getSurfaceData(params);
1214 }
1215
1216 return surfaceHandle;
1217}
1218
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001219sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001220 Client* client, DisplayID display,
1221 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1222{
1223 // initialize the surfaces
1224 switch (format) { // TODO: take h/w into account
1225 case PIXEL_FORMAT_TRANSPARENT:
1226 case PIXEL_FORMAT_TRANSLUCENT:
1227 format = PIXEL_FORMAT_RGBA_8888;
1228 break;
1229 case PIXEL_FORMAT_OPAQUE:
1230 format = PIXEL_FORMAT_RGB_565;
1231 break;
1232 }
1233
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001234 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001235 status_t err = layer->setBuffers(client, w, h, format, flags);
1236 if (LIKELY(err == NO_ERROR)) {
1237 layer->initStates(w, h, flags);
1238 addLayer_l(layer);
1239 } else {
1240 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001241 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242 }
1243 return layer;
1244}
1245
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001246sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247 Client* client, DisplayID display,
1248 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1249{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001250 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001251 layer->initStates(w, h, flags);
1252 addLayer_l(layer);
1253 return layer;
1254}
1255
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001256sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257 Client* client, DisplayID display,
1258 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1259{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001260 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261 layer->initStates(w, h, flags);
1262 addLayer_l(layer);
1263 return layer;
1264}
1265
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001266sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001267 Client* client, DisplayID display,
1268 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1269{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001270 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001271 layer->initStates(w, h, flags);
1272 addLayer_l(layer);
1273 return layer;
1274}
1275
Mathias Agopian9a112062009-04-17 19:36:26 -07001276status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001277{
Mathias Agopian9a112062009-04-17 19:36:26 -07001278 /*
1279 * called by the window manager, when a surface should be marked for
1280 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001281 *
1282 * The surface is removed from the current and drawing lists, but placed
1283 * in the purgatory queue, so it's not destroyed right-away (we need
1284 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001285 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001286
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001287 Mutex::Autolock _l(mStateLock);
1288 sp<LayerBaseClient> layer = getLayerUser_l(index);
1289 status_t err = purgatorizeLayer_l(layer);
1290 if (err == NO_ERROR) {
1291 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001292 }
1293 return err;
1294}
1295
1296status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1297{
1298 /*
1299 * called by ~ISurface() when all references are gone
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001300 *
1301 * the surface must be removed from purgatory from the main thread
1302 * since its dtor must run from there (b/c of OpenGL ES).
Mathias Agopian9a112062009-04-17 19:36:26 -07001303 */
1304
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001305 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001306 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001307 sp<LayerBaseClient> layer;
1308 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001309 MessageDestroySurface(
1310 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1311 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001312 virtual bool handler() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001313 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001314 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1315 LOGE_IF(idx<0, "layer=%p is not in the purgatory list", layer.get());
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001316 return true;
1317 }
1318 };
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001319 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320 return NO_ERROR;
1321}
1322
1323status_t SurfaceFlinger::setClientState(
1324 ClientID cid,
1325 int32_t count,
1326 const layer_state_t* states)
1327{
1328 Mutex::Autolock _l(mStateLock);
1329 uint32_t flags = 0;
1330 cid <<= 16;
1331 for (int i=0 ; i<count ; i++) {
1332 const layer_state_t& s = states[i];
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001333 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1334 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001335 const uint32_t what = s.what;
1336 // check if it has been destroyed first
1337 if (what & eDestroyed) {
1338 if (removeLayer_l(layer) == NO_ERROR) {
1339 flags |= eTransactionNeeded;
1340 // we skip everything else... well, no, not really
1341 // we skip ONLY that transaction.
1342 continue;
1343 }
1344 }
1345 if (what & ePositionChanged) {
1346 if (layer->setPosition(s.x, s.y))
1347 flags |= eTraversalNeeded;
1348 }
1349 if (what & eLayerChanged) {
1350 if (layer->setLayer(s.z)) {
1351 mCurrentState.layersSortedByZ.reorder(
1352 layer, &Layer::compareCurrentStateZ);
1353 // we need traversal (state changed)
1354 // AND transaction (list changed)
1355 flags |= eTransactionNeeded|eTraversalNeeded;
1356 }
1357 }
1358 if (what & eSizeChanged) {
1359 if (layer->setSize(s.w, s.h))
1360 flags |= eTraversalNeeded;
1361 }
1362 if (what & eAlphaChanged) {
1363 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1364 flags |= eTraversalNeeded;
1365 }
1366 if (what & eMatrixChanged) {
1367 if (layer->setMatrix(s.matrix))
1368 flags |= eTraversalNeeded;
1369 }
1370 if (what & eTransparentRegionChanged) {
1371 if (layer->setTransparentRegionHint(s.transparentRegion))
1372 flags |= eTraversalNeeded;
1373 }
1374 if (what & eVisibilityChanged) {
1375 if (layer->setFlags(s.flags, s.mask))
1376 flags |= eTraversalNeeded;
1377 }
1378 }
1379 }
1380 if (flags) {
1381 setTransactionFlags(flags);
1382 }
1383 return NO_ERROR;
1384}
1385
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001386sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001388 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1389 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001390}
1391
1392void SurfaceFlinger::screenReleased(int dpy)
1393{
1394 // this may be called by a signal handler, we can't do too much in here
1395 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1396 signalEvent();
1397}
1398
1399void SurfaceFlinger::screenAcquired(int dpy)
1400{
1401 // this may be called by a signal handler, we can't do too much in here
1402 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1403 signalEvent();
1404}
1405
1406status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1407{
1408 const size_t SIZE = 1024;
1409 char buffer[SIZE];
1410 String8 result;
1411 if (checkCallingPermission(
1412 String16("android.permission.DUMP")) == false)
1413 { // not allowed
1414 snprintf(buffer, SIZE, "Permission Denial: "
1415 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1416 IPCThreadState::self()->getCallingPid(),
1417 IPCThreadState::self()->getCallingUid());
1418 result.append(buffer);
1419 } else {
1420 Mutex::Autolock _l(mStateLock);
1421 size_t s = mClientsMap.size();
1422 char name[64];
1423 for (size_t i=0 ; i<s ; i++) {
1424 Client* client = mClientsMap.valueAt(i);
1425 sprintf(name, " Client (id=0x%08x)", client->cid);
1426 client->dump(name);
1427 }
1428 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1429 const size_t count = currentLayers.size();
1430 for (size_t i=0 ; i<count ; i++) {
1431 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001432 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001433 const Layer::State& s = layer->drawingState();
1434 snprintf(buffer, SIZE,
1435 "+ %s %p\n"
1436 " "
1437 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1438 "needsBlending=%1d, invalidate=%1d, "
1439 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001440 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001441 s.z, layer->tx(), layer->ty(), s.w, s.h,
1442 layer->needsBlending(), layer->contentDirty,
1443 s.alpha, s.flags,
1444 s.transform[0], s.transform[1],
1445 s.transform[2], s.transform[3]);
1446 result.append(buffer);
1447 buffer[0] = 0;
1448 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001449 sp<LayerBaseClient> lbc =
1450 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1451 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452 snprintf(buffer, SIZE,
1453 " "
1454 "id=0x%08x, client=0x%08x, identity=%u\n",
1455 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1456 lbc->getIdentity());
1457 }
1458 result.append(buffer);
1459 buffer[0] = 0;
1460 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001461 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1462 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463 const LayerBitmap& buf0(l->getBuffer(0));
1464 const LayerBitmap& buf1(l->getBuffer(1));
1465 snprintf(buffer, SIZE,
1466 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001467 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468 " freezeLock=%p, swapState=0x%08x\n",
1469 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001470 buf0.getWidth(), buf0.getHeight(),
1471 buf0.getBuffer()->getStride(),
1472 buf1.getWidth(), buf1.getHeight(),
1473 buf1.getBuffer()->getStride(),
1474 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001475 l->lcblk->swapState);
1476 }
1477 result.append(buffer);
1478 buffer[0] = 0;
1479 s.transparentRegion.dump(result, "transparentRegion");
1480 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1481 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1482 }
1483 mWormholeRegion.dump(result, "WormholeRegion");
1484 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1485 snprintf(buffer, SIZE,
1486 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1487 mFreezeDisplay?"yes":"no", mFreezeCount,
1488 mCurrentState.orientation, hw.canDraw());
1489 result.append(buffer);
1490
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001491 const BufferAllocator& alloc(BufferAllocator::get());
1492 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 }
1494 write(fd, result.string(), result.size());
1495 return NO_ERROR;
1496}
1497
1498status_t SurfaceFlinger::onTransact(
1499 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1500{
1501 switch (code) {
1502 case CREATE_CONNECTION:
1503 case OPEN_GLOBAL_TRANSACTION:
1504 case CLOSE_GLOBAL_TRANSACTION:
1505 case SET_ORIENTATION:
1506 case FREEZE_DISPLAY:
1507 case UNFREEZE_DISPLAY:
1508 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509 {
1510 // codes that require permission check
1511 IPCThreadState* ipc = IPCThreadState::self();
1512 const int pid = ipc->getCallingPid();
1513 const int self_pid = getpid();
1514 if (UNLIKELY(pid != self_pid)) {
1515 // we're called from a different process, do the real check
1516 if (!checkCallingPermission(
1517 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1518 {
1519 const int uid = ipc->getCallingUid();
1520 LOGE("Permission Denial: "
1521 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1522 return PERMISSION_DENIED;
1523 }
1524 }
1525 }
1526 }
1527
1528 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1529 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1530 // HARDWARE_TEST stuff...
1531 if (UNLIKELY(checkCallingPermission(
1532 String16("android.permission.HARDWARE_TEST")) == false))
1533 { // not allowed
1534 LOGE("Permission Denial: pid=%d, uid=%d\n",
1535 IPCThreadState::self()->getCallingPid(),
1536 IPCThreadState::self()->getCallingUid());
1537 return PERMISSION_DENIED;
1538 }
1539 int n;
1540 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001541 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001542 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001543 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544 return NO_ERROR;
1545 case 1002: // SHOW_UPDATES
1546 n = data.readInt32();
1547 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1548 return NO_ERROR;
1549 case 1003: // SHOW_BACKGROUND
1550 n = data.readInt32();
1551 mDebugBackground = n ? 1 : 0;
1552 return NO_ERROR;
1553 case 1004:{ // repaint everything
1554 Mutex::Autolock _l(mStateLock);
1555 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1556 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1557 signalEvent();
1558 }
1559 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560 case 1007: // set mFreezeCount
1561 mFreezeCount = data.readInt32();
1562 return NO_ERROR;
1563 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001564 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001565 reply->writeInt32(0);
1566 reply->writeInt32(mDebugRegion);
1567 reply->writeInt32(mDebugBackground);
1568 return NO_ERROR;
1569 case 1013: {
1570 Mutex::Autolock _l(mStateLock);
1571 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1572 reply->writeInt32(hw.getPageFlipCount());
1573 }
1574 return NO_ERROR;
1575 }
1576 }
1577 return err;
1578}
1579
1580// ---------------------------------------------------------------------------
1581#if 0
1582#pragma mark -
1583#endif
1584
1585Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1586 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1587{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001588 const int pgsize = getpagesize();
1589 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1590 mCblkHeap = new MemoryDealer(cblksize);
1591 mCblkMemory = mCblkHeap->allocate(cblksize);
1592 if (mCblkMemory != 0) {
1593 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1594 if (ctrlblk) { // construct the shared structure in-place.
1595 new(ctrlblk) per_client_cblk_t;
1596 }
1597 }
1598}
1599
1600Client::~Client() {
1601 if (ctrlblk) {
1602 const int pgsize = getpagesize();
1603 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1604 }
1605}
1606
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001607int32_t Client::generateId(int pid)
1608{
1609 const uint32_t i = clz( ~mBitmap );
1610 if (i >= NUM_LAYERS_MAX) {
1611 return NO_MEMORY;
1612 }
1613 mPid = pid;
1614 mInUse.add(uint8_t(i));
1615 mBitmap |= 1<<(31-i);
1616 return i;
1617}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001618
1619status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001620{
1621 ssize_t idx = mInUse.indexOf(id);
1622 if (idx < 0)
1623 return NAME_NOT_FOUND;
1624 return mLayers.insertAt(layer, idx);
1625}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001627void Client::free(int32_t id)
1628{
1629 ssize_t idx = mInUse.remove(uint8_t(id));
1630 if (idx >= 0) {
1631 mBitmap &= ~(1<<(31-id));
1632 mLayers.removeItemsAt(idx);
1633 }
1634}
1635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001636bool Client::isValid(int32_t i) const {
1637 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1638}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001639
1640sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1641 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001642 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001643 if (idx >= 0) {
1644 lbc = mLayers[idx].promote();
1645 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1646 }
1647 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001648}
1649
1650void Client::dump(const char* what)
1651{
1652}
1653
1654// ---------------------------------------------------------------------------
1655#if 0
1656#pragma mark -
1657#endif
1658
1659BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1660 : mId(cid), mFlinger(flinger), mCblk(cblk)
1661{
1662}
1663
1664BClient::~BClient() {
1665 // destroy all resources attached to this client
1666 mFlinger->destroyConnection(mId);
1667}
1668
1669void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1670 *ctrl = mCblk;
1671}
1672
1673sp<ISurface> BClient::createSurface(
1674 ISurfaceFlingerClient::surface_data_t* params, int pid,
1675 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1676 uint32_t flags)
1677{
1678 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1679}
1680
1681status_t BClient::destroySurface(SurfaceID sid)
1682{
1683 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001684 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001685}
1686
1687status_t BClient::setState(int32_t count, const layer_state_t* states)
1688{
1689 return mFlinger->setClientState(mId, count, states);
1690}
1691
1692// ---------------------------------------------------------------------------
1693
1694GraphicPlane::GraphicPlane()
1695 : mHw(0)
1696{
1697}
1698
1699GraphicPlane::~GraphicPlane() {
1700 delete mHw;
1701}
1702
1703bool GraphicPlane::initialized() const {
1704 return mHw ? true : false;
1705}
1706
1707void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1708 mHw = hw;
1709}
1710
1711void GraphicPlane::setTransform(const Transform& tr) {
1712 mTransform = tr;
1713 mGlobalTransform = mOrientationTransform * mTransform;
1714}
1715
1716status_t GraphicPlane::orientationToTransfrom(
1717 int orientation, int w, int h, Transform* tr)
1718{
1719 float a, b, c, d, x, y;
1720 switch (orientation) {
1721 case ISurfaceComposer::eOrientationDefault:
1722 a=1; b=0; c=0; d=1; x=0; y=0;
1723 break;
1724 case ISurfaceComposer::eOrientation90:
1725 a=0; b=-1; c=1; d=0; x=w; y=0;
1726 break;
1727 case ISurfaceComposer::eOrientation180:
1728 a=-1; b=0; c=0; d=-1; x=w; y=h;
1729 break;
1730 case ISurfaceComposer::eOrientation270:
1731 a=0; b=1; c=-1; d=0; x=0; y=h;
1732 break;
1733 default:
1734 return BAD_VALUE;
1735 }
1736 tr->set(a, b, c, d);
1737 tr->set(x, y);
1738 return NO_ERROR;
1739}
1740
1741status_t GraphicPlane::setOrientation(int orientation)
1742{
1743 const DisplayHardware& hw(displayHardware());
1744 const float w = hw.getWidth();
1745 const float h = hw.getHeight();
1746
1747 if (orientation == ISurfaceComposer::eOrientationDefault) {
1748 // make sure the default orientation is optimal
1749 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001750 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 mGlobalTransform = mTransform;
1752 return NO_ERROR;
1753 }
1754
1755 // If the rotation can be handled in hardware, this is where
1756 // the magic should happen.
1757 if (UNLIKELY(orientation == 42)) {
1758 float a, b, c, d, x, y;
1759 const float r = (3.14159265f / 180.0f) * 42.0f;
1760 const float si = sinf(r);
1761 const float co = cosf(r);
1762 a=co; b=-si; c=si; d=co;
1763 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1764 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1765 mOrientationTransform.set(a, b, c, d);
1766 mOrientationTransform.set(x, y);
1767 } else {
1768 GraphicPlane::orientationToTransfrom(orientation, w, h,
1769 &mOrientationTransform);
1770 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001771 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001772 mGlobalTransform = mOrientationTransform * mTransform;
1773 return NO_ERROR;
1774}
1775
1776const DisplayHardware& GraphicPlane::displayHardware() const {
1777 return *mHw;
1778}
1779
1780const Transform& GraphicPlane::transform() const {
1781 return mGlobalTransform;
1782}
1783
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001784EGLDisplay GraphicPlane::getEGLDisplay() const {
1785 return mHw->getEGLDisplay();
1786}
1787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788// ---------------------------------------------------------------------------
1789
1790}; // namespace android