From 2e768924f3a6c174ff27e3c7d55caee91a752811 Mon Sep 17 00:00:00 2001 From: Vitaly Stakhovsky Date: Mon, 20 Jan 2020 15:44:07 -0500 Subject: cmLocalVisualStudio7Generator: clean up c_str() --- Source/cmLocalVisualStudio7Generator.cxx | 91 +++++++++++++++----------------- Source/cmLocalVisualStudio7Generator.h | 4 +- 2 files changed, 45 insertions(+), 50 deletions(-) diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 55a9a72..1a6b7b2 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -146,7 +146,7 @@ void cmLocalVisualStudio7Generator::WriteStampFiles() // out of date. std::string stampName = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles"); - cmSystemTools::MakeDirectory(stampName.c_str()); + cmSystemTools::MakeDirectory(stampName); stampName += "/generate.stamp"; cmsys::ofstream stamp(stampName.c_str()); stamp << "# CMake generation timestamp file for this directory.\n"; @@ -257,12 +257,11 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() "--check-stamp-file", stampName }); std::string comment = cmStrCat("Building Custom Rule ", makefileIn); const char* no_working_directory = nullptr; - std::string fullpathStampName = - cmSystemTools::CollapseFullPath(stampName.c_str()); + std::string fullpathStampName = cmSystemTools::CollapseFullPath(stampName); this->AddCustomCommandToOutput(fullpathStampName, listFiles, makefileIn, commandLines, comment.c_str(), no_working_directory, true, false); - if (cmSourceFile* file = this->Makefile->GetSource(makefileIn.c_str())) { + if (cmSourceFile* file = this->Makefile->GetSource(makefileIn)) { // Finalize the source file path now since we're adding this after // the generator validated all project-named sources. file->ResolveFullPath(); @@ -279,7 +278,7 @@ void cmLocalVisualStudio7Generator::WriteConfigurations( { fout << "\t\n"; for (std::string const& config : configs) { - this->WriteConfiguration(fout, config.c_str(), libName, target); + this->WriteConfiguration(fout, config, libName, target); } fout << "\t\n"; } @@ -580,7 +579,7 @@ public: this->Stream << this->LG->EscapeForXML("\n"); } std::string script = this->LG->ConstructScript(ccg); - this->Stream << this->LG->EscapeForXML(script.c_str()); + this->Stream << this->LG->EscapeForXML(script); } private: @@ -733,13 +732,13 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( : target->GetDirectory(configName); /* clang-format off */ fout << "\t\t\tOutputDirectory=\"" - << this->ConvertToXMLOutputPathSingle(outDir.c_str()) << "\"\n"; + << this->ConvertToXMLOutputPathSingle(outDir) << "\"\n"; /* clang-format on */ } /* clang-format off */ fout << "\t\t\tIntermediateDirectory=\"" - << this->ConvertToXMLOutputPath(intermediateDir.c_str()) + << this->ConvertToXMLOutputPath(intermediateDir) << "\"\n" << "\t\t\tConfigurationType=\"" << configType << "\"\n" << "\t\t\tUseOfMFC=\"" << mfcFlag << "\"\n" @@ -788,8 +787,7 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( } else { modDir = "."; } - fout << "\t\t\t\tModulePath=\"" - << this->ConvertToXMLOutputPath(modDir.c_str()) + fout << "\t\t\t\tModulePath=\"" << this->ConvertToXMLOutputPath(modDir) << "\\$(ConfigurationName)\"\n"; } targetOptions.OutputAdditionalIncludeDirectories( @@ -802,7 +800,7 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( std::string pdb = target->GetCompilePDBPath(configName); if (!pdb.empty()) { fout << "\t\t\t\tProgramDataBaseFileName=\"" - << this->ConvertToXMLOutputPathSingle(pdb.c_str()) << "\"\n"; + << this->ConvertToXMLOutputPathSingle(pdb) << "\"\n"; } } fout << "/>\n"; // end of GetFullPath(); - fout << this->ConvertToXMLOutputPath(m.c_str()) << ";"; + fout << this->ConvertToXMLOutputPath(m) << ";"; } fout << "\""; } @@ -946,7 +944,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( } std::string configTypeUpper = cmSystemTools::UpperCase(configName); std::string linkFlagsConfig = cmStrCat("LINK_FLAGS_", configTypeUpper); - targetLinkFlags = target->GetProperty(linkFlagsConfig.c_str()); + targetLinkFlags = target->GetProperty(linkFlagsConfig); if (targetLinkFlags) { extraLinkOptions += " "; extraLinkOptions += targetLinkFlags; @@ -985,7 +983,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\tConvertToXMLOutputPathSingle(libpath.c_str()) << "\"/>\n"; + << this->ConvertToXMLOutputPathSingle(libpath) << "\"/>\n"; break; } case cmStateEnums::STATIC_LIBRARY: { @@ -1015,7 +1013,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tAdditionalOptions=\"" << libflags << "\"\n"; } fout << "\t\t\t\tOutputFile=\"" - << this->ConvertToXMLOutputPathSingle(libpath.c_str()) << "\"/>\n"; + << this->ConvertToXMLOutputPathSingle(libpath) << "\"/>\n"; break; } case cmStateEnums::SHARED_LIBRARY: @@ -1057,7 +1055,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( temp = cmStrCat(target->GetDirectory(configName), '/', targetNames.Output); fout << "\t\t\t\tOutputFile=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; + << this->ConvertToXMLOutputPathSingle(temp) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); linkOptions.OutputFlagMap(fout, 4); fout << "\t\t\t\tAdditionalLibraryDirectories=\""; @@ -1066,7 +1064,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( temp = cmStrCat(target->GetPDBDirectory(configName), '/', targetNames.PDB); fout << "\t\t\t\tProgramDatabaseFile=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; + << this->ConvertToXMLOutputPathSingle(temp) << "\"\n"; if (targetOptions.IsDebug()) { fout << "\t\t\t\tGenerateDebugInformation=\"true\"\n"; } @@ -1078,7 +1076,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( } } std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"); - const char* stackVal = this->Makefile->GetDefinition(stackVar.c_str()); + const char* stackVal = this->Makefile->GetDefinition(stackVar); if (stackVal) { fout << "\t\t\t\tStackReserveSize=\"" << stackVal << "\"\n"; } @@ -1086,7 +1084,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact), '/', targetNames.ImportLibrary); fout << "\t\t\t\tImportLibrary=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\""; + << this->ConvertToXMLOutputPathSingle(temp) << "\""; if (this->FortranProject) { fout << "\n\t\t\t\tLinkDLL=\"true\""; } @@ -1132,14 +1130,14 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( temp = cmStrCat(target->GetDirectory(configName), '/', targetNames.Output); fout << "\t\t\t\tOutputFile=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; + << this->ConvertToXMLOutputPathSingle(temp) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); linkOptions.OutputFlagMap(fout, 4); fout << "\t\t\t\tAdditionalLibraryDirectories=\""; this->OutputLibraryDirectories(fout, cli.GetDirectories()); fout << "\"\n"; std::string path = this->ConvertToXMLOutputPathSingle( - target->GetPDBDirectory(configName).c_str()); + target->GetPDBDirectory(configName)); fout << "\t\t\t\tProgramDatabaseFile=\"" << path << "/" << targetNames.PDB << "\"\n"; if (targetOptions.IsDebug()) { @@ -1167,7 +1165,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( << "\"\n"; } std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"); - const char* stackVal = this->Makefile->GetDefinition(stackVar.c_str()); + const char* stackVal = this->Makefile->GetDefinition(stackVar); if (stackVal) { fout << "\t\t\t\tStackReserveSize=\"" << stackVal << "\""; } @@ -1175,7 +1173,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact), '/', targetNames.ImportLibrary); fout << "\t\t\t\tImportLibrary=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"/>\n"; + << this->ConvertToXMLOutputPathSingle(temp) << "\"/>\n"; break; } case cmStateEnums::UTILITY: @@ -1256,8 +1254,8 @@ void cmLocalVisualStudio7GeneratorInternals::OutputLibraries( for (auto const& lib : libs) { if (lib.IsPath) { std::string rel = - lg->MaybeConvertToRelativePath(currentBinDir, lib.Value.c_str()); - fout << lg->ConvertToXMLOutputPath(rel.c_str()) << " "; + lg->MaybeConvertToRelativePath(currentBinDir, lib.Value); + fout << lg->ConvertToXMLOutputPath(rel) << " "; } else if (!lib.Target || lib.Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) { fout << lib.Value << " "; @@ -1282,7 +1280,7 @@ void cmLocalVisualStudio7GeneratorInternals::OutputObjects( if (!obj->GetObjectLibrary().empty()) { std::string const& objFile = obj->GetFullPath(); std::string rel = lg->MaybeConvertToRelativePath(currentBinDir, objFile); - fout << sep << lg->ConvertToXMLOutputPath(rel.c_str()); + fout << sep << lg->ConvertToXMLOutputPath(rel); sep = " "; } } @@ -1303,9 +1301,8 @@ void cmLocalVisualStudio7Generator::OutputLibraryDirectories( } // Switch to a relative path specification if it is shorter. - if (cmSystemTools::FileIsFullPath(dir.c_str())) { - std::string rel = - this->MaybeConvertToRelativePath(currentBinDir, dir.c_str()); + if (cmSystemTools::FileIsFullPath(dir)) { + std::string rel = this->MaybeConvertToRelativePath(currentBinDir, dir); if (rel.size() < dir.size()) { dir = rel; } @@ -1314,9 +1311,8 @@ void cmLocalVisualStudio7Generator::OutputLibraryDirectories( // First search a configuration-specific subdirectory and then the // original directory. fout << comma - << this->ConvertToXMLOutputPath( - (dir + "/$(ConfigurationName)").c_str()) - << "," << this->ConvertToXMLOutputPath(dir.c_str()); + << this->ConvertToXMLOutputPath(dir + "/$(ConfigurationName)") << "," + << this->ConvertToXMLOutputPath(dir); comma = ","; } } @@ -1518,13 +1514,13 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( for (std::vector::iterator j = depends.begin(); j != depends.end(); ++j) { fc.AdditionalDeps += sep; - fc.AdditionalDeps += lg->ConvertToXMLOutputPath(j->c_str()); + fc.AdditionalDeps += lg->ConvertToXMLOutputPath(*j); sep = ";"; needfc = true; } } - const std::string& linkLanguage = gt->GetLinkerLanguage(config.c_str()); + const std::string& linkLanguage = gt->GetLinkerLanguage(config); // If HEADER_FILE_ONLY is set, we must suppress this generation in // the project file fc.ExcludedFromBuild = sf.GetPropertyAsBool("HEADER_FILE_ONLY") || @@ -1629,7 +1625,7 @@ bool cmLocalVisualStudio7Generator::WriteGroup( FCInfo fcinfo(this, target, acs, configs); fout << "\t\t\tConvertToXMLOutputPathSingle(source.c_str()); + std::string d = this->ConvertToXMLOutputPathSingle(source); // Tell MS-Dev what the source is. If the compiler knows how to // build it, then it will. fout << "\t\t\t\tRelativePath=\"" << d << "\">\n"; @@ -1759,21 +1755,21 @@ void cmLocalVisualStudio7Generator::WriteCustomRule( fout << "\t\t\t\t\tEscapeForXML(fc.CompileFlags.c_str()) << "\"/>\n"; + << this->EscapeForXML(fc.CompileFlags) << "\"/>\n"; } std::string comment = this->ConstructComment(ccg); std::string script = this->ConstructScript(ccg); if (this->FortranProject) { - cmSystemTools::ReplaceString(script, "$(Configuration)", config.c_str()); + cmSystemTools::ReplaceString(script, "$(Configuration)", config); } /* clang-format off */ fout << "\t\t\t\t\tEscapeForXML(comment.c_str()) << "\"\n" + << this->EscapeForXML(comment) << "\"\n" << "\t\t\t\t\tCommandLine=\"" - << this->EscapeForXML(script.c_str()) << "\"\n" + << this->EscapeForXML(script) << "\"\n" << "\t\t\t\t\tAdditionalDependencies=\""; /* clang-format on */ if (ccg.GetDepends().empty()) { @@ -1789,8 +1785,8 @@ void cmLocalVisualStudio7Generator::WriteCustomRule( for (std::string const& d : ccg.GetDepends()) { // Get the real name of the dependency in case it is a CMake target. std::string dep; - if (this->GetRealDependency(d.c_str(), config.c_str(), dep)) { - fout << this->ConvertToXMLOutputPath(dep.c_str()) << ";"; + if (this->GetRealDependency(d, config, dep)) { + fout << this->ConvertToXMLOutputPath(dep) << ";"; } } } @@ -1802,7 +1798,7 @@ void cmLocalVisualStudio7Generator::WriteCustomRule( // Write a rule for the output generated by this command. const char* sep = ""; for (std::string const& output : ccg.GetOutputs()) { - fout << sep << this->ConvertToXMLOutputPathSingle(output.c_str()); + fout << sep << this->ConvertToXMLOutputPathSingle(output); sep = ";"; } } @@ -1948,7 +1944,7 @@ void cmLocalVisualStudio7Generator::WriteProjectStartFortran( this->WriteProjectSCC(fout, target); /* clang-format off */ fout<< "\tKeyword=\"" << keyword << "\">\n" - << "\tProjectGUID=\"{" << gg->GetGUID(libName.c_str()) << "}\">\n" + << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\">\n" << "\t\n" << "\t\tGetPlatformName() << "\"/>\n" << "\t\n"; @@ -1983,7 +1979,7 @@ void cmLocalVisualStudio7Generator::WriteProjectStart( keyword = "Win32Proj"; } fout << "\tName=\"" << projLabel << "\"\n"; - fout << "\tProjectGUID=\"{" << gg->GetGUID(libName.c_str()) << "}\"\n"; + fout << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\"\n"; this->WriteProjectSCC(fout, target); if (const char* targetFrameworkVersion = target->GetProperty("VS_DOTNET_TARGET_FRAMEWORK_VERSION")) { @@ -2037,7 +2033,7 @@ std::string cmLocalVisualStudio7Generator::EscapeForXML(const std::string& s) } std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPath( - const char* path) + const std::string& path) { std::string ret = this->ConvertToOutputFormat(path, cmOutputConverter::SHELL); @@ -2049,7 +2045,7 @@ std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPath( } std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPathSingle( - const char* path) + const std::string& path) { std::string ret = this->ConvertToOutputFormat(path, cmOutputConverter::SHELL); @@ -2130,8 +2126,7 @@ void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID( std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE"); // save the GUID in the cache this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry( - guidStoreName.c_str(), parser.GUID.c_str(), "Stored GUID", - cmStateEnums::INTERNAL); + guidStoreName, parser.GUID.c_str(), "Stored GUID", cmStateEnums::INTERNAL); } std::string cmLocalVisualStudio7Generator::GetTargetDirectory( diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h index 22a5f9a..745766c 100644 --- a/Source/cmLocalVisualStudio7Generator.h +++ b/Source/cmLocalVisualStudio7Generator.h @@ -101,8 +101,8 @@ private: void WriteConfiguration(std::ostream& fout, const std::string& configName, const std::string& libName, cmGeneratorTarget* tgt); std::string EscapeForXML(const std::string& s); - std::string ConvertToXMLOutputPath(const char* path); - std::string ConvertToXMLOutputPathSingle(const char* path); + std::string ConvertToXMLOutputPath(const std::string& path); + std::string ConvertToXMLOutputPathSingle(const std::string& path); void OutputTargetRules(std::ostream& fout, const std::string& configName, cmGeneratorTarget* target, const std::string& libName); -- cgit v0.12 id='n418' href='#n418'>418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qdeclarativeview.h>

