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 42 class GrContext; 43 #endif 44 45 extern SampleView* CreateSamplePictFileView(const char filename[]); 46 47 class PictFileFactory : public SkViewFactory { 48 SkString fFilename; 49 public: 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 57 extern SampleView* CreateSamplePdfFileViewer(const char filename[]); 58 59 class PdfFileViewerFactory : public SkViewFactory { 60 SkString fFilename; 61 public: 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" 77 SkTCPServer 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 98 static SampleWindow* gSampleWindow; 99 100 static bool gShowGMBounds; 101 102 static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) { 103 evt->setTargetID(sink->getSinkID())->post(); 104 } 105 106 /////////////////////////////////////////////////////////////////////////////// 107 108 static const char* skip_until(const char* str, const char* skip) { 109 if (!str) { 110 return NULL; 111 } 112 return strstr(str, skip); 113 } 114 115 static 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 123 static const char* gPrefFileName = "sampleapp_prefs.txt"; 124 125 static 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 147 static 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 156 class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager { 157 public: 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 349 private: 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 /////////////// 364 static const char view_inval_msg[] = "view-inval-msg"; 365 366 void SampleWindow::postInvalDelay() { 367 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1); 368 } 369 370 static bool isInvalEvent(const SkEvent& evt) { 371 return evt.isType(view_inval_msg); 372 } 373 ////////////////// 374 375 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func) 376 : fCreateFunc(func) { 377 } 378 379 SkView* SkFuncViewFactory::operator() () const { 380 return (*fCreateFunc)(); 381 } 382 383 #include "GMSampleView.h" 384 385 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func) 386 : fFunc(func) { 387 } 388 389 SkView* SkGMSampleViewFactory::operator() () const { 390 skiagm::GM* gm = fFunc(NULL); 391 gm->setMode(skiagm::GM::kSample_Mode); 392 return new GMSampleView(gm); 393 } 394 395 SkViewRegister* SkViewRegister::gHead; 396 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) { 397 fFact->ref(); 398 fChain = gHead; 399 gHead = this; 400 } 401 402 SkViewRegister::SkViewRegister(SkViewCreateFunc func) { 403 fFact = new SkFuncViewFactory(func); 404 fChain = gHead; 405 gHead = this; 406 } 407 408 SkViewRegister::SkViewRegister(GMFactoryFunc func) { 409 fFact = new SkGMSampleViewFactory(func); 410 fChain = gHead; 411 gHead = this; 412 } 413 414 class AutoUnrefArray { 415 public: 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 425 private: 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. 432 static 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 448 enum FlipAxisEnum { 449 kFlipAxis_X = (1 << 0), 450 kFlipAxis_Y = (1 << 1) 451 }; 452 453 #include "SkDrawFilter.h" 454 455 struct HintingState { 456 SkPaint::Hinting hinting; 457 const char* name; 458 const char* label; 459 }; 460 static 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 468 struct FilterLevelState { 469 SkPaint::FilterLevel fLevel; 470 const char* fName; 471 const char* fLabel; 472 }; 473 static 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 481 class FlagsDrawFilter : public SkDrawFilter { 482 public: 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 513 private: 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 526 static const char gCharEvtName[] = "SampleCode_Char_Event"; 527 static const char gKeyEvtName[] = "SampleCode_Key_Event"; 528 static const char gTitleEvtName[] = "SampleCode_Title_Event"; 529 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event"; 530 static const char gFastTextEvtName[] = "SampleCode_FastText_Event"; 531 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle"; 532 533 bool 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 543 bool 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 553 bool SampleCode::TitleQ(const SkEvent& evt) { 554 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1); 555 } 556 557 void SampleCode::TitleR(SkEvent* evt, const char title[]) { 558 SkASSERT(evt && TitleQ(*evt)); 559 evt->setString(gTitleEvtName, title); 560 } 561 562 bool 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 571 bool SampleCode::PrefSizeQ(const SkEvent& evt) { 572 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1); 573 } 574 575 void 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 583 bool SampleCode::FastTextQ(const SkEvent& evt) { 584 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1); 585 } 586 587 /////////////////////////////////////////////////////////////////////////////// 588 589 static SkMSec gAnimTime; 590 static SkMSec gAnimTimePrev; 591 592 SkMSec SampleCode::GetAnimTime() { return gAnimTime; } 593 SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; } 594 SkScalar SampleCode::GetAnimSecondsDelta() { 595 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0); 596 } 597 598 SkScalar 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 610 SkScalar 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 622 enum 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 633 struct TilingInfo { 634 const char* label; 635 SkScalar w, h; 636 }; 637 638 static 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 }; 646 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum), 647 Incomplete_tiling_labels); 648 649 SkSize 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 657 static SkView* curr_view(SkWindow* wind) { 658 SkView::F2BIter iter(wind); 659 return iter.next(); 660 } 661 662 static 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 674 void SampleWindow::setZoomCenter(float x, float y) 675 { 676 fZoomCenterX = x; 677 fZoomCenterY = y; 678 } 679 680 bool SampleWindow::zoomIn() 681 { 682 // Arbitrarily decided 683 if (fFatBitsScale == 25) return false; 684 fFatBitsScale++; 685 this->inval(NULL); 686 return true; 687 } 688 689 bool SampleWindow::zoomOut() 690 { 691 if (fFatBitsScale == 1) return false; 692 fFatBitsScale--; 693 this->inval(NULL); 694 return true; 695 } 696 697 void SampleWindow::updatePointer(int x, int y) 698 { 699 fMouseX = x; 700 fMouseY = y; 701 if (fShowZoomer) { 702 this->inval(NULL); 703 } 704 } 705 706 static 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 722 static SkString getSampleTitle(const SkViewFactory* sampleFactory) { 723 SkView* view = (*sampleFactory)(); 724 SkString title; 725 SampleCode::RequestTitle(view, &title); 726 view->unref(); 727 return title; 728 } 729 730 static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) { 731 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0; 732 } 733 734 DEFINE_string(slide, "", "Start on this sample."); 735 DEFINE_int32(msaa, 0, "Request multisampling with this count."); 736 DEFINE_string(pictureDir, "", "Read pictures from here."); 737 DEFINE_string(picture, "", "Path to single picture."); 738 DEFINE_bool(sort, false, "Sort samples by title."); 739 DEFINE_bool(list, false, "List samples?"); 740 #ifdef SAMPLE_PDF_FILE_VIEWER 741 DEFINE_string(pdfPath, "", "Path to direcotry of pdf files."); 742 #endif 743 744 SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager) 745 : INHERITED(hwnd) 746 , fDevManager(NULL) { 747 748 SkCommandLineFlags::Parse(argc, argv); 749 750 fCurrIndex = -1; 751 752 if (!FLAGS_pictureDir.isEmpty()) { 753 SkOSFile::Iter iter(FLAGS_pictureDir[0], "skp"); 754 SkString filename; 755 while (iter.next(&filename)) { 756 *fSamples.append() = new PictFileFactory( 757 SkOSPath::SkPathJoin(FLAGS_pictureDir[0], filename.c_str())); 758 } 759 } 760 if (!FLAGS_picture.isEmpty()) { 761 SkString path(FLAGS_picture[0]); 762 fCurrIndex = fSamples.count(); 763 *fSamples.append() = new PictFileFactory(path); 764 } 765 #ifdef SAMPLE_PDF_FILE_VIEWER 766 if (!FLAGS_pdfPath.isEmpty()) { 767 SkOSFile::Iter iter(FLAGS_pdfPath[0], "pdf"); 768 SkString filename; 769 while (iter.next(&filename)) { 770 *fSamples.append() = new PdfFileViewerFactory( 771 SkOSPath::SkPathJoin(FLAGS_pictureDir[0], filename.c_str())); 772 } 773 } 774 #endif 775 SkGMRegistyToSampleRegistry(); 776 { 777 const SkViewRegister* reg = SkViewRegister::Head(); 778 while (reg) { 779 *fSamples.append() = reg->factory(); 780 reg = reg->next(); 781 } 782 } 783 784 if (FLAGS_sort) { 785 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where 786 // skp -> pdf -> png fails. 787 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle); 788 } 789 790 if (!FLAGS_slide.isEmpty()) { 791 fCurrIndex = findByTitle(FLAGS_slide[0]); 792 if (fCurrIndex < 0) { 793 fprintf(stderr, "Unknown sample \"%s\"\n", FLAGS_slide[0]); 794 listTitles(); 795 } 796 } 797 798 fMSAASampleCount = FLAGS_msaa; 799 800 if (FLAGS_list) { 801 listTitles(); 802 } 803 804 if (fCurrIndex < 0) { 805 SkString title; 806 if (readTitleFromPrefs(&title)) { 807 fCurrIndex = findByTitle(title.c_str()); 808 } 809 } 810 811 if (fCurrIndex < 0) { 812 fCurrIndex = 0; 813 } 814 815 gSampleWindow = this; 816 817 #ifdef PIPE_FILE 818 //Clear existing file or create file if it doesn't exist 819 FILE* f = fopen(FILE_PATH, "wb"); 820 fclose(f); 821 #endif 822 823 fDeviceType = kRaster_DeviceType; 824 825 #if DEFAULT_TO_GPU 826 fDeviceType = kGPU_DeviceType; 827 #endif 828 #if SK_ANGLE && DEFAULT_TO_ANGLE 829 fDeviceType = kANGLE_DeviceType; 830 #endif 831 832 fUseClip = false; 833 fNClip = false; 834 fAnimating = false; 835 fRotate = false; 836 fRotateAnimTime = 0; 837 fPerspAnim = false; 838 fPerspAnimTime = 0; 839 fRequestGrabImage = false; 840 fPipeState = SkOSMenu::kOffState; 841 fTilingMode = kNo_Tiling; 842 fMeasureFPS = false; 843 fLCDState = SkOSMenu::kMixedState; 844 fAAState = SkOSMenu::kMixedState; 845 fSubpixelState = SkOSMenu::kMixedState; 846 fHintingState = 0; 847 fFilterLevelIndex = 0; 848 fFlipAxis = 0; 849 fScrollTestX = fScrollTestY = 0; 850 851 fMouseX = fMouseY = 0; 852 fFatBitsScale = 8; 853 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold); 854 fShowZoomer = false; 855 856 fZoomLevel = 0; 857 fZoomScale = SK_Scalar1; 858 859 fMagnify = false; 860 861 fSaveToPdf = false; 862 fPdfCanvas = NULL; 863 864 fTransitionNext = 6; 865 fTransitionPrev = 2; 866 867 int sinkID = this->getSinkID(); 868 fAppMenu = new SkOSMenu; 869 fAppMenu->setTitle("Global Settings"); 870 int itemID; 871 872 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0, 873 "Raster", "Picture", "OpenGL", 874 #if SK_ANGLE 875 "ANGLE", 876 #endif 877 NULL); 878 fAppMenu->assignKeyEquivalentToItem(itemID, 'd'); 879 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState); 880 fAppMenu->assignKeyEquivalentToItem(itemID, 'b'); 881 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState); 882 fAppMenu->assignKeyEquivalentToItem(itemID, 'l'); 883 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex, 884 gFilterLevelStates[0].fName, 885 gFilterLevelStates[1].fName, 886 gFilterLevelStates[2].fName, 887 gFilterLevelStates[3].fName, 888 gFilterLevelStates[4].fName, 889 NULL); 890 fAppMenu->assignKeyEquivalentToItem(itemID, 'n'); 891 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState); 892 fAppMenu->assignKeyEquivalentToItem(itemID, 's'); 893 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState, 894 gHintingStates[0].name, 895 gHintingStates[1].name, 896 gHintingStates[2].name, 897 gHintingStates[3].name, 898 gHintingStates[4].name, 899 NULL); 900 fAppMenu->assignKeyEquivalentToItem(itemID, 'h'); 901 902 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID, 903 fPipeState); 904 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P'); 905 906 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode, 907 gTilingInfo[kNo_Tiling].label, 908 gTilingInfo[kAbs_128x128_Tiling].label, 909 gTilingInfo[kAbs_256x256_Tiling].label, 910 gTilingInfo[kRel_4x4_Tiling].label, 911 gTilingInfo[kRel_1x16_Tiling].label, 912 gTilingInfo[kRel_16x1_Tiling].label, 913 NULL); 914 fAppMenu->assignKeyEquivalentToItem(itemID, 't'); 915 916 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false); 917 fAppMenu->assignKeyEquivalentToItem(itemID, 'a'); 918 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip); 919 fAppMenu->assignKeyEquivalentToItem(itemID, 'c'); 920 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false); 921 fAppMenu->assignKeyEquivalentToItem(itemID, 'x'); 922 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false); 923 fAppMenu->assignKeyEquivalentToItem(itemID, 'y'); 924 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer); 925 fAppMenu->assignKeyEquivalentToItem(itemID, 'z'); 926 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify); 927 fAppMenu->assignKeyEquivalentToItem(itemID, 'm'); 928 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID, 929 fTransitionNext, "Up", "Up and Right", "Right", 930 "Down and Right", "Down", "Down and Left", 931 "Left", "Up and Left", NULL); 932 fAppMenu->assignKeyEquivalentToItem(itemID, 'j'); 933 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID, 934 fTransitionPrev, "Up", "Up and Right", "Right", 935 "Down and Right", "Down", "Down and Left", 936 "Left", "Up and Left", NULL); 937 fAppMenu->assignKeyEquivalentToItem(itemID, 'k'); 938 itemID = fAppMenu->appendAction("Save to PDF", sinkID); 939 fAppMenu->assignKeyEquivalentToItem(itemID, 'e'); 940 941 this->addMenu(fAppMenu); 942 fSlideMenu = new SkOSMenu; 943 this->addMenu(fSlideMenu); 944 945 this->setColorType(kN32_SkColorType); 946 this->setVisibleP(true); 947 this->setClipToBounds(false); 948 949 this->loadView((*fSamples[fCurrIndex])()); 950 951 fPDFData = NULL; 952 953 if (NULL == devManager) { 954 fDevManager = new DefaultDeviceManager(); 955 } else { 956 devManager->ref(); 957 fDevManager = devManager; 958 } 959 fDevManager->setUpBackend(this, fMSAASampleCount); 960 961 // If another constructor set our dimensions, ensure that our 962 // onSizeChange gets called. 963 if (this->height() && this->width()) { 964 this->onSizeChange(); 965 } 966 967 // can't call this synchronously, since it may require a subclass to 968 // to implement, or the caller may need us to have returned from the 969 // constructor first. Hence we post an event to ourselves. 970 // this->updateTitle(); 971 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this); 972 } 973 974 SampleWindow::~SampleWindow() { 975 delete fPdfCanvas; 976 fTypeface->unref(); 977 978 SkSafeUnref(fDevManager); 979 } 980 981 982 int SampleWindow::findByTitle(const char title[]) { 983 int i, count = fSamples.count(); 984 for (i = 0; i < count; i++) { 985 if (getSampleTitle(i).equals(title)) { 986 return i; 987 } 988 } 989 return -1; 990 } 991 992 void SampleWindow::listTitles() { 993 int count = fSamples.count(); 994 SkDebugf("All Slides:\n"); 995 for (int i = 0; i < count; i++) { 996 SkDebugf(" %s\n", getSampleTitle(i).c_str()); 997 } 998 } 999 1000 static SkBitmap capture_bitmap(SkCanvas* canvas) { 1001 SkBitmap bm; 1002 if (bm.allocPixels(canvas->imageInfo())) { 1003 canvas->readPixels(&bm, 0, 0); 1004 } 1005 return bm; 1006 } 1007 1008 static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig, 1009 SkBitmap* diff) { 1010 const SkBitmap& src = canvas->getDevice()->accessBitmap(false); 1011 1012 SkAutoLockPixels alp0(src); 1013 SkAutoLockPixels alp1(orig); 1014 for (int y = 0; y < src.height(); y++) { 1015 const void* srcP = src.getAddr(0, y); 1016 const void* origP = orig.getAddr(0, y); 1017 size_t bytes = src.width() * src.bytesPerPixel(); 1018 if (memcmp(srcP, origP, bytes)) { 1019 SkDebugf("---------- difference on line %d\n", y); 1020 return true; 1021 } 1022 } 1023 return false; 1024 } 1025 1026 static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint) 1027 { 1028 SkColor desiredColor = paint.getColor(); 1029 paint.setColor(SK_ColorWHITE); 1030 const char* c_str = string.c_str(); 1031 size_t size = string.size(); 1032 SkRect bounds; 1033 paint.measureText(c_str, size, &bounds); 1034 bounds.offset(left, top); 1035 SkScalar inset = SkIntToScalar(-2); 1036 bounds.inset(inset, inset); 1037 canvas->drawRect(bounds, paint); 1038 if (desiredColor != SK_ColorBLACK) { 1039 paint.setColor(SK_ColorBLACK); 1040 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint); 1041 } 1042 paint.setColor(desiredColor); 1043 canvas->drawText(c_str, size, left, top, paint); 1044 } 1045 1046 #define XCLIP_N 8 1047 #define YCLIP_N 8 1048 1049 void SampleWindow::draw(SkCanvas* canvas) { 1050 // update the animation time 1051 if (!gAnimTimePrev && !gAnimTime) { 1052 // first time make delta be 0 1053 gAnimTime = SkTime::GetMSecs(); 1054 gAnimTimePrev = gAnimTime; 1055 } else { 1056 gAnimTimePrev = gAnimTime; 1057 gAnimTime = SkTime::GetMSecs(); 1058 } 1059 1060 if (fGesture.isActive()) { 1061 this->updateMatrix(); 1062 } 1063 1064 if (fMeasureFPS) { 1065 fMeasureFPS_Time = 0; 1066 } 1067 1068 if (fNClip) { 1069 this->INHERITED::draw(canvas); 1070 SkBitmap orig = capture_bitmap(canvas); 1071 1072 const SkScalar w = this->width(); 1073 const SkScalar h = this->height(); 1074 const SkScalar cw = w / XCLIP_N; 1075 const SkScalar ch = h / YCLIP_N; 1076 for (int y = 0; y < YCLIP_N; y++) { 1077 SkRect r; 1078 r.fTop = y * ch; 1079 r.fBottom = (y + 1) * ch; 1080 if (y == YCLIP_N - 1) { 1081 r.fBottom = h; 1082 } 1083 for (int x = 0; x < XCLIP_N; x++) { 1084 SkAutoCanvasRestore acr(canvas, true); 1085 r.fLeft = x * cw; 1086 r.fRight = (x + 1) * cw; 1087 if (x == XCLIP_N - 1) { 1088 r.fRight = w; 1089 } 1090 canvas->clipRect(r); 1091 this->INHERITED::draw(canvas); 1092 } 1093 } 1094 1095 SkBitmap diff; 1096 if (bitmap_diff(canvas, orig, &diff)) { 1097 } 1098 } else { 1099 SkSize tile = this->tileSize(); 1100 1101 if (kNo_Tiling == fTilingMode) { 1102 this->INHERITED::draw(canvas); // no looping or surfaces needed 1103 } else { 1104 const int w = SkScalarRoundToInt(tile.width()); 1105 const int h = SkScalarRoundToInt(tile.height()); 1106 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h); 1107 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info)); 1108 SkCanvas* tileCanvas = surface->getCanvas(); 1109 1110 for (SkScalar y = 0; y < height(); y += tile.height()) { 1111 for (SkScalar x = 0; x < width(); x += tile.width()) { 1112 SkAutoCanvasRestore acr(tileCanvas, true); 1113 tileCanvas->translate(-x, -y); 1114 tileCanvas->clear(0); 1115 this->INHERITED::draw(tileCanvas); 1116 surface->draw(canvas, x, y, NULL); 1117 } 1118 } 1119 1120 // for drawing the borders between tiles 1121 SkPaint paint; 1122 paint.setColor(0x60FF00FF); 1123 paint.setStyle(SkPaint::kStroke_Style); 1124 1125 for (SkScalar y = 0; y < height(); y += tile.height()) { 1126 for (SkScalar x = 0; x < width(); x += tile.width()) { 1127 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint); 1128 } 1129 } 1130 } 1131 } 1132 if (fShowZoomer && !fSaveToPdf) { 1133 showZoomer(canvas); 1134 } 1135 if (fMagnify && !fSaveToPdf) { 1136 magnify(canvas); 1137 } 1138 1139 if (fMeasureFPS && fMeasureFPS_Time) { 1140 this->updateTitle(); 1141 this->postInvalDelay(); 1142 } 1143 1144 // do this last 1145 fDevManager->publishCanvas(fDeviceType, canvas, this); 1146 } 1147 1148 static float clipW = 200; 1149 static float clipH = 200; 1150 void SampleWindow::magnify(SkCanvas* canvas) { 1151 SkRect r; 1152 int count = canvas->save(); 1153 1154 SkMatrix m = canvas->getTotalMatrix(); 1155 if (!m.invert(&m)) { 1156 return; 1157 } 1158 SkPoint offset, center; 1159 SkScalar mouseX = fMouseX * SK_Scalar1; 1160 SkScalar mouseY = fMouseY * SK_Scalar1; 1161 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset); 1162 m.mapXY(mouseX, mouseY, ¢er); 1163 1164 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX()); 1165 r.offset(offset.fX, offset.fY); 1166 1167 SkPaint paint; 1168 paint.setColor(0xFF66AAEE); 1169 paint.setStyle(SkPaint::kStroke_Style); 1170 paint.setStrokeWidth(10.f * m.getScaleX()); 1171 //lense offset 1172 //canvas->translate(0, -250); 1173 canvas->drawRect(r, paint); 1174 canvas->clipRect(r); 1175 1176 m = canvas->getTotalMatrix(); 1177 m.setTranslate(-center.fX, -center.fY); 1178 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale); 1179 m.postTranslate(center.fX, center.fY); 1180 canvas->concat(m); 1181 1182 this->INHERITED::draw(canvas); 1183 1184 canvas->restoreToCount(count); 1185 } 1186 1187 void SampleWindow::showZoomer(SkCanvas* canvas) { 1188 int count = canvas->save(); 1189 canvas->resetMatrix(); 1190 // Ensure the mouse position is on screen. 1191 int width = SkScalarRoundToInt(this->width()); 1192 int height = SkScalarRoundToInt(this->height()); 1193 if (fMouseX >= width) fMouseX = width - 1; 1194 else if (fMouseX < 0) fMouseX = 0; 1195 if (fMouseY >= height) fMouseY = height - 1; 1196 else if (fMouseY < 0) fMouseY = 0; 1197 1198 SkBitmap bitmap = capture_bitmap(canvas); 1199 bitmap.lockPixels(); 1200 1201 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle. 1202 int zoomedWidth = (width >> 1) | 1; 1203 int zoomedHeight = (height >> 1) | 1; 1204 SkIRect src; 1205 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale); 1206 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1)); 1207 SkRect dest; 1208 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight)); 1209 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight)); 1210 SkPaint paint; 1211 // Clear the background behind our zoomed in view 1212 paint.setColor(SK_ColorWHITE); 1213 canvas->drawRect(dest, paint); 1214 canvas->drawBitmapRect(bitmap, &src, dest); 1215 paint.setColor(SK_ColorBLACK); 1216 paint.setStyle(SkPaint::kStroke_Style); 1217 // Draw a border around the pixel in the middle 1218 SkRect originalPixel; 1219 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1)); 1220 SkMatrix matrix; 1221 SkRect scalarSrc; 1222 scalarSrc.set(src); 1223 SkColor color = bitmap.getColor(fMouseX, fMouseY); 1224 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) { 1225 SkRect pixel; 1226 matrix.mapRect(&pixel, originalPixel); 1227 // TODO Perhaps measure the values and make the outline white if it's "dark" 1228 if (color == SK_ColorBLACK) { 1229 paint.setColor(SK_ColorWHITE); 1230 } 1231 canvas->drawRect(pixel, paint); 1232 } 1233 paint.setColor(SK_ColorBLACK); 1234 // Draw a border around the destination rectangle 1235 canvas->drawRect(dest, paint); 1236 paint.setStyle(SkPaint::kStrokeAndFill_Style); 1237 // Identify the pixel and its color on screen 1238 paint.setTypeface(fTypeface); 1239 paint.setAntiAlias(true); 1240 SkScalar lineHeight = paint.getFontMetrics(NULL); 1241 SkString string; 1242 string.appendf("(%i, %i)", fMouseX, fMouseY); 1243 SkScalar left = dest.fLeft + SkIntToScalar(3); 1244 SkScalar i = SK_Scalar1; 1245 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1246 // Alpha 1247 i += SK_Scalar1; 1248 string.reset(); 1249 string.appendf("A: %X", SkColorGetA(color)); 1250 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1251 // Red 1252 i += SK_Scalar1; 1253 string.reset(); 1254 string.appendf("R: %X", SkColorGetR(color)); 1255 paint.setColor(SK_ColorRED); 1256 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1257 // Green 1258 i += SK_Scalar1; 1259 string.reset(); 1260 string.appendf("G: %X", SkColorGetG(color)); 1261 paint.setColor(SK_ColorGREEN); 1262 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1263 // Blue 1264 i += SK_Scalar1; 1265 string.reset(); 1266 string.appendf("B: %X", SkColorGetB(color)); 1267 paint.setColor(SK_ColorBLUE); 1268 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1269 canvas->restoreToCount(count); 1270 } 1271 1272 void SampleWindow::onDraw(SkCanvas* canvas) { 1273 } 1274 1275 #include "SkColorPriv.h" 1276 1277 void SampleWindow::saveToPdf() 1278 { 1279 fSaveToPdf = true; 1280 this->inval(NULL); 1281 } 1282 1283 SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) { 1284 if (fSaveToPdf) { 1285 const SkBitmap& bmp = canvas->getDevice()->accessBitmap(false); 1286 SkISize size = SkISize::Make(bmp.width(), bmp.height()); 1287 SkPDFDevice* pdfDevice = new SkPDFDevice(size, size, 1288 canvas->getTotalMatrix()); 1289 fPdfCanvas = new SkCanvas(pdfDevice); 1290 pdfDevice->unref(); 1291 canvas = fPdfCanvas; 1292 } else if (kPicture_DeviceType == fDeviceType) { 1293 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0); 1294 } else { 1295 #if SK_SUPPORT_GPU 1296 if (kNullGPU_DeviceType != fDeviceType) 1297 #endif 1298 { 1299 canvas = this->INHERITED::beforeChildren(canvas); 1300 } 1301 } 1302 1303 if (fUseClip) { 1304 canvas->drawColor(0xFFFF88FF); 1305 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true); 1306 } 1307 1308 return canvas; 1309 } 1310 1311 static void paint_rgn(const SkBitmap& bm, const SkIRect& r, 1312 const SkRegion& rgn) { 1313 SkCanvas canvas(bm); 1314 SkRegion inval(rgn); 1315 1316 inval.translate(r.fLeft, r.fTop); 1317 canvas.clipRegion(inval); 1318 canvas.drawColor(0xFFFF8080); 1319 } 1320 #include "SkData.h" 1321 void SampleWindow::afterChildren(SkCanvas* orig) { 1322 if (fSaveToPdf) { 1323 fSaveToPdf = false; 1324 if (fShowZoomer) { 1325 showZoomer(fPdfCanvas); 1326 } 1327 SkString name; 1328 name.printf("%s.pdf", this->getTitle()); 1329 SkPDFDocument doc; 1330 SkPDFDevice* device = static_cast<SkPDFDevice*>(fPdfCanvas->getDevice()); 1331 doc.appendPage(device); 1332 #ifdef SK_BUILD_FOR_ANDROID 1333 name.prepend("/sdcard/"); 1334 #endif 1335 1336 #ifdef SK_BUILD_FOR_IOS 1337 SkDynamicMemoryWStream mstream; 1338 doc.emitPDF(&mstream); 1339 fPDFData = mstream.copyToData(); 1340 #endif 1341 SkFILEWStream stream(name.c_str()); 1342 if (stream.isValid()) { 1343 doc.emitPDF(&stream); 1344 const char* desc = "File saved from Skia SampleApp"; 1345 this->onPDFSaved(this->getTitle(), desc, name.c_str()); 1346 } 1347 1348 delete fPdfCanvas; 1349 fPdfCanvas = NULL; 1350 1351 // We took over the draw calls in order to create the PDF, so we need 1352 // to redraw. 1353 this->inval(NULL); 1354 return; 1355 } 1356 1357 if (fRequestGrabImage) { 1358 fRequestGrabImage = false; 1359 1360 SkBaseDevice* device = orig->getDevice(); 1361 SkBitmap bmp; 1362 if (device->accessBitmap(false).copyTo(&bmp, kN32_SkColorType)) { 1363 static int gSampleGrabCounter; 1364 SkString name; 1365 name.printf("sample_grab_%d.png", gSampleGrabCounter++); 1366 SkImageEncoder::EncodeFile(name.c_str(), bmp, 1367 SkImageEncoder::kPNG_Type, 100); 1368 } 1369 } 1370 1371 if (kPicture_DeviceType == fDeviceType) { 1372 SkAutoTUnref<SkPicture> picture(fRecorder.endRecording()); 1373 1374 if (true) { 1375 SkPicture* pict = new SkPicture(*picture); 1376 this->installDrawFilter(orig); 1377 orig->drawPicture(pict); 1378 pict->unref(); 1379 } else if (true) { 1380 SkDynamicMemoryWStream ostream; 1381 picture->serialize(&ostream); 1382 1383 SkAutoDataUnref data(ostream.copyToData()); 1384 SkMemoryStream istream(data->data(), data->size()); 1385 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream)); 1386 if (pict.get() != NULL) { 1387 orig->drawPicture(pict.get()); 1388 } 1389 } else { 1390 picture->draw(orig); 1391 } 1392 } 1393 1394 // Do this after presentGL and other finishing, rather than in afterChild 1395 if (fMeasureFPS && fMeasureFPS_StartTime) { 1396 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime; 1397 } 1398 1399 // if ((fScrollTestX | fScrollTestY) != 0) 1400 if (false) { 1401 const SkBitmap& bm = orig->getDevice()->accessBitmap(true); 1402 int dx = fScrollTestX * 7; 1403 int dy = fScrollTestY * 7; 1404 SkIRect r; 1405 SkRegion inval; 1406 1407 r.set(50, 50, 50+100, 50+100); 1408 bm.scrollRect(&r, dx, dy, &inval); 1409 paint_rgn(bm, r, inval); 1410 } 1411 } 1412 1413 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) { 1414 if (fRotate) { 1415 fRotateAnimTime += SampleCode::GetAnimSecondsDelta(); 1416 1417 SkScalar cx = this->width() / 2; 1418 SkScalar cy = this->height() / 2; 1419 canvas->translate(cx, cy); 1420 canvas->rotate(fRotateAnimTime * 10); 1421 canvas->translate(-cx, -cy); 1422 } 1423 1424 if (fPerspAnim) { 1425 fPerspAnimTime += SampleCode::GetAnimSecondsDelta(); 1426 1427 static const SkScalar gAnimPeriod = 10 * SK_Scalar1; 1428 static const SkScalar gAnimMag = SK_Scalar1 / 1000; 1429 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod); 1430 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) { 1431 t = gAnimPeriod - t; 1432 } 1433 t = 2 * t - gAnimPeriod; 1434 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag); 1435 SkMatrix m; 1436 m.reset(); 1437 m.setPerspY(t); 1438 canvas->concat(m); 1439 } 1440 1441 this->installDrawFilter(canvas); 1442 1443 if (fMeasureFPS) { 1444 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) { 1445 fMeasureFPS_StartTime = SkTime::GetMSecs(); 1446 } 1447 } else { 1448 (void)SampleView::SetRepeatDraw(child, 1); 1449 } 1450 if (fPerspAnim || fRotate) { 1451 this->inval(NULL); 1452 } 1453 } 1454 1455 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) { 1456 canvas->setDrawFilter(NULL); 1457 } 1458 1459 static SkColorType gColorTypeCycle[] = { 1460 kUnknown_SkColorType, // none -> none 1461 kUnknown_SkColorType, // a8 -> none 1462 kN32_SkColorType, // 565 -> 8888 1463 kN32_SkColorType, // 4444 -> 8888 1464 kRGB_565_SkColorType, // 8888 -> 565 1465 kRGB_565_SkColorType, // 8888 -> 565 1466 kUnknown_SkColorType, // index8 -> none 1467 }; 1468 1469 static SkColorType cycle_colortypes(SkColorType c) { 1470 return gColorTypeCycle[c]; 1471 } 1472 1473 void SampleWindow::changeZoomLevel(float delta) { 1474 fZoomLevel += delta; 1475 if (fZoomLevel > 0) { 1476 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL); 1477 fZoomScale = fZoomLevel + SK_Scalar1; 1478 } else if (fZoomLevel < 0) { 1479 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL); 1480 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel); 1481 } else { 1482 fZoomScale = SK_Scalar1; 1483 } 1484 this->updateMatrix(); 1485 } 1486 1487 void SampleWindow::updateMatrix(){ 1488 SkMatrix m; 1489 m.reset(); 1490 if (fZoomLevel) { 1491 SkPoint center; 1492 //m = this->getLocalMatrix();//.invert(&m); 1493 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er); 1494 SkScalar cx = center.fX; 1495 SkScalar cy = center.fY; 1496 1497 m.setTranslate(-cx, -cy); 1498 m.postScale(fZoomScale, fZoomScale); 1499 m.postTranslate(cx, cy); 1500 } 1501 1502 if (fFlipAxis) { 1503 m.preTranslate(fZoomCenterX, fZoomCenterY); 1504 if (fFlipAxis & kFlipAxis_X) { 1505 m.preScale(-SK_Scalar1, SK_Scalar1); 1506 } 1507 if (fFlipAxis & kFlipAxis_Y) { 1508 m.preScale(SK_Scalar1, -SK_Scalar1); 1509 } 1510 m.preTranslate(-fZoomCenterX, -fZoomCenterY); 1511 //canvas->concat(m); 1512 } 1513 // Apply any gesture matrix 1514 m.preConcat(fGesture.localM()); 1515 m.preConcat(fGesture.globalM()); 1516 1517 this->setLocalMatrix(m); 1518 1519 this->updateTitle(); 1520 this->inval(NULL); 1521 } 1522 bool SampleWindow::previousSample() { 1523 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count(); 1524 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1525 fTransitionPrev)); 1526 return true; 1527 } 1528 1529 bool SampleWindow::nextSample() { 1530 fCurrIndex = (fCurrIndex + 1) % fSamples.count(); 1531 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1532 fTransitionNext)); 1533 return true; 1534 } 1535 1536 bool SampleWindow::goToSample(int i) { 1537 fCurrIndex = (i) % fSamples.count(); 1538 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6)); 1539 return true; 1540 } 1541 1542 SkString SampleWindow::getSampleTitle(int i) { 1543 return ::getSampleTitle(fSamples[i]); 1544 } 1545 1546 int SampleWindow::sampleCount() { 1547 return fSamples.count(); 1548 } 1549 1550 void SampleWindow::showOverview() { 1551 this->loadView(create_transition(curr_view(this), 1552 create_overview(fSamples.count(), fSamples.begin()), 1553 4)); 1554 } 1555 1556 void SampleWindow::installDrawFilter(SkCanvas* canvas) { 1557 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState, 1558 fHintingState, fFilterLevelIndex))->unref(); 1559 } 1560 1561 void SampleWindow::postAnimatingEvent() { 1562 if (fAnimating) { 1563 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY); 1564 } 1565 } 1566 1567 bool SampleWindow::onEvent(const SkEvent& evt) { 1568 if (evt.isType(gUpdateWindowTitleEvtName)) { 1569 this->updateTitle(); 1570 return true; 1571 } 1572 if (evt.isType(ANIMATING_EVENTTYPE)) { 1573 if (fAnimating) { 1574 this->nextSample(); 1575 this->postAnimatingEvent(); 1576 } 1577 return true; 1578 } 1579 if (evt.isType("replace-transition-view")) { 1580 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32())); 1581 return true; 1582 } 1583 if (evt.isType("set-curr-index")) { 1584 this->goToSample(evt.getFast32()); 1585 return true; 1586 } 1587 if (isInvalEvent(evt)) { 1588 this->inval(NULL); 1589 return true; 1590 } 1591 int selected = -1; 1592 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) { 1593 this->setDeviceType((DeviceType)selected); 1594 return true; 1595 } 1596 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) { 1597 #ifdef PIPE_NET 1598 if (!fPipeState != SkOSMenu::kOnState) 1599 gServer.disconnectAll(); 1600 #endif 1601 (void)SampleView::SetUsePipe(curr_view(this), fPipeState); 1602 this->updateTitle(); 1603 this->inval(NULL); 1604 return true; 1605 } 1606 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) { 1607 this->toggleSlideshow(); 1608 return true; 1609 } 1610 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) || 1611 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) || 1612 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) || 1613 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) || 1614 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) || 1615 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) || 1616 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) || 1617 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) || 1618 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) || 1619 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) { 1620 this->inval(NULL); 1621 this->updateTitle(); 1622 return true; 1623 } 1624 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) { 1625 if (SampleView::IsSampleView(curr_view(this))) { 1626 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize()); 1627 } 1628 this->inval(NULL); 1629 this->updateTitle(); 1630 return true; 1631 } 1632 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) { 1633 fFlipAxis ^= kFlipAxis_X; 1634 this->updateMatrix(); 1635 return true; 1636 } 1637 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) { 1638 fFlipAxis ^= kFlipAxis_Y; 1639 this->updateMatrix(); 1640 return true; 1641 } 1642 if (SkOSMenu::FindAction(evt,"Save to PDF")) { 1643 this->saveToPdf(); 1644 return true; 1645 } 1646 return this->INHERITED::onEvent(evt); 1647 } 1648 1649 bool SampleWindow::onQuery(SkEvent* query) { 1650 if (query->isType("get-slide-count")) { 1651 query->setFast32(fSamples.count()); 1652 return true; 1653 } 1654 if (query->isType("get-slide-title")) { 1655 SkView* view = (*fSamples[query->getFast32()])(); 1656 SkEvent evt(gTitleEvtName); 1657 if (view->doQuery(&evt)) { 1658 query->setString("title", evt.findString(gTitleEvtName)); 1659 } 1660 SkSafeUnref(view); 1661 return true; 1662 } 1663 if (query->isType("use-fast-text")) { 1664 SkEvent evt(gFastTextEvtName); 1665 return curr_view(this)->doQuery(&evt); 1666 } 1667 if (query->isType("ignore-window-bitmap")) { 1668 query->setFast32(this->getGrContext() != NULL); 1669 return true; 1670 } 1671 return this->INHERITED::onQuery(query); 1672 } 1673 1674 #if 0 // UNUSED 1675 static void cleanup_for_filename(SkString* name) { 1676 char* str = name->writable_str(); 1677 for (size_t i = 0; i < name->size(); i++) { 1678 switch (str[i]) { 1679 case ':': str[i] = '-'; break; 1680 case '/': str[i] = '-'; break; 1681 case ' ': str[i] = '_'; break; 1682 default: break; 1683 } 1684 } 1685 } 1686 #endif 1687 1688 bool SampleWindow::onHandleChar(SkUnichar uni) { 1689 { 1690 SkView* view = curr_view(this); 1691 if (view) { 1692 SkEvent evt(gCharEvtName); 1693 evt.setFast32(uni); 1694 if (view->doQuery(&evt)) { 1695 return true; 1696 } 1697 } 1698 } 1699 1700 int dx = 0xFF; 1701 int dy = 0xFF; 1702 1703 switch (uni) { 1704 case '5': dx = 0; dy = 0; break; 1705 case '8': dx = 0; dy = -1; break; 1706 case '6': dx = 1; dy = 0; break; 1707 case '2': dx = 0; dy = 1; break; 1708 case '4': dx = -1; dy = 0; break; 1709 case '7': dx = -1; dy = -1; break; 1710 case '9': dx = 1; dy = -1; break; 1711 case '3': dx = 1; dy = 1; break; 1712 case '1': dx = -1; dy = 1; break; 1713 1714 default: 1715 break; 1716 } 1717 1718 if (0xFF != dx && 0xFF != dy) { 1719 if ((dx | dy) == 0) { 1720 fScrollTestX = fScrollTestY = 0; 1721 } else { 1722 fScrollTestX += dx; 1723 fScrollTestY += dy; 1724 } 1725 this->inval(NULL); 1726 return true; 1727 } 1728 1729 switch (uni) { 1730 case 'B': 1731 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this)); 1732 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in 1733 // the queue. 1734 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this); 1735 this->inval(NULL); 1736 break; 1737 case 'f': 1738 // only 1739 toggleFPS(); 1740 break; 1741 case 'g': 1742 fRequestGrabImage = true; 1743 this->inval(NULL); 1744 break; 1745 case 'G': 1746 gShowGMBounds = !gShowGMBounds; 1747 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds), 1748 curr_view(this)); 1749 this->inval(NULL); 1750 break; 1751 case 'i': 1752 this->zoomIn(); 1753 break; 1754 case 'o': 1755 this->zoomOut(); 1756 break; 1757 case 'r': 1758 fRotate = !fRotate; 1759 fRotateAnimTime = 0; 1760 this->inval(NULL); 1761 this->updateTitle(); 1762 return true; 1763 case 'k': 1764 fPerspAnim = !fPerspAnim; 1765 this->inval(NULL); 1766 this->updateTitle(); 1767 return true; 1768 #if SK_SUPPORT_GPU 1769 case '\\': 1770 this->setDeviceType(kNullGPU_DeviceType); 1771 this->inval(NULL); 1772 this->updateTitle(); 1773 return true; 1774 case 'p': 1775 { 1776 GrContext* grContext = this->getGrContext(); 1777 if (grContext) { 1778 size_t cacheBytes; 1779 grContext->getResourceCacheUsage(NULL, &cacheBytes); 1780 grContext->freeGpuResources(); 1781 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes); 1782 } 1783 } 1784 return true; 1785 #endif 1786 default: 1787 break; 1788 } 1789 1790 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) { 1791 this->onUpdateMenu(fAppMenu); 1792 this->onUpdateMenu(fSlideMenu); 1793 return true; 1794 } 1795 return this->INHERITED::onHandleChar(uni); 1796 } 1797 1798 void SampleWindow::setDeviceType(DeviceType type) { 1799 if (type == fDeviceType) 1800 return; 1801 1802 fDevManager->tearDownBackend(this); 1803 1804 fDeviceType = type; 1805 1806 fDevManager->setUpBackend(this, fMSAASampleCount); 1807 1808 this->updateTitle(); 1809 this->inval(NULL); 1810 } 1811 1812 void SampleWindow::toggleSlideshow() { 1813 fAnimating = !fAnimating; 1814 this->postAnimatingEvent(); 1815 this->updateTitle(); 1816 } 1817 1818 void SampleWindow::toggleRendering() { 1819 this->setDeviceType(cycle_devicetype(fDeviceType)); 1820 this->updateTitle(); 1821 this->inval(NULL); 1822 } 1823 1824 void SampleWindow::toggleFPS() { 1825 fMeasureFPS = !fMeasureFPS; 1826 this->updateTitle(); 1827 this->inval(NULL); 1828 } 1829 1830 #include "SkDumpCanvas.h" 1831 1832 bool SampleWindow::onHandleKey(SkKey key) { 1833 { 1834 SkView* view = curr_view(this); 1835 if (view) { 1836 SkEvent evt(gKeyEvtName); 1837 evt.setFast32(key); 1838 if (view->doQuery(&evt)) { 1839 return true; 1840 } 1841 } 1842 } 1843 switch (key) { 1844 case kRight_SkKey: 1845 if (this->nextSample()) { 1846 return true; 1847 } 1848 break; 1849 case kLeft_SkKey: 1850 if (this->previousSample()) { 1851 return true; 1852 } 1853 return true; 1854 case kUp_SkKey: 1855 if (USE_ARROWS_FOR_ZOOM) { 1856 this->changeZoomLevel(1.f / 32.f); 1857 } else { 1858 fNClip = !fNClip; 1859 this->inval(NULL); 1860 this->updateTitle(); 1861 } 1862 return true; 1863 case kDown_SkKey: 1864 if (USE_ARROWS_FOR_ZOOM) { 1865 this->changeZoomLevel(-1.f / 32.f); 1866 } else { 1867 this->setColorType(cycle_colortypes(this->getBitmap().colorType())); 1868 this->updateTitle(); 1869 } 1870 return true; 1871 case kOK_SkKey: { 1872 SkString title; 1873 if (curr_title(this, &title)) { 1874 writeTitleToPrefs(title.c_str()); 1875 } 1876 return true; 1877 } 1878 case kBack_SkKey: 1879 this->showOverview(); 1880 return true; 1881 default: 1882 break; 1883 } 1884 return this->INHERITED::onHandleKey(key); 1885 } 1886 1887 /////////////////////////////////////////////////////////////////////////////// 1888 1889 static const char gGestureClickType[] = "GestureClickType"; 1890 1891 bool SampleWindow::onDispatchClick(int x, int y, Click::State state, 1892 void* owner, unsigned modi) { 1893 if (Click::kMoved_State == state) { 1894 updatePointer(x, y); 1895 } 1896 int w = SkScalarRoundToInt(this->width()); 1897 int h = SkScalarRoundToInt(this->height()); 1898 1899 // check for the resize-box 1900 if (w - x < 16 && h - y < 16) { 1901 return false; // let the OS handle the click 1902 } 1903 else if (fMagnify) { 1904 //it's only necessary to update the drawing if there's a click 1905 this->inval(NULL); 1906 return false; //prevent dragging while magnify is enabled 1907 } else { 1908 // capture control+option, and trigger debugger 1909 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) { 1910 if (Click::kDown_State == state) { 1911 SkEvent evt("debug-hit-test"); 1912 evt.setS32("debug-hit-test-x", x); 1913 evt.setS32("debug-hit-test-y", y); 1914 curr_view(this)->doEvent(evt); 1915 } 1916 return true; 1917 } else { 1918 return this->INHERITED::onDispatchClick(x, y, state, owner, modi); 1919 } 1920 } 1921 } 1922 1923 class GestureClick : public SkView::Click { 1924 public: 1925 GestureClick(SkView* target) : SkView::Click(target) { 1926 this->setType(gGestureClickType); 1927 } 1928 1929 static bool IsGesture(Click* click) { 1930 return click->isType(gGestureClickType); 1931 } 1932 }; 1933 1934 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y, 1935 unsigned modi) { 1936 return new GestureClick(this); 1937 } 1938 1939 bool SampleWindow::onClick(Click* click) { 1940 if (GestureClick::IsGesture(click)) { 1941 float x = static_cast<float>(click->fICurr.fX); 1942 float y = static_cast<float>(click->fICurr.fY); 1943 1944 switch (click->fState) { 1945 case SkView::Click::kDown_State: 1946 fGesture.touchBegin(click->fOwner, x, y); 1947 break; 1948 case SkView::Click::kMoved_State: 1949 fGesture.touchMoved(click->fOwner, x, y); 1950 this->updateMatrix(); 1951 break; 1952 case SkView::Click::kUp_State: 1953 fGesture.touchEnd(click->fOwner); 1954 this->updateMatrix(); 1955 break; 1956 } 1957 return true; 1958 } 1959 return false; 1960 } 1961 1962 /////////////////////////////////////////////////////////////////////////////// 1963 1964 void SampleWindow::loadView(SkView* view) { 1965 SkView::F2BIter iter(this); 1966 SkView* prev = iter.next(); 1967 if (prev) { 1968 prev->detachFromParent(); 1969 } 1970 1971 view->setVisibleP(true); 1972 view->setClipToBounds(false); 1973 this->attachChildToFront(view)->unref(); 1974 view->setSize(this->width(), this->height()); 1975 1976 //repopulate the slide menu when a view is loaded 1977 fSlideMenu->reset(); 1978 1979 (void)SampleView::SetUsePipe(view, fPipeState); 1980 if (SampleView::IsSampleView(view)) { 1981 SampleView* sampleView = (SampleView*)view; 1982 sampleView->requestMenu(fSlideMenu); 1983 sampleView->onTileSizeChanged(this->tileSize()); 1984 } 1985 this->onUpdateMenu(fSlideMenu); 1986 this->updateTitle(); 1987 } 1988 1989 static const char* gDeviceTypePrefix[] = { 1990 "raster: ", 1991 "picture: ", 1992 #if SK_SUPPORT_GPU 1993 "opengl: ", 1994 #if SK_ANGLE 1995 "angle: ", 1996 #endif // SK_ANGLE 1997 "null-gl: " 1998 #endif // SK_SUPPORT_GPU 1999 }; 2000 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt, 2001 array_size_mismatch); 2002 2003 static const char* trystate_str(SkOSMenu::TriState state, 2004 const char trueStr[], const char falseStr[]) { 2005 if (SkOSMenu::kOnState == state) { 2006 return trueStr; 2007 } else if (SkOSMenu::kOffState == state) { 2008 return falseStr; 2009 } 2010 return NULL; 2011 } 2012 2013 void SampleWindow::updateTitle() { 2014 SkView* view = curr_view(this); 2015 2016 SkString title; 2017 if (!curr_title(this, &title)) { 2018 title.set("<unknown>"); 2019 } 2020 2021 title.prepend(gDeviceTypePrefix[fDeviceType]); 2022 2023 title.prepend(" "); 2024 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType())); 2025 2026 if (fTilingMode != kNo_Tiling) { 2027 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label); 2028 } 2029 if (fAnimating) { 2030 title.prepend("<A> "); 2031 } 2032 if (fRotate) { 2033 title.prepend("<R> "); 2034 } 2035 if (fNClip) { 2036 title.prepend("<C> "); 2037 } 2038 if (fPerspAnim) { 2039 title.prepend("<K> "); 2040 } 2041 2042 title.prepend(trystate_str(fLCDState, "LCD ", "lcd ")); 2043 title.prepend(trystate_str(fAAState, "AA ", "aa ")); 2044 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel); 2045 title.prepend(trystate_str(fSubpixelState, "S ", "s ")); 2046 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL); 2047 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL); 2048 title.prepend(gHintingStates[fHintingState].label); 2049 2050 if (fZoomLevel) { 2051 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel)); 2052 } 2053 2054 if (fMeasureFPS) { 2055 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT); 2056 } 2057 if (SampleView::IsSampleView(view)) { 2058 switch (fPipeState) { 2059 case SkOSMenu::kOnState: 2060 title.prepend("<Pipe> "); 2061 break; 2062 case SkOSMenu::kMixedState: 2063 title.prepend("<Tiled Pipe> "); 2064 break; 2065 2066 default: 2067 break; 2068 } 2069 title.prepend("! "); 2070 } 2071 2072 #if SK_SUPPORT_GPU 2073 if (IsGpuDeviceType(fDeviceType) && 2074 NULL != fDevManager && 2075 fDevManager->getGrRenderTarget() && 2076 fDevManager->getGrRenderTarget()->numSamples() > 0) { 2077 title.appendf(" [MSAA: %d]", 2078 fDevManager->getGrRenderTarget()->numSamples()); 2079 } 2080 #endif 2081 2082 this->setTitle(title.c_str()); 2083 } 2084 2085 void SampleWindow::onSizeChange() { 2086 this->INHERITED::onSizeChange(); 2087 2088 SkView::F2BIter iter(this); 2089 SkView* view = iter.next(); 2090 view->setSize(this->width(), this->height()); 2091 2092 // rebuild our clippath 2093 { 2094 const SkScalar W = this->width(); 2095 const SkScalar H = this->height(); 2096 2097 fClipPath.reset(); 2098 #if 0 2099 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) { 2100 SkRect r; 2101 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30)); 2102 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0)) 2103 fClipPath.addRect(r); 2104 } 2105 #else 2106 SkRect r; 2107 r.set(0, 0, W, H); 2108 fClipPath.addRect(r, SkPath::kCCW_Direction); 2109 r.set(W/4, H/4, W*3/4, H*3/4); 2110 fClipPath.addRect(r, SkPath::kCW_Direction); 2111 #endif 2112 } 2113 2114 fZoomCenterX = SkScalarHalf(this->width()); 2115 fZoomCenterY = SkScalarHalf(this->height()); 2116 2117 #ifdef SK_BUILD_FOR_ANDROID 2118 // FIXME: The first draw after a size change does not work on Android, so 2119 // we post an invalidate. 2120 this->postInvalDelay(); 2121 #endif 2122 this->updateTitle(); // to refresh our config 2123 fDevManager->windowSizeChanged(this); 2124 2125 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) { 2126 ((SampleView*)view)->onTileSizeChanged(this->tileSize()); 2127 } 2128 } 2129 2130 /////////////////////////////////////////////////////////////////////////////// 2131 2132 static const char is_sample_view_tag[] = "sample-is-sample-view"; 2133 static const char repeat_count_tag[] = "sample-set-repeat-count"; 2134 static const char set_use_pipe_tag[] = "sample-set-use-pipe"; 2135 2136 bool SampleView::IsSampleView(SkView* view) { 2137 SkEvent evt(is_sample_view_tag); 2138 return view->doQuery(&evt); 2139 } 2140 2141 bool SampleView::SetRepeatDraw(SkView* view, int count) { 2142 SkEvent evt(repeat_count_tag); 2143 evt.setFast32(count); 2144 return view->doEvent(evt); 2145 } 2146 2147 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) { 2148 SkEvent evt; 2149 evt.setS32(set_use_pipe_tag, state); 2150 return view->doEvent(evt); 2151 } 2152 2153 bool SampleView::onEvent(const SkEvent& evt) { 2154 if (evt.isType(repeat_count_tag)) { 2155 fRepeatCount = evt.getFast32(); 2156 return true; 2157 } 2158 2159 int32_t pipeHolder; 2160 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) { 2161 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder); 2162 return true; 2163 } 2164 2165 return this->INHERITED::onEvent(evt); 2166 } 2167 2168 bool SampleView::onQuery(SkEvent* evt) { 2169 if (evt->isType(is_sample_view_tag)) { 2170 return true; 2171 } 2172 return this->INHERITED::onQuery(evt); 2173 } 2174 2175 2176 class SimplePC : public SkGPipeController { 2177 public: 2178 SimplePC(SkCanvas* target); 2179 ~SimplePC(); 2180 2181 virtual void* requestBlock(size_t minRequest, size_t* actual); 2182 virtual void notifyWritten(size_t bytes); 2183 2184 private: 2185 SkGPipeReader fReader; 2186 void* fBlock; 2187 size_t fBlockSize; 2188 size_t fBytesWritten; 2189 int fAtomsWritten; 2190 SkGPipeReader::Status fStatus; 2191 2192 size_t fTotalWritten; 2193 }; 2194 2195 SimplePC::SimplePC(SkCanvas* target) : fReader(target) { 2196 fBlock = NULL; 2197 fBlockSize = fBytesWritten = 0; 2198 fStatus = SkGPipeReader::kDone_Status; 2199 fTotalWritten = 0; 2200 fAtomsWritten = 0; 2201 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory); 2202 } 2203 2204 SimplePC::~SimplePC() { 2205 // SkASSERT(SkGPipeReader::kDone_Status == fStatus); 2206 if (fTotalWritten) { 2207 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten, 2208 fAtomsWritten, fStatus); 2209 #ifdef PIPE_FILE 2210 //File is open in append mode 2211 FILE* f = fopen(FILE_PATH, "ab"); 2212 SkASSERT(f != NULL); 2213 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f); 2214 fclose(f); 2215 #endif 2216 #ifdef PIPE_NET 2217 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done 2218 gServer.acceptConnections(); 2219 gServer.writePacket(fBlock, fTotalWritten); 2220 } 2221 #endif 2222 } 2223 sk_free(fBlock); 2224 } 2225 2226 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) { 2227 sk_free(fBlock); 2228 2229 fBlockSize = minRequest * 4; 2230 fBlock = sk_malloc_throw(fBlockSize); 2231 fBytesWritten = 0; 2232 *actual = fBlockSize; 2233 return fBlock; 2234 } 2235 2236 void SimplePC::notifyWritten(size_t bytes) { 2237 SkASSERT(fBytesWritten + bytes <= fBlockSize); 2238 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes); 2239 SkASSERT(SkGPipeReader::kError_Status != fStatus); 2240 fBytesWritten += bytes; 2241 fTotalWritten += bytes; 2242 2243 fAtomsWritten += 1; 2244 } 2245 2246 void SampleView::draw(SkCanvas* canvas) { 2247 if (SkOSMenu::kOffState == fPipeState) { 2248 this->INHERITED::draw(canvas); 2249 } else { 2250 SkGPipeWriter writer; 2251 SimplePC controller(canvas); 2252 TiledPipeController tc(canvas->getDevice()->accessBitmap(false), 2253 &SkImageDecoder::DecodeMemory, 2254 &canvas->getTotalMatrix()); 2255 SkGPipeController* pc; 2256 if (SkOSMenu::kMixedState == fPipeState) { 2257 pc = &tc; 2258 } else { 2259 pc = &controller; 2260 } 2261 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag; 2262 2263 canvas = writer.startRecording(pc, flags); 2264 //Must draw before controller goes out of scope and sends data 2265 this->INHERITED::draw(canvas); 2266 //explicitly end recording to ensure writer is flushed before the memory 2267 //is freed in the deconstructor of the controller 2268 writer.endRecording(); 2269 } 2270 } 2271 2272 void SampleView::onDraw(SkCanvas* canvas) { 2273 this->onDrawBackground(canvas); 2274 2275 for (int i = 0; i < fRepeatCount; i++) { 2276 SkAutoCanvasRestore acr(canvas, true); 2277 this->onDrawContent(canvas); 2278 } 2279 } 2280 2281 void SampleView::onDrawBackground(SkCanvas* canvas) { 2282 canvas->drawColor(fBGColor); 2283 } 2284 2285 /////////////////////////////////////////////////////////////////////////////// 2286 2287 template <typename T> void SkTBSort(T array[], int count) { 2288 for (int i = 1; i < count - 1; i++) { 2289 bool didSwap = false; 2290 for (int j = count - 1; j > i; --j) { 2291 if (array[j] < array[j-1]) { 2292 T tmp(array[j-1]); 2293 array[j-1] = array[j]; 2294 array[j] = tmp; 2295 didSwap = true; 2296 } 2297 } 2298 if (!didSwap) { 2299 break; 2300 } 2301 } 2302 2303 for (int k = 0; k < count - 1; k++) { 2304 SkASSERT(!(array[k+1] < array[k])); 2305 } 2306 } 2307 2308 #include "SkRandom.h" 2309 2310 static void rand_rect(SkIRect* rect, SkRandom& rand) { 2311 int bits = 8; 2312 int shift = 32 - bits; 2313 rect->set(rand.nextU() >> shift, rand.nextU() >> shift, 2314 rand.nextU() >> shift, rand.nextU() >> shift); 2315 rect->sort(); 2316 } 2317 2318 static void dumpRect(const SkIRect& r) { 2319 SkDebugf(" { %d, %d, %d, %d },\n", 2320 r.fLeft, r.fTop, 2321 r.fRight, r.fBottom); 2322 } 2323 2324 static void test_rects(const SkIRect rect[], int count) { 2325 SkRegion rgn0, rgn1; 2326 2327 for (int i = 0; i < count; i++) { 2328 rgn0.op(rect[i], SkRegion::kUnion_Op); 2329 // dumpRect(rect[i]); 2330 } 2331 rgn1.setRects(rect, count); 2332 2333 if (rgn0 != rgn1) { 2334 SkDebugf("\n"); 2335 for (int i = 0; i < count; i++) { 2336 dumpRect(rect[i]); 2337 } 2338 SkDebugf("\n"); 2339 } 2340 } 2341 2342 static void test() { 2343 size_t i; 2344 2345 const SkIRect r0[] = { 2346 { 0, 0, 1, 1 }, 2347 { 2, 2, 3, 3 }, 2348 }; 2349 const SkIRect r1[] = { 2350 { 0, 0, 1, 3 }, 2351 { 1, 1, 2, 2 }, 2352 { 2, 0, 3, 3 }, 2353 }; 2354 const SkIRect r2[] = { 2355 { 0, 0, 1, 2 }, 2356 { 2, 1, 3, 3 }, 2357 { 4, 0, 5, 1 }, 2358 { 6, 0, 7, 4 }, 2359 }; 2360 2361 static const struct { 2362 const SkIRect* fRects; 2363 int fCount; 2364 } gRecs[] = { 2365 { r0, SK_ARRAY_COUNT(r0) }, 2366 { r1, SK_ARRAY_COUNT(r1) }, 2367 { r2, SK_ARRAY_COUNT(r2) }, 2368 }; 2369 2370 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { 2371 test_rects(gRecs[i].fRects, gRecs[i].fCount); 2372 } 2373 2374 SkRandom rand; 2375 for (i = 0; i < 10000; i++) { 2376 SkRegion rgn0, rgn1; 2377 2378 const int N = 8; 2379 SkIRect rect[N]; 2380 for (int j = 0; j < N; j++) { 2381 rand_rect(&rect[j], rand); 2382 } 2383 test_rects(rect, N); 2384 } 2385 } 2386 2387 // FIXME: this should be in a header 2388 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv); 2389 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) { 2390 if (false) { // avoid bit rot, suppress warning 2391 test(); 2392 } 2393 return new SampleWindow(hwnd, argc, argv, NULL); 2394 } 2395 2396 // FIXME: this should be in a header 2397 void get_preferred_size(int* x, int* y, int* width, int* height); 2398 void get_preferred_size(int* x, int* y, int* width, int* height) { 2399 *x = 10; 2400 *y = 50; 2401 *width = 640; 2402 *height = 480; 2403 } 2404 2405 #ifdef SK_BUILD_FOR_IOS 2406 void save_args(int argc, char *argv[]) { 2407 } 2408 #endif 2409 2410 // FIXME: this should be in a header 2411 void application_init(); 2412 void application_init() { 2413 // setenv("ANDROID_ROOT", "../../../data", 0); 2414 #ifdef SK_BUILD_FOR_MAC 2415 setenv("ANDROID_ROOT", "/android/device/data", 0); 2416 #endif 2417 SkGraphics::Init(); 2418 SkEvent::Init(); 2419 } 2420 2421 // FIXME: this should be in a header 2422 void application_term(); 2423 void application_term() { 2424 SkEvent::Term(); 2425 SkGraphics::Term(); 2426 } 2427