blob: 8dca12489bebca9bacc082501297be089bd5f5dc [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 "CPUGauge.h"
49#include "Layer.h"
50#include "LayerBlur.h"
51#include "LayerBuffer.h"
52#include "LayerDim.h"
53#include "LayerBitmap.h"
54#include "LayerOrientationAnim.h"
55#include "OrientationAnimation.h"
56#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057
58#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
60
61#define DISPLAY_COUNT 1
62
63namespace android {
64
65// ---------------------------------------------------------------------------
66
67void SurfaceFlinger::instantiate() {
68 defaultServiceManager()->addService(
69 String16("SurfaceFlinger"), new SurfaceFlinger());
70}
71
72void SurfaceFlinger::shutdown() {
73 // we should unregister here, but not really because
74 // when (if) the service manager goes away, all the services
75 // it has a reference to will leave too.
76}
77
78// ---------------------------------------------------------------------------
79
80SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
81 : lookup(rhs.lookup), layers(rhs.layers)
82{
83}
84
85ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070086 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087{
88 if (guess<size() && lookup.keyAt(guess) == key)
89 return guess;
90 const ssize_t i = lookup.indexOfKey(key);
91 if (i>=0) {
92 const size_t idx = lookup.valueAt(i);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070093 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070095 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096 return idx;
97 }
98 return i;
99}
100
101ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700102 const sp<LayerBase>& layer,
103 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104{
105 size_t count = layers.size();
106 ssize_t l = 0;
107 ssize_t h = count-1;
108 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700109 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110 while (l <= h) {
111 mid = l + (h - l)/2;
112 const int c = cmp(a+mid, &layer);
113 if (c == 0) { l = mid; break; }
114 else if (c<0) { l = mid+1; }
115 else { h = mid-1; }
116 }
117 size_t order = l;
118 while (order<count && !cmp(&layer, a+order)) {
119 order++;
120 }
121 count = lookup.size();
122 for (size_t i=0 ; i<count ; i++) {
123 if (lookup.valueAt(i) >= order) {
124 lookup.editValueAt(i)++;
125 }
126 }
127 layers.insertAt(layer, order);
128 lookup.add(layer, order);
129 return order;
130}
131
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700132ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133{
134 const ssize_t keyIndex = lookup.indexOfKey(layer);
135 if (keyIndex >= 0) {
136 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700137 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700139 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 layers.removeItemsAt(index);
141 lookup.removeItemsAt(keyIndex);
142 const size_t count = lookup.size();
143 for (size_t i=0 ; i<count ; i++) {
144 if (lookup.valueAt(i) >= size_t(index)) {
145 lookup.editValueAt(i)--;
146 }
147 }
148 return index;
149 }
150 return NAME_NOT_FOUND;
151}
152
153ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700154 const sp<LayerBase>& layer,
155 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156{
157 // XXX: it's a little lame. but oh well...
158 ssize_t err = remove(layer);
159 if (err >=0)
160 err = add(layer, cmp);
161 return err;
162}
163
164// ---------------------------------------------------------------------------
165#if 0
166#pragma mark -
167#endif
168
169SurfaceFlinger::SurfaceFlinger()
170 : BnSurfaceComposer(), Thread(false),
171 mTransactionFlags(0),
172 mTransactionCount(0),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700173 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
175 mLastScheduledBroadcast(NULL),
176 mVisibleRegionsDirty(false),
177 mDeferReleaseConsole(false),
178 mFreezeDisplay(false),
179 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700180 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 mDebugRegion(0),
182 mDebugCpu(0),
183 mDebugFps(0),
184 mDebugBackground(0),
185 mDebugNoBootAnimation(0),
186 mSyncObject(),
187 mDeplayedTransactionPending(0),
188 mConsoleSignals(0),
189 mSecureFrameBuffer(0)
190{
191 init();
192}
193
194void SurfaceFlinger::init()
195{
196 LOGI("SurfaceFlinger is starting");
197
198 // debugging stuff...
199 char value[PROPERTY_VALUE_MAX];
200 property_get("debug.sf.showupdates", value, "0");
201 mDebugRegion = atoi(value);
202 property_get("debug.sf.showcpu", value, "0");
203 mDebugCpu = atoi(value);
204 property_get("debug.sf.showbackground", value, "0");
205 mDebugBackground = atoi(value);
206 property_get("debug.sf.showfps", value, "0");
207 mDebugFps = atoi(value);
208 property_get("debug.sf.nobootanimation", value, "0");
209 mDebugNoBootAnimation = atoi(value);
210
211 LOGI_IF(mDebugRegion, "showupdates enabled");
212 LOGI_IF(mDebugCpu, "showcpu enabled");
213 LOGI_IF(mDebugBackground, "showbackground enabled");
214 LOGI_IF(mDebugFps, "showfps enabled");
215 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
216}
217
218SurfaceFlinger::~SurfaceFlinger()
219{
220 glDeleteTextures(1, &mWormholeTexName);
221 delete mOrientationAnimation;
222}
223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
225{
226 return graphicPlane(0).displayHardware().getOverlayEngine();
227}
228
229sp<IMemory> SurfaceFlinger::getCblk() const
230{
231 return mServerCblkMemory;
232}
233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
235{
236 Mutex::Autolock _l(mStateLock);
237 uint32_t token = mTokens.acquire();
238
239 Client* client = new Client(token, this);
240 if ((client == 0) || (client->ctrlblk == 0)) {
241 mTokens.release(token);
242 return 0;
243 }
244 status_t err = mClientsMap.add(token, client);
245 if (err < 0) {
246 delete client;
247 mTokens.release(token);
248 return 0;
249 }
250 sp<BClient> bclient =
251 new BClient(this, token, client->controlBlockMemory());
252 return bclient;
253}
254
255void SurfaceFlinger::destroyConnection(ClientID cid)
256{
257 Mutex::Autolock _l(mStateLock);
258 Client* const client = mClientsMap.valueFor(cid);
259 if (client) {
260 // free all the layers this client owns
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700261 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 const size_t count = layers.size();
263 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700264 sp<LayerBaseClient> layer(layers[i].promote());
265 if (layer != 0) {
266 removeLayer_l(layer);
267 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 }
269
270 // the resources associated with this client will be freed
271 // during the next transaction, after these surfaces have been
272 // properly removed from the screen
273
274 // remove this client from our ClientID->Client mapping.
275 mClientsMap.removeItem(cid);
276
277 // and add it to the list of disconnected clients
278 mDisconnectedClients.add(client);
279
280 // request a transaction
281 setTransactionFlags(eTransactionNeeded);
282 }
283}
284
285const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
286{
287 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
288 const GraphicPlane& plane(mGraphicPlanes[dpy]);
289 return plane;
290}
291
292GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
293{
294 return const_cast<GraphicPlane&>(
295 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
296}
297
298void SurfaceFlinger::bootFinished()
299{
300 const nsecs_t now = systemTime();
301 const nsecs_t duration = now - mBootTime;
302 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
303 if (mBootAnimation != 0) {
304 mBootAnimation->requestExit();
305 mBootAnimation.clear();
306 }
307}
308
309void SurfaceFlinger::onFirstRef()
310{
311 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
312
313 // Wait for the main thread to be done with its initialization
314 mReadyToRunBarrier.wait();
315}
316
317
318static inline uint16_t pack565(int r, int g, int b) {
319 return (r<<11)|(g<<5)|b;
320}
321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322status_t SurfaceFlinger::readyToRun()
323{
324 LOGI( "SurfaceFlinger's main thread ready to run. "
325 "Initializing graphics H/W...");
326
327 // create the shared control-block
328 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
329 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
330
331 mServerCblkMemory = mServerHeap->allocate(4096);
332 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
333
334 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
335 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
336 new(mServerCblk) surface_flinger_cblk_t;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // we only support one display currently
339 int dpy = 0;
340
341 {
342 // initialize the main display
343 GraphicPlane& plane(graphicPlane(dpy));
344 DisplayHardware* const hw = new DisplayHardware(this, dpy);
345 plane.setDisplayHardware(hw);
346 }
347
348 // initialize primary screen
349 // (other display should be initialized in the same manner, but
350 // asynchronously, as they could come and go. None of this is supported
351 // yet).
352 const GraphicPlane& plane(graphicPlane(dpy));
353 const DisplayHardware& hw = plane.displayHardware();
354 const uint32_t w = hw.getWidth();
355 const uint32_t h = hw.getHeight();
356 const uint32_t f = hw.getFormat();
357 hw.makeCurrent();
358
359 // initialize the shared control block
360 mServerCblk->connected |= 1<<dpy;
361 display_cblk_t* dcblk = mServerCblk->displays + dpy;
362 memset(dcblk, 0, sizeof(display_cblk_t));
363 dcblk->w = w;
364 dcblk->h = h;
365 dcblk->format = f;
366 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
367 dcblk->xdpi = hw.getDpiX();
368 dcblk->ydpi = hw.getDpiY();
369 dcblk->fps = hw.getRefreshRate();
370 dcblk->density = hw.getDensity();
371 asm volatile ("":::"memory");
372
373 // Initialize OpenGL|ES
374 glActiveTexture(GL_TEXTURE0);
375 glBindTexture(GL_TEXTURE_2D, 0);
376 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
377 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
378 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
379 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
380 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
381 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
382 glPixelStorei(GL_PACK_ALIGNMENT, 4);
383 glEnableClientState(GL_VERTEX_ARRAY);
384 glEnable(GL_SCISSOR_TEST);
385 glShadeModel(GL_FLAT);
386 glDisable(GL_DITHER);
387 glDisable(GL_CULL_FACE);
388
389 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
390 const uint16_t g1 = pack565(0x17,0x2f,0x17);
391 const uint16_t textureData[4] = { g0, g1, g1, g0 };
392 glGenTextures(1, &mWormholeTexName);
393 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
394 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
395 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
396 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
397 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
398 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
399 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
400
401 glViewport(0, 0, w, h);
402 glMatrixMode(GL_PROJECTION);
403 glLoadIdentity();
404 glOrthof(0, w, h, 0, 0, 1);
405
406 LayerDim::initDimmer(this, w, h);
407
408 mReadyToRunBarrier.open();
409
410 /*
411 * We're now ready to accept clients...
412 */
413
414 mOrientationAnimation = new OrientationAnimation(this);
415
416 // start CPU gauge display
417 if (mDebugCpu)
418 mCpuGauge = new CPUGauge(this, ms2ns(500));
419
420 // the boot animation!
421 if (mDebugNoBootAnimation == false)
422 mBootAnimation = new BootAnimation(this);
423
424 return NO_ERROR;
425}
426
427// ----------------------------------------------------------------------------
428#if 0
429#pragma mark -
430#pragma mark Events Handler
431#endif
432
433void SurfaceFlinger::waitForEvent()
434{
435 // wait for something to do
436 if (UNLIKELY(isFrozen())) {
437 // wait 5 seconds
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700438 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
439 const nsecs_t now = systemTime();
440 if (mFreezeDisplayTime == 0) {
441 mFreezeDisplayTime = now;
442 }
443 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
444 int err = (waitTime > 0) ? mSyncObject.wait(waitTime) : TIMED_OUT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 if (err != NO_ERROR) {
446 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;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 }
453 }
454 } else {
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700455 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456 mSyncObject.wait();
457 }
458}
459
460void SurfaceFlinger::signalEvent() {
461 mSyncObject.open();
462}
463
464void SurfaceFlinger::signal() const {
465 mSyncObject.open();
466}
467
468void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
469{
470 if (android_atomic_or(1, &mDeplayedTransactionPending) == 0) {
471 sp<DelayedTransaction> delayedEvent(new DelayedTransaction(this, delay));
472 delayedEvent->run("DelayedeEvent", PRIORITY_URGENT_DISPLAY);
473 }
474}
475
476// ----------------------------------------------------------------------------
477#if 0
478#pragma mark -
479#pragma mark Main loop
480#endif
481
482bool SurfaceFlinger::threadLoop()
483{
484 waitForEvent();
485
486 // check for transactions
487 if (UNLIKELY(mConsoleSignals)) {
488 handleConsoleEvents();
489 }
490
491 if (LIKELY(mTransactionCount == 0)) {
492 // if we're in a global transaction, don't do anything.
493 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
494 uint32_t transactionFlags = getTransactionFlags(mask);
495 if (LIKELY(transactionFlags)) {
496 handleTransaction(transactionFlags);
497 }
498 }
499
500 // post surfaces (if needed)
501 handlePageFlip();
502
503 const DisplayHardware& hw(graphicPlane(0).displayHardware());
504 if (LIKELY(hw.canDraw())) {
505 // repaint the framebuffer (if needed)
506 handleRepaint();
507
508 // release the clients before we flip ('cause flip might block)
509 unlockClients();
510 executeScheduledBroadcasts();
511
512 // sample the cpu gauge
513 if (UNLIKELY(mDebugCpu)) {
514 handleDebugCpu();
515 }
516
517 postFramebuffer();
518 } else {
519 // pretend we did the post
520 unlockClients();
521 executeScheduledBroadcasts();
522 usleep(16667); // 60 fps period
523 }
524 return true;
525}
526
527void SurfaceFlinger::postFramebuffer()
528{
529 const bool skip = mOrientationAnimation->run();
530 if (UNLIKELY(skip)) {
531 return;
532 }
533
534 if (!mInvalidRegion.isEmpty()) {
535 const DisplayHardware& hw(graphicPlane(0).displayHardware());
536
537 if (UNLIKELY(mDebugFps)) {
538 debugShowFPS();
539 }
540
541 hw.flip(mInvalidRegion);
542
543 mInvalidRegion.clear();
544
545 if (Layer::deletedTextures.size()) {
546 glDeleteTextures(
547 Layer::deletedTextures.size(),
548 Layer::deletedTextures.array());
549 Layer::deletedTextures.clear();
550 }
551 }
552}
553
554void SurfaceFlinger::handleConsoleEvents()
555{
556 // something to do with the console
557 const DisplayHardware& hw = graphicPlane(0).displayHardware();
558
559 int what = android_atomic_and(0, &mConsoleSignals);
560 if (what & eConsoleAcquired) {
561 hw.acquireScreen();
562 }
563
564 if (mDeferReleaseConsole && hw.canDraw()) {
565 // We got the release signal before the aquire signal
566 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567 hw.releaseScreen();
568 }
569
570 if (what & eConsoleReleased) {
571 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572 hw.releaseScreen();
573 } else {
574 mDeferReleaseConsole = true;
575 }
576 }
577
578 mDirtyRegion.set(hw.bounds());
579}
580
581void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
582{
583 Mutex::Autolock _l(mStateLock);
584
585 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
586 const size_t count = currentLayers.size();
587
588 /*
589 * Traversal of the children
590 * (perform the transaction for each of them if needed)
591 */
592
593 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
594 if (layersNeedTransaction) {
595 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700596 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800597 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
598 if (!trFlags) continue;
599
600 const uint32_t flags = layer->doTransaction(0);
601 if (flags & Layer::eVisibleRegion)
602 mVisibleRegionsDirty = true;
603
604 if (flags & Layer::eRestartTransaction) {
605 // restart the transaction, but back-off a little
606 layer->setTransactionFlags(eTransactionNeeded);
607 setTransactionFlags(eTraversalNeeded, ms2ns(8));
608 }
609 }
610 }
611
612 /*
613 * Perform our own transaction if needed
614 */
615
616 if (transactionFlags & eTransactionNeeded) {
617 if (mCurrentState.orientation != mDrawingState.orientation) {
618 // the orientation has changed, recompute all visible regions
619 // and invalidate everything.
620
621 const int dpy = 0;
622 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700623 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800624 GraphicPlane& plane(graphicPlane(dpy));
625 plane.setOrientation(orientation);
626
627 // update the shared control block
628 const DisplayHardware& hw(plane.displayHardware());
629 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
630 dcblk->orientation = orientation;
631 if (orientation & eOrientationSwapMask) {
632 // 90 or 270 degrees orientation
633 dcblk->w = hw.getHeight();
634 dcblk->h = hw.getWidth();
635 } else {
636 dcblk->w = hw.getWidth();
637 dcblk->h = hw.getHeight();
638 }
639
640 mVisibleRegionsDirty = true;
641 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700642 mFreezeDisplayTime = 0;
643 mOrientationAnimation->onOrientationChanged(type);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644 }
645
646 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
647 // freezing or unfreezing the display -> trigger animation if needed
648 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649 }
650
651 // some layers might have been removed, so
652 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700653 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 mVisibleRegionsDirty = true;
655 }
656
657 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
658 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
659 // layers have been added
660 mVisibleRegionsDirty = true;
661 }
662
663 // get rid of all resources we don't need anymore
664 // (layers and clients)
665 free_resources_l();
666 }
667
668 commitTransaction();
669}
670
671sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
672{
673 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
674}
675
676void SurfaceFlinger::computeVisibleRegions(
677 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
678{
679 const GraphicPlane& plane(graphicPlane(0));
680 const Transform& planeTransform(plane.transform());
681
682 Region aboveOpaqueLayers;
683 Region aboveCoveredLayers;
684 Region dirty;
685
686 bool secureFrameBuffer = false;
687
688 size_t i = currentLayers.size();
689 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700690 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800691 layer->validateVisibility(planeTransform);
692
693 // start with the whole surface at its current location
694 const Layer::State& s = layer->drawingState();
695 const Rect bounds(layer->visibleBounds());
696
697 // handle hidden surfaces by setting the visible region to empty
698 Region opaqueRegion;
699 Region visibleRegion;
700 Region coveredRegion;
701 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
702 visibleRegion.clear();
703 } else {
704 const bool translucent = layer->needsBlending();
705 visibleRegion.set(bounds);
706 coveredRegion = visibleRegion;
707
708 // Remove the transparent area from the visible region
709 if (translucent) {
710 visibleRegion.subtractSelf(layer->transparentRegionScreen);
711 }
712
713 // compute the opaque region
714 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
715 // the opaque region is the visible region
716 opaqueRegion = visibleRegion;
717 }
718 }
719
720 // subtract the opaque region covered by the layers above us
721 visibleRegion.subtractSelf(aboveOpaqueLayers);
722 coveredRegion.andSelf(aboveCoveredLayers);
723
724 // compute this layer's dirty region
725 if (layer->contentDirty) {
726 // we need to invalidate the whole region
727 dirty = visibleRegion;
728 // as well, as the old visible region
729 dirty.orSelf(layer->visibleRegionScreen);
730 layer->contentDirty = false;
731 } else {
732 // compute the exposed region
733 // dirty = what's visible now - what's wasn't covered before
734 // = what's visible now & what's was covered before
735 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
736 }
737 dirty.subtractSelf(aboveOpaqueLayers);
738
739 // accumulate to the screen dirty region
740 dirtyRegion.orSelf(dirty);
741
742 // updade aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
743 aboveOpaqueLayers.orSelf(opaqueRegion);
744 aboveCoveredLayers.orSelf(bounds);
745
746 // Store the visible region is screen space
747 layer->setVisibleRegion(visibleRegion);
748 layer->setCoveredRegion(coveredRegion);
749
750 // If a secure layer is partially visible, lockdown the screen!
751 if (layer->isSecure() && !visibleRegion.isEmpty()) {
752 secureFrameBuffer = true;
753 }
754 }
755
756 mSecureFrameBuffer = secureFrameBuffer;
757 opaqueRegion = aboveOpaqueLayers;
758}
759
760
761void SurfaceFlinger::commitTransaction()
762{
763 mDrawingState = mCurrentState;
764 mTransactionCV.signal();
765}
766
767void SurfaceFlinger::handlePageFlip()
768{
769 bool visibleRegions = mVisibleRegionsDirty;
770 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
771 visibleRegions |= lockPageFlip(currentLayers);
772
773 const DisplayHardware& hw = graphicPlane(0).displayHardware();
774 const Region screenRegion(hw.bounds());
775 if (visibleRegions) {
776 Region opaqueRegion;
777 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
778 mWormholeRegion = screenRegion.subtract(opaqueRegion);
779 mVisibleRegionsDirty = false;
780 }
781
782 unlockPageFlip(currentLayers);
783 mDirtyRegion.andSelf(screenRegion);
784}
785
786bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
787{
788 bool recomputeVisibleRegions = false;
789 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700790 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700792 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800793 layer->lockPageFlip(recomputeVisibleRegions);
794 }
795 return recomputeVisibleRegions;
796}
797
798void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
799{
800 const GraphicPlane& plane(graphicPlane(0));
801 const Transform& planeTransform(plane.transform());
802 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700803 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700805 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800806 layer->unlockPageFlip(planeTransform, mDirtyRegion);
807 }
808}
809
810void SurfaceFlinger::handleRepaint()
811{
812 // set the frame buffer
813 const DisplayHardware& hw(graphicPlane(0).displayHardware());
814 glMatrixMode(GL_MODELVIEW);
815 glLoadIdentity();
816
817 if (UNLIKELY(mDebugRegion)) {
818 debugFlashRegions();
819 }
820
821 // compute the invalid region
822 mInvalidRegion.orSelf(mDirtyRegion);
823
824 uint32_t flags = hw.getFlags();
825 if (flags & DisplayHardware::BUFFER_PRESERVED) {
826 // here we assume DisplayHardware::flip()'s implementation
827 // performs the copy-back optimization.
828 } else {
829 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
830 // we need to fully redraw the part that will be updated
831 mDirtyRegion.set(mInvalidRegion.bounds());
832 } else {
833 // we need to redraw everything
834 mDirtyRegion.set(hw.bounds());
835 mInvalidRegion = mDirtyRegion;
836 }
837 }
838
839 // compose all surfaces
840 composeSurfaces(mDirtyRegion);
841
842 // clear the dirty regions
843 mDirtyRegion.clear();
844}
845
846void SurfaceFlinger::composeSurfaces(const Region& dirty)
847{
848 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
849 // should never happen unless the window manager has a bug
850 // draw something...
851 drawWormhole();
852 }
853 const SurfaceFlinger& flinger(*this);
854 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
855 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700856 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700858 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859 const Region& visibleRegion(layer->visibleRegionScreen);
860 if (!visibleRegion.isEmpty()) {
861 const Region clip(dirty.intersect(visibleRegion));
862 if (!clip.isEmpty()) {
863 layer->draw(clip);
864 }
865 }
866 }
867}
868
869void SurfaceFlinger::unlockClients()
870{
871 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
872 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700873 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800874 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700875 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800876 layer->finishPageFlip();
877 }
878}
879
880void SurfaceFlinger::scheduleBroadcast(Client* client)
881{
882 if (mLastScheduledBroadcast != client) {
883 mLastScheduledBroadcast = client;
884 mScheduledBroadcasts.add(client);
885 }
886}
887
888void SurfaceFlinger::executeScheduledBroadcasts()
889{
890 SortedVector<Client*>& list = mScheduledBroadcasts;
891 size_t count = list.size();
892 while (count--) {
893 per_client_cblk_t* const cblk = list[count]->ctrlblk;
894 if (cblk->lock.tryLock() == NO_ERROR) {
895 cblk->cv.broadcast();
896 list.removeAt(count);
897 cblk->lock.unlock();
898 } else {
899 // schedule another round
900 LOGW("executeScheduledBroadcasts() skipped, "
901 "contention on the client. We'll try again later...");
902 signalDelayedEvent(ms2ns(4));
903 }
904 }
905 mLastScheduledBroadcast = 0;
906}
907
908void SurfaceFlinger::handleDebugCpu()
909{
910 Mutex::Autolock _l(mDebugLock);
911 if (mCpuGauge != 0)
912 mCpuGauge->sample();
913}
914
915void SurfaceFlinger::debugFlashRegions()
916{
917 if (UNLIKELY(!mDirtyRegion.isRect())) {
918 // TODO: do this only if we don't have preserving
919 // swapBuffer. If we don't have update-on-demand,
920 // redraw everything.
921 composeSurfaces(Region(mDirtyRegion.bounds()));
922 }
923
924 glDisable(GL_TEXTURE_2D);
925 glDisable(GL_BLEND);
926 glDisable(GL_DITHER);
927 glDisable(GL_SCISSOR_TEST);
928
929 glColor4x(0x10000, 0, 0x10000, 0x10000);
930
931 Rect r;
932 Region::iterator iterator(mDirtyRegion);
933 while (iterator.iterate(&r)) {
934 GLfloat vertices[][2] = {
935 { r.left, r.top },
936 { r.left, r.bottom },
937 { r.right, r.bottom },
938 { r.right, r.top }
939 };
940 glVertexPointer(2, GL_FLOAT, 0, vertices);
941 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
942 }
943
944 const DisplayHardware& hw(graphicPlane(0).displayHardware());
945 hw.flip(mDirtyRegion.merge(mInvalidRegion));
946 mInvalidRegion.clear();
947
948 if (mDebugRegion > 1)
949 usleep(mDebugRegion * 1000);
950
951 glEnable(GL_SCISSOR_TEST);
952 //mDirtyRegion.dump("mDirtyRegion");
953}
954
955void SurfaceFlinger::drawWormhole() const
956{
957 const Region region(mWormholeRegion.intersect(mDirtyRegion));
958 if (region.isEmpty())
959 return;
960
961 const DisplayHardware& hw(graphicPlane(0).displayHardware());
962 const int32_t width = hw.getWidth();
963 const int32_t height = hw.getHeight();
964
965 glDisable(GL_BLEND);
966 glDisable(GL_DITHER);
967
968 if (LIKELY(!mDebugBackground)) {
969 glClearColorx(0,0,0,0);
970 Rect r;
971 Region::iterator iterator(region);
972 while (iterator.iterate(&r)) {
973 const GLint sy = height - (r.top + r.height());
974 glScissor(r.left, sy, r.width(), r.height());
975 glClear(GL_COLOR_BUFFER_BIT);
976 }
977 } else {
978 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
979 { width, height }, { 0, height } };
980 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
981 glVertexPointer(2, GL_SHORT, 0, vertices);
982 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
983 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
984 glEnable(GL_TEXTURE_2D);
985 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
986 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
987 glMatrixMode(GL_TEXTURE);
988 glLoadIdentity();
989 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
990 Rect r;
991 Region::iterator iterator(region);
992 while (iterator.iterate(&r)) {
993 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);
1029 removeLayer_l(layer);
1030 setTransactionFlags(eTransactionNeeded);
1031 return NO_ERROR;
1032}
1033
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001034status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035{
1036 layer->forceVisibilityTransaction();
1037 setTransactionFlags(eTraversalNeeded);
1038 return NO_ERROR;
1039}
1040
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001041status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042{
1043 ssize_t i = mCurrentState.layersSortedByZ.add(
1044 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001045 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1046 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047 mLayerMap.add(lbc->serverIndex(), lbc);
1048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001049 return NO_ERROR;
1050}
1051
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001052status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001053{
1054 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1055 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001056 mLayersRemoved = true;
1057 sp<LayerBaseClient> layer = LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
1058 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001059 mLayerMap.removeItem(layer->serverIndex());
1060 }
1061 return NO_ERROR;
1062 }
1063 // it's possible that we don't find a layer, because it might
1064 // have been destroyed already -- this is not technically an error
1065 // from the user because there is a race between destroySurface,
1066 // destroyclient and destroySurface-from-a-transaction.
1067 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1068}
1069
1070void SurfaceFlinger::free_resources_l()
1071{
1072 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001073 mLayersRemoved = false;
1074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075 // free resources associated with disconnected clients
1076 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1077 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1078 const size_t count = disconnectedClients.size();
1079 for (size_t i=0 ; i<count ; i++) {
1080 Client* client = disconnectedClients[i];
1081 // if this client is the scheduled broadcast list,
1082 // remove it from there (and we don't need to signal it
1083 // since it is dead).
1084 int32_t index = scheduledBroadcasts.indexOf(client);
1085 if (index >= 0) {
1086 scheduledBroadcasts.removeItemsAt(index);
1087 }
1088 mTokens.release(client->cid);
1089 delete client;
1090 }
1091 disconnectedClients.clear();
1092}
1093
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001094uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1095{
1096 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1097}
1098
1099uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1100{
1101 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1102 if ((old & flags)==0) { // wake the server up
1103 if (delay > 0) {
1104 signalDelayedEvent(delay);
1105 } else {
1106 signalEvent();
1107 }
1108 }
1109 return old;
1110}
1111
1112void SurfaceFlinger::openGlobalTransaction()
1113{
1114 android_atomic_inc(&mTransactionCount);
1115}
1116
1117void SurfaceFlinger::closeGlobalTransaction()
1118{
1119 if (android_atomic_dec(&mTransactionCount) == 1) {
1120 signalEvent();
1121 }
1122}
1123
1124status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1125{
1126 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1127 return BAD_VALUE;
1128
1129 Mutex::Autolock _l(mStateLock);
1130 mCurrentState.freezeDisplay = 1;
1131 setTransactionFlags(eTransactionNeeded);
1132
1133 // flags is intended to communicate some sort of animation behavior
1134 // (for instance fadding)
1135 return NO_ERROR;
1136}
1137
1138status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1139{
1140 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1141 return BAD_VALUE;
1142
1143 Mutex::Autolock _l(mStateLock);
1144 mCurrentState.freezeDisplay = 0;
1145 setTransactionFlags(eTransactionNeeded);
1146
1147 // flags is intended to communicate some sort of animation behavior
1148 // (for instance fadding)
1149 return NO_ERROR;
1150}
1151
Mathias Agopianc08731e2009-03-27 18:11:38 -07001152int SurfaceFlinger::setOrientation(DisplayID dpy,
1153 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154{
1155 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1156 return BAD_VALUE;
1157
1158 Mutex::Autolock _l(mStateLock);
1159 if (mCurrentState.orientation != orientation) {
1160 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001161 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162 mCurrentState.orientation = orientation;
1163 setTransactionFlags(eTransactionNeeded);
1164 mTransactionCV.wait(mStateLock);
1165 } else {
1166 orientation = BAD_VALUE;
1167 }
1168 }
1169 return orientation;
1170}
1171
1172sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1173 ISurfaceFlingerClient::surface_data_t* params,
1174 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1175 uint32_t flags)
1176{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001177 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178 sp<LayerBaseClient::Surface> surfaceHandle;
1179 Mutex::Autolock _l(mStateLock);
1180 Client* const c = mClientsMap.valueFor(clientId);
1181 if (UNLIKELY(!c)) {
1182 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1183 return surfaceHandle;
1184 }
1185
1186 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1187 int32_t id = c->generateId(pid);
1188 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1189 LOGE("createSurface() failed, generateId = %d", id);
1190 return surfaceHandle;
1191 }
1192
1193 switch (flags & eFXSurfaceMask) {
1194 case eFXSurfaceNormal:
1195 if (UNLIKELY(flags & ePushBuffers)) {
1196 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1197 } else {
1198 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1199 }
1200 break;
1201 case eFXSurfaceBlur:
1202 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1203 break;
1204 case eFXSurfaceDim:
1205 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1206 break;
1207 }
1208
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001209 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001210 setTransactionFlags(eTransactionNeeded);
1211 surfaceHandle = layer->getSurface();
1212 if (surfaceHandle != 0)
1213 surfaceHandle->getSurfaceData(params);
1214 }
1215
1216 return surfaceHandle;
1217}
1218
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001219sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001220 Client* client, DisplayID display,
1221 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1222{
1223 // initialize the surfaces
1224 switch (format) { // TODO: take h/w into account
1225 case PIXEL_FORMAT_TRANSPARENT:
1226 case PIXEL_FORMAT_TRANSLUCENT:
1227 format = PIXEL_FORMAT_RGBA_8888;
1228 break;
1229 case PIXEL_FORMAT_OPAQUE:
1230 format = PIXEL_FORMAT_RGB_565;
1231 break;
1232 }
1233
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001234 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001235 status_t err = layer->setBuffers(client, w, h, format, flags);
1236 if (LIKELY(err == NO_ERROR)) {
1237 layer->initStates(w, h, flags);
1238 addLayer_l(layer);
1239 } else {
1240 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001241 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242 }
1243 return layer;
1244}
1245
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001246sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247 Client* client, DisplayID display,
1248 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1249{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001250 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001251 layer->initStates(w, h, flags);
1252 addLayer_l(layer);
1253 return layer;
1254}
1255
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001256sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257 Client* client, DisplayID display,
1258 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1259{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001260 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261 layer->initStates(w, h, flags);
1262 addLayer_l(layer);
1263 return layer;
1264}
1265
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001266sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001267 Client* client, DisplayID display,
1268 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1269{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001270 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001271 layer->initStates(w, h, flags);
1272 addLayer_l(layer);
1273 return layer;
1274}
1275
1276status_t SurfaceFlinger::destroySurface(SurfaceID index)
1277{
1278 Mutex::Autolock _l(mStateLock);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001279 const sp<LayerBaseClient>& layer = getLayerUser_l(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001280 status_t err = removeLayer_l(layer);
1281 if (err < 0)
1282 return err;
1283 setTransactionFlags(eTransactionNeeded);
1284 return NO_ERROR;
1285}
1286
1287status_t SurfaceFlinger::setClientState(
1288 ClientID cid,
1289 int32_t count,
1290 const layer_state_t* states)
1291{
1292 Mutex::Autolock _l(mStateLock);
1293 uint32_t flags = 0;
1294 cid <<= 16;
1295 for (int i=0 ; i<count ; i++) {
1296 const layer_state_t& s = states[i];
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001297 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1298 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001299 const uint32_t what = s.what;
1300 // check if it has been destroyed first
1301 if (what & eDestroyed) {
1302 if (removeLayer_l(layer) == NO_ERROR) {
1303 flags |= eTransactionNeeded;
1304 // we skip everything else... well, no, not really
1305 // we skip ONLY that transaction.
1306 continue;
1307 }
1308 }
1309 if (what & ePositionChanged) {
1310 if (layer->setPosition(s.x, s.y))
1311 flags |= eTraversalNeeded;
1312 }
1313 if (what & eLayerChanged) {
1314 if (layer->setLayer(s.z)) {
1315 mCurrentState.layersSortedByZ.reorder(
1316 layer, &Layer::compareCurrentStateZ);
1317 // we need traversal (state changed)
1318 // AND transaction (list changed)
1319 flags |= eTransactionNeeded|eTraversalNeeded;
1320 }
1321 }
1322 if (what & eSizeChanged) {
1323 if (layer->setSize(s.w, s.h))
1324 flags |= eTraversalNeeded;
1325 }
1326 if (what & eAlphaChanged) {
1327 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1328 flags |= eTraversalNeeded;
1329 }
1330 if (what & eMatrixChanged) {
1331 if (layer->setMatrix(s.matrix))
1332 flags |= eTraversalNeeded;
1333 }
1334 if (what & eTransparentRegionChanged) {
1335 if (layer->setTransparentRegionHint(s.transparentRegion))
1336 flags |= eTraversalNeeded;
1337 }
1338 if (what & eVisibilityChanged) {
1339 if (layer->setFlags(s.flags, s.mask))
1340 flags |= eTraversalNeeded;
1341 }
1342 }
1343 }
1344 if (flags) {
1345 setTransactionFlags(flags);
1346 }
1347 return NO_ERROR;
1348}
1349
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001350sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001352 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1353 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354}
1355
1356void SurfaceFlinger::screenReleased(int dpy)
1357{
1358 // this may be called by a signal handler, we can't do too much in here
1359 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1360 signalEvent();
1361}
1362
1363void SurfaceFlinger::screenAcquired(int dpy)
1364{
1365 // this may be called by a signal handler, we can't do too much in here
1366 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1367 signalEvent();
1368}
1369
1370status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1371{
1372 const size_t SIZE = 1024;
1373 char buffer[SIZE];
1374 String8 result;
1375 if (checkCallingPermission(
1376 String16("android.permission.DUMP")) == false)
1377 { // not allowed
1378 snprintf(buffer, SIZE, "Permission Denial: "
1379 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1380 IPCThreadState::self()->getCallingPid(),
1381 IPCThreadState::self()->getCallingUid());
1382 result.append(buffer);
1383 } else {
1384 Mutex::Autolock _l(mStateLock);
1385 size_t s = mClientsMap.size();
1386 char name[64];
1387 for (size_t i=0 ; i<s ; i++) {
1388 Client* client = mClientsMap.valueAt(i);
1389 sprintf(name, " Client (id=0x%08x)", client->cid);
1390 client->dump(name);
1391 }
1392 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1393 const size_t count = currentLayers.size();
1394 for (size_t i=0 ; i<count ; i++) {
1395 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001396 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397 const Layer::State& s = layer->drawingState();
1398 snprintf(buffer, SIZE,
1399 "+ %s %p\n"
1400 " "
1401 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1402 "needsBlending=%1d, invalidate=%1d, "
1403 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001404 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001405 s.z, layer->tx(), layer->ty(), s.w, s.h,
1406 layer->needsBlending(), layer->contentDirty,
1407 s.alpha, s.flags,
1408 s.transform[0], s.transform[1],
1409 s.transform[2], s.transform[3]);
1410 result.append(buffer);
1411 buffer[0] = 0;
1412 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001413 sp<LayerBaseClient> lbc =
1414 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1415 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001416 snprintf(buffer, SIZE,
1417 " "
1418 "id=0x%08x, client=0x%08x, identity=%u\n",
1419 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1420 lbc->getIdentity());
1421 }
1422 result.append(buffer);
1423 buffer[0] = 0;
1424 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001425 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1426 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001427 const LayerBitmap& buf0(l->getBuffer(0));
1428 const LayerBitmap& buf1(l->getBuffer(1));
1429 snprintf(buffer, SIZE,
1430 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001431 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001432 " freezeLock=%p, swapState=0x%08x\n",
1433 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001434 buf0.getWidth(), buf0.getHeight(),
1435 buf0.getBuffer()->getStride(),
1436 buf1.getWidth(), buf1.getHeight(),
1437 buf1.getBuffer()->getStride(),
1438 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001439 l->lcblk->swapState);
1440 }
1441 result.append(buffer);
1442 buffer[0] = 0;
1443 s.transparentRegion.dump(result, "transparentRegion");
1444 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1445 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1446 }
1447 mWormholeRegion.dump(result, "WormholeRegion");
1448 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1449 snprintf(buffer, SIZE,
1450 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1451 mFreezeDisplay?"yes":"no", mFreezeCount,
1452 mCurrentState.orientation, hw.canDraw());
1453 result.append(buffer);
1454
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001455 const BufferAllocator& alloc(BufferAllocator::get());
1456 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001457 }
1458 write(fd, result.string(), result.size());
1459 return NO_ERROR;
1460}
1461
1462status_t SurfaceFlinger::onTransact(
1463 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1464{
1465 switch (code) {
1466 case CREATE_CONNECTION:
1467 case OPEN_GLOBAL_TRANSACTION:
1468 case CLOSE_GLOBAL_TRANSACTION:
1469 case SET_ORIENTATION:
1470 case FREEZE_DISPLAY:
1471 case UNFREEZE_DISPLAY:
1472 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001473 {
1474 // codes that require permission check
1475 IPCThreadState* ipc = IPCThreadState::self();
1476 const int pid = ipc->getCallingPid();
1477 const int self_pid = getpid();
1478 if (UNLIKELY(pid != self_pid)) {
1479 // we're called from a different process, do the real check
1480 if (!checkCallingPermission(
1481 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1482 {
1483 const int uid = ipc->getCallingUid();
1484 LOGE("Permission Denial: "
1485 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1486 return PERMISSION_DENIED;
1487 }
1488 }
1489 }
1490 }
1491
1492 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1493 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1494 // HARDWARE_TEST stuff...
1495 if (UNLIKELY(checkCallingPermission(
1496 String16("android.permission.HARDWARE_TEST")) == false))
1497 { // not allowed
1498 LOGE("Permission Denial: pid=%d, uid=%d\n",
1499 IPCThreadState::self()->getCallingPid(),
1500 IPCThreadState::self()->getCallingUid());
1501 return PERMISSION_DENIED;
1502 }
1503 int n;
1504 switch (code) {
1505 case 1000: // SHOW_CPU
1506 n = data.readInt32();
1507 mDebugCpu = n ? 1 : 0;
1508 if (mDebugCpu) {
1509 if (mCpuGauge == 0) {
1510 mCpuGauge = new CPUGauge(this, ms2ns(500));
1511 }
1512 } else {
1513 if (mCpuGauge != 0) {
1514 mCpuGauge->requestExitAndWait();
1515 Mutex::Autolock _l(mDebugLock);
1516 mCpuGauge.clear();
1517 }
1518 }
1519 return NO_ERROR;
1520 case 1001: // SHOW_FPS
1521 n = data.readInt32();
1522 mDebugFps = n ? 1 : 0;
1523 return NO_ERROR;
1524 case 1002: // SHOW_UPDATES
1525 n = data.readInt32();
1526 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1527 return NO_ERROR;
1528 case 1003: // SHOW_BACKGROUND
1529 n = data.readInt32();
1530 mDebugBackground = n ? 1 : 0;
1531 return NO_ERROR;
1532 case 1004:{ // repaint everything
1533 Mutex::Autolock _l(mStateLock);
1534 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1535 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1536 signalEvent();
1537 }
1538 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001539 case 1007: // set mFreezeCount
1540 mFreezeCount = data.readInt32();
1541 return NO_ERROR;
1542 case 1010: // interrogate.
1543 reply->writeInt32(mDebugCpu);
1544 reply->writeInt32(0);
1545 reply->writeInt32(mDebugRegion);
1546 reply->writeInt32(mDebugBackground);
1547 return NO_ERROR;
1548 case 1013: {
1549 Mutex::Autolock _l(mStateLock);
1550 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1551 reply->writeInt32(hw.getPageFlipCount());
1552 }
1553 return NO_ERROR;
1554 }
1555 }
1556 return err;
1557}
1558
1559// ---------------------------------------------------------------------------
1560#if 0
1561#pragma mark -
1562#endif
1563
1564Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1565 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1566{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001567 const int pgsize = getpagesize();
1568 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1569 mCblkHeap = new MemoryDealer(cblksize);
1570 mCblkMemory = mCblkHeap->allocate(cblksize);
1571 if (mCblkMemory != 0) {
1572 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1573 if (ctrlblk) { // construct the shared structure in-place.
1574 new(ctrlblk) per_client_cblk_t;
1575 }
1576 }
1577}
1578
1579Client::~Client() {
1580 if (ctrlblk) {
1581 const int pgsize = getpagesize();
1582 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1583 }
1584}
1585
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001586int32_t Client::generateId(int pid)
1587{
1588 const uint32_t i = clz( ~mBitmap );
1589 if (i >= NUM_LAYERS_MAX) {
1590 return NO_MEMORY;
1591 }
1592 mPid = pid;
1593 mInUse.add(uint8_t(i));
1594 mBitmap |= 1<<(31-i);
1595 return i;
1596}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001597
1598status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001599{
1600 ssize_t idx = mInUse.indexOf(id);
1601 if (idx < 0)
1602 return NAME_NOT_FOUND;
1603 return mLayers.insertAt(layer, idx);
1604}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001605
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001606void Client::free(int32_t id)
1607{
1608 ssize_t idx = mInUse.remove(uint8_t(id));
1609 if (idx >= 0) {
1610 mBitmap &= ~(1<<(31-id));
1611 mLayers.removeItemsAt(idx);
1612 }
1613}
1614
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001615bool Client::isValid(int32_t i) const {
1616 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1617}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001618
1619sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1620 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001621 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001622 if (idx >= 0) {
1623 lbc = mLayers[idx].promote();
1624 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1625 }
1626 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001627}
1628
1629void Client::dump(const char* what)
1630{
1631}
1632
1633// ---------------------------------------------------------------------------
1634#if 0
1635#pragma mark -
1636#endif
1637
1638BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1639 : mId(cid), mFlinger(flinger), mCblk(cblk)
1640{
1641}
1642
1643BClient::~BClient() {
1644 // destroy all resources attached to this client
1645 mFlinger->destroyConnection(mId);
1646}
1647
1648void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1649 *ctrl = mCblk;
1650}
1651
1652sp<ISurface> BClient::createSurface(
1653 ISurfaceFlingerClient::surface_data_t* params, int pid,
1654 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1655 uint32_t flags)
1656{
1657 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1658}
1659
1660status_t BClient::destroySurface(SurfaceID sid)
1661{
1662 sid |= (mId << 16); // add the client-part to id
1663 return mFlinger->destroySurface(sid);
1664}
1665
1666status_t BClient::setState(int32_t count, const layer_state_t* states)
1667{
1668 return mFlinger->setClientState(mId, count, states);
1669}
1670
1671// ---------------------------------------------------------------------------
1672
1673GraphicPlane::GraphicPlane()
1674 : mHw(0)
1675{
1676}
1677
1678GraphicPlane::~GraphicPlane() {
1679 delete mHw;
1680}
1681
1682bool GraphicPlane::initialized() const {
1683 return mHw ? true : false;
1684}
1685
1686void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1687 mHw = hw;
1688}
1689
1690void GraphicPlane::setTransform(const Transform& tr) {
1691 mTransform = tr;
1692 mGlobalTransform = mOrientationTransform * mTransform;
1693}
1694
1695status_t GraphicPlane::orientationToTransfrom(
1696 int orientation, int w, int h, Transform* tr)
1697{
1698 float a, b, c, d, x, y;
1699 switch (orientation) {
1700 case ISurfaceComposer::eOrientationDefault:
1701 a=1; b=0; c=0; d=1; x=0; y=0;
1702 break;
1703 case ISurfaceComposer::eOrientation90:
1704 a=0; b=-1; c=1; d=0; x=w; y=0;
1705 break;
1706 case ISurfaceComposer::eOrientation180:
1707 a=-1; b=0; c=0; d=-1; x=w; y=h;
1708 break;
1709 case ISurfaceComposer::eOrientation270:
1710 a=0; b=1; c=-1; d=0; x=0; y=h;
1711 break;
1712 default:
1713 return BAD_VALUE;
1714 }
1715 tr->set(a, b, c, d);
1716 tr->set(x, y);
1717 return NO_ERROR;
1718}
1719
1720status_t GraphicPlane::setOrientation(int orientation)
1721{
1722 const DisplayHardware& hw(displayHardware());
1723 const float w = hw.getWidth();
1724 const float h = hw.getHeight();
1725
1726 if (orientation == ISurfaceComposer::eOrientationDefault) {
1727 // make sure the default orientation is optimal
1728 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001729 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001730 mGlobalTransform = mTransform;
1731 return NO_ERROR;
1732 }
1733
1734 // If the rotation can be handled in hardware, this is where
1735 // the magic should happen.
1736 if (UNLIKELY(orientation == 42)) {
1737 float a, b, c, d, x, y;
1738 const float r = (3.14159265f / 180.0f) * 42.0f;
1739 const float si = sinf(r);
1740 const float co = cosf(r);
1741 a=co; b=-si; c=si; d=co;
1742 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1743 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1744 mOrientationTransform.set(a, b, c, d);
1745 mOrientationTransform.set(x, y);
1746 } else {
1747 GraphicPlane::orientationToTransfrom(orientation, w, h,
1748 &mOrientationTransform);
1749 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001750 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 mGlobalTransform = mOrientationTransform * mTransform;
1752 return NO_ERROR;
1753}
1754
1755const DisplayHardware& GraphicPlane::displayHardware() const {
1756 return *mHw;
1757}
1758
1759const Transform& GraphicPlane::transform() const {
1760 return mGlobalTransform;
1761}
1762
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001763EGLDisplay GraphicPlane::getEGLDisplay() const {
1764 return mHw->getEGLDisplay();
1765}
1766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001767// ---------------------------------------------------------------------------
1768
1769}; // namespace android