#ifdef hz
#undef hz
#endif
#ifdef Q_WS_MAEMO_5
#  include <QMaemo5ValueButton>
#  include <QMaemo5ListPickSelector>
#  include <QWidgetAction>
#  include <QStringListModel>
#  include "ui_recopts_maemo5.h"
#else
#  include "ui_recopts.h"
#endif

#include "qmlruntime.h"
#include <qdeclarativecontext.h>
#include <qdeclarativeengine.h>
#include <qdeclarativenetworkaccessmanagerfactory.h>
#include "qdeclarative.h"
#include <QAbstractAnimation>
#include <private/qabstractanimation_p.h>

#include <QSettings>
#include <QXmlStreamReader>
#include <QBuffer>
#include <QNetworkReply>
#include <QNetworkCookieJar>
#include <QNetworkDiskCache>
#include <QNetworkAccessManager>
#include <QSignalMapper>
#include <QDeclarativeComponent>
#include <QWidget>
#include <QApplication>
#include <QTranslator>
#include <QDir>
#include <QTextBrowser>
#include <QFile>
#include <QFileInfo>
#include <QVBoxLayout>
#include <QProgressDialog>
#include <QProcess>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QInputDialog>
#include <QTimer>
#include <QGraphicsObject>
#include <QNetworkProxyFactory>
#include <QKeyEvent>
#include <QMutex>
#include <QMutexLocker>
#include "proxysettings.h"
#include "deviceorientation.h"

