SampleApp.cpp revision bcbc1788b478b1e54079318ad073e8490aa66fae
1/* 2 * Copyright 2011 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8#include "SampleApp.h" 9 10#include "OverView.h" 11#include "SampleCode.h" 12#include "SamplePipeControllers.h" 13#include "SkCanvas.h" 14#include "SkCommandLineFlags.h" 15#include "SkData.h" 16#include "SkDevice.h" 17#include "SkGPipe.h" 18#include "SkGraphics.h" 19#include "SkImageEncoder.h" 20#include "SkOSFile.h" 21#include "SkPDFDevice.h" 22#include "SkPDFDocument.h" 23#include "SkPaint.h" 24#include "SkPicture.h" 25#include "SkPictureRecorder.h" 26#include "SkStream.h" 27#include "SkSurface.h" 28#include "SkTSort.h" 29#include "SkTime.h" 30#include "SkTypeface.h" 31#include "SkWindow.h" 32#include "TransitionView.h" 33#include "sk_tool_utils.h" 34 35#if SK_SUPPORT_GPU 36#include "gl/GrGLInterface.h" 37#include "gl/GrGLUtil.h" 38#include "GrRenderTarget.h" 39#include "GrContext.h" 40#include "SkGpuDevice.h" 41#else 42class GrContext; 43#endif 44 45extern SampleView* CreateSamplePictFileView(const char filename[]); 46 47class PictFileFactory : public SkViewFactory { 48 SkString fFilename; 49public: 50 PictFileFactory(const SkString& filename) : fFilename(filename) {} 51 virtual SkView* operator() () const SK_OVERRIDE { 52 return CreateSamplePictFileView(fFilename.c_str()); 53 } 54}; 55 56#ifdef SAMPLE_PDF_FILE_VIEWER 57extern SampleView* CreateSamplePdfFileViewer(const char filename[]); 58 59class PdfFileViewerFactory : public SkViewFactory { 60 SkString fFilename; 61public: 62 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {} 63 virtual SkView* operator() () const SK_OVERRIDE { 64 return CreateSamplePdfFileViewer(fFilename.c_str()); 65 } 66}; 67#endif // SAMPLE_PDF_FILE_VIEWER 68 69#define PIPE_FILEx 70#ifdef PIPE_FILE 71#define FILE_PATH "/path/to/drawing.data" 72#endif 73 74#define PIPE_NETx 75#ifdef PIPE_NET 76#include "SkSockets.h" 77SkTCPServer gServer; 78#endif 79 80#define USE_ARROWS_FOR_ZOOM true 81 82#if SK_ANGLE 83//#define DEFAULT_TO_ANGLE 1 84#else 85#define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU 86#endif 87 88#define ANIMATING_EVENTTYPE "nextSample" 89#define ANIMATING_DELAY 250 90 91#ifdef SK_DEBUG 92 #define FPS_REPEAT_MULTIPLIER 1 93#else 94 #define FPS_REPEAT_MULTIPLIER 10 95#endif 96#define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER) 97 98static SampleWindow* gSampleWindow; 99 100static bool gShowGMBounds; 101 102static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) { 103 evt->setTargetID(sink->getSinkID())->post(); 104} 105 106/////////////////////////////////////////////////////////////////////////////// 107 108static const char* skip_until(const char* str, const char* skip) { 109 if (!str) { 110 return NULL; 111 } 112 return strstr(str, skip); 113} 114 115static const char* skip_past(const char* str, const char* skip) { 116 const char* found = skip_until(str, skip); 117 if (!found) { 118 return NULL; 119 } 120 return found + strlen(skip); 121} 122 123static const char* gPrefFileName = "sampleapp_prefs.txt"; 124 125static bool readTitleFromPrefs(SkString* title) { 126 SkFILEStream stream(gPrefFileName); 127 if (!stream.isValid()) { 128 return false; 129 } 130 131 size_t len = stream.getLength(); 132 SkString data(len); 133 stream.read(data.writable_str(), len); 134 const char* s = data.c_str(); 135 136 s = skip_past(s, "curr-slide-title"); 137 s = skip_past(s, "="); 138 s = skip_past(s, "\""); 139 const char* stop = skip_until(s, "\""); 140 if (stop > s) { 141 title->set(s, stop - s); 142 return true; 143 } 144 return false; 145} 146 147static void writeTitleToPrefs(const char* title) { 148 SkFILEWStream stream(gPrefFileName); 149 SkString data; 150 data.printf("curr-slide-title = \"%s\"\n", title); 151 stream.write(data.c_str(), data.size()); 152} 153 154/////////////////////////////////////////////////////////////////////////////// 155 156class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager { 157public: 158 159 DefaultDeviceManager() { 160#if SK_SUPPORT_GPU 161 fCurContext = NULL; 162 fCurIntf = NULL; 163 fCurRenderTarget = NULL; 164 fMSAASampleCount = 0; 165#endif 166 fBackend = kNone_BackEndType; 167 } 168 169 virtual ~DefaultDeviceManager() { 170#if SK_SUPPORT_GPU 171 SkSafeUnref(fCurContext); 172 SkSafeUnref(fCurIntf); 173 SkSafeUnref(fCurRenderTarget); 174#endif 175 } 176 177 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) { 178 SkASSERT(kNone_BackEndType == fBackend); 179 180 fBackend = kNone_BackEndType; 181 182#if SK_SUPPORT_GPU 183 switch (win->getDeviceType()) { 184 case kRaster_DeviceType: 185 // fallthrough 186 case kPicture_DeviceType: 187 // fallthrough 188 case kGPU_DeviceType: 189 // fallthrough 190 case kNullGPU_DeviceType: 191 // all these guys use the native backend 192 fBackend = kNativeGL_BackEndType; 193 break; 194#if SK_ANGLE 195 case kANGLE_DeviceType: 196 // ANGLE is really the only odd man out 197 fBackend = kANGLE_BackEndType; 198 break; 199#endif // SK_ANGLE 200 default: 201 SkASSERT(false); 202 break; 203 } 204 AttachmentInfo attachmentInfo; 205 bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo); 206 if (!result) { 207 SkDebugf("Failed to initialize GL"); 208 return; 209 } 210 fMSAASampleCount = msaaSampleCount; 211 212 SkASSERT(NULL == fCurIntf); 213 SkAutoTUnref<const GrGLInterface> glInterface; 214 switch (win->getDeviceType()) { 215 case kRaster_DeviceType: 216 // fallthrough 217 case kPicture_DeviceType: 218 // fallthrough 219 case kGPU_DeviceType: 220 // all these guys use the native interface 221 glInterface.reset(GrGLCreateNativeInterface()); 222 break; 223#if SK_ANGLE 224 case kANGLE_DeviceType: 225 glInterface.reset(GrGLCreateANGLEInterface()); 226 break; 227#endif // SK_ANGLE 228 case kNullGPU_DeviceType: 229 glInterface.reset(GrGLCreateNullInterface()); 230 break; 231 default: 232 SkASSERT(false); 233 break; 234 } 235 236 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped 237 // when the driver doesn't support NVPR. 238 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get()); 239 240 SkASSERT(NULL == fCurContext); 241 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf); 242 243 if (NULL == fCurContext || NULL == fCurIntf) { 244 // We need some context and interface to see results 245 SkSafeUnref(fCurContext); 246 SkSafeUnref(fCurIntf); 247 fCurContext = NULL; 248 fCurIntf = NULL; 249 SkDebugf("Failed to setup 3D"); 250 251 win->detach(); 252 } 253#endif // SK_SUPPORT_GPU 254 // call windowSizeChanged to create the render target 255 this->windowSizeChanged(win); 256 } 257 258 virtual void tearDownBackend(SampleWindow *win) { 259#if SK_SUPPORT_GPU 260 SkSafeUnref(fCurContext); 261 fCurContext = NULL; 262 263 SkSafeUnref(fCurIntf); 264 fCurIntf = NULL; 265 266 SkSafeUnref(fCurRenderTarget); 267 fCurRenderTarget = NULL; 268#endif 269 win->detach(); 270 fBackend = kNone_BackEndType; 271 } 272 273 virtual SkCanvas* createCanvas(SampleWindow::DeviceType dType, 274 SampleWindow* win) { 275#if SK_SUPPORT_GPU 276 if (IsGpuDeviceType(dType) && NULL != fCurContext) { 277 SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fCurContext, fCurRenderTarget)); 278 return new SkCanvas(device); 279 } else 280#endif 281 { 282 return NULL; 283 } 284 } 285 286 virtual void publishCanvas(SampleWindow::DeviceType dType, 287 SkCanvas* canvas, 288 SampleWindow* win) { 289#if SK_SUPPORT_GPU 290 if (fCurContext) { 291 // in case we have queued drawing calls 292 fCurContext->flush(); 293 294 if (!IsGpuDeviceType(dType)) { 295 // need to send the raster bits to the (gpu) window 296 fCurContext->setRenderTarget(fCurRenderTarget); 297 const SkBitmap& bm = win->getBitmap(); 298 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(), 299 SkImageInfo2GrPixelConfig(bm.colorType(), 300 bm.alphaType()), 301 bm.getPixels(), 302 bm.rowBytes()); 303 } 304 } 305#endif 306 307 win->present(); 308 } 309 310 virtual void windowSizeChanged(SampleWindow* win) { 311#if SK_SUPPORT_GPU 312 if (fCurContext) { 313 AttachmentInfo attachmentInfo; 314 win->attach(fBackend, fMSAASampleCount, &attachmentInfo); 315 316 GrBackendRenderTargetDesc desc; 317 desc.fWidth = SkScalarRoundToInt(win->width()); 318 desc.fHeight = SkScalarRoundToInt(win->height()); 319 desc.fConfig = kSkia8888_GrPixelConfig; 320 desc.fOrigin = kBottomLeft_GrSurfaceOrigin; 321 desc.fSampleCnt = attachmentInfo.fSampleCount; 322 desc.fStencilBits = attachmentInfo.fStencilBits; 323 GrGLint buffer; 324 GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer); 325 desc.fRenderTargetHandle = buffer; 326 327 SkSafeUnref(fCurRenderTarget); 328 fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc); 329 } 330#endif 331 } 332 333 virtual GrContext* getGrContext() { 334#if SK_SUPPORT_GPU 335 return fCurContext; 336#else 337 return NULL; 338#endif 339 } 340 341 virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE { 342#if SK_SUPPORT_GPU 343 return fCurRenderTarget; 344#else 345 return NULL; 346#endif 347 } 348 349private: 350 351#if SK_SUPPORT_GPU 352 GrContext* fCurContext; 353 const GrGLInterface* fCurIntf; 354 GrRenderTarget* fCurRenderTarget; 355 int fMSAASampleCount; 356#endif 357 358 SkOSWindow::SkBackEndTypes fBackend; 359 360 typedef SampleWindow::DeviceManager INHERITED; 361}; 362 363/////////////// 364static const char view_inval_msg[] = "view-inval-msg"; 365 366void SampleWindow::postInvalDelay() { 367 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1); 368} 369 370static bool isInvalEvent(const SkEvent& evt) { 371 return evt.isType(view_inval_msg); 372} 373////////////////// 374 375SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func) 376 : fCreateFunc(func) { 377} 378 379SkView* SkFuncViewFactory::operator() () const { 380 return (*fCreateFunc)(); 381} 382 383#include "GMSampleView.h" 384 385SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func) 386 : fFunc(func) { 387} 388 389SkView* SkGMSampleViewFactory::operator() () const { 390 skiagm::GM* gm = fFunc(NULL); 391 gm->setMode(skiagm::GM::kSample_Mode); 392 return new GMSampleView(gm); 393} 394 395SkViewRegister* SkViewRegister::gHead; 396SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) { 397 fFact->ref(); 398 fChain = gHead; 399 gHead = this; 400} 401 402SkViewRegister::SkViewRegister(SkViewCreateFunc func) { 403 fFact = new SkFuncViewFactory(func); 404 fChain = gHead; 405 gHead = this; 406} 407 408SkViewRegister::SkViewRegister(GMFactoryFunc func) { 409 fFact = new SkGMSampleViewFactory(func); 410 fChain = gHead; 411 gHead = this; 412} 413 414class AutoUnrefArray { 415public: 416 AutoUnrefArray() {} 417 ~AutoUnrefArray() { 418 int count = fObjs.count(); 419 for (int i = 0; i < count; ++i) { 420 fObjs[i]->unref(); 421 } 422 } 423 SkRefCnt*& push_back() { return *fObjs.append(); } 424 425private: 426 SkTDArray<SkRefCnt*> fObjs; 427}; 428 429// registers GMs as Samples 430// This can't be performed during static initialization because it could be 431// run before GMRegistry has been fully built. 432static void SkGMRegistyToSampleRegistry() { 433 static bool gOnce; 434 static AutoUnrefArray fRegisters; 435 436 if (!gOnce) { 437 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head(); 438 while (gmreg) { 439 fRegisters.push_back() = new SkViewRegister(gmreg->factory()); 440 gmreg = gmreg->next(); 441 } 442 gOnce = true; 443 } 444} 445 446////////////////////////////////////////////////////////////////////////////// 447 448enum FlipAxisEnum { 449 kFlipAxis_X = (1 << 0), 450 kFlipAxis_Y = (1 << 1) 451}; 452 453#include "SkDrawFilter.h" 454 455struct HintingState { 456 SkPaint::Hinting hinting; 457 const char* name; 458 const char* label; 459}; 460static HintingState gHintingStates[] = { 461 {SkPaint::kNo_Hinting, "Mixed", NULL }, 462 {SkPaint::kNo_Hinting, "None", "H0 " }, 463 {SkPaint::kSlight_Hinting, "Slight", "Hs " }, 464 {SkPaint::kNormal_Hinting, "Normal", "Hn " }, 465 {SkPaint::kFull_Hinting, "Full", "Hf " }, 466}; 467 468struct FilterLevelState { 469 SkPaint::FilterLevel fLevel; 470 const char* fName; 471 const char* fLabel; 472}; 473static FilterLevelState gFilterLevelStates[] = { 474 { SkPaint::kNone_FilterLevel, "Mixed", NULL }, 475 { SkPaint::kNone_FilterLevel, "None", "F0 " }, 476 { SkPaint::kLow_FilterLevel, "Low", "F1 " }, 477 { SkPaint::kMedium_FilterLevel, "Medium", "F2 " }, 478 { SkPaint::kHigh_FilterLevel, "High", "F3 " }, 479}; 480 481class FlagsDrawFilter : public SkDrawFilter { 482public: 483 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa, 484 SkOSMenu::TriState subpixel, int hinting, int filterlevel) 485 : fLCDState(lcd) 486 , fAAState(aa) 487 , fSubpixelState(subpixel) 488 , fHintingState(hinting) 489 , fFilterLevelIndex(filterlevel) 490 { 491 SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates)); 492 } 493 494 virtual bool filter(SkPaint* paint, Type t) { 495 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) { 496 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState); 497 } 498 if (SkOSMenu::kMixedState != fAAState) { 499 paint->setAntiAlias(SkOSMenu::kOnState == fAAState); 500 } 501 if (0 != fFilterLevelIndex) { 502 paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel); 503 } 504 if (SkOSMenu::kMixedState != fSubpixelState) { 505 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState); 506 } 507 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) { 508 paint->setHinting(gHintingStates[fHintingState].hinting); 509 } 510 return true; 511 } 512 513private: 514 SkOSMenu::TriState fLCDState; 515 SkOSMenu::TriState fAAState; 516 SkOSMenu::TriState fSubpixelState; 517 int fHintingState; 518 int fFilterLevelIndex; 519}; 520 521////////////////////////////////////////////////////////////////////////////// 522 523#define MAX_ZOOM_LEVEL 8 524#define MIN_ZOOM_LEVEL -8 525 526static const char gCharEvtName[] = "SampleCode_Char_Event"; 527static const char gKeyEvtName[] = "SampleCode_Key_Event"; 528static const char gTitleEvtName[] = "SampleCode_Title_Event"; 529static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event"; 530static const char gFastTextEvtName[] = "SampleCode_FastText_Event"; 531static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle"; 532 533bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) { 534 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) { 535 if (outUni) { 536 *outUni = evt.getFast32(); 537 } 538 return true; 539 } 540 return false; 541} 542 543bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) { 544 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) { 545 if (outKey) { 546 *outKey = (SkKey)evt.getFast32(); 547 } 548 return true; 549 } 550 return false; 551} 552 553bool SampleCode::TitleQ(const SkEvent& evt) { 554 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1); 555} 556 557void SampleCode::TitleR(SkEvent* evt, const char title[]) { 558 SkASSERT(evt && TitleQ(*evt)); 559 evt->setString(gTitleEvtName, title); 560} 561 562bool SampleCode::RequestTitle(SkView* view, SkString* title) { 563 SkEvent evt(gTitleEvtName); 564 if (view->doQuery(&evt)) { 565 title->set(evt.findString(gTitleEvtName)); 566 return true; 567 } 568 return false; 569} 570 571bool SampleCode::PrefSizeQ(const SkEvent& evt) { 572 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1); 573} 574 575void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) { 576 SkASSERT(evt && PrefSizeQ(*evt)); 577 SkScalar size[2]; 578 size[0] = width; 579 size[1] = height; 580 evt->setScalars(gPrefSizeEvtName, 2, size); 581} 582 583bool SampleCode::FastTextQ(const SkEvent& evt) { 584 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1); 585} 586 587/////////////////////////////////////////////////////////////////////////////// 588 589static SkMSec gAnimTime; 590static SkMSec gAnimTimePrev; 591 592SkMSec SampleCode::GetAnimTime() { return gAnimTime; } 593SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; } 594SkScalar SampleCode::GetAnimSecondsDelta() { 595 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0); 596} 597 598SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) { 599 // since gAnimTime can be up to 32 bits, we can't convert it to a float 600 // or we'll lose the low bits. Hence we use doubles for the intermediate 601 // calculations 602 double seconds = (double)gAnimTime / 1000.0; 603 double value = SkScalarToDouble(speed) * seconds; 604 if (period) { 605 value = ::fmod(value, SkScalarToDouble(period)); 606 } 607 return SkDoubleToScalar(value); 608} 609 610SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude, 611 SkScalar periodInSec, 612 SkScalar phaseInSec) { 613 if (!periodInSec) { 614 return 0; 615 } 616 double t = (double)gAnimTime / 1000.0 + phaseInSec; 617 t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec; 618 amplitude = SK_ScalarHalf * amplitude; 619 return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude; 620} 621 622enum TilingMode { 623 kNo_Tiling, 624 kAbs_128x128_Tiling, 625 kAbs_256x256_Tiling, 626 kRel_4x4_Tiling, 627 kRel_1x16_Tiling, 628 kRel_16x1_Tiling, 629 630 kLast_TilingMode_Enum 631}; 632 633struct TilingInfo { 634 const char* label; 635 SkScalar w, h; 636}; 637 638static const struct TilingInfo gTilingInfo[] = { 639 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling 640 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling 641 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling 642 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling 643 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling 644 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling 645}; 646SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum), 647 Incomplete_tiling_labels); 648 649SkSize SampleWindow::tileSize() const { 650 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum); 651 const struct TilingInfo* info = gTilingInfo + fTilingMode; 652 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w, 653 info->h > SK_Scalar1 ? info->h : this->height() * info->h); 654} 655////////////////////////////////////////////////////////////////////////////// 656 657static SkView* curr_view(SkWindow* wind) { 658 SkView::F2BIter iter(wind); 659 return iter.next(); 660} 661 662static bool curr_title(SkWindow* wind, SkString* title) { 663 SkView* view = curr_view(wind); 664 if (view) { 665 SkEvent evt(gTitleEvtName); 666 if (view->doQuery(&evt)) { 667 title->set(evt.findString(gTitleEvtName)); 668 return true; 669 } 670 } 671 return false; 672} 673 674void SampleWindow::setZoomCenter(float x, float y) 675{ 676 fZoomCenterX = x; 677 fZoomCenterY = y; 678} 679 680bool SampleWindow::zoomIn() 681{ 682 // Arbitrarily decided 683 if (fFatBitsScale == 25) return false; 684 fFatBitsScale++; 685 this->inval(NULL); 686 return true; 687} 688 689bool SampleWindow::zoomOut() 690{ 691 if (fFatBitsScale == 1) return false; 692 fFatBitsScale--; 693 this->inval(NULL); 694 return true; 695} 696 697void SampleWindow::updatePointer(int x, int y) 698{ 699 fMouseX = x; 700 fMouseY = y; 701 if (fShowZoomer) { 702 this->inval(NULL); 703 } 704} 705 706static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) { 707 static const SampleWindow::DeviceType gCT[] = { 708 SampleWindow::kPicture_DeviceType, 709#if SK_SUPPORT_GPU 710 SampleWindow::kGPU_DeviceType, 711#if SK_ANGLE 712 SampleWindow::kANGLE_DeviceType, 713#endif // SK_ANGLE 714 SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling 715#endif // SK_SUPPORT_GPU 716 SampleWindow::kRaster_DeviceType 717 }; 718 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch); 719 return gCT[ct]; 720} 721 722static void usage(const char * argv0) { 723 SkDebugf("%s [--slide sampleName] [-i resourcePath] [--msaa sampleCount] [--pictureDir dirPath] [--picture path] [--sort]\n", argv0); 724#ifdef SAMPLE_PDF_FILE_VIEWER 725 SkDebugf(" [--pdfDir pdfPath]\n"); 726 SkDebugf(" pdfPath: path to directory pdf files are read from\n"); 727#endif // SAMPLE_PDF_FILE_VIEWER 728 SkDebugf(" sampleName: sample at which to start.\n"); 729 SkDebugf(" resourcePath: directory that stores image resources.\n"); 730 SkDebugf(" msaa: request multisampling with the given sample count.\n"); 731 SkDebugf(" dirPath: path to directory skia pictures are read from\n"); 732 SkDebugf(" path: path to skia picture\n"); 733 SkDebugf(" --sort: sort samples by title, this would help to compare pdf rendering (P:foo.pdf) with skp rendering (P:foo.pdf)\n"); 734} 735 736static SkString getSampleTitle(const SkViewFactory* sampleFactory) { 737 SkView* view = (*sampleFactory)(); 738 SkString title; 739 SampleCode::RequestTitle(view, &title); 740 view->unref(); 741 return title; 742} 743 744static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) { 745 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0; 746} 747 748SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager) 749 : INHERITED(hwnd) 750 , fDevManager(NULL) { 751 752 fCurrIndex = -1; 753 754 this->registerPictFileSamples(argv, argc); 755 this->registerPictFileSample(argv, argc); 756#ifdef SAMPLE_PDF_FILE_VIEWER 757 this->registerPdfFileViewerSamples(argv, argc); 758#endif // SAMPLE_PDF_FILE_VIEWER 759 SkGMRegistyToSampleRegistry(); 760 { 761 const SkViewRegister* reg = SkViewRegister::Head(); 762 while (reg) { 763 *fSamples.append() = reg->factory(); 764 reg = reg->next(); 765 } 766 } 767 768 bool sort = false; 769 for (int i = 0; i < argc; ++i) { 770 if (!strcmp(argv[i], "--sort")) { 771 sort = true; 772 break; 773 } 774 } 775 776 if (sort) { 777 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where 778 // skp -> pdf -> png fails. 779 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle); 780 } 781 782 fMSAASampleCount = 0; 783 784 SkCommandLineFlags::Parse(argc, argv); 785 786 const char* const commandName = argv[0]; 787 char* const* stop = argv + argc; 788 for (++argv; argv < stop; ++argv) { 789 if (strcmp(*argv, "--slide") == 0) { 790 argv++; 791 if (argv < stop && **argv) { 792 fCurrIndex = findByTitle(*argv); 793 if (fCurrIndex < 0) { 794 fprintf(stderr, "Unknown sample \"%s\"\n", *argv); 795 listTitles(); 796 } 797 } 798 } else if (strcmp(*argv, "--msaa") == 0) { 799 ++argv; 800 if (argv < stop && **argv) { 801 fMSAASampleCount = atoi(*argv); 802 } 803 } else if (strcmp(*argv, "--list") == 0) { 804 listTitles(); 805 } else if (strcmp(*argv, "--pictureDir") == 0) { 806 ++argv; // This case is dealt with in registerPictFileSamples(). 807 } else if (strcmp(*argv, "--picture") == 0) { 808 ++argv; // This case is dealt with in registerPictFileSample(). 809 } 810 else { 811 usage(commandName); 812 } 813 } 814 815 if (fCurrIndex < 0) { 816 SkString title; 817 if (readTitleFromPrefs(&title)) { 818 fCurrIndex = findByTitle(title.c_str()); 819 } 820 } 821 822 if (fCurrIndex < 0) { 823 fCurrIndex = 0; 824 } 825 826 gSampleWindow = this; 827 828#ifdef PIPE_FILE 829 //Clear existing file or create file if it doesn't exist 830 FILE* f = fopen(FILE_PATH, "wb"); 831 fclose(f); 832#endif 833 834 fDeviceType = kRaster_DeviceType; 835 836#if DEFAULT_TO_GPU 837 fDeviceType = kGPU_DeviceType; 838#endif 839#if SK_ANGLE && DEFAULT_TO_ANGLE 840 fDeviceType = kANGLE_DeviceType; 841#endif 842 843 fUseClip = false; 844 fNClip = false; 845 fAnimating = false; 846 fRotate = false; 847 fRotateAnimTime = 0; 848 fPerspAnim = false; 849 fPerspAnimTime = 0; 850 fRequestGrabImage = false; 851 fPipeState = SkOSMenu::kOffState; 852 fTilingMode = kNo_Tiling; 853 fMeasureFPS = false; 854 fLCDState = SkOSMenu::kMixedState; 855 fAAState = SkOSMenu::kMixedState; 856 fSubpixelState = SkOSMenu::kMixedState; 857 fHintingState = 0; 858 fFilterLevelIndex = 0; 859 fFlipAxis = 0; 860 fScrollTestX = fScrollTestY = 0; 861 862 fMouseX = fMouseY = 0; 863 fFatBitsScale = 8; 864 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold); 865 fShowZoomer = false; 866 867 fZoomLevel = 0; 868 fZoomScale = SK_Scalar1; 869 870 fMagnify = false; 871 872 fSaveToPdf = false; 873 fPdfCanvas = NULL; 874 875 fTransitionNext = 6; 876 fTransitionPrev = 2; 877 878 int sinkID = this->getSinkID(); 879 fAppMenu = new SkOSMenu; 880 fAppMenu->setTitle("Global Settings"); 881 int itemID; 882 883 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0, 884 "Raster", "Picture", "OpenGL", 885#if SK_ANGLE 886 "ANGLE", 887#endif 888 NULL); 889 fAppMenu->assignKeyEquivalentToItem(itemID, 'd'); 890 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState); 891 fAppMenu->assignKeyEquivalentToItem(itemID, 'b'); 892 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState); 893 fAppMenu->assignKeyEquivalentToItem(itemID, 'l'); 894 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex, 895 gFilterLevelStates[0].fName, 896 gFilterLevelStates[1].fName, 897 gFilterLevelStates[2].fName, 898 gFilterLevelStates[3].fName, 899 gFilterLevelStates[4].fName, 900 NULL); 901 fAppMenu->assignKeyEquivalentToItem(itemID, 'n'); 902 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState); 903 fAppMenu->assignKeyEquivalentToItem(itemID, 's'); 904 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState, 905 gHintingStates[0].name, 906 gHintingStates[1].name, 907 gHintingStates[2].name, 908 gHintingStates[3].name, 909 gHintingStates[4].name, 910 NULL); 911 fAppMenu->assignKeyEquivalentToItem(itemID, 'h'); 912 913 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID, 914 fPipeState); 915 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P'); 916 917 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode, 918 gTilingInfo[kNo_Tiling].label, 919 gTilingInfo[kAbs_128x128_Tiling].label, 920 gTilingInfo[kAbs_256x256_Tiling].label, 921 gTilingInfo[kRel_4x4_Tiling].label, 922 gTilingInfo[kRel_1x16_Tiling].label, 923 gTilingInfo[kRel_16x1_Tiling].label, 924 NULL); 925 fAppMenu->assignKeyEquivalentToItem(itemID, 't'); 926 927 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false); 928 fAppMenu->assignKeyEquivalentToItem(itemID, 'a'); 929 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip); 930 fAppMenu->assignKeyEquivalentToItem(itemID, 'c'); 931 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false); 932 fAppMenu->assignKeyEquivalentToItem(itemID, 'x'); 933 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false); 934 fAppMenu->assignKeyEquivalentToItem(itemID, 'y'); 935 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer); 936 fAppMenu->assignKeyEquivalentToItem(itemID, 'z'); 937 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify); 938 fAppMenu->assignKeyEquivalentToItem(itemID, 'm'); 939 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID, 940 fTransitionNext, "Up", "Up and Right", "Right", 941 "Down and Right", "Down", "Down and Left", 942 "Left", "Up and Left", NULL); 943 fAppMenu->assignKeyEquivalentToItem(itemID, 'j'); 944 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID, 945 fTransitionPrev, "Up", "Up and Right", "Right", 946 "Down and Right", "Down", "Down and Left", 947 "Left", "Up and Left", NULL); 948 fAppMenu->assignKeyEquivalentToItem(itemID, 'k'); 949 itemID = fAppMenu->appendAction("Save to PDF", sinkID); 950 fAppMenu->assignKeyEquivalentToItem(itemID, 'e'); 951 952 this->addMenu(fAppMenu); 953 fSlideMenu = new SkOSMenu; 954 this->addMenu(fSlideMenu); 955 956 this->setColorType(kN32_SkColorType); 957 this->setVisibleP(true); 958 this->setClipToBounds(false); 959 960 this->loadView((*fSamples[fCurrIndex])()); 961 962 fPDFData = NULL; 963 964 if (NULL == devManager) { 965 fDevManager = new DefaultDeviceManager(); 966 } else { 967 devManager->ref(); 968 fDevManager = devManager; 969 } 970 fDevManager->setUpBackend(this, fMSAASampleCount); 971 972 // If another constructor set our dimensions, ensure that our 973 // onSizeChange gets called. 974 if (this->height() && this->width()) { 975 this->onSizeChange(); 976 } 977 978 // can't call this synchronously, since it may require a subclass to 979 // to implement, or the caller may need us to have returned from the 980 // constructor first. Hence we post an event to ourselves. 981// this->updateTitle(); 982 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this); 983} 984 985SampleWindow::~SampleWindow() { 986 delete fPdfCanvas; 987 fTypeface->unref(); 988 989 SkSafeUnref(fDevManager); 990} 991 992static void make_filepath(SkString* path, const char* dir, const SkString& name) { 993 size_t len = strlen(dir); 994 path->set(dir); 995 if (len > 0 && dir[len - 1] != '/') { 996 path->append("/"); 997 } 998 path->append(name); 999} 1000 1001void SampleWindow::registerPictFileSample(char** argv, int argc) { 1002 const char* pict = NULL; 1003 1004 for (int i = 0; i < argc; ++i) { 1005 if (!strcmp(argv[i], "--picture")) { 1006 i += 1; 1007 if (i < argc) { 1008 pict = argv[i]; 1009 break; 1010 } 1011 } 1012 } 1013 if (pict) { 1014 SkString path(pict); 1015 fCurrIndex = fSamples.count(); 1016 *fSamples.append() = new PictFileFactory(path); 1017 } 1018} 1019 1020void SampleWindow::registerPictFileSamples(char** argv, int argc) { 1021 const char* pictDir = NULL; 1022 1023 for (int i = 0; i < argc; ++i) { 1024 if (!strcmp(argv[i], "--pictureDir")) { 1025 i += 1; 1026 if (i < argc) { 1027 pictDir = argv[i]; 1028 break; 1029 } 1030 } 1031 } 1032 if (pictDir) { 1033 SkOSFile::Iter iter(pictDir, "skp"); 1034 SkString filename; 1035 while (iter.next(&filename)) { 1036 SkString path; 1037 make_filepath(&path, pictDir, filename); 1038 *fSamples.append() = new PictFileFactory(path); 1039 } 1040 } 1041} 1042 1043#ifdef SAMPLE_PDF_FILE_VIEWER 1044void SampleWindow::registerPdfFileViewerSamples(char** argv, int argc) { 1045 const char* pdfDir = NULL; 1046 1047 for (int i = 0; i < argc; ++i) { 1048 if (!strcmp(argv[i], "--pdfDir")) { 1049 i += 1; 1050 if (i < argc) { 1051 pdfDir = argv[i]; 1052 break; 1053 } 1054 } 1055 } 1056 if (pdfDir) { 1057 SkOSFile::Iter iter(pdfDir, "pdf"); 1058 SkString filename; 1059 while (iter.next(&filename)) { 1060 SkString path; 1061 make_filepath(&path, pdfDir, filename); 1062 *fSamples.append() = new PdfFileViewerFactory(path); 1063 } 1064 } 1065} 1066#endif // SAMPLE_PDF_FILE_VIEWER 1067 1068 1069int SampleWindow::findByTitle(const char title[]) { 1070 int i, count = fSamples.count(); 1071 for (i = 0; i < count; i++) { 1072 if (getSampleTitle(i).equals(title)) { 1073 return i; 1074 } 1075 } 1076 return -1; 1077} 1078 1079void SampleWindow::listTitles() { 1080 int count = fSamples.count(); 1081 SkDebugf("All Slides:\n"); 1082 for (int i = 0; i < count; i++) { 1083 SkDebugf(" %s\n", getSampleTitle(i).c_str()); 1084 } 1085} 1086 1087static SkBitmap capture_bitmap(SkCanvas* canvas) { 1088 SkBitmap bm; 1089 if (bm.allocPixels(canvas->imageInfo())) { 1090 canvas->readPixels(&bm, 0, 0); 1091 } 1092 return bm; 1093} 1094 1095static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig, 1096 SkBitmap* diff) { 1097 const SkBitmap& src = canvas->getDevice()->accessBitmap(false); 1098 1099 SkAutoLockPixels alp0(src); 1100 SkAutoLockPixels alp1(orig); 1101 for (int y = 0; y < src.height(); y++) { 1102 const void* srcP = src.getAddr(0, y); 1103 const void* origP = orig.getAddr(0, y); 1104 size_t bytes = src.width() * src.bytesPerPixel(); 1105 if (memcmp(srcP, origP, bytes)) { 1106 SkDebugf("---------- difference on line %d\n", y); 1107 return true; 1108 } 1109 } 1110 return false; 1111} 1112 1113static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint) 1114{ 1115 SkColor desiredColor = paint.getColor(); 1116 paint.setColor(SK_ColorWHITE); 1117 const char* c_str = string.c_str(); 1118 size_t size = string.size(); 1119 SkRect bounds; 1120 paint.measureText(c_str, size, &bounds); 1121 bounds.offset(left, top); 1122 SkScalar inset = SkIntToScalar(-2); 1123 bounds.inset(inset, inset); 1124 canvas->drawRect(bounds, paint); 1125 if (desiredColor != SK_ColorBLACK) { 1126 paint.setColor(SK_ColorBLACK); 1127 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint); 1128 } 1129 paint.setColor(desiredColor); 1130 canvas->drawText(c_str, size, left, top, paint); 1131} 1132 1133#define XCLIP_N 8 1134#define YCLIP_N 8 1135 1136void SampleWindow::draw(SkCanvas* canvas) { 1137 // update the animation time 1138 if (!gAnimTimePrev && !gAnimTime) { 1139 // first time make delta be 0 1140 gAnimTime = SkTime::GetMSecs(); 1141 gAnimTimePrev = gAnimTime; 1142 } else { 1143 gAnimTimePrev = gAnimTime; 1144 gAnimTime = SkTime::GetMSecs(); 1145 } 1146 1147 if (fGesture.isActive()) { 1148 this->updateMatrix(); 1149 } 1150 1151 if (fMeasureFPS) { 1152 fMeasureFPS_Time = 0; 1153 } 1154 1155 if (fNClip) { 1156 this->INHERITED::draw(canvas); 1157 SkBitmap orig = capture_bitmap(canvas); 1158 1159 const SkScalar w = this->width(); 1160 const SkScalar h = this->height(); 1161 const SkScalar cw = w / XCLIP_N; 1162 const SkScalar ch = h / YCLIP_N; 1163 for (int y = 0; y < YCLIP_N; y++) { 1164 SkRect r; 1165 r.fTop = y * ch; 1166 r.fBottom = (y + 1) * ch; 1167 if (y == YCLIP_N - 1) { 1168 r.fBottom = h; 1169 } 1170 for (int x = 0; x < XCLIP_N; x++) { 1171 SkAutoCanvasRestore acr(canvas, true); 1172 r.fLeft = x * cw; 1173 r.fRight = (x + 1) * cw; 1174 if (x == XCLIP_N - 1) { 1175 r.fRight = w; 1176 } 1177 canvas->clipRect(r); 1178 this->INHERITED::draw(canvas); 1179 } 1180 } 1181 1182 SkBitmap diff; 1183 if (bitmap_diff(canvas, orig, &diff)) { 1184 } 1185 } else { 1186 SkSize tile = this->tileSize(); 1187 1188 if (kNo_Tiling == fTilingMode) { 1189 this->INHERITED::draw(canvas); // no looping or surfaces needed 1190 } else { 1191 const int w = SkScalarRoundToInt(tile.width()); 1192 const int h = SkScalarRoundToInt(tile.height()); 1193 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h); 1194 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info)); 1195 SkCanvas* tileCanvas = surface->getCanvas(); 1196 1197 for (SkScalar y = 0; y < height(); y += tile.height()) { 1198 for (SkScalar x = 0; x < width(); x += tile.width()) { 1199 SkAutoCanvasRestore acr(tileCanvas, true); 1200 tileCanvas->translate(-x, -y); 1201 tileCanvas->clear(0); 1202 this->INHERITED::draw(tileCanvas); 1203 surface->draw(canvas, x, y, NULL); 1204 } 1205 } 1206 1207 // for drawing the borders between tiles 1208 SkPaint paint; 1209 paint.setColor(0x60FF00FF); 1210 paint.setStyle(SkPaint::kStroke_Style); 1211 1212 for (SkScalar y = 0; y < height(); y += tile.height()) { 1213 for (SkScalar x = 0; x < width(); x += tile.width()) { 1214 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint); 1215 } 1216 } 1217 } 1218 } 1219 if (fShowZoomer && !fSaveToPdf) { 1220 showZoomer(canvas); 1221 } 1222 if (fMagnify && !fSaveToPdf) { 1223 magnify(canvas); 1224 } 1225 1226 if (fMeasureFPS && fMeasureFPS_Time) { 1227 this->updateTitle(); 1228 this->postInvalDelay(); 1229 } 1230 1231 // do this last 1232 fDevManager->publishCanvas(fDeviceType, canvas, this); 1233} 1234 1235static float clipW = 200; 1236static float clipH = 200; 1237void SampleWindow::magnify(SkCanvas* canvas) { 1238 SkRect r; 1239 int count = canvas->save(); 1240 1241 SkMatrix m = canvas->getTotalMatrix(); 1242 if (!m.invert(&m)) { 1243 return; 1244 } 1245 SkPoint offset, center; 1246 SkScalar mouseX = fMouseX * SK_Scalar1; 1247 SkScalar mouseY = fMouseY * SK_Scalar1; 1248 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset); 1249 m.mapXY(mouseX, mouseY, ¢er); 1250 1251 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX()); 1252 r.offset(offset.fX, offset.fY); 1253 1254 SkPaint paint; 1255 paint.setColor(0xFF66AAEE); 1256 paint.setStyle(SkPaint::kStroke_Style); 1257 paint.setStrokeWidth(10.f * m.getScaleX()); 1258 //lense offset 1259 //canvas->translate(0, -250); 1260 canvas->drawRect(r, paint); 1261 canvas->clipRect(r); 1262 1263 m = canvas->getTotalMatrix(); 1264 m.setTranslate(-center.fX, -center.fY); 1265 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale); 1266 m.postTranslate(center.fX, center.fY); 1267 canvas->concat(m); 1268 1269 this->INHERITED::draw(canvas); 1270 1271 canvas->restoreToCount(count); 1272} 1273 1274void SampleWindow::showZoomer(SkCanvas* canvas) { 1275 int count = canvas->save(); 1276 canvas->resetMatrix(); 1277 // Ensure the mouse position is on screen. 1278 int width = SkScalarRoundToInt(this->width()); 1279 int height = SkScalarRoundToInt(this->height()); 1280 if (fMouseX >= width) fMouseX = width - 1; 1281 else if (fMouseX < 0) fMouseX = 0; 1282 if (fMouseY >= height) fMouseY = height - 1; 1283 else if (fMouseY < 0) fMouseY = 0; 1284 1285 SkBitmap bitmap = capture_bitmap(canvas); 1286 bitmap.lockPixels(); 1287 1288 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle. 1289 int zoomedWidth = (width >> 1) | 1; 1290 int zoomedHeight = (height >> 1) | 1; 1291 SkIRect src; 1292 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale); 1293 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1)); 1294 SkRect dest; 1295 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight)); 1296 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight)); 1297 SkPaint paint; 1298 // Clear the background behind our zoomed in view 1299 paint.setColor(SK_ColorWHITE); 1300 canvas->drawRect(dest, paint); 1301 canvas->drawBitmapRect(bitmap, &src, dest); 1302 paint.setColor(SK_ColorBLACK); 1303 paint.setStyle(SkPaint::kStroke_Style); 1304 // Draw a border around the pixel in the middle 1305 SkRect originalPixel; 1306 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1)); 1307 SkMatrix matrix; 1308 SkRect scalarSrc; 1309 scalarSrc.set(src); 1310 SkColor color = bitmap.getColor(fMouseX, fMouseY); 1311 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) { 1312 SkRect pixel; 1313 matrix.mapRect(&pixel, originalPixel); 1314 // TODO Perhaps measure the values and make the outline white if it's "dark" 1315 if (color == SK_ColorBLACK) { 1316 paint.setColor(SK_ColorWHITE); 1317 } 1318 canvas->drawRect(pixel, paint); 1319 } 1320 paint.setColor(SK_ColorBLACK); 1321 // Draw a border around the destination rectangle 1322 canvas->drawRect(dest, paint); 1323 paint.setStyle(SkPaint::kStrokeAndFill_Style); 1324 // Identify the pixel and its color on screen 1325 paint.setTypeface(fTypeface); 1326 paint.setAntiAlias(true); 1327 SkScalar lineHeight = paint.getFontMetrics(NULL); 1328 SkString string; 1329 string.appendf("(%i, %i)", fMouseX, fMouseY); 1330 SkScalar left = dest.fLeft + SkIntToScalar(3); 1331 SkScalar i = SK_Scalar1; 1332 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1333 // Alpha 1334 i += SK_Scalar1; 1335 string.reset(); 1336 string.appendf("A: %X", SkColorGetA(color)); 1337 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1338 // Red 1339 i += SK_Scalar1; 1340 string.reset(); 1341 string.appendf("R: %X", SkColorGetR(color)); 1342 paint.setColor(SK_ColorRED); 1343 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1344 // Green 1345 i += SK_Scalar1; 1346 string.reset(); 1347 string.appendf("G: %X", SkColorGetG(color)); 1348 paint.setColor(SK_ColorGREEN); 1349 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1350 // Blue 1351 i += SK_Scalar1; 1352 string.reset(); 1353 string.appendf("B: %X", SkColorGetB(color)); 1354 paint.setColor(SK_ColorBLUE); 1355 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1356 canvas->restoreToCount(count); 1357} 1358 1359void SampleWindow::onDraw(SkCanvas* canvas) { 1360} 1361 1362#include "SkColorPriv.h" 1363 1364void SampleWindow::saveToPdf() 1365{ 1366 fSaveToPdf = true; 1367 this->inval(NULL); 1368} 1369 1370SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) { 1371 if (fSaveToPdf) { 1372 const SkBitmap& bmp = canvas->getDevice()->accessBitmap(false); 1373 SkISize size = SkISize::Make(bmp.width(), bmp.height()); 1374 SkPDFDevice* pdfDevice = new SkPDFDevice(size, size, 1375 canvas->getTotalMatrix()); 1376 fPdfCanvas = new SkCanvas(pdfDevice); 1377 pdfDevice->unref(); 1378 canvas = fPdfCanvas; 1379 } else if (kPicture_DeviceType == fDeviceType) { 1380 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0); 1381 } else { 1382#if SK_SUPPORT_GPU 1383 if (kNullGPU_DeviceType != fDeviceType) 1384#endif 1385 { 1386 canvas = this->INHERITED::beforeChildren(canvas); 1387 } 1388 } 1389 1390 if (fUseClip) { 1391 canvas->drawColor(0xFFFF88FF); 1392 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true); 1393 } 1394 1395 return canvas; 1396} 1397 1398static void paint_rgn(const SkBitmap& bm, const SkIRect& r, 1399 const SkRegion& rgn) { 1400 SkCanvas canvas(bm); 1401 SkRegion inval(rgn); 1402 1403 inval.translate(r.fLeft, r.fTop); 1404 canvas.clipRegion(inval); 1405 canvas.drawColor(0xFFFF8080); 1406} 1407#include "SkData.h" 1408void SampleWindow::afterChildren(SkCanvas* orig) { 1409 if (fSaveToPdf) { 1410 fSaveToPdf = false; 1411 if (fShowZoomer) { 1412 showZoomer(fPdfCanvas); 1413 } 1414 SkString name; 1415 name.printf("%s.pdf", this->getTitle()); 1416 SkPDFDocument doc; 1417 SkPDFDevice* device = static_cast<SkPDFDevice*>(fPdfCanvas->getDevice()); 1418 doc.appendPage(device); 1419#ifdef SK_BUILD_FOR_ANDROID 1420 name.prepend("/sdcard/"); 1421#endif 1422 1423#ifdef SK_BUILD_FOR_IOS 1424 SkDynamicMemoryWStream mstream; 1425 doc.emitPDF(&mstream); 1426 fPDFData = mstream.copyToData(); 1427#endif 1428 SkFILEWStream stream(name.c_str()); 1429 if (stream.isValid()) { 1430 doc.emitPDF(&stream); 1431 const char* desc = "File saved from Skia SampleApp"; 1432 this->onPDFSaved(this->getTitle(), desc, name.c_str()); 1433 } 1434 1435 delete fPdfCanvas; 1436 fPdfCanvas = NULL; 1437 1438 // We took over the draw calls in order to create the PDF, so we need 1439 // to redraw. 1440 this->inval(NULL); 1441 return; 1442 } 1443 1444 if (fRequestGrabImage) { 1445 fRequestGrabImage = false; 1446 1447 SkBaseDevice* device = orig->getDevice(); 1448 SkBitmap bmp; 1449 if (device->accessBitmap(false).copyTo(&bmp, kN32_SkColorType)) { 1450 static int gSampleGrabCounter; 1451 SkString name; 1452 name.printf("sample_grab_%d.png", gSampleGrabCounter++); 1453 SkImageEncoder::EncodeFile(name.c_str(), bmp, 1454 SkImageEncoder::kPNG_Type, 100); 1455 } 1456 } 1457 1458 if (kPicture_DeviceType == fDeviceType) { 1459 SkAutoTUnref<SkPicture> picture(fRecorder.endRecording()); 1460 1461 if (true) { 1462 SkPicture* pict = new SkPicture(*picture); 1463 this->installDrawFilter(orig); 1464 orig->drawPicture(pict); 1465 pict->unref(); 1466 } else if (true) { 1467 SkDynamicMemoryWStream ostream; 1468 picture->serialize(&ostream); 1469 1470 SkAutoDataUnref data(ostream.copyToData()); 1471 SkMemoryStream istream(data->data(), data->size()); 1472 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream)); 1473 if (pict.get() != NULL) { 1474 orig->drawPicture(pict.get()); 1475 } 1476 } else { 1477 picture->draw(orig); 1478 } 1479 } 1480 1481 // Do this after presentGL and other finishing, rather than in afterChild 1482 if (fMeasureFPS && fMeasureFPS_StartTime) { 1483 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime; 1484 } 1485 1486 // if ((fScrollTestX | fScrollTestY) != 0) 1487 if (false) { 1488 const SkBitmap& bm = orig->getDevice()->accessBitmap(true); 1489 int dx = fScrollTestX * 7; 1490 int dy = fScrollTestY * 7; 1491 SkIRect r; 1492 SkRegion inval; 1493 1494 r.set(50, 50, 50+100, 50+100); 1495 bm.scrollRect(&r, dx, dy, &inval); 1496 paint_rgn(bm, r, inval); 1497 } 1498} 1499 1500void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) { 1501 if (fRotate) { 1502 fRotateAnimTime += SampleCode::GetAnimSecondsDelta(); 1503 1504 SkScalar cx = this->width() / 2; 1505 SkScalar cy = this->height() / 2; 1506 canvas->translate(cx, cy); 1507 canvas->rotate(fRotateAnimTime * 10); 1508 canvas->translate(-cx, -cy); 1509 } 1510 1511 if (fPerspAnim) { 1512 fPerspAnimTime += SampleCode::GetAnimSecondsDelta(); 1513 1514 static const SkScalar gAnimPeriod = 10 * SK_Scalar1; 1515 static const SkScalar gAnimMag = SK_Scalar1 / 1000; 1516 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod); 1517 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) { 1518 t = gAnimPeriod - t; 1519 } 1520 t = 2 * t - gAnimPeriod; 1521 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag); 1522 SkMatrix m; 1523 m.reset(); 1524 m.setPerspY(t); 1525 canvas->concat(m); 1526 } 1527 1528 this->installDrawFilter(canvas); 1529 1530 if (fMeasureFPS) { 1531 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) { 1532 fMeasureFPS_StartTime = SkTime::GetMSecs(); 1533 } 1534 } else { 1535 (void)SampleView::SetRepeatDraw(child, 1); 1536 } 1537 if (fPerspAnim || fRotate) { 1538 this->inval(NULL); 1539 } 1540} 1541 1542void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) { 1543 canvas->setDrawFilter(NULL); 1544} 1545 1546static SkColorType gColorTypeCycle[] = { 1547 kUnknown_SkColorType, // none -> none 1548 kUnknown_SkColorType, // a8 -> none 1549 kN32_SkColorType, // 565 -> 8888 1550 kN32_SkColorType, // 4444 -> 8888 1551 kRGB_565_SkColorType, // 8888 -> 565 1552 kRGB_565_SkColorType, // 8888 -> 565 1553 kUnknown_SkColorType, // index8 -> none 1554}; 1555 1556static SkColorType cycle_colortypes(SkColorType c) { 1557 return gColorTypeCycle[c]; 1558} 1559 1560void SampleWindow::changeZoomLevel(float delta) { 1561 fZoomLevel += delta; 1562 if (fZoomLevel > 0) { 1563 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL); 1564 fZoomScale = fZoomLevel + SK_Scalar1; 1565 } else if (fZoomLevel < 0) { 1566 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL); 1567 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel); 1568 } else { 1569 fZoomScale = SK_Scalar1; 1570 } 1571 this->updateMatrix(); 1572} 1573 1574void SampleWindow::updateMatrix(){ 1575 SkMatrix m; 1576 m.reset(); 1577 if (fZoomLevel) { 1578 SkPoint center; 1579 //m = this->getLocalMatrix();//.invert(&m); 1580 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er); 1581 SkScalar cx = center.fX; 1582 SkScalar cy = center.fY; 1583 1584 m.setTranslate(-cx, -cy); 1585 m.postScale(fZoomScale, fZoomScale); 1586 m.postTranslate(cx, cy); 1587 } 1588 1589 if (fFlipAxis) { 1590 m.preTranslate(fZoomCenterX, fZoomCenterY); 1591 if (fFlipAxis & kFlipAxis_X) { 1592 m.preScale(-SK_Scalar1, SK_Scalar1); 1593 } 1594 if (fFlipAxis & kFlipAxis_Y) { 1595 m.preScale(SK_Scalar1, -SK_Scalar1); 1596 } 1597 m.preTranslate(-fZoomCenterX, -fZoomCenterY); 1598 //canvas->concat(m); 1599 } 1600 // Apply any gesture matrix 1601 m.preConcat(fGesture.localM()); 1602 m.preConcat(fGesture.globalM()); 1603 1604 this->setLocalMatrix(m); 1605 1606 this->updateTitle(); 1607 this->inval(NULL); 1608} 1609bool SampleWindow::previousSample() { 1610 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count(); 1611 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1612 fTransitionPrev)); 1613 return true; 1614} 1615 1616bool SampleWindow::nextSample() { 1617 fCurrIndex = (fCurrIndex + 1) % fSamples.count(); 1618 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1619 fTransitionNext)); 1620 return true; 1621} 1622 1623bool SampleWindow::goToSample(int i) { 1624 fCurrIndex = (i) % fSamples.count(); 1625 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6)); 1626 return true; 1627} 1628 1629SkString SampleWindow::getSampleTitle(int i) { 1630 return ::getSampleTitle(fSamples[i]); 1631} 1632 1633int SampleWindow::sampleCount() { 1634 return fSamples.count(); 1635} 1636 1637void SampleWindow::showOverview() { 1638 this->loadView(create_transition(curr_view(this), 1639 create_overview(fSamples.count(), fSamples.begin()), 1640 4)); 1641} 1642 1643void SampleWindow::installDrawFilter(SkCanvas* canvas) { 1644 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState, 1645 fHintingState, fFilterLevelIndex))->unref(); 1646} 1647 1648void SampleWindow::postAnimatingEvent() { 1649 if (fAnimating) { 1650 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY); 1651 } 1652} 1653 1654bool SampleWindow::onEvent(const SkEvent& evt) { 1655 if (evt.isType(gUpdateWindowTitleEvtName)) { 1656 this->updateTitle(); 1657 return true; 1658 } 1659 if (evt.isType(ANIMATING_EVENTTYPE)) { 1660 if (fAnimating) { 1661 this->nextSample(); 1662 this->postAnimatingEvent(); 1663 } 1664 return true; 1665 } 1666 if (evt.isType("replace-transition-view")) { 1667 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32())); 1668 return true; 1669 } 1670 if (evt.isType("set-curr-index")) { 1671 this->goToSample(evt.getFast32()); 1672 return true; 1673 } 1674 if (isInvalEvent(evt)) { 1675 this->inval(NULL); 1676 return true; 1677 } 1678 int selected = -1; 1679 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) { 1680 this->setDeviceType((DeviceType)selected); 1681 return true; 1682 } 1683 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) { 1684#ifdef PIPE_NET 1685 if (!fPipeState != SkOSMenu::kOnState) 1686 gServer.disconnectAll(); 1687#endif 1688 (void)SampleView::SetUsePipe(curr_view(this), fPipeState); 1689 this->updateTitle(); 1690 this->inval(NULL); 1691 return true; 1692 } 1693 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) { 1694 this->toggleSlideshow(); 1695 return true; 1696 } 1697 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) || 1698 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) || 1699 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) || 1700 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) || 1701 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) || 1702 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) || 1703 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) || 1704 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) || 1705 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) || 1706 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) { 1707 this->inval(NULL); 1708 this->updateTitle(); 1709 return true; 1710 } 1711 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) { 1712 if (SampleView::IsSampleView(curr_view(this))) { 1713 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize()); 1714 } 1715 this->inval(NULL); 1716 this->updateTitle(); 1717 return true; 1718 } 1719 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) { 1720 fFlipAxis ^= kFlipAxis_X; 1721 this->updateMatrix(); 1722 return true; 1723 } 1724 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) { 1725 fFlipAxis ^= kFlipAxis_Y; 1726 this->updateMatrix(); 1727 return true; 1728 } 1729 if (SkOSMenu::FindAction(evt,"Save to PDF")) { 1730 this->saveToPdf(); 1731 return true; 1732 } 1733 return this->INHERITED::onEvent(evt); 1734} 1735 1736bool SampleWindow::onQuery(SkEvent* query) { 1737 if (query->isType("get-slide-count")) { 1738 query->setFast32(fSamples.count()); 1739 return true; 1740 } 1741 if (query->isType("get-slide-title")) { 1742 SkView* view = (*fSamples[query->getFast32()])(); 1743 SkEvent evt(gTitleEvtName); 1744 if (view->doQuery(&evt)) { 1745 query->setString("title", evt.findString(gTitleEvtName)); 1746 } 1747 SkSafeUnref(view); 1748 return true; 1749 } 1750 if (query->isType("use-fast-text")) { 1751 SkEvent evt(gFastTextEvtName); 1752 return curr_view(this)->doQuery(&evt); 1753 } 1754 if (query->isType("ignore-window-bitmap")) { 1755 query->setFast32(this->getGrContext() != NULL); 1756 return true; 1757 } 1758 return this->INHERITED::onQuery(query); 1759} 1760 1761#if 0 // UNUSED 1762static void cleanup_for_filename(SkString* name) { 1763 char* str = name->writable_str(); 1764 for (size_t i = 0; i < name->size(); i++) { 1765 switch (str[i]) { 1766 case ':': str[i] = '-'; break; 1767 case '/': str[i] = '-'; break; 1768 case ' ': str[i] = '_'; break; 1769 default: break; 1770 } 1771 } 1772} 1773#endif 1774 1775bool SampleWindow::onHandleChar(SkUnichar uni) { 1776 { 1777 SkView* view = curr_view(this); 1778 if (view) { 1779 SkEvent evt(gCharEvtName); 1780 evt.setFast32(uni); 1781 if (view->doQuery(&evt)) { 1782 return true; 1783 } 1784 } 1785 } 1786 1787 int dx = 0xFF; 1788 int dy = 0xFF; 1789 1790 switch (uni) { 1791 case '5': dx = 0; dy = 0; break; 1792 case '8': dx = 0; dy = -1; break; 1793 case '6': dx = 1; dy = 0; break; 1794 case '2': dx = 0; dy = 1; break; 1795 case '4': dx = -1; dy = 0; break; 1796 case '7': dx = -1; dy = -1; break; 1797 case '9': dx = 1; dy = -1; break; 1798 case '3': dx = 1; dy = 1; break; 1799 case '1': dx = -1; dy = 1; break; 1800 1801 default: 1802 break; 1803 } 1804 1805 if (0xFF != dx && 0xFF != dy) { 1806 if ((dx | dy) == 0) { 1807 fScrollTestX = fScrollTestY = 0; 1808 } else { 1809 fScrollTestX += dx; 1810 fScrollTestY += dy; 1811 } 1812 this->inval(NULL); 1813 return true; 1814 } 1815 1816 switch (uni) { 1817 case 'B': 1818 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this)); 1819 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in 1820 // the queue. 1821 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this); 1822 this->inval(NULL); 1823 break; 1824 case 'f': 1825 // only 1826 toggleFPS(); 1827 break; 1828 case 'g': 1829 fRequestGrabImage = true; 1830 this->inval(NULL); 1831 break; 1832 case 'G': 1833 gShowGMBounds = !gShowGMBounds; 1834 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds), 1835 curr_view(this)); 1836 this->inval(NULL); 1837 break; 1838 case 'i': 1839 this->zoomIn(); 1840 break; 1841 case 'o': 1842 this->zoomOut(); 1843 break; 1844 case 'r': 1845 fRotate = !fRotate; 1846 fRotateAnimTime = 0; 1847 this->inval(NULL); 1848 this->updateTitle(); 1849 return true; 1850 case 'k': 1851 fPerspAnim = !fPerspAnim; 1852 this->inval(NULL); 1853 this->updateTitle(); 1854 return true; 1855#if SK_SUPPORT_GPU 1856 case '\\': 1857 this->setDeviceType(kNullGPU_DeviceType); 1858 this->inval(NULL); 1859 this->updateTitle(); 1860 return true; 1861 case 'p': 1862 { 1863 GrContext* grContext = this->getGrContext(); 1864 if (grContext) { 1865 size_t cacheBytes; 1866 grContext->getResourceCacheUsage(NULL, &cacheBytes); 1867 grContext->freeGpuResources(); 1868 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes); 1869 } 1870 } 1871 return true; 1872#endif 1873 default: 1874 break; 1875 } 1876 1877 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) { 1878 this->onUpdateMenu(fAppMenu); 1879 this->onUpdateMenu(fSlideMenu); 1880 return true; 1881 } 1882 return this->INHERITED::onHandleChar(uni); 1883} 1884 1885void SampleWindow::setDeviceType(DeviceType type) { 1886 if (type == fDeviceType) 1887 return; 1888 1889 fDevManager->tearDownBackend(this); 1890 1891 fDeviceType = type; 1892 1893 fDevManager->setUpBackend(this, fMSAASampleCount); 1894 1895 this->updateTitle(); 1896 this->inval(NULL); 1897} 1898 1899void SampleWindow::toggleSlideshow() { 1900 fAnimating = !fAnimating; 1901 this->postAnimatingEvent(); 1902 this->updateTitle(); 1903} 1904 1905void SampleWindow::toggleRendering() { 1906 this->setDeviceType(cycle_devicetype(fDeviceType)); 1907 this->updateTitle(); 1908 this->inval(NULL); 1909} 1910 1911void SampleWindow::toggleFPS() { 1912 fMeasureFPS = !fMeasureFPS; 1913 this->updateTitle(); 1914 this->inval(NULL); 1915} 1916 1917#include "SkDumpCanvas.h" 1918 1919bool SampleWindow::onHandleKey(SkKey key) { 1920 { 1921 SkView* view = curr_view(this); 1922 if (view) { 1923 SkEvent evt(gKeyEvtName); 1924 evt.setFast32(key); 1925 if (view->doQuery(&evt)) { 1926 return true; 1927 } 1928 } 1929 } 1930 switch (key) { 1931 case kRight_SkKey: 1932 if (this->nextSample()) { 1933 return true; 1934 } 1935 break; 1936 case kLeft_SkKey: 1937 if (this->previousSample()) { 1938 return true; 1939 } 1940 return true; 1941 case kUp_SkKey: 1942 if (USE_ARROWS_FOR_ZOOM) { 1943 this->changeZoomLevel(1.f / 32.f); 1944 } else { 1945 fNClip = !fNClip; 1946 this->inval(NULL); 1947 this->updateTitle(); 1948 } 1949 return true; 1950 case kDown_SkKey: 1951 if (USE_ARROWS_FOR_ZOOM) { 1952 this->changeZoomLevel(-1.f / 32.f); 1953 } else { 1954 this->setColorType(cycle_colortypes(this->getBitmap().colorType())); 1955 this->updateTitle(); 1956 } 1957 return true; 1958 case kOK_SkKey: { 1959 SkString title; 1960 if (curr_title(this, &title)) { 1961 writeTitleToPrefs(title.c_str()); 1962 } 1963 return true; 1964 } 1965 case kBack_SkKey: 1966 this->showOverview(); 1967 return true; 1968 default: 1969 break; 1970 } 1971 return this->INHERITED::onHandleKey(key); 1972} 1973 1974/////////////////////////////////////////////////////////////////////////////// 1975 1976static const char gGestureClickType[] = "GestureClickType"; 1977 1978bool SampleWindow::onDispatchClick(int x, int y, Click::State state, 1979 void* owner, unsigned modi) { 1980 if (Click::kMoved_State == state) { 1981 updatePointer(x, y); 1982 } 1983 int w = SkScalarRoundToInt(this->width()); 1984 int h = SkScalarRoundToInt(this->height()); 1985 1986 // check for the resize-box 1987 if (w - x < 16 && h - y < 16) { 1988 return false; // let the OS handle the click 1989 } 1990 else if (fMagnify) { 1991 //it's only necessary to update the drawing if there's a click 1992 this->inval(NULL); 1993 return false; //prevent dragging while magnify is enabled 1994 } else { 1995 // capture control+option, and trigger debugger 1996 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) { 1997 if (Click::kDown_State == state) { 1998 SkEvent evt("debug-hit-test"); 1999 evt.setS32("debug-hit-test-x", x); 2000 evt.setS32("debug-hit-test-y", y); 2001 curr_view(this)->doEvent(evt); 2002 } 2003 return true; 2004 } else { 2005 return this->INHERITED::onDispatchClick(x, y, state, owner, modi); 2006 } 2007 } 2008} 2009 2010class GestureClick : public SkView::Click { 2011public: 2012 GestureClick(SkView* target) : SkView::Click(target) { 2013 this->setType(gGestureClickType); 2014 } 2015 2016 static bool IsGesture(Click* click) { 2017 return click->isType(gGestureClickType); 2018 } 2019}; 2020 2021SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y, 2022 unsigned modi) { 2023 return new GestureClick(this); 2024} 2025 2026bool SampleWindow::onClick(Click* click) { 2027 if (GestureClick::IsGesture(click)) { 2028 float x = static_cast<float>(click->fICurr.fX); 2029 float y = static_cast<float>(click->fICurr.fY); 2030 2031 switch (click->fState) { 2032 case SkView::Click::kDown_State: 2033 fGesture.touchBegin(click->fOwner, x, y); 2034 break; 2035 case SkView::Click::kMoved_State: 2036 fGesture.touchMoved(click->fOwner, x, y); 2037 this->updateMatrix(); 2038 break; 2039 case SkView::Click::kUp_State: 2040 fGesture.touchEnd(click->fOwner); 2041 this->updateMatrix(); 2042 break; 2043 } 2044 return true; 2045 } 2046 return false; 2047} 2048 2049/////////////////////////////////////////////////////////////////////////////// 2050 2051void SampleWindow::loadView(SkView* view) { 2052 SkView::F2BIter iter(this); 2053 SkView* prev = iter.next(); 2054 if (prev) { 2055 prev->detachFromParent(); 2056 } 2057 2058 view->setVisibleP(true); 2059 view->setClipToBounds(false); 2060 this->attachChildToFront(view)->unref(); 2061 view->setSize(this->width(), this->height()); 2062 2063 //repopulate the slide menu when a view is loaded 2064 fSlideMenu->reset(); 2065 2066 (void)SampleView::SetUsePipe(view, fPipeState); 2067 if (SampleView::IsSampleView(view)) { 2068 SampleView* sampleView = (SampleView*)view; 2069 sampleView->requestMenu(fSlideMenu); 2070 sampleView->onTileSizeChanged(this->tileSize()); 2071 } 2072 this->onUpdateMenu(fSlideMenu); 2073 this->updateTitle(); 2074} 2075 2076static const char* gDeviceTypePrefix[] = { 2077 "raster: ", 2078 "picture: ", 2079#if SK_SUPPORT_GPU 2080 "opengl: ", 2081#if SK_ANGLE 2082 "angle: ", 2083#endif // SK_ANGLE 2084 "null-gl: " 2085#endif // SK_SUPPORT_GPU 2086}; 2087SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt, 2088 array_size_mismatch); 2089 2090static const char* trystate_str(SkOSMenu::TriState state, 2091 const char trueStr[], const char falseStr[]) { 2092 if (SkOSMenu::kOnState == state) { 2093 return trueStr; 2094 } else if (SkOSMenu::kOffState == state) { 2095 return falseStr; 2096 } 2097 return NULL; 2098} 2099 2100void SampleWindow::updateTitle() { 2101 SkView* view = curr_view(this); 2102 2103 SkString title; 2104 if (!curr_title(this, &title)) { 2105 title.set("<unknown>"); 2106 } 2107 2108 title.prepend(gDeviceTypePrefix[fDeviceType]); 2109 2110 title.prepend(" "); 2111 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType())); 2112 2113 if (fTilingMode != kNo_Tiling) { 2114 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label); 2115 } 2116 if (fAnimating) { 2117 title.prepend("<A> "); 2118 } 2119 if (fRotate) { 2120 title.prepend("<R> "); 2121 } 2122 if (fNClip) { 2123 title.prepend("<C> "); 2124 } 2125 if (fPerspAnim) { 2126 title.prepend("<K> "); 2127 } 2128 2129 title.prepend(trystate_str(fLCDState, "LCD ", "lcd ")); 2130 title.prepend(trystate_str(fAAState, "AA ", "aa ")); 2131 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel); 2132 title.prepend(trystate_str(fSubpixelState, "S ", "s ")); 2133 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL); 2134 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL); 2135 title.prepend(gHintingStates[fHintingState].label); 2136 2137 if (fZoomLevel) { 2138 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel)); 2139 } 2140 2141 if (fMeasureFPS) { 2142 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT); 2143 } 2144 if (SampleView::IsSampleView(view)) { 2145 switch (fPipeState) { 2146 case SkOSMenu::kOnState: 2147 title.prepend("<Pipe> "); 2148 break; 2149 case SkOSMenu::kMixedState: 2150 title.prepend("<Tiled Pipe> "); 2151 break; 2152 2153 default: 2154 break; 2155 } 2156 title.prepend("! "); 2157 } 2158 2159#if SK_SUPPORT_GPU 2160 if (IsGpuDeviceType(fDeviceType) && 2161 NULL != fDevManager && 2162 fDevManager->getGrRenderTarget() && 2163 fDevManager->getGrRenderTarget()->numSamples() > 0) { 2164 title.appendf(" [MSAA: %d]", 2165 fDevManager->getGrRenderTarget()->numSamples()); 2166 } 2167#endif 2168 2169 this->setTitle(title.c_str()); 2170} 2171 2172void SampleWindow::onSizeChange() { 2173 this->INHERITED::onSizeChange(); 2174 2175 SkView::F2BIter iter(this); 2176 SkView* view = iter.next(); 2177 view->setSize(this->width(), this->height()); 2178 2179 // rebuild our clippath 2180 { 2181 const SkScalar W = this->width(); 2182 const SkScalar H = this->height(); 2183 2184 fClipPath.reset(); 2185#if 0 2186 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) { 2187 SkRect r; 2188 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30)); 2189 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0)) 2190 fClipPath.addRect(r); 2191 } 2192#else 2193 SkRect r; 2194 r.set(0, 0, W, H); 2195 fClipPath.addRect(r, SkPath::kCCW_Direction); 2196 r.set(W/4, H/4, W*3/4, H*3/4); 2197 fClipPath.addRect(r, SkPath::kCW_Direction); 2198#endif 2199 } 2200 2201 fZoomCenterX = SkScalarHalf(this->width()); 2202 fZoomCenterY = SkScalarHalf(this->height()); 2203 2204#ifdef SK_BUILD_FOR_ANDROID 2205 // FIXME: The first draw after a size change does not work on Android, so 2206 // we post an invalidate. 2207 this->postInvalDelay(); 2208#endif 2209 this->updateTitle(); // to refresh our config 2210 fDevManager->windowSizeChanged(this); 2211 2212 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) { 2213 ((SampleView*)view)->onTileSizeChanged(this->tileSize()); 2214 } 2215} 2216 2217/////////////////////////////////////////////////////////////////////////////// 2218 2219static const char is_sample_view_tag[] = "sample-is-sample-view"; 2220static const char repeat_count_tag[] = "sample-set-repeat-count"; 2221static const char set_use_pipe_tag[] = "sample-set-use-pipe"; 2222 2223bool SampleView::IsSampleView(SkView* view) { 2224 SkEvent evt(is_sample_view_tag); 2225 return view->doQuery(&evt); 2226} 2227 2228bool SampleView::SetRepeatDraw(SkView* view, int count) { 2229 SkEvent evt(repeat_count_tag); 2230 evt.setFast32(count); 2231 return view->doEvent(evt); 2232} 2233 2234bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) { 2235 SkEvent evt; 2236 evt.setS32(set_use_pipe_tag, state); 2237 return view->doEvent(evt); 2238} 2239 2240bool SampleView::onEvent(const SkEvent& evt) { 2241 if (evt.isType(repeat_count_tag)) { 2242 fRepeatCount = evt.getFast32(); 2243 return true; 2244 } 2245 2246 int32_t pipeHolder; 2247 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) { 2248 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder); 2249 return true; 2250 } 2251 2252 return this->INHERITED::onEvent(evt); 2253} 2254 2255bool SampleView::onQuery(SkEvent* evt) { 2256 if (evt->isType(is_sample_view_tag)) { 2257 return true; 2258 } 2259 return this->INHERITED::onQuery(evt); 2260} 2261 2262 2263class SimplePC : public SkGPipeController { 2264public: 2265 SimplePC(SkCanvas* target); 2266 ~SimplePC(); 2267 2268 virtual void* requestBlock(size_t minRequest, size_t* actual); 2269 virtual void notifyWritten(size_t bytes); 2270 2271private: 2272 SkGPipeReader fReader; 2273 void* fBlock; 2274 size_t fBlockSize; 2275 size_t fBytesWritten; 2276 int fAtomsWritten; 2277 SkGPipeReader::Status fStatus; 2278 2279 size_t fTotalWritten; 2280}; 2281 2282SimplePC::SimplePC(SkCanvas* target) : fReader(target) { 2283 fBlock = NULL; 2284 fBlockSize = fBytesWritten = 0; 2285 fStatus = SkGPipeReader::kDone_Status; 2286 fTotalWritten = 0; 2287 fAtomsWritten = 0; 2288 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory); 2289} 2290 2291SimplePC::~SimplePC() { 2292// SkASSERT(SkGPipeReader::kDone_Status == fStatus); 2293 if (fTotalWritten) { 2294 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten, 2295 fAtomsWritten, fStatus); 2296#ifdef PIPE_FILE 2297 //File is open in append mode 2298 FILE* f = fopen(FILE_PATH, "ab"); 2299 SkASSERT(f != NULL); 2300 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f); 2301 fclose(f); 2302#endif 2303#ifdef PIPE_NET 2304 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done 2305 gServer.acceptConnections(); 2306 gServer.writePacket(fBlock, fTotalWritten); 2307 } 2308#endif 2309 } 2310 sk_free(fBlock); 2311} 2312 2313void* SimplePC::requestBlock(size_t minRequest, size_t* actual) { 2314 sk_free(fBlock); 2315 2316 fBlockSize = minRequest * 4; 2317 fBlock = sk_malloc_throw(fBlockSize); 2318 fBytesWritten = 0; 2319 *actual = fBlockSize; 2320 return fBlock; 2321} 2322 2323void SimplePC::notifyWritten(size_t bytes) { 2324 SkASSERT(fBytesWritten + bytes <= fBlockSize); 2325 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes); 2326 SkASSERT(SkGPipeReader::kError_Status != fStatus); 2327 fBytesWritten += bytes; 2328 fTotalWritten += bytes; 2329 2330 fAtomsWritten += 1; 2331} 2332 2333void SampleView::draw(SkCanvas* canvas) { 2334 if (SkOSMenu::kOffState == fPipeState) { 2335 this->INHERITED::draw(canvas); 2336 } else { 2337 SkGPipeWriter writer; 2338 SimplePC controller(canvas); 2339 TiledPipeController tc(canvas->getDevice()->accessBitmap(false), 2340 &SkImageDecoder::DecodeMemory, 2341 &canvas->getTotalMatrix()); 2342 SkGPipeController* pc; 2343 if (SkOSMenu::kMixedState == fPipeState) { 2344 pc = &tc; 2345 } else { 2346 pc = &controller; 2347 } 2348 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag; 2349 2350 canvas = writer.startRecording(pc, flags); 2351 //Must draw before controller goes out of scope and sends data 2352 this->INHERITED::draw(canvas); 2353 //explicitly end recording to ensure writer is flushed before the memory 2354 //is freed in the deconstructor of the controller 2355 writer.endRecording(); 2356 } 2357} 2358 2359void SampleView::onDraw(SkCanvas* canvas) { 2360 this->onDrawBackground(canvas); 2361 2362 for (int i = 0; i < fRepeatCount; i++) { 2363 SkAutoCanvasRestore acr(canvas, true); 2364 this->onDrawContent(canvas); 2365 } 2366} 2367 2368void SampleView::onDrawBackground(SkCanvas* canvas) { 2369 canvas->drawColor(fBGColor); 2370} 2371 2372/////////////////////////////////////////////////////////////////////////////// 2373 2374template <typename T> void SkTBSort(T array[], int count) { 2375 for (int i = 1; i < count - 1; i++) { 2376 bool didSwap = false; 2377 for (int j = count - 1; j > i; --j) { 2378 if (array[j] < array[j-1]) { 2379 T tmp(array[j-1]); 2380 array[j-1] = array[j]; 2381 array[j] = tmp; 2382 didSwap = true; 2383 } 2384 } 2385 if (!didSwap) { 2386 break; 2387 } 2388 } 2389 2390 for (int k = 0; k < count - 1; k++) { 2391 SkASSERT(!(array[k+1] < array[k])); 2392 } 2393} 2394 2395#include "SkRandom.h" 2396 2397static void rand_rect(SkIRect* rect, SkRandom& rand) { 2398 int bits = 8; 2399 int shift = 32 - bits; 2400 rect->set(rand.nextU() >> shift, rand.nextU() >> shift, 2401 rand.nextU() >> shift, rand.nextU() >> shift); 2402 rect->sort(); 2403} 2404 2405static void dumpRect(const SkIRect& r) { 2406 SkDebugf(" { %d, %d, %d, %d },\n", 2407 r.fLeft, r.fTop, 2408 r.fRight, r.fBottom); 2409} 2410 2411static void test_rects(const SkIRect rect[], int count) { 2412 SkRegion rgn0, rgn1; 2413 2414 for (int i = 0; i < count; i++) { 2415 rgn0.op(rect[i], SkRegion::kUnion_Op); 2416 // dumpRect(rect[i]); 2417 } 2418 rgn1.setRects(rect, count); 2419 2420 if (rgn0 != rgn1) { 2421 SkDebugf("\n"); 2422 for (int i = 0; i < count; i++) { 2423 dumpRect(rect[i]); 2424 } 2425 SkDebugf("\n"); 2426 } 2427} 2428 2429static void test() { 2430 size_t i; 2431 2432 const SkIRect r0[] = { 2433 { 0, 0, 1, 1 }, 2434 { 2, 2, 3, 3 }, 2435 }; 2436 const SkIRect r1[] = { 2437 { 0, 0, 1, 3 }, 2438 { 1, 1, 2, 2 }, 2439 { 2, 0, 3, 3 }, 2440 }; 2441 const SkIRect r2[] = { 2442 { 0, 0, 1, 2 }, 2443 { 2, 1, 3, 3 }, 2444 { 4, 0, 5, 1 }, 2445 { 6, 0, 7, 4 }, 2446 }; 2447 2448 static const struct { 2449 const SkIRect* fRects; 2450 int fCount; 2451 } gRecs[] = { 2452 { r0, SK_ARRAY_COUNT(r0) }, 2453 { r1, SK_ARRAY_COUNT(r1) }, 2454 { r2, SK_ARRAY_COUNT(r2) }, 2455 }; 2456 2457 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { 2458 test_rects(gRecs[i].fRects, gRecs[i].fCount); 2459 } 2460 2461 SkRandom rand; 2462 for (i = 0; i < 10000; i++) { 2463 SkRegion rgn0, rgn1; 2464 2465 const int N = 8; 2466 SkIRect rect[N]; 2467 for (int j = 0; j < N; j++) { 2468 rand_rect(&rect[j], rand); 2469 } 2470 test_rects(rect, N); 2471 } 2472} 2473 2474// FIXME: this should be in a header 2475SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv); 2476SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) { 2477 if (false) { // avoid bit rot, suppress warning 2478 test(); 2479 } 2480 return new SampleWindow(hwnd, argc, argv, NULL); 2481} 2482 2483// FIXME: this should be in a header 2484void get_preferred_size(int* x, int* y, int* width, int* height); 2485void get_preferred_size(int* x, int* y, int* width, int* height) { 2486 *x = 10; 2487 *y = 50; 2488 *width = 640; 2489 *height = 480; 2490} 2491 2492#ifdef SK_BUILD_FOR_IOS 2493void save_args(int argc, char *argv[]) { 2494} 2495#endif 2496 2497// FIXME: this should be in a header 2498void application_init(); 2499void application_init() { 2500// setenv("ANDROID_ROOT", "../../../data", 0); 2501#ifdef SK_BUILD_FOR_MAC 2502 setenv("ANDROID_ROOT", "/android/device/data", 0); 2503#endif 2504 SkGraphics::Init(); 2505 SkEvent::Init(); 2506} 2507 2508// FIXME: this should be in a header 2509void application_term(); 2510void application_term() { 2511 SkEvent::Term(); 2512 SkGraphics::Term(); 2513} 2514