blob: 0d1be2d06c979b405c1eb81818061d3bca58b1ca [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()),
178 mLastScheduledBroadcast(NULL),
179 mVisibleRegionsDirty(false),
180 mDeferReleaseConsole(false),
181 mFreezeDisplay(false),
182 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700183 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185 mDebugBackground(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186 mConsoleSignals(0),
187 mSecureFrameBuffer(0)
188{
189 init();
190}
191
192void SurfaceFlinger::init()
193{
194 LOGI("SurfaceFlinger is starting");
195
196 // debugging stuff...
197 char value[PROPERTY_VALUE_MAX];
198 property_get("debug.sf.showupdates", value, "0");
199 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 property_get("debug.sf.showbackground", value, "0");
201 mDebugBackground = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202
203 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205}
206
207SurfaceFlinger::~SurfaceFlinger()
208{
209 glDeleteTextures(1, &mWormholeTexName);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210}
211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
213{
214 return graphicPlane(0).displayHardware().getOverlayEngine();
215}
216
217sp<IMemory> SurfaceFlinger::getCblk() const
218{
219 return mServerCblkMemory;
220}
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
223{
224 Mutex::Autolock _l(mStateLock);
225 uint32_t token = mTokens.acquire();
226
227 Client* client = new Client(token, this);
228 if ((client == 0) || (client->ctrlblk == 0)) {
229 mTokens.release(token);
230 return 0;
231 }
232 status_t err = mClientsMap.add(token, client);
233 if (err < 0) {
234 delete client;
235 mTokens.release(token);
236 return 0;
237 }
238 sp<BClient> bclient =
239 new BClient(this, token, client->controlBlockMemory());
240 return bclient;
241}
242
243void SurfaceFlinger::destroyConnection(ClientID cid)
244{
245 Mutex::Autolock _l(mStateLock);
246 Client* const client = mClientsMap.valueFor(cid);
247 if (client) {
248 // free all the layers this client owns
Mathias Agopian3d579642009-06-04 18:46:21 -0700249 Vector< wp<LayerBaseClient> > layers(client->getLayers());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 const size_t count = layers.size();
251 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700252 sp<LayerBaseClient> layer(layers[i].promote());
253 if (layer != 0) {
Mathias Agopian3d579642009-06-04 18:46:21 -0700254 purgatorizeLayer_l(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
257
258 // the resources associated with this client will be freed
259 // during the next transaction, after these surfaces have been
260 // properly removed from the screen
261
262 // remove this client from our ClientID->Client mapping.
263 mClientsMap.removeItem(cid);
264
265 // and add it to the list of disconnected clients
266 mDisconnectedClients.add(client);
267
268 // request a transaction
269 setTransactionFlags(eTransactionNeeded);
270 }
271}
272
273const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
274{
275 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
276 const GraphicPlane& plane(mGraphicPlanes[dpy]);
277 return plane;
278}
279
280GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
281{
282 return const_cast<GraphicPlane&>(
283 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
284}
285
286void SurfaceFlinger::bootFinished()
287{
288 const nsecs_t now = systemTime();
289 const nsecs_t duration = now - mBootTime;
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700290 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
291 property_set("ctl.stop", "bootanim");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292}
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
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700399 // start boot animation
400 property_set("ctl.start", "bootanim");
401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402 return NO_ERROR;
403}
404
405// ----------------------------------------------------------------------------
406#if 0
407#pragma mark -
408#pragma mark Events Handler
409#endif
410
411void SurfaceFlinger::waitForEvent()
412{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700413 while (true) {
414 nsecs_t timeout = -1;
415 if (UNLIKELY(isFrozen())) {
416 // wait 5 seconds
417 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
418 const nsecs_t now = systemTime();
419 if (mFreezeDisplayTime == 0) {
420 mFreezeDisplayTime = now;
421 }
422 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
423 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700424 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700425
Mathias Agopianb6683b52009-04-28 03:17:50 -0700426 MessageList::value_type msg = mEventQueue.waitMessage(timeout);
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700427 if (msg != 0) {
428 mFreezeDisplayTime = 0;
429 switch (msg->what) {
430 case MessageQueue::INVALIDATE:
431 // invalidate message, just return to the main loop
432 return;
433 }
434 } else {
435 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 if (isFrozen()) {
437 // we timed out and are still frozen
438 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
439 mFreezeDisplay, mFreezeCount);
440 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700441 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700442 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443 }
444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 }
446}
447
448void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700449 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450}
451
452void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700453 // this is the IPC call
454 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455}
456
457void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
458{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700459 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460}
461
462// ----------------------------------------------------------------------------
463#if 0
464#pragma mark -
465#pragma mark Main loop
466#endif
467
468bool SurfaceFlinger::threadLoop()
469{
470 waitForEvent();
471
472 // check for transactions
473 if (UNLIKELY(mConsoleSignals)) {
474 handleConsoleEvents();
475 }
476
477 if (LIKELY(mTransactionCount == 0)) {
478 // if we're in a global transaction, don't do anything.
479 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
480 uint32_t transactionFlags = getTransactionFlags(mask);
481 if (LIKELY(transactionFlags)) {
482 handleTransaction(transactionFlags);
483 }
484 }
485
486 // post surfaces (if needed)
487 handlePageFlip();
488
489 const DisplayHardware& hw(graphicPlane(0).displayHardware());
490 if (LIKELY(hw.canDraw())) {
491 // repaint the framebuffer (if needed)
492 handleRepaint();
493
494 // release the clients before we flip ('cause flip might block)
495 unlockClients();
496 executeScheduledBroadcasts();
497
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498 postFramebuffer();
499 } else {
500 // pretend we did the post
501 unlockClients();
502 executeScheduledBroadcasts();
503 usleep(16667); // 60 fps period
504 }
505 return true;
506}
507
508void SurfaceFlinger::postFramebuffer()
509{
Mathias Agopian0926f502009-05-04 14:17:04 -0700510 if (isFrozen()) {
511 // we are not allowed to draw, but pause a bit to make sure
512 // apps don't end up using the whole CPU, if they depend on
513 // surfaceflinger for synchronization.
514 usleep(8333); // 8.3ms ~ 120fps
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515 return;
516 }
517
518 if (!mInvalidRegion.isEmpty()) {
519 const DisplayHardware& hw(graphicPlane(0).displayHardware());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 mInvalidRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522 }
523}
524
525void SurfaceFlinger::handleConsoleEvents()
526{
527 // something to do with the console
528 const DisplayHardware& hw = graphicPlane(0).displayHardware();
529
530 int what = android_atomic_and(0, &mConsoleSignals);
531 if (what & eConsoleAcquired) {
532 hw.acquireScreen();
533 }
534
535 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700536 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 hw.releaseScreen();
539 }
540
541 if (what & eConsoleReleased) {
542 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 hw.releaseScreen();
544 } else {
545 mDeferReleaseConsole = true;
546 }
547 }
548
549 mDirtyRegion.set(hw.bounds());
550}
551
552void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
553{
Mathias Agopian3d579642009-06-04 18:46:21 -0700554 Vector< sp<LayerBase> > ditchedLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555
Mathias Agopian3d579642009-06-04 18:46:21 -0700556 { // scope for the lock
557 Mutex::Autolock _l(mStateLock);
558 handleTransactionLocked(transactionFlags, ditchedLayers);
559 }
560
561 // do this without lock held
562 const size_t count = ditchedLayers.size();
563 for (size_t i=0 ; i<count ; i++) {
564 //LOGD("ditching layer %p", ditchedLayers[i].get());
565 ditchedLayers[i]->ditch();
566 }
567}
568
569void SurfaceFlinger::handleTransactionLocked(
570 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
571{
572 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573 const size_t count = currentLayers.size();
574
575 /*
576 * Traversal of the children
577 * (perform the transaction for each of them if needed)
578 */
579
580 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
581 if (layersNeedTransaction) {
582 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700583 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
585 if (!trFlags) continue;
586
587 const uint32_t flags = layer->doTransaction(0);
588 if (flags & Layer::eVisibleRegion)
589 mVisibleRegionsDirty = true;
590
591 if (flags & Layer::eRestartTransaction) {
592 // restart the transaction, but back-off a little
593 layer->setTransactionFlags(eTransactionNeeded);
594 setTransactionFlags(eTraversalNeeded, ms2ns(8));
595 }
596 }
597 }
598
599 /*
600 * Perform our own transaction if needed
601 */
602
603 if (transactionFlags & eTransactionNeeded) {
604 if (mCurrentState.orientation != mDrawingState.orientation) {
605 // the orientation has changed, recompute all visible regions
606 // and invalidate everything.
607
608 const int dpy = 0;
609 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700610 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800611 GraphicPlane& plane(graphicPlane(dpy));
612 plane.setOrientation(orientation);
613
614 // update the shared control block
615 const DisplayHardware& hw(plane.displayHardware());
616 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
617 dcblk->orientation = orientation;
618 if (orientation & eOrientationSwapMask) {
619 // 90 or 270 degrees orientation
620 dcblk->w = hw.getHeight();
621 dcblk->h = hw.getWidth();
622 } else {
623 dcblk->w = hw.getWidth();
624 dcblk->h = hw.getHeight();
625 }
626
627 mVisibleRegionsDirty = true;
628 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700629 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630 }
631
632 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
633 // freezing or unfreezing the display -> trigger animation if needed
634 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635 }
636
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700637 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
638 // layers have been added
639 mVisibleRegionsDirty = true;
640 }
641
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 // some layers might have been removed, so
643 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700644 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700646 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
Mathias Agopian3d579642009-06-04 18:46:21 -0700647 const size_t count = previousLayers.size();
648 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700649 const sp<LayerBase>& layer(previousLayers[i]);
650 if (currentLayers.indexOf( layer ) < 0) {
651 // this layer is not visible anymore
Mathias Agopian3d579642009-06-04 18:46:21 -0700652 ditchedLayers.add(layer);
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700653 }
654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800655 }
656
657 // get rid of all resources we don't need anymore
658 // (layers and clients)
659 free_resources_l();
660 }
661
662 commitTransaction();
663}
664
665sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
666{
667 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
668}
669
670void SurfaceFlinger::computeVisibleRegions(
671 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
672{
673 const GraphicPlane& plane(graphicPlane(0));
674 const Transform& planeTransform(plane.transform());
675
676 Region aboveOpaqueLayers;
677 Region aboveCoveredLayers;
678 Region dirty;
679
680 bool secureFrameBuffer = false;
681
682 size_t i = currentLayers.size();
683 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700684 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685 layer->validateVisibility(planeTransform);
686
687 // start with the whole surface at its current location
688 const Layer::State& s = layer->drawingState();
689 const Rect bounds(layer->visibleBounds());
690
691 // handle hidden surfaces by setting the visible region to empty
692 Region opaqueRegion;
693 Region visibleRegion;
694 Region coveredRegion;
695 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
696 visibleRegion.clear();
697 } else {
698 const bool translucent = layer->needsBlending();
699 visibleRegion.set(bounds);
700 coveredRegion = visibleRegion;
701
702 // Remove the transparent area from the visible region
703 if (translucent) {
704 visibleRegion.subtractSelf(layer->transparentRegionScreen);
705 }
706
707 // compute the opaque region
708 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
709 // the opaque region is the visible region
710 opaqueRegion = visibleRegion;
711 }
712 }
713
714 // subtract the opaque region covered by the layers above us
715 visibleRegion.subtractSelf(aboveOpaqueLayers);
716 coveredRegion.andSelf(aboveCoveredLayers);
717
718 // compute this layer's dirty region
719 if (layer->contentDirty) {
720 // we need to invalidate the whole region
721 dirty = visibleRegion;
722 // as well, as the old visible region
723 dirty.orSelf(layer->visibleRegionScreen);
724 layer->contentDirty = false;
725 } else {
726 // compute the exposed region
727 // dirty = what's visible now - what's wasn't covered before
728 // = what's visible now & what's was covered before
729 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
730 }
731 dirty.subtractSelf(aboveOpaqueLayers);
732
733 // accumulate to the screen dirty region
734 dirtyRegion.orSelf(dirty);
735
Mathias Agopian62b74442009-04-14 23:02:51 -0700736 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800737 aboveOpaqueLayers.orSelf(opaqueRegion);
738 aboveCoveredLayers.orSelf(bounds);
739
740 // Store the visible region is screen space
741 layer->setVisibleRegion(visibleRegion);
742 layer->setCoveredRegion(coveredRegion);
743
Mathias Agopian62b74442009-04-14 23:02:51 -0700744 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800745 if (layer->isSecure() && !visibleRegion.isEmpty()) {
746 secureFrameBuffer = true;
747 }
748 }
749
750 mSecureFrameBuffer = secureFrameBuffer;
751 opaqueRegion = aboveOpaqueLayers;
752}
753
754
755void SurfaceFlinger::commitTransaction()
756{
757 mDrawingState = mCurrentState;
758 mTransactionCV.signal();
759}
760
761void SurfaceFlinger::handlePageFlip()
762{
763 bool visibleRegions = mVisibleRegionsDirty;
764 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
765 visibleRegions |= lockPageFlip(currentLayers);
766
767 const DisplayHardware& hw = graphicPlane(0).displayHardware();
768 const Region screenRegion(hw.bounds());
769 if (visibleRegions) {
770 Region opaqueRegion;
771 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
772 mWormholeRegion = screenRegion.subtract(opaqueRegion);
773 mVisibleRegionsDirty = false;
774 }
775
776 unlockPageFlip(currentLayers);
777 mDirtyRegion.andSelf(screenRegion);
778}
779
780bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
781{
782 bool recomputeVisibleRegions = false;
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->lockPageFlip(recomputeVisibleRegions);
788 }
789 return recomputeVisibleRegions;
790}
791
792void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
793{
794 const GraphicPlane& plane(graphicPlane(0));
795 const Transform& planeTransform(plane.transform());
796 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700797 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800798 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700799 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800 layer->unlockPageFlip(planeTransform, mDirtyRegion);
801 }
802}
803
804void SurfaceFlinger::handleRepaint()
805{
806 // set the frame buffer
807 const DisplayHardware& hw(graphicPlane(0).displayHardware());
808 glMatrixMode(GL_MODELVIEW);
809 glLoadIdentity();
810
811 if (UNLIKELY(mDebugRegion)) {
812 debugFlashRegions();
813 }
814
815 // compute the invalid region
816 mInvalidRegion.orSelf(mDirtyRegion);
817
818 uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700819 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
820 (flags & DisplayHardware::BUFFER_PRESERVED))
821 {
822 // we can redraw only what's dirty
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800823 } else {
824 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700825 // we need to redraw the rectangle that will be updated
826 // (pushed to the framebuffer).
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827 mDirtyRegion.set(mInvalidRegion.bounds());
828 } else {
829 // we need to redraw everything
830 mDirtyRegion.set(hw.bounds());
831 mInvalidRegion = mDirtyRegion;
832 }
833 }
834
835 // compose all surfaces
836 composeSurfaces(mDirtyRegion);
837
838 // clear the dirty regions
839 mDirtyRegion.clear();
840}
841
842void SurfaceFlinger::composeSurfaces(const Region& dirty)
843{
844 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
845 // should never happen unless the window manager has a bug
846 // draw something...
847 drawWormhole();
848 }
849 const SurfaceFlinger& flinger(*this);
850 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
851 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700852 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800853 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700854 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855 const Region& visibleRegion(layer->visibleRegionScreen);
856 if (!visibleRegion.isEmpty()) {
857 const Region clip(dirty.intersect(visibleRegion));
858 if (!clip.isEmpty()) {
859 layer->draw(clip);
860 }
861 }
862 }
863}
864
865void SurfaceFlinger::unlockClients()
866{
867 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
868 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700869 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800870 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700871 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800872 layer->finishPageFlip();
873 }
874}
875
876void SurfaceFlinger::scheduleBroadcast(Client* client)
877{
878 if (mLastScheduledBroadcast != client) {
879 mLastScheduledBroadcast = client;
880 mScheduledBroadcasts.add(client);
881 }
882}
883
884void SurfaceFlinger::executeScheduledBroadcasts()
885{
886 SortedVector<Client*>& list = mScheduledBroadcasts;
887 size_t count = list.size();
888 while (count--) {
889 per_client_cblk_t* const cblk = list[count]->ctrlblk;
890 if (cblk->lock.tryLock() == NO_ERROR) {
891 cblk->cv.broadcast();
892 list.removeAt(count);
893 cblk->lock.unlock();
894 } else {
895 // schedule another round
896 LOGW("executeScheduledBroadcasts() skipped, "
897 "contention on the client. We'll try again later...");
898 signalDelayedEvent(ms2ns(4));
899 }
900 }
901 mLastScheduledBroadcast = 0;
902}
903
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800904void SurfaceFlinger::debugFlashRegions()
905{
Mathias Agopian0926f502009-05-04 14:17:04 -0700906 const DisplayHardware& hw(graphicPlane(0).displayHardware());
907 const uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700908
909 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
910 (flags & DisplayHardware::BUFFER_PRESERVED))) {
Mathias Agopian0926f502009-05-04 14:17:04 -0700911 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
912 mDirtyRegion.bounds() : hw.bounds());
913 composeSurfaces(repaint);
914 }
915
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800916 glDisable(GL_TEXTURE_2D);
917 glDisable(GL_BLEND);
918 glDisable(GL_DITHER);
919 glDisable(GL_SCISSOR_TEST);
920
Mathias Agopian0926f502009-05-04 14:17:04 -0700921 static int toggle = 0;
922 toggle = 1 - toggle;
923 if (toggle) {
924 glColor4x(0x10000, 0, 0x10000, 0x10000);
925 } else {
926 glColor4x(0x10000, 0x10000, 0, 0x10000);
927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800928
Mathias Agopian20f68782009-05-11 00:03:41 -0700929 Region::const_iterator it = mDirtyRegion.begin();
930 Region::const_iterator const end = mDirtyRegion.end();
931 while (it != end) {
932 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800933 GLfloat vertices[][2] = {
934 { r.left, r.top },
935 { r.left, r.bottom },
936 { r.right, r.bottom },
937 { r.right, r.top }
938 };
939 glVertexPointer(2, GL_FLOAT, 0, vertices);
940 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
941 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700942
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800943 hw.flip(mDirtyRegion.merge(mInvalidRegion));
944 mInvalidRegion.clear();
945
946 if (mDebugRegion > 1)
947 usleep(mDebugRegion * 1000);
948
949 glEnable(GL_SCISSOR_TEST);
950 //mDirtyRegion.dump("mDirtyRegion");
951}
952
953void SurfaceFlinger::drawWormhole() const
954{
955 const Region region(mWormholeRegion.intersect(mDirtyRegion));
956 if (region.isEmpty())
957 return;
958
959 const DisplayHardware& hw(graphicPlane(0).displayHardware());
960 const int32_t width = hw.getWidth();
961 const int32_t height = hw.getHeight();
962
963 glDisable(GL_BLEND);
964 glDisable(GL_DITHER);
965
966 if (LIKELY(!mDebugBackground)) {
967 glClearColorx(0,0,0,0);
Mathias Agopian20f68782009-05-11 00:03:41 -0700968 Region::const_iterator it = region.begin();
969 Region::const_iterator const end = region.end();
970 while (it != end) {
971 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800972 const GLint sy = height - (r.top + r.height());
973 glScissor(r.left, sy, r.width(), r.height());
974 glClear(GL_COLOR_BUFFER_BIT);
975 }
976 } else {
977 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
978 { width, height }, { 0, height } };
979 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
980 glVertexPointer(2, GL_SHORT, 0, vertices);
981 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
982 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
983 glEnable(GL_TEXTURE_2D);
984 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
985 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
986 glMatrixMode(GL_TEXTURE);
987 glLoadIdentity();
988 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
Mathias Agopian20f68782009-05-11 00:03:41 -0700989 Region::const_iterator it = region.begin();
990 Region::const_iterator const end = region.end();
991 while (it != end) {
992 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993 const GLint sy = height - (r.top + r.height());
994 glScissor(r.left, sy, r.width(), r.height());
995 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
996 }
997 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
998 }
999}
1000
1001void SurfaceFlinger::debugShowFPS() const
1002{
1003 static int mFrameCount;
1004 static int mLastFrameCount = 0;
1005 static nsecs_t mLastFpsTime = 0;
1006 static float mFps = 0;
1007 mFrameCount++;
1008 nsecs_t now = systemTime();
1009 nsecs_t diff = now - mLastFpsTime;
1010 if (diff > ms2ns(250)) {
1011 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1012 mLastFpsTime = now;
1013 mLastFrameCount = mFrameCount;
1014 }
1015 // XXX: mFPS has the value we want
1016 }
1017
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001018status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019{
1020 Mutex::Autolock _l(mStateLock);
1021 addLayer_l(layer);
1022 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1023 return NO_ERROR;
1024}
1025
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001026status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027{
1028 Mutex::Autolock _l(mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001029 status_t err = purgatorizeLayer_l(layer);
1030 if (err == NO_ERROR)
1031 setTransactionFlags(eTransactionNeeded);
1032 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033}
1034
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001035status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036{
1037 layer->forceVisibilityTransaction();
1038 setTransactionFlags(eTraversalNeeded);
1039 return NO_ERROR;
1040}
1041
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001042status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043{
1044 ssize_t i = mCurrentState.layersSortedByZ.add(
1045 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001046 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1047 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048 mLayerMap.add(lbc->serverIndex(), lbc);
1049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001050 return NO_ERROR;
1051}
1052
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001053status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001054{
1055 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1056 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001057 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001058 sp<LayerBaseClient> layer =
1059 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001060 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001061 mLayerMap.removeItem(layer->serverIndex());
1062 }
1063 return NO_ERROR;
1064 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001065 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066}
1067
Mathias Agopian9a112062009-04-17 19:36:26 -07001068status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1069{
1070 // First add the layer to the purgatory list, which makes sure it won't
1071 // go away, then remove it from the main list (through a transaction).
1072 ssize_t err = removeLayer_l(layerBase);
1073 if (err >= 0) {
1074 mLayerPurgatory.add(layerBase);
1075 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001076 // it's possible that we don't find a layer, because it might
1077 // have been destroyed already -- this is not technically an error
1078 // from the user because there is a race between BClient::destroySurface(),
1079 // ~BClient() and ~ISurface().
Mathias Agopian9a112062009-04-17 19:36:26 -07001080 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1081}
1082
1083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001084void SurfaceFlinger::free_resources_l()
1085{
1086 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001087 mLayersRemoved = false;
1088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089 // free resources associated with disconnected clients
1090 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1091 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1092 const size_t count = disconnectedClients.size();
1093 for (size_t i=0 ; i<count ; i++) {
1094 Client* client = disconnectedClients[i];
1095 // if this client is the scheduled broadcast list,
1096 // remove it from there (and we don't need to signal it
1097 // since it is dead).
1098 int32_t index = scheduledBroadcasts.indexOf(client);
1099 if (index >= 0) {
1100 scheduledBroadcasts.removeItemsAt(index);
1101 }
1102 mTokens.release(client->cid);
1103 delete client;
1104 }
1105 disconnectedClients.clear();
1106}
1107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001108uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1109{
1110 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1111}
1112
1113uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1114{
1115 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1116 if ((old & flags)==0) { // wake the server up
1117 if (delay > 0) {
1118 signalDelayedEvent(delay);
1119 } else {
1120 signalEvent();
1121 }
1122 }
1123 return old;
1124}
1125
1126void SurfaceFlinger::openGlobalTransaction()
1127{
1128 android_atomic_inc(&mTransactionCount);
1129}
1130
1131void SurfaceFlinger::closeGlobalTransaction()
1132{
1133 if (android_atomic_dec(&mTransactionCount) == 1) {
1134 signalEvent();
1135 }
1136}
1137
1138status_t SurfaceFlinger::freezeDisplay(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 = 1;
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
1152status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1153{
1154 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1155 return BAD_VALUE;
1156
1157 Mutex::Autolock _l(mStateLock);
1158 mCurrentState.freezeDisplay = 0;
1159 setTransactionFlags(eTransactionNeeded);
1160
1161 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001162 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001163 return NO_ERROR;
1164}
1165
Mathias Agopianc08731e2009-03-27 18:11:38 -07001166int SurfaceFlinger::setOrientation(DisplayID dpy,
1167 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001168{
1169 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1170 return BAD_VALUE;
1171
1172 Mutex::Autolock _l(mStateLock);
1173 if (mCurrentState.orientation != orientation) {
1174 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001175 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176 mCurrentState.orientation = orientation;
1177 setTransactionFlags(eTransactionNeeded);
1178 mTransactionCV.wait(mStateLock);
1179 } else {
1180 orientation = BAD_VALUE;
1181 }
1182 }
1183 return orientation;
1184}
1185
1186sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1187 ISurfaceFlingerClient::surface_data_t* params,
1188 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1189 uint32_t flags)
1190{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001191 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001192 sp<LayerBaseClient::Surface> surfaceHandle;
1193 Mutex::Autolock _l(mStateLock);
1194 Client* const c = mClientsMap.valueFor(clientId);
1195 if (UNLIKELY(!c)) {
1196 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1197 return surfaceHandle;
1198 }
1199
1200 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1201 int32_t id = c->generateId(pid);
1202 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1203 LOGE("createSurface() failed, generateId = %d", id);
1204 return surfaceHandle;
1205 }
1206
1207 switch (flags & eFXSurfaceMask) {
1208 case eFXSurfaceNormal:
1209 if (UNLIKELY(flags & ePushBuffers)) {
1210 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1211 } else {
1212 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1213 }
1214 break;
1215 case eFXSurfaceBlur:
1216 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1217 break;
1218 case eFXSurfaceDim:
1219 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1220 break;
1221 }
1222
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001223 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001224 setTransactionFlags(eTransactionNeeded);
1225 surfaceHandle = layer->getSurface();
1226 if (surfaceHandle != 0)
1227 surfaceHandle->getSurfaceData(params);
1228 }
1229
1230 return surfaceHandle;
1231}
1232
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001233sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001234 Client* client, DisplayID display,
1235 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1236{
1237 // initialize the surfaces
1238 switch (format) { // TODO: take h/w into account
1239 case PIXEL_FORMAT_TRANSPARENT:
1240 case PIXEL_FORMAT_TRANSLUCENT:
1241 format = PIXEL_FORMAT_RGBA_8888;
1242 break;
1243 case PIXEL_FORMAT_OPAQUE:
1244 format = PIXEL_FORMAT_RGB_565;
1245 break;
1246 }
1247
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001248 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249 status_t err = layer->setBuffers(client, w, h, format, flags);
1250 if (LIKELY(err == NO_ERROR)) {
1251 layer->initStates(w, h, flags);
1252 addLayer_l(layer);
1253 } else {
1254 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001255 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256 }
1257 return layer;
1258}
1259
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001260sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261 Client* client, DisplayID display,
1262 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1263{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001264 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001265 layer->initStates(w, h, flags);
1266 addLayer_l(layer);
1267 return layer;
1268}
1269
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001270sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001271 Client* client, DisplayID display,
1272 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1273{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001274 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001275 layer->initStates(w, h, flags);
1276 addLayer_l(layer);
1277 return layer;
1278}
1279
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001280sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281 Client* client, DisplayID display,
1282 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1283{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001284 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001285 layer->initStates(w, h, flags);
1286 addLayer_l(layer);
1287 return layer;
1288}
1289
Mathias Agopian9a112062009-04-17 19:36:26 -07001290status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001291{
Mathias Agopian9a112062009-04-17 19:36:26 -07001292 /*
1293 * called by the window manager, when a surface should be marked for
1294 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001295 *
1296 * The surface is removed from the current and drawing lists, but placed
1297 * in the purgatory queue, so it's not destroyed right-away (we need
1298 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001299 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001300
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001301 Mutex::Autolock _l(mStateLock);
1302 sp<LayerBaseClient> layer = getLayerUser_l(index);
1303 status_t err = purgatorizeLayer_l(layer);
1304 if (err == NO_ERROR) {
1305 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001306 }
1307 return err;
1308}
1309
1310status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1311{
Mathias Agopian3d579642009-06-04 18:46:21 -07001312 /* called by ~ISurface() when all references are gone */
Mathias Agopian9a112062009-04-17 19:36:26 -07001313
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001314 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001315 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001316 sp<LayerBaseClient> layer;
1317 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001318 MessageDestroySurface(
1319 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1320 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001321 virtual bool handler() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001322 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001323 // remove the layer from the current list -- chances are that it's
1324 // not in the list anyway, because it should have been removed
1325 // already upon request of the client (eg: window manager).
1326 // However, a buggy client could have not done that.
1327 // Since we know we don't have any more clients, we don't need
1328 // to use the purgatory.
1329 status_t err = flinger->removeLayer_l(layer);
1330 if (err == NAME_NOT_FOUND) {
1331 // The surface wasn't in the current list, which means it was
1332 // removed already, which means it is in the purgatory,
1333 // and need to be removed from there.
1334 // This needs to happen from the main thread since its dtor
1335 // must run from there (b/c of OpenGL ES). Additionally, we
1336 // can't really acquire our internal lock from
1337 // destroySurface() -- see postMessage() below.
1338 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1339 LOGE_IF(idx < 0,
1340 "layer=%p is not in the purgatory list", layer.get());
1341 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001342 return true;
1343 }
1344 };
Mathias Agopian3d579642009-06-04 18:46:21 -07001345
1346 // It's better to not acquire our internal lock here, because it's hard
1347 // to predict that it's not going to be already taken when ~Surface()
1348 // is called.
1349
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001350 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351 return NO_ERROR;
1352}
1353
1354status_t SurfaceFlinger::setClientState(
1355 ClientID cid,
1356 int32_t count,
1357 const layer_state_t* states)
1358{
1359 Mutex::Autolock _l(mStateLock);
1360 uint32_t flags = 0;
1361 cid <<= 16;
1362 for (int i=0 ; i<count ; i++) {
1363 const layer_state_t& s = states[i];
Mathias Agopian3d579642009-06-04 18:46:21 -07001364 sp<LayerBaseClient> layer(getLayerUser_l(s.surface | cid));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001365 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001366 const uint32_t what = s.what;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001367 if (what & ePositionChanged) {
1368 if (layer->setPosition(s.x, s.y))
1369 flags |= eTraversalNeeded;
1370 }
1371 if (what & eLayerChanged) {
1372 if (layer->setLayer(s.z)) {
1373 mCurrentState.layersSortedByZ.reorder(
1374 layer, &Layer::compareCurrentStateZ);
1375 // we need traversal (state changed)
1376 // AND transaction (list changed)
1377 flags |= eTransactionNeeded|eTraversalNeeded;
1378 }
1379 }
1380 if (what & eSizeChanged) {
1381 if (layer->setSize(s.w, s.h))
1382 flags |= eTraversalNeeded;
1383 }
1384 if (what & eAlphaChanged) {
1385 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1386 flags |= eTraversalNeeded;
1387 }
1388 if (what & eMatrixChanged) {
1389 if (layer->setMatrix(s.matrix))
1390 flags |= eTraversalNeeded;
1391 }
1392 if (what & eTransparentRegionChanged) {
1393 if (layer->setTransparentRegionHint(s.transparentRegion))
1394 flags |= eTraversalNeeded;
1395 }
1396 if (what & eVisibilityChanged) {
1397 if (layer->setFlags(s.flags, s.mask))
1398 flags |= eTraversalNeeded;
1399 }
1400 }
1401 }
1402 if (flags) {
1403 setTransactionFlags(flags);
1404 }
1405 return NO_ERROR;
1406}
1407
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001408sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001409{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001410 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1411 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001412}
1413
1414void SurfaceFlinger::screenReleased(int dpy)
1415{
1416 // this may be called by a signal handler, we can't do too much in here
1417 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1418 signalEvent();
1419}
1420
1421void SurfaceFlinger::screenAcquired(int dpy)
1422{
1423 // this may be called by a signal handler, we can't do too much in here
1424 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1425 signalEvent();
1426}
1427
1428status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1429{
1430 const size_t SIZE = 1024;
1431 char buffer[SIZE];
1432 String8 result;
1433 if (checkCallingPermission(
1434 String16("android.permission.DUMP")) == false)
1435 { // not allowed
1436 snprintf(buffer, SIZE, "Permission Denial: "
1437 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1438 IPCThreadState::self()->getCallingPid(),
1439 IPCThreadState::self()->getCallingUid());
1440 result.append(buffer);
1441 } else {
1442 Mutex::Autolock _l(mStateLock);
1443 size_t s = mClientsMap.size();
1444 char name[64];
1445 for (size_t i=0 ; i<s ; i++) {
1446 Client* client = mClientsMap.valueAt(i);
1447 sprintf(name, " Client (id=0x%08x)", client->cid);
1448 client->dump(name);
1449 }
1450 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1451 const size_t count = currentLayers.size();
1452 for (size_t i=0 ; i<count ; i++) {
1453 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001454 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001455 const Layer::State& s = layer->drawingState();
1456 snprintf(buffer, SIZE,
1457 "+ %s %p\n"
1458 " "
1459 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1460 "needsBlending=%1d, invalidate=%1d, "
1461 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001462 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463 s.z, layer->tx(), layer->ty(), s.w, s.h,
1464 layer->needsBlending(), layer->contentDirty,
1465 s.alpha, s.flags,
1466 s.transform[0], s.transform[1],
1467 s.transform[2], s.transform[3]);
1468 result.append(buffer);
1469 buffer[0] = 0;
1470 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001471 sp<LayerBaseClient> lbc =
1472 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1473 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001474 snprintf(buffer, SIZE,
1475 " "
1476 "id=0x%08x, client=0x%08x, identity=%u\n",
1477 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1478 lbc->getIdentity());
1479 }
1480 result.append(buffer);
1481 buffer[0] = 0;
1482 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001483 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1484 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001485 const LayerBitmap& buf0(l->getBuffer(0));
1486 const LayerBitmap& buf1(l->getBuffer(1));
1487 snprintf(buffer, SIZE,
1488 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001489 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001490 " freezeLock=%p, swapState=0x%08x\n",
1491 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001492 buf0.getWidth(), buf0.getHeight(),
1493 buf0.getBuffer()->getStride(),
1494 buf1.getWidth(), buf1.getHeight(),
1495 buf1.getBuffer()->getStride(),
1496 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001497 l->lcblk->swapState);
1498 }
1499 result.append(buffer);
1500 buffer[0] = 0;
1501 s.transparentRegion.dump(result, "transparentRegion");
1502 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1503 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1504 }
1505 mWormholeRegion.dump(result, "WormholeRegion");
1506 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1507 snprintf(buffer, SIZE,
1508 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1509 mFreezeDisplay?"yes":"no", mFreezeCount,
1510 mCurrentState.orientation, hw.canDraw());
1511 result.append(buffer);
Mathias Agopian3d579642009-06-04 18:46:21 -07001512 snprintf(buffer, SIZE, " purgatory size: %d\n", mLayerPurgatory.size());
1513 result.append(buffer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001514 const BufferAllocator& alloc(BufferAllocator::get());
1515 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516 }
1517 write(fd, result.string(), result.size());
1518 return NO_ERROR;
1519}
1520
1521status_t SurfaceFlinger::onTransact(
1522 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1523{
1524 switch (code) {
1525 case CREATE_CONNECTION:
1526 case OPEN_GLOBAL_TRANSACTION:
1527 case CLOSE_GLOBAL_TRANSACTION:
1528 case SET_ORIENTATION:
1529 case FREEZE_DISPLAY:
1530 case UNFREEZE_DISPLAY:
1531 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001532 {
1533 // codes that require permission check
1534 IPCThreadState* ipc = IPCThreadState::self();
1535 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07001536 const int uid = ipc->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001537 const int self_pid = getpid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07001538 if (UNLIKELY(pid != self_pid && uid != AID_GRAPHICS)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001539 // we're called from a different process, do the real check
1540 if (!checkCallingPermission(
1541 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1542 {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001543 LOGE("Permission Denial: "
1544 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1545 return PERMISSION_DENIED;
1546 }
1547 }
1548 }
1549 }
1550
1551 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1552 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1553 // HARDWARE_TEST stuff...
1554 if (UNLIKELY(checkCallingPermission(
1555 String16("android.permission.HARDWARE_TEST")) == false))
1556 { // not allowed
1557 LOGE("Permission Denial: pid=%d, uid=%d\n",
1558 IPCThreadState::self()->getCallingPid(),
1559 IPCThreadState::self()->getCallingUid());
1560 return PERMISSION_DENIED;
1561 }
1562 int n;
1563 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001564 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001565 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001566 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001567 return NO_ERROR;
1568 case 1002: // SHOW_UPDATES
1569 n = data.readInt32();
1570 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1571 return NO_ERROR;
1572 case 1003: // SHOW_BACKGROUND
1573 n = data.readInt32();
1574 mDebugBackground = n ? 1 : 0;
1575 return NO_ERROR;
1576 case 1004:{ // repaint everything
1577 Mutex::Autolock _l(mStateLock);
1578 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1579 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1580 signalEvent();
1581 }
1582 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583 case 1007: // set mFreezeCount
1584 mFreezeCount = data.readInt32();
1585 return NO_ERROR;
1586 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001587 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001588 reply->writeInt32(0);
1589 reply->writeInt32(mDebugRegion);
1590 reply->writeInt32(mDebugBackground);
1591 return NO_ERROR;
1592 case 1013: {
1593 Mutex::Autolock _l(mStateLock);
1594 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1595 reply->writeInt32(hw.getPageFlipCount());
1596 }
1597 return NO_ERROR;
1598 }
1599 }
1600 return err;
1601}
1602
1603// ---------------------------------------------------------------------------
1604#if 0
1605#pragma mark -
1606#endif
1607
1608Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1609 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1610{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001611 const int pgsize = getpagesize();
1612 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1613 mCblkHeap = new MemoryDealer(cblksize);
1614 mCblkMemory = mCblkHeap->allocate(cblksize);
1615 if (mCblkMemory != 0) {
1616 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1617 if (ctrlblk) { // construct the shared structure in-place.
1618 new(ctrlblk) per_client_cblk_t;
1619 }
1620 }
1621}
1622
1623Client::~Client() {
1624 if (ctrlblk) {
1625 const int pgsize = getpagesize();
1626 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1627 }
1628}
1629
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001630int32_t Client::generateId(int pid)
1631{
1632 const uint32_t i = clz( ~mBitmap );
1633 if (i >= NUM_LAYERS_MAX) {
1634 return NO_MEMORY;
1635 }
1636 mPid = pid;
1637 mInUse.add(uint8_t(i));
1638 mBitmap |= 1<<(31-i);
1639 return i;
1640}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001641
1642status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001643{
1644 ssize_t idx = mInUse.indexOf(id);
1645 if (idx < 0)
1646 return NAME_NOT_FOUND;
1647 return mLayers.insertAt(layer, idx);
1648}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001649
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001650void Client::free(int32_t id)
1651{
1652 ssize_t idx = mInUse.remove(uint8_t(id));
1653 if (idx >= 0) {
1654 mBitmap &= ~(1<<(31-id));
1655 mLayers.removeItemsAt(idx);
1656 }
1657}
1658
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001659bool Client::isValid(int32_t i) const {
1660 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1661}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001662
1663sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1664 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001665 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001666 if (idx >= 0) {
1667 lbc = mLayers[idx].promote();
1668 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1669 }
1670 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001671}
1672
1673void Client::dump(const char* what)
1674{
1675}
1676
1677// ---------------------------------------------------------------------------
1678#if 0
1679#pragma mark -
1680#endif
1681
1682BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1683 : mId(cid), mFlinger(flinger), mCblk(cblk)
1684{
1685}
1686
1687BClient::~BClient() {
1688 // destroy all resources attached to this client
1689 mFlinger->destroyConnection(mId);
1690}
1691
1692void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1693 *ctrl = mCblk;
1694}
1695
1696sp<ISurface> BClient::createSurface(
1697 ISurfaceFlingerClient::surface_data_t* params, int pid,
1698 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1699 uint32_t flags)
1700{
1701 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1702}
1703
1704status_t BClient::destroySurface(SurfaceID sid)
1705{
1706 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001707 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001708}
1709
1710status_t BClient::setState(int32_t count, const layer_state_t* states)
1711{
1712 return mFlinger->setClientState(mId, count, states);
1713}
1714
1715// ---------------------------------------------------------------------------
1716
1717GraphicPlane::GraphicPlane()
1718 : mHw(0)
1719{
1720}
1721
1722GraphicPlane::~GraphicPlane() {
1723 delete mHw;
1724}
1725
1726bool GraphicPlane::initialized() const {
1727 return mHw ? true : false;
1728}
1729
1730void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1731 mHw = hw;
1732}
1733
1734void GraphicPlane::setTransform(const Transform& tr) {
1735 mTransform = tr;
1736 mGlobalTransform = mOrientationTransform * mTransform;
1737}
1738
1739status_t GraphicPlane::orientationToTransfrom(
1740 int orientation, int w, int h, Transform* tr)
1741{
1742 float a, b, c, d, x, y;
1743 switch (orientation) {
1744 case ISurfaceComposer::eOrientationDefault:
1745 a=1; b=0; c=0; d=1; x=0; y=0;
1746 break;
1747 case ISurfaceComposer::eOrientation90:
1748 a=0; b=-1; c=1; d=0; x=w; y=0;
1749 break;
1750 case ISurfaceComposer::eOrientation180:
1751 a=-1; b=0; c=0; d=-1; x=w; y=h;
1752 break;
1753 case ISurfaceComposer::eOrientation270:
1754 a=0; b=1; c=-1; d=0; x=0; y=h;
1755 break;
1756 default:
1757 return BAD_VALUE;
1758 }
1759 tr->set(a, b, c, d);
1760 tr->set(x, y);
1761 return NO_ERROR;
1762}
1763
1764status_t GraphicPlane::setOrientation(int orientation)
1765{
1766 const DisplayHardware& hw(displayHardware());
1767 const float w = hw.getWidth();
1768 const float h = hw.getHeight();
1769
1770 if (orientation == ISurfaceComposer::eOrientationDefault) {
1771 // make sure the default orientation is optimal
1772 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001773 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001774 mGlobalTransform = mTransform;
1775 return NO_ERROR;
1776 }
1777
1778 // If the rotation can be handled in hardware, this is where
1779 // the magic should happen.
1780 if (UNLIKELY(orientation == 42)) {
1781 float a, b, c, d, x, y;
1782 const float r = (3.14159265f / 180.0f) * 42.0f;
1783 const float si = sinf(r);
1784 const float co = cosf(r);
1785 a=co; b=-si; c=si; d=co;
1786 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1787 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1788 mOrientationTransform.set(a, b, c, d);
1789 mOrientationTransform.set(x, y);
1790 } else {
1791 GraphicPlane::orientationToTransfrom(orientation, w, h,
1792 &mOrientationTransform);
1793 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001794 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 mGlobalTransform = mOrientationTransform * mTransform;
1796 return NO_ERROR;
1797}
1798
1799const DisplayHardware& GraphicPlane::displayHardware() const {
1800 return *mHw;
1801}
1802
1803const Transform& GraphicPlane::transform() const {
1804 return mGlobalTransform;
1805}
1806
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001807EGLDisplay GraphicPlane::getEGLDisplay() const {
1808 return mHw->getEGLDisplay();
1809}
1810
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811// ---------------------------------------------------------------------------
1812
1813}; // namespace android