#ifdef GL_SUPPORTED
#include <QGLWidget>
#endif

#if defined(Q_WS_S60)
#include <aknappui.h> // For locking app orientation
#endif

#include <qdeclarativetester.h>

QT_BEGIN_NAMESPACE

class DragAndDropView : public QDeclarativeView
{
    Q_OBJECT
public:
    DragAndDropView(QDeclarativeViewer *parent = 0)
    : QDeclarativeView(parent)
    {
        setAcceptDrops(true);
    }

    void dragEnterEvent(QDragEnterEvent *event)
    {
        const QMimeData *mimeData = event->mimeData();
        if (mimeData->hasUrls())
            event->acceptProposedAction();
    }

    void dragMoveEvent(QDragMoveEvent *event)
    {
        event->acceptProposedAction();
    }

    void dragLeaveEvent(QDragLeaveEvent *event)
    {
        event->accept();
    }

    void dropEvent(QDropEvent *event)
    {
        const QMimeData *mimeData = event->mimeData();
        if (!mimeData->hasUrls())
            return;
        const QList<QUrl> urlList = mimeData->urls();
        foreach (const QUrl &url, urlList) {
            if (url.scheme() == QLatin1String("file")) {
                static_cast<QDeclarativeViewer *>(parent())->open(url.toLocalFile());
                event->accept();
                return;
            }
        }
    }
};

class Runtime : public QObject
{
    Q_OBJECT

    Q_PROPERTY(bool isActiveWindow READ isActiveWindow NOTIFY isActiveWindowChanged)
    Q_PROPERTY(DeviceOrientation::Orientation orientation READ orientation NOTIFY orientationChanged)

public:
    static Runtime* instance()
    {
        static Runtime *instance = 0;
        if (!instance)
            instance = new Runtime;
        return instance;
    }

    bool isActiveWindow() const { return activeWindow; }
    void setActiveWindow(bool active)
    {
        if (active == activeWindow)
            return;
        activeWindow = active;
        emit isActiveWindowChanged();
    }

    DeviceOrientation::Orientation orientation() const { return DeviceOrientation::instance()->orientation(); }

Q_SIGNALS:
    void isActiveWindowChanged();
    void orientationChanged();

private:
    Runtime(QObject *parent=0) : QObject(parent), activeWindow(false)
    {
        connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
                this, SIGNAL(orientationChanged()));
    }

    bool activeWindow;
};



#if defined(Q_WS_MAEMO_5)

class Maemo5PickerAction : public QWidgetAction {
    Q_OBJECT
public:
    Maemo5PickerAction(const QString &text, QActionGroup *actions, QObject *parent)
        : QWidgetAction(parent), m_text(text), m_actions(actions)
    { }

    QWidget *createWidget(QWidget *parent)
    {
	QMaemo5ValueButton *button = new QMaemo5ValueButton(m_text, parent);
	button->setValueLayout(QMaemo5ValueButton::ValueUnderTextCentered);
        QMaemo5ListPickSelector *pick = new QMaemo5ListPickSelector(button);
	button->setPickSelector(pick);
	if (m_actions) {
	    QStringList sl;
	    int curIdx = -1, idx = 0;
	    foreach (QAction *a, m_actions->actions()) {
		sl << a->text();
		if (a->isChecked())
		    curIdx = idx;
		idx++;
            }
	    pick->setModel(new QStringListModel(sl));
	    pick->setCurrentIndex(curIdx);
	} else {
	    button->setEnabled(false);
	}
	connect(pick, SIGNAL(selected(QString)), this, SLOT(emitTriggered()));
	return button;
    }

private slots:
    void emitTriggered()
    {
	QMaemo5ListPickSelector *pick = qobject_cast<QMaemo5ListPickSelector *>(sender());
	if (!pick)
	    return;
	int idx = pick->currentIndex();

	if (m_actions && idx >= 0 && idx < m_actions->actions().count())
	    m_actions->actions().at(idx)->trigger();
    }

private:
    QString m_text;
    QPointer<QActionGroup> m_actions;
};

#endif // Q_WS_MAEMO_5

static struct { const char *name, *args; } ffmpegprofiles[] = {
    {"Maximum Quality", "-sameq"},
    {"High Quality", "-qmax 2"},
    {"Medium Quality", "-qmax 6"},
    {"Low Quality", "-qmax 16"},
    {"Custom ffmpeg arguments", ""},
    {0,0}
};

class RecordingDialog : public QDialog, public Ui::RecordingOptions {
    Q_OBJECT

public:
    RecordingDialog(QWidget *parent) : QDialog(parent)
    {
        setupUi(this);
#ifndef Q_WS_MAEMO_5
        hz->setValidator(new QDoubleValidator(hz));
#endif
        for (int i=0; ffmpegprofiles[i].name; ++i) {
            profile->addItem(ffmpegprofiles[i].name);
        }
    }

    void setArguments(QString a)
    {
        int i;
        for (i=0; ffmpegprofiles[i].args[0]; ++i) {
            if (ffmpegprofiles[i].args == a) {
                profile->setCurrentIndex(i);
                args->setText(QLatin1String(ffmpegprofiles[i].args));
                return;
            }
        }
        customargs = a;
        args->setText(a);
        profile->setCurrentIndex(i);
    }

    QString arguments() const
    {
        int i = profile->currentIndex();
        return ffmpegprofiles[i].args[0] ? QLatin1String(ffmpegprofiles[i].args) : customargs;
    }

    void setOriginalSize(const QSize &s)
    {
        QString str = tr("Original (%1x%2)").arg(s.width()).arg(s.height());

#ifdef Q_WS_MAEMO_5
        sizeCombo->setItemText(0, str);
#else
        sizeOriginal->setText(str);
        if (sizeWidth->value()<=1) {
            sizeWidth->setValue(s.width());
            sizeHeight->setValue(s.height());
        }
#endif
    }

    void showffmpegOptions(bool b)
    {
#ifdef Q_WS_MAEMO_5
        profileLabel->setVisible(b);
        profile->setVisible(b);
        ffmpegHelp->setVisible(b);
        args->setVisible(b);
#else
        ffmpegOptions->setVisible(b);
#endif
    }

    void showRateOptions(bool b)
    {
#ifdef Q_WS_MAEMO_5
        rateLabel->setVisible(b);
        rateCombo->setVisible(b);
#else
        rateOptions->setVisible(b);
#endif
    }

