blob: 1b6d6def59c53634c0cd0f399b27c5aaa83c2065 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080017#include <stdlib.h>
18#include <stdio.h>
19#include <stdint.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <errno.h>
23#include <math.h>
Jean-Baptiste Querua837ba72009-01-26 11:51:12 -080024#include <limits.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/ioctl.h>
28
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
32#include <utils/IPCThreadState.h>
33#include <utils/IServiceManager.h>
34#include <utils/MemoryDealer.h>
35#include <utils/MemoryBase.h>
36#include <utils/String8.h>
37#include <utils/String16.h>
38#include <utils/StopWatch.h>
39
40#include <ui/PixelFormat.h>
41#include <ui/DisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
43#include <pixelflinger/pixelflinger.h>
44#include <GLES/gl.h>
45
46#include "clz.h"
Mathias Agopian076b1cc2009-04-10 14:24:30 -070047#include "BufferAllocator.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#include "Layer.h"
49#include "LayerBlur.h"
50#include "LayerBuffer.h"
51#include "LayerDim.h"
52#include "LayerBitmap.h"
53#include "LayerOrientationAnim.h"
54#include "OrientationAnimation.h"
55#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056
57#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#define DISPLAY_COUNT 1
60
61namespace android {
62
63// ---------------------------------------------------------------------------
64
65void SurfaceFlinger::instantiate() {
66 defaultServiceManager()->addService(
67 String16("SurfaceFlinger"), new SurfaceFlinger());
68}
69
70void SurfaceFlinger::shutdown() {
71 // we should unregister here, but not really because
72 // when (if) the service manager goes away, all the services
73 // it has a reference to will leave too.
74}
75
76// ---------------------------------------------------------------------------
77
78SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
79 : lookup(rhs.lookup), layers(rhs.layers)
80{
81}
82
83ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070084 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085{
86 if (guess<size() && lookup.keyAt(guess) == key)
87 return guess;
88 const ssize_t i = lookup.indexOfKey(key);
89 if (i>=0) {
90 const size_t idx = lookup.valueAt(i);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070091 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070093 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094 return idx;
95 }
96 return i;
97}
98
99ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700100 const sp<LayerBase>& layer,
101 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102{
103 size_t count = layers.size();
104 ssize_t l = 0;
105 ssize_t h = count-1;
106 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700107 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108 while (l <= h) {
109 mid = l + (h - l)/2;
110 const int c = cmp(a+mid, &layer);
111 if (c == 0) { l = mid; break; }
112 else if (c<0) { l = mid+1; }
113 else { h = mid-1; }
114 }
115 size_t order = l;
116 while (order<count && !cmp(&layer, a+order)) {
117 order++;
118 }
119 count = lookup.size();
120 for (size_t i=0 ; i<count ; i++) {
121 if (lookup.valueAt(i) >= order) {
122 lookup.editValueAt(i)++;
123 }
124 }
125 layers.insertAt(layer, order);
126 lookup.add(layer, order);
127 return order;
128}
129
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131{
132 const ssize_t keyIndex = lookup.indexOfKey(layer);
133 if (keyIndex >= 0) {
134 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700137 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 layers.removeItemsAt(index);
139 lookup.removeItemsAt(keyIndex);
140 const size_t count = lookup.size();
141 for (size_t i=0 ; i<count ; i++) {
142 if (lookup.valueAt(i) >= size_t(index)) {
143 lookup.editValueAt(i)--;
144 }
145 }
146 return index;
147 }
148 return NAME_NOT_FOUND;
149}
150
151ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700152 const sp<LayerBase>& layer,
153 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154{
155 // XXX: it's a little lame. but oh well...
156 ssize_t err = remove(layer);
157 if (err >=0)
158 err = add(layer, cmp);
159 return err;
160}
161
162// ---------------------------------------------------------------------------
163#if 0
164#pragma mark -
165#endif
166
167SurfaceFlinger::SurfaceFlinger()
168 : BnSurfaceComposer(), Thread(false),
169 mTransactionFlags(0),
170 mTransactionCount(0),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mBootTime(systemTime()),
173 mLastScheduledBroadcast(NULL),
174 mVisibleRegionsDirty(false),
175 mDeferReleaseConsole(false),
176 mFreezeDisplay(false),
177 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700178 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 mDebugFps(0),
181 mDebugBackground(0),
182 mDebugNoBootAnimation(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 mConsoleSignals(0),
184 mSecureFrameBuffer(0)
185{
186 init();
187}
188
189void SurfaceFlinger::init()
190{
191 LOGI("SurfaceFlinger is starting");
192
193 // debugging stuff...
194 char value[PROPERTY_VALUE_MAX];
195 property_get("debug.sf.showupdates", value, "0");
196 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 property_get("debug.sf.showbackground", value, "0");
198 mDebugBackground = atoi(value);
199 property_get("debug.sf.showfps", value, "0");
200 mDebugFps = atoi(value);
201 property_get("debug.sf.nobootanimation", value, "0");
202 mDebugNoBootAnimation = atoi(value);
203
204 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 LOGI_IF(mDebugBackground, "showbackground enabled");
206 LOGI_IF(mDebugFps, "showfps enabled");
207 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
208}
209
210SurfaceFlinger::~SurfaceFlinger()
211{
212 glDeleteTextures(1, &mWormholeTexName);
213 delete mOrientationAnimation;
214}
215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
217{
218 return graphicPlane(0).displayHardware().getOverlayEngine();
219}
220
221sp<IMemory> SurfaceFlinger::getCblk() const
222{
223 return mServerCblkMemory;
224}
225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
227{
228 Mutex::Autolock _l(mStateLock);
229 uint32_t token = mTokens.acquire();
230
231 Client* client = new Client(token, this);
232 if ((client == 0) || (client->ctrlblk == 0)) {
233 mTokens.release(token);
234 return 0;
235 }
236 status_t err = mClientsMap.add(token, client);
237 if (err < 0) {
238 delete client;
239 mTokens.release(token);
240 return 0;
241 }
242 sp<BClient> bclient =
243 new BClient(this, token, client->controlBlockMemory());
244 return bclient;
245}
246
247void SurfaceFlinger::destroyConnection(ClientID cid)
248{
249 Mutex::Autolock _l(mStateLock);
250 Client* const client = mClientsMap.valueFor(cid);
251 if (client) {
252 // free all the layers this client owns
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700253 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 const size_t count = layers.size();
255 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700256 sp<LayerBaseClient> layer(layers[i].promote());
257 if (layer != 0) {
258 removeLayer_l(layer);
259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 }
261
262 // the resources associated with this client will be freed
263 // during the next transaction, after these surfaces have been
264 // properly removed from the screen
265
266 // remove this client from our ClientID->Client mapping.
267 mClientsMap.removeItem(cid);
268
269 // and add it to the list of disconnected clients
270 mDisconnectedClients.add(client);
271
272 // request a transaction
273 setTransactionFlags(eTransactionNeeded);
274 }
275}
276
277const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
278{
279 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
280 const GraphicPlane& plane(mGraphicPlanes[dpy]);
281 return plane;
282}
283
284GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
285{
286 return const_cast<GraphicPlane&>(
287 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
288}
289
290void SurfaceFlinger::bootFinished()
291{
292 const nsecs_t now = systemTime();
293 const nsecs_t duration = now - mBootTime;
294 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
295 if (mBootAnimation != 0) {
296 mBootAnimation->requestExit();
297 mBootAnimation.clear();
298 }
299}
300
301void SurfaceFlinger::onFirstRef()
302{
303 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
304
305 // Wait for the main thread to be done with its initialization
306 mReadyToRunBarrier.wait();
307}
308
309
310static inline uint16_t pack565(int r, int g, int b) {
311 return (r<<11)|(g<<5)|b;
312}
313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314status_t SurfaceFlinger::readyToRun()
315{
316 LOGI( "SurfaceFlinger's main thread ready to run. "
317 "Initializing graphics H/W...");
318
319 // create the shared control-block
320 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
321 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
322
323 mServerCblkMemory = mServerHeap->allocate(4096);
324 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
325
326 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
327 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
328 new(mServerCblk) surface_flinger_cblk_t;
329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330 // we only support one display currently
331 int dpy = 0;
332
333 {
334 // initialize the main display
335 GraphicPlane& plane(graphicPlane(dpy));
336 DisplayHardware* const hw = new DisplayHardware(this, dpy);
337 plane.setDisplayHardware(hw);
338 }
339
340 // initialize primary screen
341 // (other display should be initialized in the same manner, but
342 // asynchronously, as they could come and go. None of this is supported
343 // yet).
344 const GraphicPlane& plane(graphicPlane(dpy));
345 const DisplayHardware& hw = plane.displayHardware();
346 const uint32_t w = hw.getWidth();
347 const uint32_t h = hw.getHeight();
348 const uint32_t f = hw.getFormat();
349 hw.makeCurrent();
350
351 // initialize the shared control block
352 mServerCblk->connected |= 1<<dpy;
353 display_cblk_t* dcblk = mServerCblk->displays + dpy;
354 memset(dcblk, 0, sizeof(display_cblk_t));
355 dcblk->w = w;
356 dcblk->h = h;
357 dcblk->format = f;
358 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
359 dcblk->xdpi = hw.getDpiX();
360 dcblk->ydpi = hw.getDpiY();
361 dcblk->fps = hw.getRefreshRate();
362 dcblk->density = hw.getDensity();
363 asm volatile ("":::"memory");
364
365 // Initialize OpenGL|ES
366 glActiveTexture(GL_TEXTURE0);
367 glBindTexture(GL_TEXTURE_2D, 0);
368 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
369 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
370 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
371 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
372 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
373 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
374 glPixelStorei(GL_PACK_ALIGNMENT, 4);
375 glEnableClientState(GL_VERTEX_ARRAY);
376 glEnable(GL_SCISSOR_TEST);
377 glShadeModel(GL_FLAT);
378 glDisable(GL_DITHER);
379 glDisable(GL_CULL_FACE);
380
381 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
382 const uint16_t g1 = pack565(0x17,0x2f,0x17);
383 const uint16_t textureData[4] = { g0, g1, g1, g0 };
384 glGenTextures(1, &mWormholeTexName);
385 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
386 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
387 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
388 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
389 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
390 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
391 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
392
393 glViewport(0, 0, w, h);
394 glMatrixMode(GL_PROJECTION);
395 glLoadIdentity();
396 glOrthof(0, w, h, 0, 0, 1);
397
398 LayerDim::initDimmer(this, w, h);
399
400 mReadyToRunBarrier.open();
401
402 /*
403 * We're now ready to accept clients...
404 */
405
406 mOrientationAnimation = new OrientationAnimation(this);
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 // the boot animation!
409 if (mDebugNoBootAnimation == false)
410 mBootAnimation = new BootAnimation(this);
411
412 return NO_ERROR;
413}
414
415// ----------------------------------------------------------------------------
416#if 0
417#pragma mark -
418#pragma mark Events Handler
419#endif
420
421void SurfaceFlinger::waitForEvent()
422{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700423 while (true) {
424 nsecs_t timeout = -1;
425 if (UNLIKELY(isFrozen())) {
426 // wait 5 seconds
427 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
428 const nsecs_t now = systemTime();
429 if (mFreezeDisplayTime == 0) {
430 mFreezeDisplayTime = now;
431 }
432 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
433 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700434 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700435
436 MessageList::NODE_PTR msg = mEventQueue.waitMessage(timeout);
437 if (msg != 0) {
438 mFreezeDisplayTime = 0;
439 switch (msg->what) {
440 case MessageQueue::INVALIDATE:
441 // invalidate message, just return to the main loop
442 return;
443 }
444 } else {
445 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 if (isFrozen()) {
447 // we timed out and are still frozen
448 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
449 mFreezeDisplay, mFreezeCount);
450 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700451 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700452 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 }
454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455 }
456}
457
458void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700459 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460}
461
462void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700463 // this is the IPC call
464 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465}
466
467void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
468{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700469 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470}
471
472// ----------------------------------------------------------------------------
473#if 0
474#pragma mark -
475#pragma mark Main loop
476#endif
477
478bool SurfaceFlinger::threadLoop()
479{
480 waitForEvent();
481
482 // check for transactions
483 if (UNLIKELY(mConsoleSignals)) {
484 handleConsoleEvents();
485 }
486
487 if (LIKELY(mTransactionCount == 0)) {
488 // if we're in a global transaction, don't do anything.
489 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
490 uint32_t transactionFlags = getTransactionFlags(mask);
491 if (LIKELY(transactionFlags)) {
492 handleTransaction(transactionFlags);
493 }
494 }
495
496 // post surfaces (if needed)
497 handlePageFlip();
498
499 const DisplayHardware& hw(graphicPlane(0).displayHardware());
500 if (LIKELY(hw.canDraw())) {
501 // repaint the framebuffer (if needed)
502 handleRepaint();
503
504 // release the clients before we flip ('cause flip might block)
505 unlockClients();
506 executeScheduledBroadcasts();
507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508 postFramebuffer();
509 } else {
510 // pretend we did the post
511 unlockClients();
512 executeScheduledBroadcasts();
513 usleep(16667); // 60 fps period
514 }
515 return true;
516}
517
518void SurfaceFlinger::postFramebuffer()
519{
520 const bool skip = mOrientationAnimation->run();
521 if (UNLIKELY(skip)) {
522 return;
523 }
524
525 if (!mInvalidRegion.isEmpty()) {
526 const DisplayHardware& hw(graphicPlane(0).displayHardware());
527
528 if (UNLIKELY(mDebugFps)) {
529 debugShowFPS();
530 }
531
532 hw.flip(mInvalidRegion);
533
534 mInvalidRegion.clear();
535
536 if (Layer::deletedTextures.size()) {
537 glDeleteTextures(
538 Layer::deletedTextures.size(),
539 Layer::deletedTextures.array());
540 Layer::deletedTextures.clear();
541 }
542 }
543}
544
545void SurfaceFlinger::handleConsoleEvents()
546{
547 // something to do with the console
548 const DisplayHardware& hw = graphicPlane(0).displayHardware();
549
550 int what = android_atomic_and(0, &mConsoleSignals);
551 if (what & eConsoleAcquired) {
552 hw.acquireScreen();
553 }
554
555 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700556 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800557 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558 hw.releaseScreen();
559 }
560
561 if (what & eConsoleReleased) {
562 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800563 hw.releaseScreen();
564 } else {
565 mDeferReleaseConsole = true;
566 }
567 }
568
569 mDirtyRegion.set(hw.bounds());
570}
571
572void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
573{
574 Mutex::Autolock _l(mStateLock);
575
576 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
577 const size_t count = currentLayers.size();
578
579 /*
580 * Traversal of the children
581 * (perform the transaction for each of them if needed)
582 */
583
584 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
585 if (layersNeedTransaction) {
586 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700587 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800588 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
589 if (!trFlags) continue;
590
591 const uint32_t flags = layer->doTransaction(0);
592 if (flags & Layer::eVisibleRegion)
593 mVisibleRegionsDirty = true;
594
595 if (flags & Layer::eRestartTransaction) {
596 // restart the transaction, but back-off a little
597 layer->setTransactionFlags(eTransactionNeeded);
598 setTransactionFlags(eTraversalNeeded, ms2ns(8));
599 }
600 }
601 }
602
603 /*
604 * Perform our own transaction if needed
605 */
606
607 if (transactionFlags & eTransactionNeeded) {
608 if (mCurrentState.orientation != mDrawingState.orientation) {
609 // the orientation has changed, recompute all visible regions
610 // and invalidate everything.
611
612 const int dpy = 0;
613 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700614 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800615 GraphicPlane& plane(graphicPlane(dpy));
616 plane.setOrientation(orientation);
617
618 // update the shared control block
619 const DisplayHardware& hw(plane.displayHardware());
620 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
621 dcblk->orientation = orientation;
622 if (orientation & eOrientationSwapMask) {
623 // 90 or 270 degrees orientation
624 dcblk->w = hw.getHeight();
625 dcblk->h = hw.getWidth();
626 } else {
627 dcblk->w = hw.getWidth();
628 dcblk->h = hw.getHeight();
629 }
630
631 mVisibleRegionsDirty = true;
632 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700633 mFreezeDisplayTime = 0;
634 mOrientationAnimation->onOrientationChanged(type);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635 }
636
637 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
638 // freezing or unfreezing the display -> trigger animation if needed
639 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640 }
641
642 // 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;
646 }
647
648 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
649 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
650 // layers have been added
651 mVisibleRegionsDirty = true;
652 }
653
654 // get rid of all resources we don't need anymore
655 // (layers and clients)
656 free_resources_l();
657 }
658
659 commitTransaction();
660}
661
662sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
663{
664 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
665}
666
667void SurfaceFlinger::computeVisibleRegions(
668 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
669{
670 const GraphicPlane& plane(graphicPlane(0));
671 const Transform& planeTransform(plane.transform());
672
673 Region aboveOpaqueLayers;
674 Region aboveCoveredLayers;
675 Region dirty;
676
677 bool secureFrameBuffer = false;
678
679 size_t i = currentLayers.size();
680 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700681 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800682 layer->validateVisibility(planeTransform);
683
684 // start with the whole surface at its current location
685 const Layer::State& s = layer->drawingState();
686 const Rect bounds(layer->visibleBounds());
687
688 // handle hidden surfaces by setting the visible region to empty
689 Region opaqueRegion;
690 Region visibleRegion;
691 Region coveredRegion;
692 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
693 visibleRegion.clear();
694 } else {
695 const bool translucent = layer->needsBlending();
696 visibleRegion.set(bounds);
697 coveredRegion = visibleRegion;
698
699 // Remove the transparent area from the visible region
700 if (translucent) {
701 visibleRegion.subtractSelf(layer->transparentRegionScreen);
702 }
703
704 // compute the opaque region
705 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
706 // the opaque region is the visible region
707 opaqueRegion = visibleRegion;
708 }
709 }
710
711 // subtract the opaque region covered by the layers above us
712 visibleRegion.subtractSelf(aboveOpaqueLayers);
713 coveredRegion.andSelf(aboveCoveredLayers);
714
715 // compute this layer's dirty region
716 if (layer->contentDirty) {
717 // we need to invalidate the whole region
718 dirty = visibleRegion;
719 // as well, as the old visible region
720 dirty.orSelf(layer->visibleRegionScreen);
721 layer->contentDirty = false;
722 } else {
723 // compute the exposed region
724 // dirty = what's visible now - what's wasn't covered before
725 // = what's visible now & what's was covered before
726 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
727 }
728 dirty.subtractSelf(aboveOpaqueLayers);
729
730 // accumulate to the screen dirty region
731 dirtyRegion.orSelf(dirty);
732
Mathias Agopian62b74442009-04-14 23:02:51 -0700733 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800734 aboveOpaqueLayers.orSelf(opaqueRegion);
735 aboveCoveredLayers.orSelf(bounds);
736
737 // Store the visible region is screen space
738 layer->setVisibleRegion(visibleRegion);
739 layer->setCoveredRegion(coveredRegion);
740
Mathias Agopian62b74442009-04-14 23:02:51 -0700741 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742 if (layer->isSecure() && !visibleRegion.isEmpty()) {
743 secureFrameBuffer = true;
744 }
745 }
746
747 mSecureFrameBuffer = secureFrameBuffer;
748 opaqueRegion = aboveOpaqueLayers;
749}
750
751
752void SurfaceFlinger::commitTransaction()
753{
754 mDrawingState = mCurrentState;
755 mTransactionCV.signal();
756}
757
758void SurfaceFlinger::handlePageFlip()
759{
760 bool visibleRegions = mVisibleRegionsDirty;
761 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
762 visibleRegions |= lockPageFlip(currentLayers);
763
764 const DisplayHardware& hw = graphicPlane(0).displayHardware();
765 const Region screenRegion(hw.bounds());
766 if (visibleRegions) {
767 Region opaqueRegion;
768 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
769 mWormholeRegion = screenRegion.subtract(opaqueRegion);
770 mVisibleRegionsDirty = false;
771 }
772
773 unlockPageFlip(currentLayers);
774 mDirtyRegion.andSelf(screenRegion);
775}
776
777bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
778{
779 bool recomputeVisibleRegions = false;
780 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700781 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700783 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784 layer->lockPageFlip(recomputeVisibleRegions);
785 }
786 return recomputeVisibleRegions;
787}
788
789void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
790{
791 const GraphicPlane& plane(graphicPlane(0));
792 const Transform& planeTransform(plane.transform());
793 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700794 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700796 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800797 layer->unlockPageFlip(planeTransform, mDirtyRegion);
798 }
799}
800
801void SurfaceFlinger::handleRepaint()
802{
803 // set the frame buffer
804 const DisplayHardware& hw(graphicPlane(0).displayHardware());
805 glMatrixMode(GL_MODELVIEW);
806 glLoadIdentity();
807
808 if (UNLIKELY(mDebugRegion)) {
809 debugFlashRegions();
810 }
811
812 // compute the invalid region
813 mInvalidRegion.orSelf(mDirtyRegion);
814
815 uint32_t flags = hw.getFlags();
816 if (flags & DisplayHardware::BUFFER_PRESERVED) {
817 // here we assume DisplayHardware::flip()'s implementation
818 // performs the copy-back optimization.
819 } else {
820 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
821 // we need to fully redraw the part that will be updated
822 mDirtyRegion.set(mInvalidRegion.bounds());
823 } else {
824 // we need to redraw everything
825 mDirtyRegion.set(hw.bounds());
826 mInvalidRegion = mDirtyRegion;
827 }
828 }
829
830 // compose all surfaces
831 composeSurfaces(mDirtyRegion);
832
833 // clear the dirty regions
834 mDirtyRegion.clear();
835}
836
837void SurfaceFlinger::composeSurfaces(const Region& dirty)
838{
839 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
840 // should never happen unless the window manager has a bug
841 // draw something...
842 drawWormhole();
843 }
844 const SurfaceFlinger& flinger(*this);
845 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
846 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700847 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700849 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800850 const Region& visibleRegion(layer->visibleRegionScreen);
851 if (!visibleRegion.isEmpty()) {
852 const Region clip(dirty.intersect(visibleRegion));
853 if (!clip.isEmpty()) {
854 layer->draw(clip);
855 }
856 }
857 }
858}
859
860void SurfaceFlinger::unlockClients()
861{
862 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
863 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700864 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800865 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700866 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800867 layer->finishPageFlip();
868 }
869}
870
871void SurfaceFlinger::scheduleBroadcast(Client* client)
872{
873 if (mLastScheduledBroadcast != client) {
874 mLastScheduledBroadcast = client;
875 mScheduledBroadcasts.add(client);
876 }
877}
878
879void SurfaceFlinger::executeScheduledBroadcasts()
880{
881 SortedVector<Client*>& list = mScheduledBroadcasts;
882 size_t count = list.size();
883 while (count--) {
884 per_client_cblk_t* const cblk = list[count]->ctrlblk;
885 if (cblk->lock.tryLock() == NO_ERROR) {
886 cblk->cv.broadcast();
887 list.removeAt(count);
888 cblk->lock.unlock();
889 } else {
890 // schedule another round
891 LOGW("executeScheduledBroadcasts() skipped, "
892 "contention on the client. We'll try again later...");
893 signalDelayedEvent(ms2ns(4));
894 }
895 }
896 mLastScheduledBroadcast = 0;
897}
898
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800899void SurfaceFlinger::debugFlashRegions()
900{
901 if (UNLIKELY(!mDirtyRegion.isRect())) {
902 // TODO: do this only if we don't have preserving
903 // swapBuffer. If we don't have update-on-demand,
904 // redraw everything.
905 composeSurfaces(Region(mDirtyRegion.bounds()));
906 }
907
908 glDisable(GL_TEXTURE_2D);
909 glDisable(GL_BLEND);
910 glDisable(GL_DITHER);
911 glDisable(GL_SCISSOR_TEST);
912
913 glColor4x(0x10000, 0, 0x10000, 0x10000);
914
915 Rect r;
916 Region::iterator iterator(mDirtyRegion);
917 while (iterator.iterate(&r)) {
918 GLfloat vertices[][2] = {
919 { r.left, r.top },
920 { r.left, r.bottom },
921 { r.right, r.bottom },
922 { r.right, r.top }
923 };
924 glVertexPointer(2, GL_FLOAT, 0, vertices);
925 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
926 }
927
928 const DisplayHardware& hw(graphicPlane(0).displayHardware());
929 hw.flip(mDirtyRegion.merge(mInvalidRegion));
930 mInvalidRegion.clear();
931
932 if (mDebugRegion > 1)
933 usleep(mDebugRegion * 1000);
934
935 glEnable(GL_SCISSOR_TEST);
936 //mDirtyRegion.dump("mDirtyRegion");
937}
938
939void SurfaceFlinger::drawWormhole() const
940{
941 const Region region(mWormholeRegion.intersect(mDirtyRegion));
942 if (region.isEmpty())
943 return;
944
945 const DisplayHardware& hw(graphicPlane(0).displayHardware());
946 const int32_t width = hw.getWidth();
947 const int32_t height = hw.getHeight();
948
949 glDisable(GL_BLEND);
950 glDisable(GL_DITHER);
951
952 if (LIKELY(!mDebugBackground)) {
953 glClearColorx(0,0,0,0);
954 Rect r;
955 Region::iterator iterator(region);
956 while (iterator.iterate(&r)) {
957 const GLint sy = height - (r.top + r.height());
958 glScissor(r.left, sy, r.width(), r.height());
959 glClear(GL_COLOR_BUFFER_BIT);
960 }
961 } else {
962 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
963 { width, height }, { 0, height } };
964 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
965 glVertexPointer(2, GL_SHORT, 0, vertices);
966 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
967 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
968 glEnable(GL_TEXTURE_2D);
969 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
970 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
971 glMatrixMode(GL_TEXTURE);
972 glLoadIdentity();
973 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
974 Rect r;
975 Region::iterator iterator(region);
976 while (iterator.iterate(&r)) {
977 const GLint sy = height - (r.top + r.height());
978 glScissor(r.left, sy, r.width(), r.height());
979 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
980 }
981 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
982 }
983}
984
985void SurfaceFlinger::debugShowFPS() const
986{
987 static int mFrameCount;
988 static int mLastFrameCount = 0;
989 static nsecs_t mLastFpsTime = 0;
990 static float mFps = 0;
991 mFrameCount++;
992 nsecs_t now = systemTime();
993 nsecs_t diff = now - mLastFpsTime;
994 if (diff > ms2ns(250)) {
995 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
996 mLastFpsTime = now;
997 mLastFrameCount = mFrameCount;
998 }
999 // XXX: mFPS has the value we want
1000 }
1001
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001002status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001003{
1004 Mutex::Autolock _l(mStateLock);
1005 addLayer_l(layer);
1006 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1007 return NO_ERROR;
1008}
1009
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001010status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001011{
1012 Mutex::Autolock _l(mStateLock);
1013 removeLayer_l(layer);
1014 setTransactionFlags(eTransactionNeeded);
1015 return NO_ERROR;
1016}
1017
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001018status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019{
1020 layer->forceVisibilityTransaction();
1021 setTransactionFlags(eTraversalNeeded);
1022 return NO_ERROR;
1023}
1024
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001025status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001026{
1027 ssize_t i = mCurrentState.layersSortedByZ.add(
1028 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001029 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1030 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031 mLayerMap.add(lbc->serverIndex(), lbc);
1032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033 return NO_ERROR;
1034}
1035
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001036status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
1038 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1039 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001040 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001041 sp<LayerBaseClient> layer =
1042 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001043 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001044 mLayerMap.removeItem(layer->serverIndex());
1045 }
1046 return NO_ERROR;
1047 }
1048 // it's possible that we don't find a layer, because it might
1049 // have been destroyed already -- this is not technically an error
Mathias Agopian9a112062009-04-17 19:36:26 -07001050 // from the user because there is a race between BClient::destroySurface(),
1051 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001052 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1053}
1054
Mathias Agopian9a112062009-04-17 19:36:26 -07001055status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1056{
1057 // First add the layer to the purgatory list, which makes sure it won't
1058 // go away, then remove it from the main list (through a transaction).
1059 ssize_t err = removeLayer_l(layerBase);
1060 if (err >= 0) {
1061 mLayerPurgatory.add(layerBase);
1062 }
1063 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1064}
1065
1066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067void SurfaceFlinger::free_resources_l()
1068{
1069 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001070 mLayersRemoved = false;
1071
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001072 // free resources associated with disconnected clients
1073 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1074 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1075 const size_t count = disconnectedClients.size();
1076 for (size_t i=0 ; i<count ; i++) {
1077 Client* client = disconnectedClients[i];
1078 // if this client is the scheduled broadcast list,
1079 // remove it from there (and we don't need to signal it
1080 // since it is dead).
1081 int32_t index = scheduledBroadcasts.indexOf(client);
1082 if (index >= 0) {
1083 scheduledBroadcasts.removeItemsAt(index);
1084 }
1085 mTokens.release(client->cid);
1086 delete client;
1087 }
1088 disconnectedClients.clear();
1089}
1090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1092{
1093 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1094}
1095
1096uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1097{
1098 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1099 if ((old & flags)==0) { // wake the server up
1100 if (delay > 0) {
1101 signalDelayedEvent(delay);
1102 } else {
1103 signalEvent();
1104 }
1105 }
1106 return old;
1107}
1108
1109void SurfaceFlinger::openGlobalTransaction()
1110{
1111 android_atomic_inc(&mTransactionCount);
1112}
1113
1114void SurfaceFlinger::closeGlobalTransaction()
1115{
1116 if (android_atomic_dec(&mTransactionCount) == 1) {
1117 signalEvent();
1118 }
1119}
1120
1121status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1122{
1123 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1124 return BAD_VALUE;
1125
1126 Mutex::Autolock _l(mStateLock);
1127 mCurrentState.freezeDisplay = 1;
1128 setTransactionFlags(eTransactionNeeded);
1129
1130 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001131 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001132 return NO_ERROR;
1133}
1134
1135status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1136{
1137 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1138 return BAD_VALUE;
1139
1140 Mutex::Autolock _l(mStateLock);
1141 mCurrentState.freezeDisplay = 0;
1142 setTransactionFlags(eTransactionNeeded);
1143
1144 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001145 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001146 return NO_ERROR;
1147}
1148
Mathias Agopianc08731e2009-03-27 18:11:38 -07001149int SurfaceFlinger::setOrientation(DisplayID dpy,
1150 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001151{
1152 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1153 return BAD_VALUE;
1154
1155 Mutex::Autolock _l(mStateLock);
1156 if (mCurrentState.orientation != orientation) {
1157 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001158 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159 mCurrentState.orientation = orientation;
1160 setTransactionFlags(eTransactionNeeded);
1161 mTransactionCV.wait(mStateLock);
1162 } else {
1163 orientation = BAD_VALUE;
1164 }
1165 }
1166 return orientation;
1167}
1168
1169sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1170 ISurfaceFlingerClient::surface_data_t* params,
1171 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1172 uint32_t flags)
1173{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001174 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175 sp<LayerBaseClient::Surface> surfaceHandle;
1176 Mutex::Autolock _l(mStateLock);
1177 Client* const c = mClientsMap.valueFor(clientId);
1178 if (UNLIKELY(!c)) {
1179 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1180 return surfaceHandle;
1181 }
1182
1183 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1184 int32_t id = c->generateId(pid);
1185 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1186 LOGE("createSurface() failed, generateId = %d", id);
1187 return surfaceHandle;
1188 }
1189
1190 switch (flags & eFXSurfaceMask) {
1191 case eFXSurfaceNormal:
1192 if (UNLIKELY(flags & ePushBuffers)) {
1193 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1194 } else {
1195 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1196 }
1197 break;
1198 case eFXSurfaceBlur:
1199 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1200 break;
1201 case eFXSurfaceDim:
1202 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1203 break;
1204 }
1205
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001206 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207 setTransactionFlags(eTransactionNeeded);
1208 surfaceHandle = layer->getSurface();
1209 if (surfaceHandle != 0)
1210 surfaceHandle->getSurfaceData(params);
1211 }
1212
1213 return surfaceHandle;
1214}
1215
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001216sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217 Client* client, DisplayID display,
1218 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1219{
1220 // initialize the surfaces
1221 switch (format) { // TODO: take h/w into account
1222 case PIXEL_FORMAT_TRANSPARENT:
1223 case PIXEL_FORMAT_TRANSLUCENT:
1224 format = PIXEL_FORMAT_RGBA_8888;
1225 break;
1226 case PIXEL_FORMAT_OPAQUE:
1227 format = PIXEL_FORMAT_RGB_565;
1228 break;
1229 }
1230
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001231 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001232 status_t err = layer->setBuffers(client, w, h, format, flags);
1233 if (LIKELY(err == NO_ERROR)) {
1234 layer->initStates(w, h, flags);
1235 addLayer_l(layer);
1236 } else {
1237 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001238 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239 }
1240 return layer;
1241}
1242
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001243sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244 Client* client, DisplayID display,
1245 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1246{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001247 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001248 layer->initStates(w, h, flags);
1249 addLayer_l(layer);
1250 return layer;
1251}
1252
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001253sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254 Client* client, DisplayID display,
1255 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1256{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001257 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258 layer->initStates(w, h, flags);
1259 addLayer_l(layer);
1260 return layer;
1261}
1262
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001263sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
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<LayerBuffer> layer = new LayerBuffer(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 Agopian9a112062009-04-17 19:36:26 -07001273status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001274{
Mathias Agopian9a112062009-04-17 19:36:26 -07001275 /*
1276 * called by the window manager, when a surface should be marked for
1277 * destruction.
1278 */
1279
1280 // TODO: here we should make the surface disappear from the screen
1281 // and mark it for removal. however, we can't free anything until all
1282 // client are done. All operations on this surface should return errors.
1283
1284 status_t err = NAME_NOT_FOUND;
1285 sp<LayerBaseClient> layer;
1286
1287 { // scope for the lock
1288 Mutex::Autolock _l(mStateLock);
1289 layer = getLayerUser_l(index);
1290 err = purgatorizeLayer_l(layer);
1291 if (err == NO_ERROR) {
1292 setTransactionFlags(eTransactionNeeded);
1293 }
1294 }
1295
1296 if (layer != 0) {
1297 // do this outside of mStateLock
1298 layer->ditch();
1299 }
1300 return err;
1301}
1302
1303status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1304{
1305 /*
1306 * called by ~ISurface() when all references are gone
1307 */
1308
1309 /* FIXME:
Mathias Agopian9a112062009-04-17 19:36:26 -07001310 * - ideally we want to release as much GL state as possible after
1311 * purgatorizeLayer_l() has been called and the surface is not in any
1312 * active list.
Mathias Agopian9a112062009-04-17 19:36:26 -07001313 */
1314
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001315 class MessageDestroySurface : public MessageBase {
1316 sp<SurfaceFlinger> flinger;
1317 sp<LayerBaseClient> layer;
1318 public:
1319 MessageDestroySurface(const sp<SurfaceFlinger>& flinger,
1320 const sp<LayerBaseClient>& layer)
1321 : MessageBase(0), flinger(flinger), layer(layer) {
1322 }
1323 ~MessageDestroySurface() {
1324 //LOGD("~MessageDestroySurface, layer=%p", layer.get());
1325 }
1326 virtual bool handler() {
1327 //LOGD("MessageDestroySurface handler, layer=%p", layer.get());
1328 Mutex::Autolock _l(flinger->mStateLock);
1329 flinger->mLayerPurgatory.remove(layer);
1330 return true;
1331 }
1332 };
1333
1334 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
1335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336 return NO_ERROR;
1337}
1338
1339status_t SurfaceFlinger::setClientState(
1340 ClientID cid,
1341 int32_t count,
1342 const layer_state_t* states)
1343{
1344 Mutex::Autolock _l(mStateLock);
1345 uint32_t flags = 0;
1346 cid <<= 16;
1347 for (int i=0 ; i<count ; i++) {
1348 const layer_state_t& s = states[i];
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001349 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1350 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351 const uint32_t what = s.what;
1352 // check if it has been destroyed first
1353 if (what & eDestroyed) {
1354 if (removeLayer_l(layer) == NO_ERROR) {
1355 flags |= eTransactionNeeded;
1356 // we skip everything else... well, no, not really
1357 // we skip ONLY that transaction.
1358 continue;
1359 }
1360 }
1361 if (what & ePositionChanged) {
1362 if (layer->setPosition(s.x, s.y))
1363 flags |= eTraversalNeeded;
1364 }
1365 if (what & eLayerChanged) {
1366 if (layer->setLayer(s.z)) {
1367 mCurrentState.layersSortedByZ.reorder(
1368 layer, &Layer::compareCurrentStateZ);
1369 // we need traversal (state changed)
1370 // AND transaction (list changed)
1371 flags |= eTransactionNeeded|eTraversalNeeded;
1372 }
1373 }
1374 if (what & eSizeChanged) {
1375 if (layer->setSize(s.w, s.h))
1376 flags |= eTraversalNeeded;
1377 }
1378 if (what & eAlphaChanged) {
1379 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1380 flags |= eTraversalNeeded;
1381 }
1382 if (what & eMatrixChanged) {
1383 if (layer->setMatrix(s.matrix))
1384 flags |= eTraversalNeeded;
1385 }
1386 if (what & eTransparentRegionChanged) {
1387 if (layer->setTransparentRegionHint(s.transparentRegion))
1388 flags |= eTraversalNeeded;
1389 }
1390 if (what & eVisibilityChanged) {
1391 if (layer->setFlags(s.flags, s.mask))
1392 flags |= eTraversalNeeded;
1393 }
1394 }
1395 }
1396 if (flags) {
1397 setTransactionFlags(flags);
1398 }
1399 return NO_ERROR;
1400}
1401
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001402sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001403{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001404 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1405 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001406}
1407
1408void SurfaceFlinger::screenReleased(int dpy)
1409{
1410 // this may be called by a signal handler, we can't do too much in here
1411 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1412 signalEvent();
1413}
1414
1415void SurfaceFlinger::screenAcquired(int dpy)
1416{
1417 // this may be called by a signal handler, we can't do too much in here
1418 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1419 signalEvent();
1420}
1421
1422status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1423{
1424 const size_t SIZE = 1024;
1425 char buffer[SIZE];
1426 String8 result;
1427 if (checkCallingPermission(
1428 String16("android.permission.DUMP")) == false)
1429 { // not allowed
1430 snprintf(buffer, SIZE, "Permission Denial: "
1431 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1432 IPCThreadState::self()->getCallingPid(),
1433 IPCThreadState::self()->getCallingUid());
1434 result.append(buffer);
1435 } else {
1436 Mutex::Autolock _l(mStateLock);
1437 size_t s = mClientsMap.size();
1438 char name[64];
1439 for (size_t i=0 ; i<s ; i++) {
1440 Client* client = mClientsMap.valueAt(i);
1441 sprintf(name, " Client (id=0x%08x)", client->cid);
1442 client->dump(name);
1443 }
1444 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1445 const size_t count = currentLayers.size();
1446 for (size_t i=0 ; i<count ; i++) {
1447 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001448 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001449 const Layer::State& s = layer->drawingState();
1450 snprintf(buffer, SIZE,
1451 "+ %s %p\n"
1452 " "
1453 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1454 "needsBlending=%1d, invalidate=%1d, "
1455 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001456 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001457 s.z, layer->tx(), layer->ty(), s.w, s.h,
1458 layer->needsBlending(), layer->contentDirty,
1459 s.alpha, s.flags,
1460 s.transform[0], s.transform[1],
1461 s.transform[2], s.transform[3]);
1462 result.append(buffer);
1463 buffer[0] = 0;
1464 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001465 sp<LayerBaseClient> lbc =
1466 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1467 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468 snprintf(buffer, SIZE,
1469 " "
1470 "id=0x%08x, client=0x%08x, identity=%u\n",
1471 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1472 lbc->getIdentity());
1473 }
1474 result.append(buffer);
1475 buffer[0] = 0;
1476 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001477 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1478 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001479 const LayerBitmap& buf0(l->getBuffer(0));
1480 const LayerBitmap& buf1(l->getBuffer(1));
1481 snprintf(buffer, SIZE,
1482 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001483 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001484 " freezeLock=%p, swapState=0x%08x\n",
1485 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001486 buf0.getWidth(), buf0.getHeight(),
1487 buf0.getBuffer()->getStride(),
1488 buf1.getWidth(), buf1.getHeight(),
1489 buf1.getBuffer()->getStride(),
1490 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001491 l->lcblk->swapState);
1492 }
1493 result.append(buffer);
1494 buffer[0] = 0;
1495 s.transparentRegion.dump(result, "transparentRegion");
1496 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1497 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1498 }
1499 mWormholeRegion.dump(result, "WormholeRegion");
1500 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1501 snprintf(buffer, SIZE,
1502 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1503 mFreezeDisplay?"yes":"no", mFreezeCount,
1504 mCurrentState.orientation, hw.canDraw());
1505 result.append(buffer);
1506
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001507 const BufferAllocator& alloc(BufferAllocator::get());
1508 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509 }
1510 write(fd, result.string(), result.size());
1511 return NO_ERROR;
1512}
1513
1514status_t SurfaceFlinger::onTransact(
1515 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1516{
1517 switch (code) {
1518 case CREATE_CONNECTION:
1519 case OPEN_GLOBAL_TRANSACTION:
1520 case CLOSE_GLOBAL_TRANSACTION:
1521 case SET_ORIENTATION:
1522 case FREEZE_DISPLAY:
1523 case UNFREEZE_DISPLAY:
1524 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001525 {
1526 // codes that require permission check
1527 IPCThreadState* ipc = IPCThreadState::self();
1528 const int pid = ipc->getCallingPid();
1529 const int self_pid = getpid();
1530 if (UNLIKELY(pid != self_pid)) {
1531 // we're called from a different process, do the real check
1532 if (!checkCallingPermission(
1533 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1534 {
1535 const int uid = ipc->getCallingUid();
1536 LOGE("Permission Denial: "
1537 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1538 return PERMISSION_DENIED;
1539 }
1540 }
1541 }
1542 }
1543
1544 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1545 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1546 // HARDWARE_TEST stuff...
1547 if (UNLIKELY(checkCallingPermission(
1548 String16("android.permission.HARDWARE_TEST")) == false))
1549 { // not allowed
1550 LOGE("Permission Denial: pid=%d, uid=%d\n",
1551 IPCThreadState::self()->getCallingPid(),
1552 IPCThreadState::self()->getCallingUid());
1553 return PERMISSION_DENIED;
1554 }
1555 int n;
1556 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001557 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001558 return NO_ERROR;
1559 case 1001: // SHOW_FPS
1560 n = data.readInt32();
1561 mDebugFps = n ? 1 : 0;
1562 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