blob: 90e0bb56cf8617c2366c99b5430ab5915b24e7bf [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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryDealer.h>
35#include <binder/MemoryBase.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036#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
Mathias Agopiana1ecca92009-05-21 19:21:59 -070057/* ideally AID_GRAPHICS would be in a semi-public header
58 * or there would be a way to map a user/group name to its id
59 */
60#ifndef AID_GRAPHICS
61#define AID_GRAPHICS 1003
62#endif
63
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#define DISPLAY_COUNT 1
65
66namespace android {
67
68// ---------------------------------------------------------------------------
69
70void SurfaceFlinger::instantiate() {
71 defaultServiceManager()->addService(
72 String16("SurfaceFlinger"), new SurfaceFlinger());
73}
74
75void SurfaceFlinger::shutdown() {
76 // we should unregister here, but not really because
77 // when (if) the service manager goes away, all the services
78 // it has a reference to will leave too.
79}
80
81// ---------------------------------------------------------------------------
82
83SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
84 : lookup(rhs.lookup), layers(rhs.layers)
85{
86}
87
88ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070089 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090{
91 if (guess<size() && lookup.keyAt(guess) == key)
92 return guess;
93 const ssize_t i = lookup.indexOfKey(key);
94 if (i>=0) {
95 const size_t idx = lookup.valueAt(i);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070096 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070098 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099 return idx;
100 }
101 return i;
102}
103
104ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700105 const sp<LayerBase>& layer,
106 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107{
108 size_t count = layers.size();
109 ssize_t l = 0;
110 ssize_t h = count-1;
111 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700112 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113 while (l <= h) {
114 mid = l + (h - l)/2;
115 const int c = cmp(a+mid, &layer);
116 if (c == 0) { l = mid; break; }
117 else if (c<0) { l = mid+1; }
118 else { h = mid-1; }
119 }
120 size_t order = l;
121 while (order<count && !cmp(&layer, a+order)) {
122 order++;
123 }
124 count = lookup.size();
125 for (size_t i=0 ; i<count ; i++) {
126 if (lookup.valueAt(i) >= order) {
127 lookup.editValueAt(i)++;
128 }
129 }
130 layers.insertAt(layer, order);
131 lookup.add(layer, order);
132 return order;
133}
134
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136{
137 const ssize_t keyIndex = lookup.indexOfKey(layer);
138 if (keyIndex >= 0) {
139 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700140 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700142 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 layers.removeItemsAt(index);
144 lookup.removeItemsAt(keyIndex);
145 const size_t count = lookup.size();
146 for (size_t i=0 ; i<count ; i++) {
147 if (lookup.valueAt(i) >= size_t(index)) {
148 lookup.editValueAt(i)--;
149 }
150 }
151 return index;
152 }
153 return NAME_NOT_FOUND;
154}
155
156ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700157 const sp<LayerBase>& layer,
158 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159{
160 // XXX: it's a little lame. but oh well...
161 ssize_t err = remove(layer);
162 if (err >=0)
163 err = add(layer, cmp);
164 return err;
165}
166
167// ---------------------------------------------------------------------------
168#if 0
169#pragma mark -
170#endif
171
172SurfaceFlinger::SurfaceFlinger()
173 : BnSurfaceComposer(), Thread(false),
174 mTransactionFlags(0),
175 mTransactionCount(0),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700176 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 mBootTime(systemTime()),
Mathias Agopian375f5632009-06-15 18:24:59 -0700178 mHardwareTest("android.permission.HARDWARE_TEST"),
179 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
180 mDump("android.permission.DUMP"),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 mLastScheduledBroadcast(NULL),
182 mVisibleRegionsDirty(false),
183 mDeferReleaseConsole(false),
184 mFreezeDisplay(false),
185 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700186 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188 mDebugBackground(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 mConsoleSignals(0),
190 mSecureFrameBuffer(0)
191{
192 init();
193}
194
195void SurfaceFlinger::init()
196{
197 LOGI("SurfaceFlinger is starting");
198
199 // debugging stuff...
200 char value[PROPERTY_VALUE_MAX];
201 property_get("debug.sf.showupdates", value, "0");
202 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showbackground", value, "0");
204 mDebugBackground = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205
206 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208}
209
210SurfaceFlinger::~SurfaceFlinger()
211{
212 glDeleteTextures(1, &mWormholeTexName);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213}
214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
216{
217 return graphicPlane(0).displayHardware().getOverlayEngine();
218}
219
220sp<IMemory> SurfaceFlinger::getCblk() const
221{
222 return mServerCblkMemory;
223}
224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
226{
227 Mutex::Autolock _l(mStateLock);
228 uint32_t token = mTokens.acquire();
229
230 Client* client = new Client(token, this);
231 if ((client == 0) || (client->ctrlblk == 0)) {
232 mTokens.release(token);
233 return 0;
234 }
235 status_t err = mClientsMap.add(token, client);
236 if (err < 0) {
237 delete client;
238 mTokens.release(token);
239 return 0;
240 }
241 sp<BClient> bclient =
242 new BClient(this, token, client->controlBlockMemory());
243 return bclient;
244}
245
246void SurfaceFlinger::destroyConnection(ClientID cid)
247{
248 Mutex::Autolock _l(mStateLock);
249 Client* const client = mClientsMap.valueFor(cid);
250 if (client) {
251 // free all the layers this client owns
Mathias Agopian3d579642009-06-04 18:46:21 -0700252 Vector< wp<LayerBaseClient> > layers(client->getLayers());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 const size_t count = layers.size();
254 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700255 sp<LayerBaseClient> layer(layers[i].promote());
256 if (layer != 0) {
Mathias Agopian3d579642009-06-04 18:46:21 -0700257 purgatorizeLayer_l(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700258 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 }
260
261 // the resources associated with this client will be freed
262 // during the next transaction, after these surfaces have been
263 // properly removed from the screen
264
265 // remove this client from our ClientID->Client mapping.
266 mClientsMap.removeItem(cid);
267
268 // and add it to the list of disconnected clients
269 mDisconnectedClients.add(client);
270
271 // request a transaction
272 setTransactionFlags(eTransactionNeeded);
273 }
274}
275
276const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
277{
278 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
279 const GraphicPlane& plane(mGraphicPlanes[dpy]);
280 return plane;
281}
282
283GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
284{
285 return const_cast<GraphicPlane&>(
286 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
287}
288
289void SurfaceFlinger::bootFinished()
290{
291 const nsecs_t now = systemTime();
292 const nsecs_t duration = now - mBootTime;
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700293 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
294 property_set("ctl.stop", "bootanim");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800295}
296
297void SurfaceFlinger::onFirstRef()
298{
299 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
300
301 // Wait for the main thread to be done with its initialization
302 mReadyToRunBarrier.wait();
303}
304
305
306static inline uint16_t pack565(int r, int g, int b) {
307 return (r<<11)|(g<<5)|b;
308}
309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310status_t SurfaceFlinger::readyToRun()
311{
312 LOGI( "SurfaceFlinger's main thread ready to run. "
313 "Initializing graphics H/W...");
314
315 // create the shared control-block
316 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
317 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
318
319 mServerCblkMemory = mServerHeap->allocate(4096);
320 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
321
322 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
323 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
324 new(mServerCblk) surface_flinger_cblk_t;
325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 // we only support one display currently
327 int dpy = 0;
328
329 {
330 // initialize the main display
331 GraphicPlane& plane(graphicPlane(dpy));
332 DisplayHardware* const hw = new DisplayHardware(this, dpy);
333 plane.setDisplayHardware(hw);
334 }
335
336 // initialize primary screen
337 // (other display should be initialized in the same manner, but
338 // asynchronously, as they could come and go. None of this is supported
339 // yet).
340 const GraphicPlane& plane(graphicPlane(dpy));
341 const DisplayHardware& hw = plane.displayHardware();
342 const uint32_t w = hw.getWidth();
343 const uint32_t h = hw.getHeight();
344 const uint32_t f = hw.getFormat();
345 hw.makeCurrent();
346
347 // initialize the shared control block
348 mServerCblk->connected |= 1<<dpy;
349 display_cblk_t* dcblk = mServerCblk->displays + dpy;
350 memset(dcblk, 0, sizeof(display_cblk_t));
351 dcblk->w = w;
352 dcblk->h = h;
353 dcblk->format = f;
354 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
355 dcblk->xdpi = hw.getDpiX();
356 dcblk->ydpi = hw.getDpiY();
357 dcblk->fps = hw.getRefreshRate();
358 dcblk->density = hw.getDensity();
359 asm volatile ("":::"memory");
360
361 // Initialize OpenGL|ES
362 glActiveTexture(GL_TEXTURE0);
363 glBindTexture(GL_TEXTURE_2D, 0);
364 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
365 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
366 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
367 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
368 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
369 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
370 glPixelStorei(GL_PACK_ALIGNMENT, 4);
371 glEnableClientState(GL_VERTEX_ARRAY);
372 glEnable(GL_SCISSOR_TEST);
373 glShadeModel(GL_FLAT);
374 glDisable(GL_DITHER);
375 glDisable(GL_CULL_FACE);
376
377 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
378 const uint16_t g1 = pack565(0x17,0x2f,0x17);
379 const uint16_t textureData[4] = { g0, g1, g1, g0 };
380 glGenTextures(1, &mWormholeTexName);
381 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
382 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
383 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
384 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
385 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
386 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
387 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
388
389 glViewport(0, 0, w, h);
390 glMatrixMode(GL_PROJECTION);
391 glLoadIdentity();
392 glOrthof(0, w, h, 0, 0, 1);
393
394 LayerDim::initDimmer(this, w, h);
395
396 mReadyToRunBarrier.open();
397
398 /*
399 * We're now ready to accept clients...
400 */
401
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700402 // start boot animation
403 property_set("ctl.start", "bootanim");
404
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 return NO_ERROR;
406}
407
408// ----------------------------------------------------------------------------
409#if 0
410#pragma mark -
411#pragma mark Events Handler
412#endif
413
414void SurfaceFlinger::waitForEvent()
415{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700416 while (true) {
417 nsecs_t timeout = -1;
418 if (UNLIKELY(isFrozen())) {
419 // wait 5 seconds
420 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
421 const nsecs_t now = systemTime();
422 if (mFreezeDisplayTime == 0) {
423 mFreezeDisplayTime = now;
424 }
425 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
426 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700427 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700428
Mathias Agopianb6683b52009-04-28 03:17:50 -0700429 MessageList::value_type msg = mEventQueue.waitMessage(timeout);
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700430 if (msg != 0) {
431 mFreezeDisplayTime = 0;
432 switch (msg->what) {
433 case MessageQueue::INVALIDATE:
434 // invalidate message, just return to the main loop
435 return;
436 }
437 } else {
438 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 if (isFrozen()) {
440 // we timed out and are still frozen
441 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
442 mFreezeDisplay, mFreezeCount);
443 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700444 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700445 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 }
447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448 }
449}
450
451void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700452 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453}
454
455void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700456 // this is the IPC call
457 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
460void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
461{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700462 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463}
464
465// ----------------------------------------------------------------------------
466#if 0
467#pragma mark -
468#pragma mark Main loop
469#endif
470
471bool SurfaceFlinger::threadLoop()
472{
473 waitForEvent();
474
475 // check for transactions
476 if (UNLIKELY(mConsoleSignals)) {
477 handleConsoleEvents();
478 }
479
480 if (LIKELY(mTransactionCount == 0)) {
481 // if we're in a global transaction, don't do anything.
482 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
483 uint32_t transactionFlags = getTransactionFlags(mask);
484 if (LIKELY(transactionFlags)) {
485 handleTransaction(transactionFlags);
486 }
487 }
488
489 // post surfaces (if needed)
490 handlePageFlip();
491
492 const DisplayHardware& hw(graphicPlane(0).displayHardware());
493 if (LIKELY(hw.canDraw())) {
494 // repaint the framebuffer (if needed)
495 handleRepaint();
496
497 // release the clients before we flip ('cause flip might block)
498 unlockClients();
499 executeScheduledBroadcasts();
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501 postFramebuffer();
502 } else {
503 // pretend we did the post
504 unlockClients();
505 executeScheduledBroadcasts();
506 usleep(16667); // 60 fps period
507 }
508 return true;
509}
510
511void SurfaceFlinger::postFramebuffer()
512{
Mathias Agopian0926f502009-05-04 14:17:04 -0700513 if (isFrozen()) {
514 // we are not allowed to draw, but pause a bit to make sure
515 // apps don't end up using the whole CPU, if they depend on
516 // surfaceflinger for synchronization.
517 usleep(8333); // 8.3ms ~ 120fps
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800518 return;
519 }
520
521 if (!mInvalidRegion.isEmpty()) {
522 const DisplayHardware& hw(graphicPlane(0).displayHardware());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 mInvalidRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 }
526}
527
528void SurfaceFlinger::handleConsoleEvents()
529{
530 // something to do with the console
531 const DisplayHardware& hw = graphicPlane(0).displayHardware();
532
533 int what = android_atomic_and(0, &mConsoleSignals);
534 if (what & eConsoleAcquired) {
535 hw.acquireScreen();
536 }
537
538 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700539 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 hw.releaseScreen();
542 }
543
544 if (what & eConsoleReleased) {
545 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 hw.releaseScreen();
547 } else {
548 mDeferReleaseConsole = true;
549 }
550 }
551
552 mDirtyRegion.set(hw.bounds());
553}
554
555void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
556{
Mathias Agopian3d579642009-06-04 18:46:21 -0700557 Vector< sp<LayerBase> > ditchedLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558
Mathias Agopian3d579642009-06-04 18:46:21 -0700559 { // scope for the lock
560 Mutex::Autolock _l(mStateLock);
561 handleTransactionLocked(transactionFlags, ditchedLayers);
562 }
563
564 // do this without lock held
565 const size_t count = ditchedLayers.size();
566 for (size_t i=0 ; i<count ; i++) {
567 //LOGD("ditching layer %p", ditchedLayers[i].get());
568 ditchedLayers[i]->ditch();
569 }
570}
571
572void SurfaceFlinger::handleTransactionLocked(
573 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
574{
575 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576 const size_t count = currentLayers.size();
577
578 /*
579 * Traversal of the children
580 * (perform the transaction for each of them if needed)
581 */
582
583 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
584 if (layersNeedTransaction) {
585 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700586 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
588 if (!trFlags) continue;
589
590 const uint32_t flags = layer->doTransaction(0);
591 if (flags & Layer::eVisibleRegion)
592 mVisibleRegionsDirty = true;
593
594 if (flags & Layer::eRestartTransaction) {
595 // restart the transaction, but back-off a little
596 layer->setTransactionFlags(eTransactionNeeded);
597 setTransactionFlags(eTraversalNeeded, ms2ns(8));
598 }
599 }
600 }
601
602 /*
603 * Perform our own transaction if needed
604 */
605
606 if (transactionFlags & eTransactionNeeded) {
607 if (mCurrentState.orientation != mDrawingState.orientation) {
608 // the orientation has changed, recompute all visible regions
609 // and invalidate everything.
610
611 const int dpy = 0;
612 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700613 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800614 GraphicPlane& plane(graphicPlane(dpy));
615 plane.setOrientation(orientation);
616
617 // update the shared control block
618 const DisplayHardware& hw(plane.displayHardware());
619 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
620 dcblk->orientation = orientation;
621 if (orientation & eOrientationSwapMask) {
622 // 90 or 270 degrees orientation
623 dcblk->w = hw.getHeight();
624 dcblk->h = hw.getWidth();
625 } else {
626 dcblk->w = hw.getWidth();
627 dcblk->h = hw.getHeight();
628 }
629
630 mVisibleRegionsDirty = true;
631 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700632 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800633 }
634
635 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
636 // freezing or unfreezing the display -> trigger animation if needed
637 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800638 }
639
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700640 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
641 // layers have been added
642 mVisibleRegionsDirty = true;
643 }
644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645 // some layers might have been removed, so
646 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700647 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700649 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
Mathias Agopian3d579642009-06-04 18:46:21 -0700650 const size_t count = previousLayers.size();
651 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700652 const sp<LayerBase>& layer(previousLayers[i]);
653 if (currentLayers.indexOf( layer ) < 0) {
654 // this layer is not visible anymore
Mathias Agopian3d579642009-06-04 18:46:21 -0700655 ditchedLayers.add(layer);
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700656 }
657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800658 }
659
660 // get rid of all resources we don't need anymore
661 // (layers and clients)
662 free_resources_l();
663 }
664
665 commitTransaction();
666}
667
668sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
669{
670 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
671}
672
673void SurfaceFlinger::computeVisibleRegions(
674 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
675{
676 const GraphicPlane& plane(graphicPlane(0));
677 const Transform& planeTransform(plane.transform());
678
679 Region aboveOpaqueLayers;
680 Region aboveCoveredLayers;
681 Region dirty;
682
683 bool secureFrameBuffer = false;
684
685 size_t i = currentLayers.size();
686 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700687 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688 layer->validateVisibility(planeTransform);
689
690 // start with the whole surface at its current location
691 const Layer::State& s = layer->drawingState();
692 const Rect bounds(layer->visibleBounds());
693
694 // handle hidden surfaces by setting the visible region to empty
695 Region opaqueRegion;
696 Region visibleRegion;
697 Region coveredRegion;
698 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
699 visibleRegion.clear();
700 } else {
701 const bool translucent = layer->needsBlending();
702 visibleRegion.set(bounds);
703 coveredRegion = visibleRegion;
704
705 // Remove the transparent area from the visible region
706 if (translucent) {
707 visibleRegion.subtractSelf(layer->transparentRegionScreen);
708 }
709
710 // compute the opaque region
711 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
712 // the opaque region is the visible region
713 opaqueRegion = visibleRegion;
714 }
715 }
716
717 // subtract the opaque region covered by the layers above us
718 visibleRegion.subtractSelf(aboveOpaqueLayers);
719 coveredRegion.andSelf(aboveCoveredLayers);
720
721 // compute this layer's dirty region
722 if (layer->contentDirty) {
723 // we need to invalidate the whole region
724 dirty = visibleRegion;
725 // as well, as the old visible region
726 dirty.orSelf(layer->visibleRegionScreen);
727 layer->contentDirty = false;
728 } else {
729 // compute the exposed region
730 // dirty = what's visible now - what's wasn't covered before
731 // = what's visible now & what's was covered before
732 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
733 }
734 dirty.subtractSelf(aboveOpaqueLayers);
735
736 // accumulate to the screen dirty region
737 dirtyRegion.orSelf(dirty);
738
Mathias Agopian62b74442009-04-14 23:02:51 -0700739 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800740 aboveOpaqueLayers.orSelf(opaqueRegion);
741 aboveCoveredLayers.orSelf(bounds);
742
743 // Store the visible region is screen space
744 layer->setVisibleRegion(visibleRegion);
745 layer->setCoveredRegion(coveredRegion);
746
Mathias Agopian62b74442009-04-14 23:02:51 -0700747 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800748 if (layer->isSecure() && !visibleRegion.isEmpty()) {
749 secureFrameBuffer = true;
750 }
751 }
752
753 mSecureFrameBuffer = secureFrameBuffer;
754 opaqueRegion = aboveOpaqueLayers;
755}
756
757
758void SurfaceFlinger::commitTransaction()
759{
760 mDrawingState = mCurrentState;
761 mTransactionCV.signal();
762}
763
764void SurfaceFlinger::handlePageFlip()
765{
766 bool visibleRegions = mVisibleRegionsDirty;
767 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
768 visibleRegions |= lockPageFlip(currentLayers);
769
770 const DisplayHardware& hw = graphicPlane(0).displayHardware();
771 const Region screenRegion(hw.bounds());
772 if (visibleRegions) {
773 Region opaqueRegion;
774 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
775 mWormholeRegion = screenRegion.subtract(opaqueRegion);
776 mVisibleRegionsDirty = false;
777 }
778
779 unlockPageFlip(currentLayers);
780 mDirtyRegion.andSelf(screenRegion);
781}
782
783bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
784{
785 bool recomputeVisibleRegions = false;
786 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700787 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800788 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700789 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790 layer->lockPageFlip(recomputeVisibleRegions);
791 }
792 return recomputeVisibleRegions;
793}
794
795void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
796{
797 const GraphicPlane& plane(graphicPlane(0));
798 const Transform& planeTransform(plane.transform());
799 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700800 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700802 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800803 layer->unlockPageFlip(planeTransform, mDirtyRegion);
804 }
805}
806
807void SurfaceFlinger::handleRepaint()
808{
809 // set the frame buffer
810 const DisplayHardware& hw(graphicPlane(0).displayHardware());
811 glMatrixMode(GL_MODELVIEW);
812 glLoadIdentity();
813
814 if (UNLIKELY(mDebugRegion)) {
815 debugFlashRegions();
816 }
817
818 // compute the invalid region
819 mInvalidRegion.orSelf(mDirtyRegion);
820
821 uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700822 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
823 (flags & DisplayHardware::BUFFER_PRESERVED))
824 {
825 // we can redraw only what's dirty
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826 } else {
827 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700828 // we need to redraw the rectangle that will be updated
829 // (pushed to the framebuffer).
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800830 mDirtyRegion.set(mInvalidRegion.bounds());
831 } else {
832 // we need to redraw everything
833 mDirtyRegion.set(hw.bounds());
834 mInvalidRegion = mDirtyRegion;
835 }
836 }
837
838 // compose all surfaces
839 composeSurfaces(mDirtyRegion);
840
841 // clear the dirty regions
842 mDirtyRegion.clear();
843}
844
845void SurfaceFlinger::composeSurfaces(const Region& dirty)
846{
847 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
848 // should never happen unless the window manager has a bug
849 // draw something...
850 drawWormhole();
851 }
852 const SurfaceFlinger& flinger(*this);
853 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
854 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700855 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800856 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700857 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800858 const Region& visibleRegion(layer->visibleRegionScreen);
859 if (!visibleRegion.isEmpty()) {
860 const Region clip(dirty.intersect(visibleRegion));
861 if (!clip.isEmpty()) {
862 layer->draw(clip);
863 }
864 }
865 }
866}
867
868void SurfaceFlinger::unlockClients()
869{
870 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
871 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700872 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800873 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700874 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875 layer->finishPageFlip();
876 }
877}
878
879void SurfaceFlinger::scheduleBroadcast(Client* client)
880{
881 if (mLastScheduledBroadcast != client) {
882 mLastScheduledBroadcast = client;
883 mScheduledBroadcasts.add(client);
884 }
885}
886
887void SurfaceFlinger::executeScheduledBroadcasts()
888{
889 SortedVector<Client*>& list = mScheduledBroadcasts;
890 size_t count = list.size();
891 while (count--) {
892 per_client_cblk_t* const cblk = list[count]->ctrlblk;
893 if (cblk->lock.tryLock() == NO_ERROR) {
894 cblk->cv.broadcast();
895 list.removeAt(count);
896 cblk->lock.unlock();
897 } else {
898 // schedule another round
899 LOGW("executeScheduledBroadcasts() skipped, "
900 "contention on the client. We'll try again later...");
901 signalDelayedEvent(ms2ns(4));
902 }
903 }
904 mLastScheduledBroadcast = 0;
905}
906
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907void SurfaceFlinger::debugFlashRegions()
908{
Mathias Agopian0926f502009-05-04 14:17:04 -0700909 const DisplayHardware& hw(graphicPlane(0).displayHardware());
910 const uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700911
912 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
913 (flags & DisplayHardware::BUFFER_PRESERVED))) {
Mathias Agopian0926f502009-05-04 14:17:04 -0700914 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
915 mDirtyRegion.bounds() : hw.bounds());
916 composeSurfaces(repaint);
917 }
918
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800919 glDisable(GL_TEXTURE_2D);
920 glDisable(GL_BLEND);
921 glDisable(GL_DITHER);
922 glDisable(GL_SCISSOR_TEST);
923
Mathias Agopian0926f502009-05-04 14:17:04 -0700924 static int toggle = 0;
925 toggle = 1 - toggle;
926 if (toggle) {
927 glColor4x(0x10000, 0, 0x10000, 0x10000);
928 } else {
929 glColor4x(0x10000, 0x10000, 0, 0x10000);
930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800931
Mathias Agopian20f68782009-05-11 00:03:41 -0700932 Region::const_iterator it = mDirtyRegion.begin();
933 Region::const_iterator const end = mDirtyRegion.end();
934 while (it != end) {
935 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800936 GLfloat vertices[][2] = {
937 { r.left, r.top },
938 { r.left, r.bottom },
939 { r.right, r.bottom },
940 { r.right, r.top }
941 };
942 glVertexPointer(2, GL_FLOAT, 0, vertices);
943 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
944 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700945
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946 hw.flip(mDirtyRegion.merge(mInvalidRegion));
947 mInvalidRegion.clear();
948
949 if (mDebugRegion > 1)
950 usleep(mDebugRegion * 1000);
951
952 glEnable(GL_SCISSOR_TEST);
953 //mDirtyRegion.dump("mDirtyRegion");
954}
955
956void SurfaceFlinger::drawWormhole() const
957{
958 const Region region(mWormholeRegion.intersect(mDirtyRegion));
959 if (region.isEmpty())
960 return;
961
962 const DisplayHardware& hw(graphicPlane(0).displayHardware());
963 const int32_t width = hw.getWidth();
964 const int32_t height = hw.getHeight();
965
966 glDisable(GL_BLEND);
967 glDisable(GL_DITHER);
968
969 if (LIKELY(!mDebugBackground)) {
970 glClearColorx(0,0,0,0);
Mathias Agopian20f68782009-05-11 00:03:41 -0700971 Region::const_iterator it = region.begin();
972 Region::const_iterator const end = region.end();
973 while (it != end) {
974 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975 const GLint sy = height - (r.top + r.height());
976 glScissor(r.left, sy, r.width(), r.height());
977 glClear(GL_COLOR_BUFFER_BIT);
978 }
979 } else {
980 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
981 { width, height }, { 0, height } };
982 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
983 glVertexPointer(2, GL_SHORT, 0, vertices);
984 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
985 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
986 glEnable(GL_TEXTURE_2D);
987 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
988 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
989 glMatrixMode(GL_TEXTURE);
990 glLoadIdentity();
991 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
Mathias Agopian20f68782009-05-11 00:03:41 -0700992 Region::const_iterator it = region.begin();
993 Region::const_iterator const end = region.end();
994 while (it != end) {
995 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996 const GLint sy = height - (r.top + r.height());
997 glScissor(r.left, sy, r.width(), r.height());
998 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
999 }
1000 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1001 }
1002}
1003
1004void SurfaceFlinger::debugShowFPS() const
1005{
1006 static int mFrameCount;
1007 static int mLastFrameCount = 0;
1008 static nsecs_t mLastFpsTime = 0;
1009 static float mFps = 0;
1010 mFrameCount++;
1011 nsecs_t now = systemTime();
1012 nsecs_t diff = now - mLastFpsTime;
1013 if (diff > ms2ns(250)) {
1014 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1015 mLastFpsTime = now;
1016 mLastFrameCount = mFrameCount;
1017 }
1018 // XXX: mFPS has the value we want
1019 }
1020
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001021status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001022{
1023 Mutex::Autolock _l(mStateLock);
1024 addLayer_l(layer);
1025 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1026 return NO_ERROR;
1027}
1028
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001029status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030{
1031 Mutex::Autolock _l(mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001032 status_t err = purgatorizeLayer_l(layer);
1033 if (err == NO_ERROR)
1034 setTransactionFlags(eTransactionNeeded);
1035 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036}
1037
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001038status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039{
1040 layer->forceVisibilityTransaction();
1041 setTransactionFlags(eTraversalNeeded);
1042 return NO_ERROR;
1043}
1044
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001045status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001046{
1047 ssize_t i = mCurrentState.layersSortedByZ.add(
1048 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001049 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1050 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001051 mLayerMap.add(lbc->serverIndex(), lbc);
1052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001053 return NO_ERROR;
1054}
1055
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001056status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001057{
1058 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1059 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001060 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001061 sp<LayerBaseClient> layer =
1062 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001063 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064 mLayerMap.removeItem(layer->serverIndex());
1065 }
1066 return NO_ERROR;
1067 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001068 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001069}
1070
Mathias Agopian9a112062009-04-17 19:36:26 -07001071status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1072{
1073 // First add the layer to the purgatory list, which makes sure it won't
1074 // go away, then remove it from the main list (through a transaction).
1075 ssize_t err = removeLayer_l(layerBase);
1076 if (err >= 0) {
1077 mLayerPurgatory.add(layerBase);
1078 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001079 // it's possible that we don't find a layer, because it might
1080 // have been destroyed already -- this is not technically an error
1081 // from the user because there is a race between BClient::destroySurface(),
1082 // ~BClient() and ~ISurface().
Mathias Agopian9a112062009-04-17 19:36:26 -07001083 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1084}
1085
1086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001087void SurfaceFlinger::free_resources_l()
1088{
1089 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001090 mLayersRemoved = false;
1091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001092 // free resources associated with disconnected clients
1093 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1094 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1095 const size_t count = disconnectedClients.size();
1096 for (size_t i=0 ; i<count ; i++) {
1097 Client* client = disconnectedClients[i];
1098 // if this client is the scheduled broadcast list,
1099 // remove it from there (and we don't need to signal it
1100 // since it is dead).
1101 int32_t index = scheduledBroadcasts.indexOf(client);
1102 if (index >= 0) {
1103 scheduledBroadcasts.removeItemsAt(index);
1104 }
1105 mTokens.release(client->cid);
1106 delete client;
1107 }
1108 disconnectedClients.clear();
1109}
1110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001111uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1112{
1113 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1114}
1115
1116uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1117{
1118 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1119 if ((old & flags)==0) { // wake the server up
1120 if (delay > 0) {
1121 signalDelayedEvent(delay);
1122 } else {
1123 signalEvent();
1124 }
1125 }
1126 return old;
1127}
1128
1129void SurfaceFlinger::openGlobalTransaction()
1130{
1131 android_atomic_inc(&mTransactionCount);
1132}
1133
1134void SurfaceFlinger::closeGlobalTransaction()
1135{
1136 if (android_atomic_dec(&mTransactionCount) == 1) {
1137 signalEvent();
1138 }
1139}
1140
1141status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1142{
1143 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1144 return BAD_VALUE;
1145
1146 Mutex::Autolock _l(mStateLock);
1147 mCurrentState.freezeDisplay = 1;
1148 setTransactionFlags(eTransactionNeeded);
1149
1150 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001151 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001152 return NO_ERROR;
1153}
1154
1155status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1156{
1157 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1158 return BAD_VALUE;
1159
1160 Mutex::Autolock _l(mStateLock);
1161 mCurrentState.freezeDisplay = 0;
1162 setTransactionFlags(eTransactionNeeded);
1163
1164 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001165 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166 return NO_ERROR;
1167}
1168
Mathias Agopianc08731e2009-03-27 18:11:38 -07001169int SurfaceFlinger::setOrientation(DisplayID dpy,
1170 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171{
1172 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1173 return BAD_VALUE;
1174
1175 Mutex::Autolock _l(mStateLock);
1176 if (mCurrentState.orientation != orientation) {
1177 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001178 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179 mCurrentState.orientation = orientation;
1180 setTransactionFlags(eTransactionNeeded);
1181 mTransactionCV.wait(mStateLock);
1182 } else {
1183 orientation = BAD_VALUE;
1184 }
1185 }
1186 return orientation;
1187}
1188
1189sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1190 ISurfaceFlingerClient::surface_data_t* params,
1191 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1192 uint32_t flags)
1193{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001194 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001195 sp<LayerBaseClient::Surface> surfaceHandle;
1196 Mutex::Autolock _l(mStateLock);
1197 Client* const c = mClientsMap.valueFor(clientId);
1198 if (UNLIKELY(!c)) {
1199 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1200 return surfaceHandle;
1201 }
1202
1203 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1204 int32_t id = c->generateId(pid);
1205 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1206 LOGE("createSurface() failed, generateId = %d", id);
1207 return surfaceHandle;
1208 }
1209
1210 switch (flags & eFXSurfaceMask) {
1211 case eFXSurfaceNormal:
1212 if (UNLIKELY(flags & ePushBuffers)) {
1213 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1214 } else {
1215 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1216 }
1217 break;
1218 case eFXSurfaceBlur:
1219 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1220 break;
1221 case eFXSurfaceDim:
1222 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1223 break;
1224 }
1225
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001226 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227 setTransactionFlags(eTransactionNeeded);
1228 surfaceHandle = layer->getSurface();
1229 if (surfaceHandle != 0)
1230 surfaceHandle->getSurfaceData(params);
1231 }
1232
1233 return surfaceHandle;
1234}
1235
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001236sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237 Client* client, DisplayID display,
1238 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1239{
1240 // initialize the surfaces
1241 switch (format) { // TODO: take h/w into account
1242 case PIXEL_FORMAT_TRANSPARENT:
1243 case PIXEL_FORMAT_TRANSLUCENT:
1244 format = PIXEL_FORMAT_RGBA_8888;
1245 break;
1246 case PIXEL_FORMAT_OPAQUE:
1247 format = PIXEL_FORMAT_RGB_565;
1248 break;
1249 }
1250
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001251 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252 status_t err = layer->setBuffers(client, w, h, format, flags);
1253 if (LIKELY(err == NO_ERROR)) {
1254 layer->initStates(w, h, flags);
1255 addLayer_l(layer);
1256 } else {
1257 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001258 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259 }
1260 return layer;
1261}
1262
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001263sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
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<LayerBlur> layer = new LayerBlur(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::createDimSurfaceLocked(
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<LayerDim> layer = new LayerDim(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 Agopian076b1cc2009-04-10 14:24:30 -07001283sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001284 Client* client, DisplayID display,
1285 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1286{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001287 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288 layer->initStates(w, h, flags);
1289 addLayer_l(layer);
1290 return layer;
1291}
1292
Mathias Agopian9a112062009-04-17 19:36:26 -07001293status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294{
Mathias Agopian9a112062009-04-17 19:36:26 -07001295 /*
1296 * called by the window manager, when a surface should be marked for
1297 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001298 *
1299 * The surface is removed from the current and drawing lists, but placed
1300 * in the purgatory queue, so it's not destroyed right-away (we need
1301 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001302 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001303
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001304 Mutex::Autolock _l(mStateLock);
1305 sp<LayerBaseClient> layer = getLayerUser_l(index);
1306 status_t err = purgatorizeLayer_l(layer);
1307 if (err == NO_ERROR) {
1308 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001309 }
1310 return err;
1311}
1312
1313status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1314{
Mathias Agopian3d579642009-06-04 18:46:21 -07001315 /* called by ~ISurface() when all references are gone */
Mathias Agopian9a112062009-04-17 19:36:26 -07001316
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001317 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001318 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001319 sp<LayerBaseClient> layer;
1320 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001321 MessageDestroySurface(
1322 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1323 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001324 virtual bool handler() {
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001325 sp<LayerBaseClient> l(layer);
1326 layer.clear(); // clear it outside of the lock;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001327 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001328 // remove the layer from the current list -- chances are that it's
1329 // not in the list anyway, because it should have been removed
1330 // already upon request of the client (eg: window manager).
1331 // However, a buggy client could have not done that.
1332 // Since we know we don't have any more clients, we don't need
1333 // to use the purgatory.
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001334 status_t err = flinger->removeLayer_l(l);
Mathias Agopian3d579642009-06-04 18:46:21 -07001335 if (err == NAME_NOT_FOUND) {
1336 // The surface wasn't in the current list, which means it was
1337 // removed already, which means it is in the purgatory,
1338 // and need to be removed from there.
1339 // This needs to happen from the main thread since its dtor
1340 // must run from there (b/c of OpenGL ES). Additionally, we
1341 // can't really acquire our internal lock from
1342 // destroySurface() -- see postMessage() below.
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001343 ssize_t idx = flinger->mLayerPurgatory.remove(l);
Mathias Agopian3d579642009-06-04 18:46:21 -07001344 LOGE_IF(idx < 0,
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001345 "layer=%p is not in the purgatory list", l.get());
Mathias Agopian3d579642009-06-04 18:46:21 -07001346 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001347 return true;
1348 }
1349 };
Mathias Agopian3d579642009-06-04 18:46:21 -07001350
1351 // It's better to not acquire our internal lock here, because it's hard
1352 // to predict that it's not going to be already taken when ~Surface()
1353 // is called.
1354
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001355 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001356 return NO_ERROR;
1357}
1358
1359status_t SurfaceFlinger::setClientState(
1360 ClientID cid,
1361 int32_t count,
1362 const layer_state_t* states)
1363{
1364 Mutex::Autolock _l(mStateLock);
1365 uint32_t flags = 0;
1366 cid <<= 16;
1367 for (int i=0 ; i<count ; i++) {
1368 const layer_state_t& s = states[i];
Mathias Agopian3d579642009-06-04 18:46:21 -07001369 sp<LayerBaseClient> layer(getLayerUser_l(s.surface | cid));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001370 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371 const uint32_t what = s.what;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001372 if (what & ePositionChanged) {
1373 if (layer->setPosition(s.x, s.y))
1374 flags |= eTraversalNeeded;
1375 }
1376 if (what & eLayerChanged) {
1377 if (layer->setLayer(s.z)) {
1378 mCurrentState.layersSortedByZ.reorder(
1379 layer, &Layer::compareCurrentStateZ);
1380 // we need traversal (state changed)
1381 // AND transaction (list changed)
1382 flags |= eTransactionNeeded|eTraversalNeeded;
1383 }
1384 }
1385 if (what & eSizeChanged) {
1386 if (layer->setSize(s.w, s.h))
1387 flags |= eTraversalNeeded;
1388 }
1389 if (what & eAlphaChanged) {
1390 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1391 flags |= eTraversalNeeded;
1392 }
1393 if (what & eMatrixChanged) {
1394 if (layer->setMatrix(s.matrix))
1395 flags |= eTraversalNeeded;
1396 }
1397 if (what & eTransparentRegionChanged) {
1398 if (layer->setTransparentRegionHint(s.transparentRegion))
1399 flags |= eTraversalNeeded;
1400 }
1401 if (what & eVisibilityChanged) {
1402 if (layer->setFlags(s.flags, s.mask))
1403 flags |= eTraversalNeeded;
1404 }
1405 }
1406 }
1407 if (flags) {
1408 setTransactionFlags(flags);
1409 }
1410 return NO_ERROR;
1411}
1412
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001413sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001414{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001415 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1416 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001417}
1418
1419void SurfaceFlinger::screenReleased(int dpy)
1420{
1421 // this may be called by a signal handler, we can't do too much in here
1422 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1423 signalEvent();
1424}
1425
1426void SurfaceFlinger::screenAcquired(int dpy)
1427{
1428 // this may be called by a signal handler, we can't do too much in here
1429 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1430 signalEvent();
1431}
1432
1433status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1434{
1435 const size_t SIZE = 1024;
1436 char buffer[SIZE];
1437 String8 result;
Mathias Agopian375f5632009-06-15 18:24:59 -07001438 if (!mDump.checkCalling()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001439 snprintf(buffer, SIZE, "Permission Denial: "
1440 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1441 IPCThreadState::self()->getCallingPid(),
1442 IPCThreadState::self()->getCallingUid());
1443 result.append(buffer);
1444 } else {
1445 Mutex::Autolock _l(mStateLock);
1446 size_t s = mClientsMap.size();
1447 char name[64];
1448 for (size_t i=0 ; i<s ; i++) {
1449 Client* client = mClientsMap.valueAt(i);
1450 sprintf(name, " Client (id=0x%08x)", client->cid);
1451 client->dump(name);
1452 }
1453 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1454 const size_t count = currentLayers.size();
1455 for (size_t i=0 ; i<count ; i++) {
1456 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001457 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458 const Layer::State& s = layer->drawingState();
1459 snprintf(buffer, SIZE,
1460 "+ %s %p\n"
1461 " "
1462 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1463 "needsBlending=%1d, invalidate=%1d, "
1464 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001465 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001466 s.z, layer->tx(), layer->ty(), s.w, s.h,
1467 layer->needsBlending(), layer->contentDirty,
1468 s.alpha, s.flags,
1469 s.transform[0], s.transform[1],
1470 s.transform[2], s.transform[3]);
1471 result.append(buffer);
1472 buffer[0] = 0;
1473 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001474 sp<LayerBaseClient> lbc =
1475 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1476 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001477 snprintf(buffer, SIZE,
1478 " "
1479 "id=0x%08x, client=0x%08x, identity=%u\n",
1480 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1481 lbc->getIdentity());
1482 }
1483 result.append(buffer);
1484 buffer[0] = 0;
1485 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001486 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1487 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488 const LayerBitmap& buf0(l->getBuffer(0));
1489 const LayerBitmap& buf1(l->getBuffer(1));
1490 snprintf(buffer, SIZE,
1491 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001492 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 " freezeLock=%p, swapState=0x%08x\n",
1494 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001495 buf0.getWidth(), buf0.getHeight(),
1496 buf0.getBuffer()->getStride(),
1497 buf1.getWidth(), buf1.getHeight(),
1498 buf1.getBuffer()->getStride(),
1499 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500 l->lcblk->swapState);
1501 }
1502 result.append(buffer);
1503 buffer[0] = 0;
1504 s.transparentRegion.dump(result, "transparentRegion");
1505 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1506 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1507 }
1508 mWormholeRegion.dump(result, "WormholeRegion");
1509 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1510 snprintf(buffer, SIZE,
1511 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1512 mFreezeDisplay?"yes":"no", mFreezeCount,
1513 mCurrentState.orientation, hw.canDraw());
1514 result.append(buffer);
Mathias Agopian3d579642009-06-04 18:46:21 -07001515 snprintf(buffer, SIZE, " purgatory size: %d\n", mLayerPurgatory.size());
1516 result.append(buffer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001517 const BufferAllocator& alloc(BufferAllocator::get());
1518 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001519 }
1520 write(fd, result.string(), result.size());
1521 return NO_ERROR;
1522}
1523
1524status_t SurfaceFlinger::onTransact(
1525 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1526{
1527 switch (code) {
1528 case CREATE_CONNECTION:
1529 case OPEN_GLOBAL_TRANSACTION:
1530 case CLOSE_GLOBAL_TRANSACTION:
1531 case SET_ORIENTATION:
1532 case FREEZE_DISPLAY:
1533 case UNFREEZE_DISPLAY:
1534 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535 {
1536 // codes that require permission check
1537 IPCThreadState* ipc = IPCThreadState::self();
1538 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07001539 const int uid = ipc->getCallingUid();
Mathias Agopian375f5632009-06-15 18:24:59 -07001540 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1541 LOGE("Permission Denial: "
1542 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1543 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544 }
1545 }
1546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1548 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopian375f5632009-06-15 18:24:59 -07001549 if (UNLIKELY(!mHardwareTest.checkCalling())) {
1550 IPCThreadState* ipc = IPCThreadState::self();
1551 const int pid = ipc->getCallingPid();
1552 const int uid = ipc->getCallingUid();
1553 LOGE("Permission Denial: "
1554 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001555 return PERMISSION_DENIED;
1556 }
1557 int n;
1558 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001559 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001561 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562 return NO_ERROR;
1563 case 1002: // SHOW_UPDATES
1564 n = data.readInt32();
1565 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1566 return NO_ERROR;
1567 case 1003: // SHOW_BACKGROUND
1568 n = data.readInt32();
1569 mDebugBackground = n ? 1 : 0;
1570 return NO_ERROR;
1571 case 1004:{ // repaint everything
1572 Mutex::Autolock _l(mStateLock);
1573 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1574 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1575 signalEvent();
1576 }
1577 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001578 case 1007: // set mFreezeCount
1579 mFreezeCount = data.readInt32();
1580 return NO_ERROR;
1581 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001582 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583 reply->writeInt32(0);
1584 reply->writeInt32(mDebugRegion);
1585 reply->writeInt32(mDebugBackground);
1586 return NO_ERROR;
1587 case 1013: {
1588 Mutex::Autolock _l(mStateLock);
1589 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1590 reply->writeInt32(hw.getPageFlipCount());
1591 }
1592 return NO_ERROR;
1593 }
1594 }
1595 return err;
1596}
1597
1598// ---------------------------------------------------------------------------
1599#if 0
1600#pragma mark -
1601#endif
1602
1603Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1604 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1605{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001606 const int pgsize = getpagesize();
1607 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1608 mCblkHeap = new MemoryDealer(cblksize);
1609 mCblkMemory = mCblkHeap->allocate(cblksize);
1610 if (mCblkMemory != 0) {
1611 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1612 if (ctrlblk) { // construct the shared structure in-place.
1613 new(ctrlblk) per_client_cblk_t;
1614 }
1615 }
1616}
1617
1618Client::~Client() {
1619 if (ctrlblk) {
1620 const int pgsize = getpagesize();
1621 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1622 }
1623}
1624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001625int32_t Client::generateId(int pid)
1626{
1627 const uint32_t i = clz( ~mBitmap );
1628 if (i >= NUM_LAYERS_MAX) {
1629 return NO_MEMORY;
1630 }
1631 mPid = pid;
1632 mInUse.add(uint8_t(i));
1633 mBitmap |= 1<<(31-i);
1634 return i;
1635}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001636
1637status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001638{
1639 ssize_t idx = mInUse.indexOf(id);
1640 if (idx < 0)
1641 return NAME_NOT_FOUND;
1642 return mLayers.insertAt(layer, idx);
1643}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645void Client::free(int32_t id)
1646{
1647 ssize_t idx = mInUse.remove(uint8_t(id));
1648 if (idx >= 0) {
1649 mBitmap &= ~(1<<(31-id));
1650 mLayers.removeItemsAt(idx);
1651 }
1652}
1653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001654bool Client::isValid(int32_t i) const {
1655 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1656}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001657
1658sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1659 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001660 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001661 if (idx >= 0) {
1662 lbc = mLayers[idx].promote();
1663 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1664 }
1665 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001666}
1667
1668void Client::dump(const char* what)
1669{
1670}
1671
1672// ---------------------------------------------------------------------------
1673#if 0
1674#pragma mark -
1675#endif
1676
1677BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1678 : mId(cid), mFlinger(flinger), mCblk(cblk)
1679{
1680}
1681
1682BClient::~BClient() {
1683 // destroy all resources attached to this client
1684 mFlinger->destroyConnection(mId);
1685}
1686
1687void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1688 *ctrl = mCblk;
1689}
1690
1691sp<ISurface> BClient::createSurface(
1692 ISurfaceFlingerClient::surface_data_t* params, int pid,
1693 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1694 uint32_t flags)
1695{
1696 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1697}
1698
1699status_t BClient::destroySurface(SurfaceID sid)
1700{
1701 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001702 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001703}
1704
1705status_t BClient::setState(int32_t count, const layer_state_t* states)
1706{
1707 return mFlinger->setClientState(mId, count, states);
1708}
1709
1710// ---------------------------------------------------------------------------
1711
1712GraphicPlane::GraphicPlane()
1713 : mHw(0)
1714{
1715}
1716
1717GraphicPlane::~GraphicPlane() {
1718 delete mHw;
1719}
1720
1721bool GraphicPlane::initialized() const {
1722 return mHw ? true : false;
1723}
1724
1725void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1726 mHw = hw;
1727}
1728
1729void GraphicPlane::setTransform(const Transform& tr) {
1730 mTransform = tr;
1731 mGlobalTransform = mOrientationTransform * mTransform;
1732}
1733
1734status_t GraphicPlane::orientationToTransfrom(
1735 int orientation, int w, int h, Transform* tr)
1736{
1737 float a, b, c, d, x, y;
1738 switch (orientation) {
1739 case ISurfaceComposer::eOrientationDefault:
1740 a=1; b=0; c=0; d=1; x=0; y=0;
1741 break;
1742 case ISurfaceComposer::eOrientation90:
1743 a=0; b=-1; c=1; d=0; x=w; y=0;
1744 break;
1745 case ISurfaceComposer::eOrientation180:
1746 a=-1; b=0; c=0; d=-1; x=w; y=h;
1747 break;
1748 case ISurfaceComposer::eOrientation270:
1749 a=0; b=1; c=-1; d=0; x=0; y=h;
1750 break;
1751 default:
1752 return BAD_VALUE;
1753 }
1754 tr->set(a, b, c, d);
1755 tr->set(x, y);
1756 return NO_ERROR;
1757}
1758
1759status_t GraphicPlane::setOrientation(int orientation)
1760{
1761 const DisplayHardware& hw(displayHardware());
1762 const float w = hw.getWidth();
1763 const float h = hw.getHeight();
1764
1765 if (orientation == ISurfaceComposer::eOrientationDefault) {
1766 // make sure the default orientation is optimal
1767 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001768 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769 mGlobalTransform = mTransform;
1770 return NO_ERROR;
1771 }
1772
1773 // If the rotation can be handled in hardware, this is where
1774 // the magic should happen.
1775 if (UNLIKELY(orientation == 42)) {
1776 float a, b, c, d, x, y;
1777 const float r = (3.14159265f / 180.0f) * 42.0f;
1778 const float si = sinf(r);
1779 const float co = cosf(r);
1780 a=co; b=-si; c=si; d=co;
1781 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1782 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1783 mOrientationTransform.set(a, b, c, d);
1784 mOrientationTransform.set(x, y);
1785 } else {
1786 GraphicPlane::orientationToTransfrom(orientation, w, h,
1787 &mOrientationTransform);
1788 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001789 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790 mGlobalTransform = mOrientationTransform * mTransform;
1791 return NO_ERROR;
1792}
1793
1794const DisplayHardware& GraphicPlane::displayHardware() const {
1795 return *mHw;
1796}
1797
1798const Transform& GraphicPlane::transform() const {
1799 return mGlobalTransform;
1800}
1801
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001802EGLDisplay GraphicPlane::getEGLDisplay() const {
1803 return mHw->getEGLDisplay();
1804}
1805
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806// ---------------------------------------------------------------------------
1807
1808}; // namespace android