    void setVideoRate(int rate)
    {
#ifdef Q_WS_MAEMO_5
        int idx;
        if (rate >= 60)
            idx = 0;
        else if (rate >= 50)
            idx = 2;
        else if (rate >= 25)
            idx = 3;
        else if (rate >= 24)
            idx = 4;
        else if (rate >= 20)
            idx = 5;
        else if (rate >= 15)
            idx = 6;
        else
            idx = 7;
        rateCombo->setCurrentIndex(idx);
#else
        if (rate == 24)
            hz24->setChecked(true);
        else if (rate == 25)
            hz25->setChecked(true);
        else if (rate == 50)
            hz50->setChecked(true);
        else if (rate == 60)
            hz60->setChecked(true);
        else {
            hzCustom->setChecked(true);
            hz->setText(QString::number(rate));
        }
#endif
    }

    int videoRate() const
    {
#ifdef Q_WS_MAEMO_5
        switch (rateCombo->currentIndex()) {
            case 0: return 60;
            case 1: return 50;
            case 2: return 25;
            case 3: return 24;
            case 4: return 20;
            case 5: return 15;
            case 7: return 10;
            default: return 60;
        }
#else
        if (hz24->isChecked())
            return 24;
        else if (hz25->isChecked())
            return 25;
        else if (hz50->isChecked())
            return 50;
        else if (hz60->isChecked())
            return 60;
        else {
            return hz->text().toInt();
        }
#endif
    }

    QSize videoSize() const
    {
#ifdef Q_WS_MAEMO_5
        switch (sizeCombo->currentIndex()) {
            case 0: return QSize();
            case 1: return QSize(640,480);
            case 2: return QSize(320,240);
            case 3: return QSize(1280,720);
            default: return QSize();
        }
#else
        if (sizeOriginal->isChecked())
            return QSize();
        else if (size720p->isChecked())
            return QSize(1280,720);
        else if (sizeVGA->isChecked())
            return QSize(640,480);
        else if (sizeQVGA->isChecked())
            return QSize(320,240);
        else
            return QSize(sizeWidth->value(), sizeHeight->value());
#endif
    }



private slots:
    void pickProfile(int i)
    {
        if (ffmpegprofiles[i].args[0]) {
            args->setText(QLatin1String(ffmpegprofiles[i].args));
        } else {
            args->setText(customargs);
        }
    }

    void storeCustomArgs(QString s)
    {
        setArguments(s);
    }

private:
    QString customargs;
};

class PersistentCookieJar : public QNetworkCookieJar {
public:
    PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
    ~PersistentCookieJar() { save(); }

    virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const
    {
        QMutexLocker lock(&mutex);
        return QNetworkCookieJar::cookiesForUrl(url);
    }

    virtual bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
    {
        QMutexLocker lock(&mutex);
        return QNetworkCookieJar::setCookiesFromUrl(cookieList, url);
    }

private:
    void save()
    {
        QMutexLocker lock(&mutex);
        QList<QNetworkCookie> list = allCookies();
        QByteArray data;
        foreach (QNetworkCookie cookie, list) {
            if (!cookie.isSessionCookie()) {
                data.append(cookie.toRawForm());
                data.append("\n");
            }
        }
        QSettings settings;
        settings.setValue("Cookies",data);
    }

    void load()
    {
        QMutexLocker lock(&mutex);
        QSettings settings;
        QByteArray data = settings.value("Cookies").toByteArray();
        setAllCookies(QNetworkCookie::parseCookies(data));
    }

    mutable QMutex mutex;
};

class SystemProxyFactory : public QNetworkProxyFactory
{
public:
    SystemProxyFactory() : proxyDirty(true), httpProxyInUse(false) {
    }

    virtual QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query)
    {
        if (proxyDirty)
            setupProxy();
        QString protocolTag = query.protocolTag();
        if (httpProxyInUse && (protocolTag == "http" || protocolTag == "https")) {
            QList<QNetworkProxy> ret;
            ret << httpProxy;
            return ret;
        }
#ifdef Q_OS_WIN
        // systemProxyForQuery can take insanely long on Windows (QTBUG-10106)
        return QNetworkProxyFactory::proxyForQuery(query);
#else
        return QNetworkProxyFactory::systemProxyForQuery(query);
#endif
    }

    void setupProxy() {
        // Don't bother locking because we know that the proxy only
        // changes in response to the settings dialog and that
        // the view will be reloaded.
        proxyDirty = false;
        httpProxyInUse = ProxySettings::httpProxyInUse();
        if (httpProxyInUse)
            httpProxy = ProxySettings::httpProxy();
    }

    void proxyChanged() {
        proxyDirty = true;
    }

private:
    volatile bool proxyDirty;
    bool httpProxyInUse;
    QNetworkProxy httpProxy;
};

class NetworkAccessManagerFactory : public QObject, public QDeclarativeNetworkAccessManagerFactory
{
    Q_OBJECT
public:
    NetworkAccessManagerFactory() : cacheSize(0) {}
    ~NetworkAccessManagerFactory() {}

    QNetworkAccessManager *create(QObject *parent);

    void setCacheSize(int size) {
        if (size != cacheSize) {
            cacheSize = size;
        }
    }

    void proxyChanged() {
        foreach (QNetworkAccessManager *nam, namList) {
            static_cast<SystemProxyFactory*>(nam->proxyFactory())->proxyChanged();
        }
    }

    static PersistentCookieJar *cookieJar;

private slots:
    void managerDestroyed(QObject *obj) {
        namList.removeOne(static_cast<QNetworkAccessManager*>(obj));
    }

private:
    QMutex mutex;
    int cacheSize;
    QList<QNetworkAccessManager*> namList;
};

PersistentCookieJar *NetworkAccessManagerFactory::cookieJar = 0;

static void cleanup_cookieJar()
{
    delete NetworkAccessManagerFactory::cookieJar;
    NetworkAccessManagerFactory::cookieJar = 0;
}

QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
{
    QMutexLocker lock(&mutex);
    QNetworkAccessManager *manager = new QNetworkAccessManager(parent);
    if (!cookieJar) {
        qAddPostRoutine(cleanup_cookieJar);
        cookieJar = new PersistentCookieJar(0);
    }
    manager->setCookieJar(cookieJar);
    cookieJar->setParent(0);
    manager->setProxyFactory(new SystemProxyFactory);
    if (cacheSize > 0) {
        QNetworkDiskCache *cache = new QNetworkDiskCache;
        cache->setCacheDirectory(QDir::tempPath()+QLatin1String("/qml-viewer-network-cache"));
        cache->setMaximumCacheSize(cacheSize);
        manager->setCache(cache);
    } else {
        manager->setCache(0);
    }
    connect(manager, SIGNAL(destroyed(QObject*)), this, SLOT(managerDestroyed(QObject*)));
    namList.append(manager);
    qDebug() << "created new network access manager for" << parent;
    return manager;
}

QString QDeclarativeViewer::getVideoFileName()
{
    QString title = convertAvailable || ffmpegAvailable ? tr("Save Video File") : tr("Save PNG Frames");
    QStringList types;
    if (ffmpegAvailable) types += tr("Common Video files")+QLatin1String(" (*.avi *.mpeg *.mov)");
    if (convertAvailable) types += tr("GIF Animation")+QLatin1String(" (*.gif)");
    types += tr("Individual PNG frames")+QLatin1String(" (*.png)");
    if (ffmpegAvailable) types += tr("All ffmpeg formats (*.*)");
    return QFileDialog::getSaveFileName(this, title, "", types.join(";; "));
}

QDeclarativeViewer::QDeclarativeViewer(QWidget *parent, Qt::WindowFlags flags)
    : QMainWindow(parent, flags)
      , loggerWindow(new LoggerWidget(this))
      , frame_stream(0)
      , rotateAction(0)
      , orientation(0)
      , showWarningsWindow(0)
      , m_scriptOptions(0)
      , tester(0)
      , useQmlFileBrowser(true)
      , translator(0)
{
    QDeclarativeViewer::registerTypes();
    setWindowTitle(tr("Qt QML Viewer"));
#ifdef Q_WS_MAEMO_5
    setAttribute(Qt::WA_Maemo5StackedWindow);
//    setPalette(QApplication::palette("QLabel"));
#endif

    devicemode = false;
    canvas = 0;
    record_autotime = 0;
    record_rate = 50;
    record_args += QLatin1String("-sameq");

    recdlg = new RecordingDialog(this);
    connect(recdlg->pickfile, SIGNAL(clicked()), this, SLOT(pickRecordingFile()));
    senseFfmpeg();
    senseImageMagick();
    if (!ffmpegAvailable)
        recdlg->showffmpegOptions(false);
    if (!ffmpegAvailable && !convertAvailable)
        recdlg->showRateOptions(false);
    QString warn;
    if (!ffmpegAvailable) {
        if (!convertAvailable)
            warn = tr("ffmpeg and ImageMagick not available - no video output");
        else
            warn = tr("ffmpeg not available - GIF and PNG outputs only");
        recdlg->warning->setText(warn);
    } else {
        recdlg->warning->hide();
    }

    canvas = new DragAndDropView(this);

    canvas->setAttribute(Qt::WA_OpaquePaintEvent);
    canvas->setAttribute(Qt::WA_NoSystemBackground);

    canvas->setFocus();

    QObject::connect(canvas, SIGNAL(sceneResized(QSize)), this, SLOT(sceneResized(QSize)));
    QObject::connect(canvas, SIGNAL(statusChanged(QDeclarativeView::Status)), this, SLOT(statusChanged()));
    QObject::connect(canvas->engine(), SIGNAL(quit()), this, SLOT(close()));

    QObject::connect(warningsWidget(), SIGNAL(opened()), this, SLOT(warningsWidgetOpened()));
    QObject::connect(warningsWidget(), SIGNAL(closed()), this, SLOT(warningsWidgetClosed()));

    if (!(flags & Qt::FramelessWindowHint)) {
        createMenu();
        changeOrientation(orientation->actions().value(0));
    } else {
        setMenuBar(0);
    }

    setCentralWidget(canvas);

    namFactory = new NetworkAccessManagerFactory;
    canvas->engine()->setNetworkAccessManagerFactory(namFactory);

    connect(&autoStartTimer, SIGNAL(timeout()), this, SLOT(autoStartRecording()));
    connect(&autoStopTimer, SIGNAL(timeout()), this, SLOT(autoStopRecording()));
    connect(&recordTimer, SIGNAL(timeout()), this, SLOT(recordFrame()));
    connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
            this, SLOT(orientationChanged()), Qt::QueuedConnection);
    autoStartTimer.setSingleShot(true);
    autoStopTimer.setSingleShot(true);
    recordTimer.setSingleShot(false);

    QObject::connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(appAboutToQuit()));
}

QDeclarativeViewer::~QDeclarativeViewer()
{
    delete loggerWindow;
    canvas->engine()->setNetworkAccessManagerFactory(0);
    delete namFactory;
}

void QDeclarativeViewer::enableExperimentalGestures()
{
    canvas->viewport()->grabGesture(Qt::TapGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
    canvas->viewport()->grabGesture(Qt::TapAndHoldGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
    canvas->viewport()->grabGesture(Qt::PanGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
    canvas->viewport()->grabGesture(Qt::PinchGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
    canvas->viewport()->grabGesture(Qt::SwipeGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
    canvas->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);
}

QDeclarativeView *QDeclarativeViewer::view() const
{
    return canvas;
}

LoggerWidget *QDeclarativeViewer::warningsWidget() const
{
    return loggerWindow;
}

void QDeclarativeViewer::createMenu()
{
    QAction *openAction = new QAction(tr("&Open..."), this);
    openAction->setShortcuts(QKeySequence::Open);
    connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));

    QAction *openUrlAction = new QAction(tr("Open &URL..."), this);
    connect(openUrlAction, SIGNAL(triggered()), this, SLOT(openUrl()));

    QAction *reloadAction = new QAction(tr("&Reload"), this);
    reloadAction->setShortcuts(QKeySequence::Refresh);
    connect(reloadAction, SIGNAL(triggered()), this, SLOT(reload()));

    QAction *snapshotAction = new QAction(tr("&Take Snapshot"), this);
    snapshotAction->setShortcut(QKeySequence("F3"));
    connect(snapshotAction, SIGNAL(triggered()), this, SLOT(takeSnapShot()));

    recordAction = new QAction(tr("Start Recording &Video"), this);
    recordAction->setShortcut(QKeySequence("F9"));
    connect(recordAction, SIGNAL(triggered()), this, SLOT(toggleRecordingWithSelection()));

    QAction *recordOptions = new QAction(tr("Video &Options..."), this);
    connect(recordOptions, SIGNAL(triggered()), this, SLOT(chooseRecordingOptions()));

    QAction *slowAction = new QAction(tr("&Slow Down Animations"), this);
    slowAction->setShortcut(QKeySequence("Ctrl+."));
    slowAction->setCheckable(true);
    connect(slowAction, SIGNAL(triggered(bool)), this, SLOT(setSlowMode(bool)));

    showWarningsWindow = new QAction(tr("Show Warnings"), this);
    showWarningsWindow->setCheckable((true));
    showWarningsWindow->setChecked(loggerWindow->isVisible());
    connect(showWarningsWindow, SIGNAL(triggered(bool)), this, SLOT(showWarnings(bool)));

    QAction *proxyAction = new QAction(tr("HTTP &Proxy..."), this);
    connect(proxyAction, SIGNAL(triggered()), this, SLOT(showProxySettings()));

    QAction *fullscreenAction = new QAction(tr("Full Screen"), this);
    fullscreenAction->setCheckable(true);
    connect(fullscreenAction, SIGNAL(triggered()), this, SLOT(toggleFullScreen()));

    rotateAction = new QAction(tr("Rotate orientation"), this);
    rotateAction->setShortcut(QKeySequence("Ctrl+T"));
    connect(rotateAction, SIGNAL(triggered()), this, SLOT(rotateOrientation()));

    orientation = new QActionGroup(this);
    orientation->setExclusive(true);
    connect(orientation, SIGNAL(triggered(QAction*)), this, SLOT(changeOrientation(QAction*)));

#if defined(Q_OS_SYMBIAN)
    QAction *autoOrientationAction = new QAction(tr("Auto-orientation"), this);
    autoOrientationAction->setCheckable(true);
#endif
    QAction *portraitAction = new QAction(tr("Portrait"), this);
    portraitAction->setCheckable(true);
    QAction *landscapeAction = new QAction(tr("Landscape"), this);
    landscapeAction->setCheckable(true);
#if !defined(Q_OS_SYMBIAN)
    QAction *portraitInvAction = new QAction(tr("Portrait (inverted)"), this);
    portraitInvAction->setCheckable(true);
    QAction *landscapeInvAction = new QAction(tr("Landscape (inverted)"), this);
    landscapeInvAction->setCheckable(true);
#endif

    QAction *aboutAction = new QAction(tr("&About Qt..."), this);
    aboutAction->setMenuRole(QAction::AboutQtRole);
    connect(aboutAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

    QAction *closeAction = new QAction(tr("&Close"), this);
    closeAction->setShortcuts(QKeySequence::Close);
    connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));

    QAction *quitAction = new QAction(tr("&Quit"), this);
    quitAction->setMenuRole(QAction::QuitRole);
    quitAction->setShortcuts(QKeySequence::Quit);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    QMenuBar *menu = menuBar();
    if (!menu)
	return;

#if defined(Q_WS_MAEMO_5)
    menu->addAction(openAction);
    menu->addAction(openUrlAction);
    menu->addAction(reloadAction);

    menu->addAction(snapshotAction);
    menu->addAction(recordAction);

    menu->addAction(recordOptions);
    menu->addAction(proxyAction);

    menu->addAction(slowAction);
    menu->addAction(showWarningsWindow);

    orientation->addAction(landscapeAction);
    orientation->addAction(portraitAction);
    menu->addAction(new Maemo5PickerAction(tr("Set orientation"), orientation, this));
    menu->addAction(fullscreenAction);
    return;
#endif // Q_WS_MAEMO_5

    QMenu *fileMenu = menu->addMenu(tr("&File"));
    fileMenu->addAction(openAction);
    fileMenu->addAction(openUrlAction);
    fileMenu->addAction(reloadAction);
    fileMenu->addSeparator();
    fileMenu->addAction(closeAction);
#if !defined(Q_OS_SYMBIAN)    
    fileMenu->addAction(quitAction);

    QMenu *recordMenu = menu->addMenu(tr("&Recording"));
    recordMenu->addAction(snapshotAction);
    recordMenu->addAction(recordAction);

    QMenu *debugMenu = menu->addMenu(tr("&Debugging"));
    debugMenu->addAction(slowAction);
    debugMenu->addAction(showWarningsWindow);
#endif // ! Q_OS_SYMBIAN

    QMenu *settingsMenu = menu->addMenu(tr("&Settings"));
    settingsMenu->addAction(proxyAction);
#if defined(Q_OS_SYMBIAN)
    settingsMenu->addAction(fullscreenAction);
#else 
    settingsMenu->addAction(recordOptions);
    settingsMenu->addMenu(loggerWindow->preferencesMenu());
#endif // !Q_OS_SYMBIAN
    settingsMenu->addAction(rotateAction);

    QMenu *propertiesMenu = settingsMenu->addMenu(tr("Properties"));

#if defined(Q_OS_SYMBIAN)
    orientation->addAction(autoOrientationAction);
#endif
    orientation->addAction(portraitAction);
    orientation->addAction(landscapeAction);
#if !defined(Q_OS_SYMBIAN)
    orientation->addAction(portraitInvAction);
    orientation->addAction(landscapeInvAction);
#endif
    propertiesMenu->addActions(orientation->actions());

    QMenu *helpMenu = menu->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAction);
}

void QDeclarativeViewer::showProxySettings()
{
    ProxySettings settingsDlg (this);

    connect (&settingsDlg, SIGNAL (accepted()), this, SLOT (proxySettingsChanged ()));

    settingsDlg.exec();
}

void QDeclarativeViewer::proxySettingsChanged()
{
    namFactory->proxyChanged();
    reload ();
}

void QDeclarativeViewer::rotateOrientation()
{
#if defined(Q_WS_S60)
    CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
    if (appUi) {
        CAknAppUi::TAppUiOrientation oldOrientation = appUi->Orientation();
        QString newOrientation;
        if (oldOrientation == CAknAppUi::EAppUiOrientationPortrait) {
            newOrientation = QLatin1String("Landscape");
        } else {
            newOrientation = QLatin1String("Portrait");
        }
        foreach (QAction *action, orientation->actions()) {
            if (action->text() == newOrientation) {
                changeOrientation(action);
            }
        }
    }
#else
    QAction *current = orientation->checkedAction();
    QList<QAction *> actions = orientation->actions();
    int index = actions.indexOf(current);
    if (index < 0)
        return;

    QAction *newOrientation = actions[(index + 1) % actions.count()];
    changeOrientation(newOrientation);
#endif
}

void QDeclarativeViewer::toggleFullScreen()
{
    if (isFullScreen())
        showMaximized();
    else
        showFullScreen();
}

void QDeclarativeViewer::showWarnings(bool show)
{
    loggerWindow->setVisible(show);
}

void QDeclarativeViewer::warningsWidgetOpened()
{
    showWarningsWindow->setChecked(true);
}

void QDeclarativeViewer::warningsWidgetClosed()
{
    showWarningsWindow->setChecked(false);
}

void QDeclarativeViewer::takeSnapShot()
{
    static int snapshotcount = 1;
    QString snapFileName = QString(QLatin1String("snapshot%1.png")).arg(snapshotcount);
    QPixmap::grabWidget(canvas).save(snapFileName);
    qDebug() << "Wrote" << snapFileName;
    ++snapshotcount;
}

void QDeclarativeViewer::pickRecordingFile()
{
    QString fileName = getVideoFileName();
    if (!fileName.isEmpty())
        recdlg->file->setText(fileName);
}

void QDeclarativeViewer::chooseRecordingOptions()
{
    // File
    recdlg->file->setText(record_file);

    // Size
    recdlg->setOriginalSize(canvas->size());

    // Rate
    recdlg->setVideoRate(record_rate);


    // Profile
    recdlg->setArguments(record_args.join(" "));
    if (recdlg->exec()) {
        // File
        record_file = recdlg->file->text();
        // Size
        record_outsize = recdlg->videoSize();
        // Rate
        record_rate = recdlg->videoRate();
        // Profile
        record_args = recdlg->arguments().split(" ",QString::SkipEmptyParts);
    }
}

void QDeclarativeViewer::toggleRecordingWithSelection()
{
    if (!recordTimer.isActive()) {
        if (record_file.isEmpty()) {
            QString fileName = getVideoFileName();
            if (fileName.isEmpty())
                return;
            if (!fileName.contains(QRegExp(".[^\\/]*$")))
                fileName += ".avi";
            setRecordFile(fileName);
        }
    }
    toggleRecording();
}

void QDeclarativeViewer::toggleRecording()
{
    if (record_file.isEmpty()) {
        toggleRecordingWithSelection();
        return;
    }
    bool recording = !recordTimer.isActive();
    recordAction->setText(recording ? tr("&Stop Recording Video\tF9") : tr("&Start Recording Video\tF9"));
    setRecording(recording);
}

void QDeclarativeViewer::setSlowMode(bool enable)
{
    QUnifiedTimer::instance()->setSlowModeEnabled(enable);
}

void QDeclarativeViewer::addLibraryPath(const QString& lib)
{
    canvas->engine()->addImportPath(lib);
}

void QDeclarativeViewer::addPluginPath(const QString& plugin)
{
    canvas->engine()->addPluginPath(plugin);
}

void QDeclarativeViewer::reload()
{
    open(currentFileOrUrl);
}

void QDeclarativeViewer::openFile()
{
    QString cur = canvas->source().toLocalFile();
    if (useQmlFileBrowser) {
        open("qrc:/browser/Browser.qml");
    } else {
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open QML file"), cur, tr("QML Files (*.qml)"));
        if (!fileName.isEmpty()) {
            QFileInfo fi(fileName);
            open(fi.absoluteFilePath());
        }
    }
}

void QDeclarativeViewer::openUrl()
{
    QString cur = canvas->source().toLocalFile();
    QString url= QInputDialog::getText(this, tr("Open QML file"), tr("URL of main QML file:"), QLineEdit::Normal, cur);
    if (!url.isEmpty())
        open(url);
}

void QDeclarativeViewer::statusChanged()
{
    if (canvas->status() == QDeclarativeView::Error && tester)
        tester->executefailure();

    if (canvas->status() == QDeclarativeView::Ready) {
        initialSize = canvas->initialSize();
        updateSizeHints(true);
    }
}

void QDeclarativeViewer::launch(const QString& file_or_url)
{
    QMetaObject::invokeMethod(this, "open", Qt::QueuedConnection, Q_ARG(QString, file_or_url));
}

void QDeclarativeViewer::loadTranslationFile(const QString& directory)
{
    if (!translator) {
        translator = new QTranslator(this);
        QApplication::installTranslator(translator);
    }

    translator->load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
}

void QDeclarativeViewer::loadDummyDataFiles(const QString& directory)
{
    QDir dir(directory+"/dummydata", "*.qml");
    QStringList list = dir.entryList();
    for (int i = 0; i < list.size(); ++i) {
        QString qml = list.at(i);
        QFile f(dir.filePath(qml));
        f.open(QIODevice::ReadOnly);
        QByteArray data = f.readAll();
        QDeclarativeComponent comp(canvas->engine());
        comp.setData(data, QUrl());
        QObject *dummyData = comp.create();

        if(comp.isError()) {
            QList<QDeclarativeError> errors = comp.errors();
            foreach (const QDeclarativeError &error, errors) {
                qWarning() << error;
            }
            if (tester) tester->executefailure();
        }

        if (dummyData) {
            qWarning() << "Loaded dummy data:" << dir.filePath(qml);
            qml.truncate(qml.length()-4);
            canvas->rootContext()->setContextProperty(qml, dummyData);
            dummyData->setParent(this);
        }
    }
}

bool QDeclarativeViewer::open(const QString& file_or_url)
{
    currentFileOrUrl = file_or_url;

    QUrl url;
    QFileInfo fi(file_or_url);
    if (fi.exists())
        url = QUrl::fromLocalFile(fi.absoluteFilePath());
    else
        url = QUrl(file_or_url);
    setWindowTitle(tr("%1 - Qt QML Viewer").arg(file_or_url));

    if (!m_script.isEmpty())
        tester = new QDeclarativeTester(m_script, m_scriptOptions, canvas);

    delete canvas->rootObject();
    canvas->engine()->clearComponentCache();
    QDeclarativeContext *ctxt = canvas->rootContext();
    ctxt->setContextProperty("qmlViewer", this);
#ifdef Q_OS_SYMBIAN
    ctxt->setContextProperty("qmlViewerFolder", "E:\\"); // Documents on your S60 phone
#else
    ctxt->setContextProperty("qmlViewerFolder", QDir::currentPath());
#endif

    ctxt->setContextProperty("runtime", Runtime::instance());

    QString fileName = url.toLocalFile();
    if (!fileName.isEmpty()) {
        fi.setFile(fileName);
        if (fi.exists()) {
            if (fi.suffix().toLower() != QLatin1String("qml")) {
                qWarning() << "qml cannot open non-QML file" << fileName;
                return false;
            }

            QFileInfo fi(fileName);
            loadTranslationFile(fi.path());
            loadDummyDataFiles(fi.path());
        } else {
            qWarning() << "qml cannot find file:" << fileName;
            return false;
        }
    }

    QTime t;
    t.start();

    canvas->setSource(url);

    return true;
}

void QDeclarativeViewer::setAutoRecord(int from, int to)
{
    if (from==0) from=1; // ensure resized
    record_autotime = to-from;
    autoStartTimer.setInterval(from);
    autoStartTimer.start();
}

void QDeclarativeViewer::setRecordArgs(const QStringList& a)
{
    record_args = a;
}

void QDeclarativeViewer::setRecordFile(const QString& f)
{
    record_file = f;
}

void QDeclarativeViewer::setRecordRate(int fps)
{
    record_rate = fps;
}

void QDeclarativeViewer::sceneResized(QSize)
{
    updateSizeHints();
}

void QDeclarativeViewer::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_0 && devicemode)
        exit(0);
    else if (event->key() == Qt::Key_F1 || (event->key() == Qt::Key_1 && devicemode)) {
        qDebug() << "F1 - help\n"
                 << "F2 - save test script\n"
                 << "F3 - take PNG snapshot\n"
                 << "F4 - show items and state\n"
                 << "F5 - reload QML\n"
                 << "F6 - show object tree\n"
                 << "F7 - show timing\n"
                 << "F9 - toggle video recording\n"
                 << "F10 - toggle orientation\n"
                 << "device keys: 0=quit, 1..8=F1..F8"
                ;
    } else if (event->key() == Qt::Key_F2 || (event->key() == Qt::Key_2 && devicemode)) {
        if (tester && m_scriptOptions & Record)
            tester->save();
    } else if (event->key() == Qt::Key_F3 || (event->key() == Qt::Key_3 && devicemode)) {
        takeSnapShot();
    } else if (event->key() == Qt::Key_F5 || (event->key() == Qt::Key_5 && devicemode)) {
        reload();
    } else if (event->key() == Qt::Key_F9 || (event->key() == Qt::Key_9 && devicemode)) {
        toggleRecording();
    } else if (event->key() == Qt::Key_F10) {
        rotateOrientation();
    }

    QWidget::keyPressEvent(event);
}

bool QDeclarativeViewer::event(QEvent *event)
{
    if (event->type() == QEvent::WindowActivate) {
        Runtime::instance()->setActiveWindow(true);
    } else if (event->type() == QEvent::WindowDeactivate) {
        Runtime::instance()->setActiveWindow(false);
    }
    return QWidget::event(event);
}

void QDeclarativeViewer::senseImageMagick()
{
    QProcess proc;
    proc.start("convert", QStringList() << "-h");
    proc.waitForFinished(2000);
    QString help = proc.readAllStandardOutput();
    convertAvailable = help.contains("ImageMagick");
}

void QDeclarativeViewer::senseFfmpeg()
{
    QProcess proc;
    proc.start("ffmpeg", QStringList() << "-h");
    proc.waitForFinished(2000);
    QString ffmpegHelp = proc.readAllStandardOutput();
    ffmpegAvailable = ffmpegHelp.contains("-s ");
    ffmpegHelp = tr("Video recording uses ffmpeg:")+"\n\n"+ffmpegHelp;

    QDialog *d = new QDialog(recdlg);
    QVBoxLayout *l = new QVBoxLayout(d);
    QTextBrowser *b = new QTextBrowser(d);
    QFont f = b->font();
    f.setFamily("courier");
    b->setFont(f);
    b->setText(ffmpegHelp);
    l->addWidget(b);
    d->setLayout(l);
    ffmpegHelpWindow = d;
    connect(recdlg->ffmpegHelp,SIGNAL(clicked()), ffmpegHelpWindow, SLOT(show()));
}

void QDeclarativeViewer::setRecording(bool on)
{
    if (on == recordTimer.isActive())
        return;

    int period = int(1000/record_rate+0.5);
    QUnifiedTimer::instance()->setTimingInterval(on ? period:16);
    QUnifiedTimer::instance()->setConsistentTiming(on);
    if (on) {
        canvas->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
        recordTimer.setInterval(period);
        recordTimer.start();
        frame_fmt = record_file.right(4).toLower();
        frame = QImage(canvas->width(),canvas->height(),QImage::Format_RGB32);
        if (frame_fmt != ".png" && (!convertAvailable || frame_fmt != ".gif")) {
            // Stream video to ffmpeg

            QProcess *proc = new QProcess(this);
            connect(proc, SIGNAL(finished(int)), this, SLOT(ffmpegFinished(int)));
            frame_stream = proc;

            QStringList args;
            args << "-y";
            args << "-r" << QString::number(record_rate);
            args << "-f" << "rawvideo";
            args << "-pix_fmt" << (frame_fmt == ".gif" ? "rgb24" : "rgb32");
            args << "-s" << QString("%1x%2").arg(canvas->width()).arg(canvas->height());
            args << "-i" << "-";
            if (record_outsize.isValid()) {
                args << "-s" << QString("%1x%2").arg(record_outsize.width()).arg(record_outsize.height());
                args << "-aspect" << QString::number(double(canvas->width())/canvas->height());
            }
            args += record_args;
            args << record_file;
            proc->start("ffmpeg",args);

        } else {
            // Store frames, save to GIF/PNG
            frame_stream = 0;
        }
    } else {
        canvas->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
        recordTimer.stop();
        if (frame_stream) {
            qDebug() << "Saving video...";
            frame_stream->close();
            qDebug() << "Wrote" << record_file;
        } else {
            QProgressDialog progress(tr("Saving frames..."), tr("Cancel"), 0, frames.count()+10, this);
            progress.setWindowModality(Qt::WindowModal);

            int frame=0;
            QStringList inputs;
            qDebug() << "Saving frames...";

            QString framename;
            bool png_output = false;
            if (record_file.right(4).toLower()==".png") {
                if (record_file.contains('%'))
                    framename = record_file;
                else
                    framename = record_file.left(record_file.length()-4)+"%04d"+record_file.right(4);
                png_output = true;
            } else {
                framename = "tmp-frame%04d.png";
                png_output = false;
            }
            foreach (QImage* img, frames) {
                progress.setValue(progress.value()+1);
                if (progress.wasCanceled())
                    break;
                QString name;
                name.sprintf(framename.toLocal8Bit(),frame++);
                if (record_outsize.isValid())
                    *img = img->scaled(record_outsize,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
                if (record_dither=="ordered")
                    img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::OrderedDither).save(name);
                else if (record_dither=="threshold")
                    img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::ThresholdDither).save(name);
                else if (record_dither=="floyd")
                    img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither).save(name);
                else
                    img->save(name);
                inputs << name;
                delete img;
            }

            if (!progress.wasCanceled()) {
                if (png_output) {
                    framename.replace(QRegExp("%\\d*."),"*");
                    qDebug() << "Wrote frames" << framename;
                    inputs.clear(); // don't remove them
                } else {
                    // ImageMagick and gifsicle for GIF encoding
                    progress.setLabelText(tr("Converting frames to GIF file..."));
                    QStringList args;
                    args << "-delay" << QString::number(period/10);
                    args << inputs;
                    args << record_file;
                    qDebug() << "Converting..." << record_file << "(this may take a while)";
                    if (0!=QProcess::execute("convert", args)) {
                        qWarning() << "Cannot run ImageMagick 'convert' - recorded frames not converted";
                        inputs.clear(); // don't remove them
                        qDebug() << "Wrote frames tmp-frame*.png";
                    } else {
                        if (record_file.right(4).toLower() == ".gif") {
                            qDebug() << "Compressing..." << record_file;
                            if (0!=QProcess::execute("gifsicle", QStringList() << "-O2" << "-o" << record_file << record_file))
                                qWarning() << "Cannot run 'gifsicle' - not compressed";
                        }
                        qDebug() << "Wrote" << record_file;
                    }
                }
            }

            progress.setValue(progress.maximum()-1);
            foreach (QString name, inputs)
                QFile::remove(name);

            frames.clear();
        }
    }
    qDebug() << "Recording: " << (recordTimer.isActive()?"ON":"OFF");
}

void QDeclarativeViewer::ffmpegFinished(int code)
{
    qDebug() << "ffmpeg returned" << code << frame_stream->readAllStandardError();
}

void QDeclarativeViewer::appAboutToQuit()
{
    // avoid QGLContext errors about invalid contexts on exit
    canvas->setViewport(0);

    // avoid crashes if messages are received after app has closed
    delete loggerWindow;
    loggerWindow = 0;
}

void QDeclarativeViewer::autoStartRecording()
{
    setRecording(true);
    autoStopTimer.setInterval(record_autotime);
    autoStopTimer.start();
}

void QDeclarativeViewer::autoStopRecording()
{
    setRecording(false);
}

void QDeclarativeViewer::recordFrame()
{
    canvas->QWidget::render(&frame);
    if (frame_stream) {
        if (frame_fmt == ".gif") {
            // ffmpeg can't do 32bpp with gif
            QImage rgb24 = frame.convertToFormat(QImage::Format_RGB888);
            frame_stream->write((char*)rgb24.bits(),rgb24.numBytes());
        } else {
            frame_stream->write((char*)frame.bits(),frame.numBytes());
        }
    } else {
        frames.append(new QImage(frame));
    }
}

void QDeclarativeViewer::changeOrientation(QAction *action)
{
    if (!action)
        return;
    QString o = action->text();
    action->setChecked(true);
#if defined(Q_WS_S60)
    CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
    if (appUi) {
        CAknAppUi::TAppUiOrientation orientation = appUi->Orientation();
        if (o == QLatin1String("Auto-orientation")) {
            appUi->SetOrientationL(CAknAppUi::EAppUiOrientationAutomatic);
            rotateAction->setVisible(false);
        } else if (o == QLatin1String("Portrait")) {
            appUi->SetOrientationL(CAknAppUi::EAppUiOrientationPortrait);
            rotateAction->setVisible(true);
        } else if (o == QLatin1String("Landscape")) {
            appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape);
            rotateAction->setVisible(true);
        }
    }
#else
    if (o == QLatin1String("Portrait"))
        DeviceOrientation::instance()->setOrientation(DeviceOrientation::Portrait);
    else if (o == QLatin1String("Landscape"))
        DeviceOrientation::instance()->setOrientation(DeviceOrientation::Landscape);
    else if (o == QLatin1String("Portrait (inverted)"))
        DeviceOrientation::instance()->setOrientation(DeviceOrientation::PortraitInverted);
    else if (o == QLatin1String("Landscape (inverted)"))
        DeviceOrientation::instance()->setOrientation(DeviceOrientation::LandscapeInverted);
#endif
}

void QDeclarativeViewer::orientationChanged()
{
    updateSizeHints();
}

void QDeclarativeViewer::setDeviceKeys(bool on)
{
    devicemode = on;
}

void QDeclarativeViewer::setNetworkCacheSize(int size)
{
    namFactory->setCacheSize(size);
}

void QDeclarativeViewer::setUseGL(bool useGL)
{
#ifdef GL_SUPPORTED
    if (useGL) {
        QGLFormat format = QGLFormat::defaultFormat();
#ifdef Q_WS_MAC
        format.setSampleBuffers(true);
#else
        format.setSampleBuffers(false);
#endif

        QGLWidget *glWidget = new QGLWidget(format);
        //### potentially faster, but causes junk to appear if top-level is Item, not Rectangle
        //glWidget->setAutoFillBackground(false);

        canvas->setViewport(glWidget);
    }
#else
    Q_UNUSED(useGL)
#endif
}

void QDeclarativeViewer::setUseNativeFileBrowser(bool use)
{
    useQmlFileBrowser = !use;
}

void QDeclarativeViewer::setSizeToView(bool sizeToView)
{
    QDeclarativeView::ResizeMode resizeMode = sizeToView ? QDeclarativeView::SizeRootObjectToView : QDeclarativeView::SizeViewToRootObject;
    if (resizeMode != canvas->resizeMode()) {
        canvas->setResizeMode(resizeMode);
        updateSizeHints();
    }
}

void QDeclarativeViewer::updateSizeHints(bool initial)
{
    static bool isRecursive = false;

    if (isRecursive)
        return;
    isRecursive = true;

    if (initial || (canvas->resizeMode() == QDeclarativeView::SizeViewToRootObject)) {
        QSize newWindowSize = initial ? initialSize : canvas->sizeHint();
        //qWarning() << "USH:" << (initial ? "INIT:" : "V2R:") << "setting fixed size " << newWindowSize;
        if (!isFullScreen() && !isMaximized()) {
            canvas->setFixedSize(newWindowSize);
            resize(1, 1);
            layout()->setSizeConstraint(QLayout::SetFixedSize);
            layout()->activate();
        }
    }
    //qWarning() << "USH: R2V: setting free size ";
    layout()->setSizeConstraint(QLayout::SetNoConstraint);
    layout()->activate();
    setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
    canvas->setMinimumSize(QSize(0,0));
    canvas->setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));

    isRecursive = false;
}

void QDeclarativeViewer::registerTypes()
{
    static bool registered = false;

    if (!registered) {
        // registering only for exposing the DeviceOrientation::Orientation enum
        qmlRegisterUncreatableType<DeviceOrientation>("Qt",4,7,"Orientation","");
        registered = true;
    }
}

QT_END_NAMESPACE

#include "qmlruntime.moc"