summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/CODEOWNERS3
-rw-r--r--.gitignore1
-rw-r--r--.travis.yml24
-rw-r--r--core/SCsub1
-rw-r--r--core/array.cpp10
-rw-r--r--core/bind/core_bind.cpp66
-rw-r--r--core/bind/core_bind.h5
-rw-r--r--core/class_db.cpp52
-rw-r--r--core/class_db.h3
-rw-r--r--core/color.cpp34
-rw-r--r--core/crypto/SCsub38
-rw-r--r--core/crypto/crypto.cpp170
-rw-r--r--core/crypto/crypto.h105
-rw-r--r--core/crypto/crypto_core.cpp (renamed from core/math/crypto_core.cpp)32
-rw-r--r--core/crypto/crypto_core.h (renamed from core/math/crypto_core.h)20
-rw-r--r--core/crypto/hashing_context.cpp137
-rw-r--r--core/crypto/hashing_context.h66
-rw-r--r--core/engine.cpp5
-rw-r--r--core/hash_map.h16
-rw-r--r--core/image.cpp65
-rw-r--r--core/image.h2
-rw-r--r--core/input_map.cpp5
-rw-r--r--core/io/config_file.cpp9
-rw-r--r--core/io/file_access_buffered.cpp12
-rw-r--r--core/io/file_access_buffered_fa.h5
-rw-r--r--core/io/file_access_encrypted.cpp7
-rw-r--r--core/io/file_access_pack.cpp19
-rw-r--r--core/io/ip_address.cpp14
-rw-r--r--core/io/marshalls.cpp10
-rw-r--r--core/io/multiplayer_api.cpp162
-rw-r--r--core/io/packet_peer.cpp3
-rw-r--r--core/io/pck_packer.cpp5
-rw-r--r--core/io/resource_format_binary.cpp46
-rw-r--r--core/io/resource_loader.cpp42
-rw-r--r--core/io/resource_saver.cpp6
-rw-r--r--core/io/stream_peer_ssl.cpp68
-rw-r--r--core/io/stream_peer_ssl.h13
-rw-r--r--core/io/translation_loader_po.cpp25
-rw-r--r--core/io/xml_parser.cpp6
-rw-r--r--core/math/SCsub33
-rw-r--r--core/math/a_star.cpp271
-rw-r--r--core/math/a_star.h36
-rw-r--r--core/math/basis.cpp5
-rw-r--r--core/math/delaunay.h4
-rw-r--r--core/math/expression.cpp11
-rw-r--r--core/math/geometry.h3
-rw-r--r--core/math/octree.h5
-rw-r--r--core/math/vector2.cpp13
-rw-r--r--core/math/vector2.h24
-rw-r--r--core/math/vector3.h40
-rw-r--r--core/message_queue.cpp11
-rw-r--r--core/node_path.cpp3
-rw-r--r--core/oa_hash_map.h66
-rw-r--r--core/object.cpp79
-rw-r--r--core/object.h2
-rw-r--r--core/os/file_access.cpp8
-rw-r--r--core/os/input.cpp1
-rw-r--r--core/os/input.h1
-rw-r--r--core/os/main_loop.cpp8
-rw-r--r--core/os/main_loop.h1
-rw-r--r--core/os/os.cpp13
-rw-r--r--core/os/os.h6
-rw-r--r--core/pool_allocator.cpp7
-rw-r--r--core/pool_vector.cpp3
-rw-r--r--core/pool_vector.h6
-rw-r--r--core/project_settings.cpp26
-rw-r--r--core/register_core_types.cpp24
-rw-r--r--core/resource.cpp8
-rw-r--r--core/script_debugger_remote.cpp9
-rw-r--r--core/translation.cpp3
-rw-r--r--core/ustring.cpp17
-rw-r--r--core/variant.cpp5
-rw-r--r--core/variant_call.cpp29
-rw-r--r--doc/classes/AStar.xml23
-rw-r--r--doc/classes/AStar2D.xml23
-rw-r--r--doc/classes/AnimationPlayer.xml1
-rw-r--r--doc/classes/ClassDB.xml4
-rw-r--r--doc/classes/Control.xml14
-rw-r--r--doc/classes/Crypto.xml43
-rw-r--r--doc/classes/CryptoKey.xml29
-rw-r--r--doc/classes/Directory.xml4
-rw-r--r--doc/classes/FileDialog.xml2
-rw-r--r--doc/classes/GeometryInstance.xml12
-rw-r--r--doc/classes/HashingContext.xml41
-rw-r--r--doc/classes/Input.xml20
-rw-r--r--doc/classes/MainLoop.xml12
-rw-r--r--doc/classes/OS.xml44
-rw-r--r--doc/classes/PoolByteArray.xml13
-rw-r--r--doc/classes/ProjectSettings.xml4
-rw-r--r--doc/classes/ResourceFormatLoaderCrypto.xml13
-rw-r--r--doc/classes/ResourceFormatSaverCrypto.xml13
-rw-r--r--doc/classes/RigidBody2D.xml2
-rw-r--r--doc/classes/SceneTree.xml9
-rw-r--r--doc/classes/StreamPeerSSL.xml10
-rw-r--r--doc/classes/TextEdit.xml4
-rw-r--r--doc/classes/Tree.xml2
-rw-r--r--doc/classes/TreeItem.xml20
-rw-r--r--doc/classes/Vector2.xml33
-rw-r--r--doc/classes/Vector3.xml31
-rw-r--r--doc/classes/VisualShaderNodeCustom.xml30
-rw-r--r--doc/classes/VisualShaderNodeGlobalExpression.xml13
-rw-r--r--doc/classes/VisualShaderNodeGroupBase.xml4
-rw-r--r--doc/classes/X509Certificate.xml29
-rw-r--r--drivers/gles2/rasterizer_canvas_gles2.cpp7
-rw-r--r--drivers/gles2/rasterizer_scene_gles2.cpp3
-rw-r--r--drivers/gles2/rasterizer_storage_gles2.cpp8
-rw-r--r--drivers/gles2/shader_compiler_gles2.cpp13
-rw-r--r--drivers/gles2/shaders/stdlib.glsl75
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.cpp5
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp3
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.cpp5
-rw-r--r--drivers/gles3/shader_compiler_gles3.cpp11
-rw-r--r--drivers/gles3/shaders/copy.glsl4
-rw-r--r--drivers/png/png_driver_common.cpp9
-rw-r--r--drivers/png/resource_saver_png.cpp5
-rw-r--r--drivers/unix/file_access_unix.cpp19
-rw-r--r--drivers/unix/ip_unix.cpp4
-rw-r--r--drivers/unix/os_unix.cpp20
-rw-r--r--drivers/wasapi/audio_driver_wasapi.cpp3
-rw-r--r--drivers/windows/file_access_windows.cpp22
-rw-r--r--drivers/xaudio2/audio_driver_xaudio2.cpp21
-rw-r--r--editor/animation_track_editor.cpp17
-rw-r--r--editor/code_editor.cpp2
-rw-r--r--editor/collada/collada.cpp6
-rw-r--r--editor/connections_dialog.cpp7
-rw-r--r--editor/doc/doc_data.cpp24
-rw-r--r--editor/editor_about.cpp4
-rw-r--r--editor/editor_asset_installer.cpp4
-rw-r--r--editor/editor_autoload_settings.cpp16
-rw-r--r--editor/editor_data.cpp21
-rw-r--r--editor/editor_data.h1
-rw-r--r--editor/editor_export.cpp10
-rw-r--r--editor/editor_file_dialog.cpp6
-rw-r--r--editor/editor_file_system.cpp3
-rw-r--r--editor/editor_help.cpp15
-rw-r--r--editor/editor_help.h1
-rw-r--r--editor/editor_help_search.cpp2
-rw-r--r--editor/editor_node.cpp103
-rw-r--r--editor/editor_node.h5
-rw-r--r--editor/editor_path.cpp3
-rw-r--r--editor/editor_plugin.cpp7
-rw-r--r--editor/editor_plugin.h5
-rw-r--r--editor/editor_properties.cpp15
-rw-r--r--editor/editor_resource_preview.cpp6
-rw-r--r--editor/editor_settings.cpp64
-rw-r--r--editor/editor_settings.h3
-rw-r--r--editor/editor_spin_slider.cpp56
-rw-r--r--editor/editor_themes.cpp5
-rw-r--r--editor/export_template_manager.cpp6
-rw-r--r--editor/file_type_cache.cpp5
-rw-r--r--editor/filesystem_dock.cpp413
-rw-r--r--editor/filesystem_dock.h8
-rw-r--r--editor/find_in_files.cpp8
-rw-r--r--editor/icons/icon_editor_curve_handle.svg1
-rw-r--r--editor/icons/icon_editor_path_sharp_handle.svg1
-rw-r--r--editor/icons/icon_editor_path_smooth_handle.svg1
-rw-r--r--editor/icons/icon_timeline_indicator.svg1
-rw-r--r--editor/import/editor_import_collada.cpp24
-rw-r--r--editor/import/editor_scene_importer_gltf.cpp5
-rw-r--r--editor/import/resource_importer_csv_translation.cpp3
-rw-r--r--editor/import/resource_importer_obj.cpp6
-rw-r--r--editor/import/resource_importer_scene.cpp66
-rw-r--r--editor/import/resource_importer_scene.h2
-rw-r--r--editor/import/resource_importer_wav.cpp15
-rw-r--r--editor/node_dock.cpp7
-rw-r--r--editor/plugins/abstract_polygon_2d_editor.cpp3
-rw-r--r--editor/plugins/asset_library_editor_plugin.cpp84
-rw-r--r--editor/plugins/asset_library_editor_plugin.h2
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp260
-rw-r--r--editor/plugins/canvas_item_editor_plugin.h38
-rw-r--r--editor/plugins/cpu_particles_2d_editor_plugin.cpp6
-rw-r--r--editor/plugins/multimesh_editor_plugin.cpp9
-rw-r--r--editor/plugins/particles_2d_editor_plugin.cpp6
-rw-r--r--editor/plugins/path_2d_editor_plugin.cpp42
-rw-r--r--editor/plugins/path_editor_plugin.cpp3
-rw-r--r--editor/plugins/polygon_2d_editor_plugin.cpp7
-rw-r--r--editor/plugins/shader_editor_plugin.cpp1
-rw-r--r--editor/plugins/spatial_editor_plugin.cpp130
-rw-r--r--editor/plugins/theme_editor_plugin.cpp6
-rw-r--r--editor/plugins/tile_map_editor_plugin.cpp7
-rw-r--r--editor/plugins/tile_set_editor_plugin.cpp88
-rw-r--r--editor/plugins/tile_set_editor_plugin.h6
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp182
-rw-r--r--editor/plugins/visual_shader_editor_plugin.h14
-rw-r--r--editor/project_export.cpp13
-rw-r--r--editor/project_manager.cpp207
-rw-r--r--editor/project_manager.h3
-rw-r--r--editor/scene_tree_dock.cpp12
-rw-r--r--editor/scene_tree_editor.cpp54
-rw-r--r--editor/script_create_dialog.cpp118
-rw-r--r--editor/script_create_dialog.h19
-rw-r--r--editor/script_editor_debugger.cpp2
-rw-r--r--editor/spatial_editor_gizmos.cpp24
-rw-r--r--main/gamecontrollerdb.txt51
-rw-r--r--main/input_default.cpp4
-rw-r--r--main/input_default.h1
-rw-r--r--main/main.cpp27
-rw-r--r--main/tests/test_oa_hash_map.cpp19
-rwxr-xr-xmisc/hooks/pre-commit-clang-format3
-rw-r--r--misc/ide/jetbrains/build.gradle2
-rw-r--r--misc/ide/jetbrains/gradle/wrapper/gradle-wrapper.properties4
-rwxr-xr-xmisc/travis/clang-format.sh2
-rw-r--r--modules/arkit/arkit_interface.h6
-rw-r--r--modules/arkit/arkit_interface.mm6
-rw-r--r--modules/arkit/arkit_session_delegate.h6
-rw-r--r--modules/arkit/arkit_session_delegate.mm6
-rw-r--r--modules/csg/csg.cpp10
-rw-r--r--modules/etc/texture_loader_pkm.cpp4
-rw-r--r--modules/gdnative/nativescript/nativescript.cpp2
-rw-r--r--modules/gdnative/pluginscript/pluginscript_script.cpp2
-rw-r--r--modules/gdscript/SCsub1
-rw-r--r--modules/gdscript/gdscript.cpp2
-rw-r--r--modules/gdscript/gdscript_editor.cpp2
-rw-r--r--modules/gdscript/gdscript_parser.cpp460
-rw-r--r--modules/gdscript/gdscript_parser.h1
-rw-r--r--modules/gdscript/language_server/gdscript_extend_parser.cpp759
-rw-r--r--modules/gdscript/language_server/gdscript_extend_parser.h103
-rw-r--r--modules/gdscript/language_server/gdscript_language_protocol.cpp211
-rw-r--r--modules/gdscript/language_server/gdscript_language_protocol.h93
-rw-r--r--modules/gdscript/language_server/gdscript_language_server.cpp88
-rw-r--r--modules/gdscript/language_server/gdscript_language_server.h60
-rw-r--r--modules/gdscript/language_server/gdscript_text_document.cpp391
-rw-r--r--modules/gdscript/language_server/gdscript_text_document.h73
-rw-r--r--modules/gdscript/language_server/gdscript_workspace.cpp504
-rw-r--r--modules/gdscript/language_server/gdscript_workspace.h91
-rw-r--r--modules/gdscript/language_server/lsp.hpp1506
-rw-r--r--modules/gdscript/register_types.cpp7
-rw-r--r--modules/hdr/image_loader_hdr.cpp9
-rw-r--r--modules/jsonrpc/SCsub7
-rw-r--r--modules/jsonrpc/config.py5
-rw-r--r--modules/jsonrpc/jsonrpc.cpp171
-rw-r--r--modules/jsonrpc/jsonrpc.h70
-rw-r--r--modules/jsonrpc/register_types.cpp40
-rw-r--r--modules/jsonrpc/register_types.h32
-rw-r--r--modules/mbedtls/crypto_mbedtls.cpp285
-rw-r--r--modules/mbedtls/crypto_mbedtls.h124
-rwxr-xr-xmodules/mbedtls/register_types.cpp6
-rw-r--r--modules/mbedtls/ssl_context_mbedtls.cpp151
-rw-r--r--modules/mbedtls/ssl_context_mbedtls.h73
-rwxr-xr-xmodules/mbedtls/stream_peer_mbedtls.cpp (renamed from modules/mbedtls/stream_peer_mbed_tls.cpp)101
-rwxr-xr-xmodules/mbedtls/stream_peer_mbedtls.h (renamed from modules/mbedtls/stream_peer_mbed_tls.h)24
-rw-r--r--modules/mono/SCsub16
-rw-r--r--modules/mono/build_scripts/make_android_mono_config.py19
-rw-r--r--modules/mono/class_db_api_json.cpp4
-rw-r--r--modules/mono/class_db_api_json.h4
-rw-r--r--modules/mono/csharp_script.cpp2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj1
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj1
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj1
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj1
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj1
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs2
-rw-r--r--modules/mono/editor/editor_internal_calls.cpp2
-rw-r--r--modules/mono/glue/Managed/Files/Vector2.cs49
-rw-r--r--modules/mono/glue/Managed/Files/Vector3.cs46
-rw-r--r--modules/mono/glue/Managed/Managed.csproj1
-rw-r--r--modules/mono/mono_gd/android_mono_config.h43
-rw-r--r--modules/mono/mono_gd/gd_mono.cpp2
-rw-r--r--modules/webp/image_loader_webp.cpp7
-rw-r--r--modules/webrtc/register_types.cpp7
-rw-r--r--modules/webrtc/webrtc_data_channel.cpp2
-rw-r--r--modules/webrtc/webrtc_data_channel.h4
-rw-r--r--modules/webrtc/webrtc_data_channel_js.cpp2
-rw-r--r--modules/websocket/websocket_multiplayer_peer.cpp15
-rw-r--r--modules/websocket/wsl_client.cpp26
-rw-r--r--modules/websocket/wsl_peer.cpp4
-rw-r--r--modules/websocket/wsl_server.cpp25
-rw-r--r--modules/xatlas_unwrap/register_types.cpp3
-rw-r--r--platform/android/SCsub9
-rw-r--r--platform/android/detect.py20
-rw-r--r--platform/android/java/AndroidManifest.xml87
-rw-r--r--platform/android/java/README.md47
-rw-r--r--platform/android/java/THIRDPARTY.md39
-rw-r--r--platform/android/java/aidl/com/android/vending/billing/IInAppBillingService.aidl201
-rw-r--r--platform/android/java/aidl/com/android/vending/licensing/ILicenseResultListener.aidl (renamed from platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.aidl)2
-rw-r--r--platform/android/java/aidl/com/android/vending/licensing/ILicensingService.aidl (renamed from platform/android/java/src/com/google/android/vending/licensing/ILicensingService.aidl)2
-rw-r--r--platform/android/java/build.gradle138
-rw-r--r--platform/android/java/gradle/wrapper/gradle-wrapper.properties2
-rw-r--r--platform/android/java/patches/com.google.android.vending.expansion.downloader.patch300
-rw-r--r--platform/android/java/patches/com.google.android.vending.licensing.patch42
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/Constants.java165
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/DownloadProgressInfo.java80
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java311
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java284
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java466
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderClient.java56
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderService.java28
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/IStub.java6
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java175
-rw-r--r--[-rwxr-xr-x]platform/android/java/src/com/google/android/vending/expansion/downloader/impl/CustomIntentService.java131
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadInfo.java112
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java343
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java1401
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java1898
-rw-r--r--[-rwxr-xr-x]platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadsDB.java885
-rw-r--r--platform/android/java/src/com/google/android/vending/expansion/downloader/impl/HttpDateTime.java295
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/AESObfuscator.java124
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/APKExpansionPolicy.java541
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/DeviceLimiter.java4
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.java100
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/ILicensingService.java100
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/LicenseChecker.java554
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/LicenseCheckerCallback.java26
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/LicenseValidator.java367
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/NullDeviceLimiter.java6
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/Obfuscator.java8
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/Policy.java26
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java84
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/ResponseData.java83
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/ServerManagedPolicy.java335
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/StrictPolicy.java75
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/ValidationException.java14
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/util/Base64.java704
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/util/Base64DecoderException.java14
-rw-r--r--platform/android/java/src/com/google/android/vending/licensing/util/URIQueryDecoder.java50
-rw-r--r--platform/android/java/src/org/godotengine/godot/Godot.java94
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotLib.java148
-rw-r--r--platform/android/java/src/org/godotengine/godot/xr/XRMode.java8
-rw-r--r--platform/android/java_godot_lib_jni.cpp2
-rw-r--r--platform/android/java_godot_lib_jni.h2
-rw-r--r--platform/android/java_godot_wrapper.cpp19
-rw-r--r--platform/android/java_godot_wrapper.h4
-rw-r--r--platform/android/os_android.cpp6
-rw-r--r--platform/android/os_android.h1
-rw-r--r--platform/iphone/app_delegate.mm5
-rw-r--r--platform/iphone/os_iphone.cpp6
-rw-r--r--platform/iphone/os_iphone.h1
-rw-r--r--platform/iphone/view_controller.h4
-rw-r--r--platform/iphone/view_controller.mm12
-rw-r--r--platform/osx/os_osx.h25
-rw-r--r--platform/osx/os_osx.mm94
-rw-r--r--platform/uwp/export/export.cpp2
-rw-r--r--scene/2d/navigation_2d.cpp4
-rw-r--r--scene/2d/path_2d.cpp2
-rw-r--r--scene/2d/physics_body_2d.cpp6
-rw-r--r--scene/3d/collision_polygon.cpp2
-rw-r--r--scene/3d/physics_body.cpp4
-rw-r--r--scene/3d/physics_body.h1
-rw-r--r--scene/3d/ray_cast.cpp2
-rw-r--r--scene/animation/animation_player.cpp4
-rw-r--r--scene/animation/animation_tree.cpp1
-rw-r--r--scene/gui/color_picker.cpp32
-rw-r--r--scene/gui/color_picker.h2
-rw-r--r--scene/gui/control.cpp14
-rw-r--r--scene/gui/file_dialog.cpp2
-rw-r--r--scene/gui/graph_edit.cpp10
-rw-r--r--scene/gui/text_edit.cpp937
-rw-r--r--scene/gui/text_edit.h24
-rw-r--r--scene/gui/tree.cpp29
-rw-r--r--scene/gui/tree.h4
-rw-r--r--scene/main/node.cpp11
-rw-r--r--scene/main/node.h2
-rw-r--r--scene/main/scene_tree.cpp7
-rw-r--r--scene/main/scene_tree.h1
-rw-r--r--scene/register_scene_types.cpp3
-rw-r--r--scene/resources/animation.cpp8
-rw-r--r--scene/resources/default_theme/default_theme.cpp10
-rw-r--r--scene/resources/dynamic_font.cpp8
-rw-r--r--scene/resources/visual_shader.cpp69
-rw-r--r--scene/resources/visual_shader.h19
-rw-r--r--servers/arvr/arvr_interface.h2
-rw-r--r--servers/physics/body_sw.cpp1
-rw-r--r--servers/physics_2d/body_2d_sw.cpp30
-rw-r--r--servers/physics_2d/body_2d_sw.h1
-rw-r--r--servers/visual/shader_language.cpp195
-rw-r--r--servers/visual/shader_language.h13
368 files changed, 15890 insertions, 7805 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 399fca03e8..3bbe47af2a 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -30,7 +30,6 @@ doc_classes/* @godotengine/documentation
/modules/bullet/ @AndreaCatania
/modules/csg/ @BastiaanOlij
/modules/enet/ @godotengine/network
-/modules/gdnative/ @karroffel
/modules/gdnative/*arvr/ @BastiaanOlij
/modules/gdscript/ @vnen @bojidar-bg
/modules/mbedtls/ @godotengine/network
@@ -45,6 +44,6 @@ doc_classes/* @godotengine/documentation
/platform/uwp/ @vnen
/server/physics*/ @reduz @AndreaCatania
-/server/visual*/ @reduz @karroffel
+/server/visual*/ @reduz
/thirdparty/ @akien-mga
diff --git a/.gitignore b/.gitignore
index f43f68f25f..0ee2a8b382 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
# Godot auto generated files
*.gen.*
+.import/
# Documentation generated by doxygen or from classes.xml
doc/_build/
diff --git a/.travis.yml b/.travis.yml
index b52e40200f..a763fa5376 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,7 +2,10 @@ language: cpp
# OS config, depends on actual 'os' in build matrix
dist: xenial
-sudo: false
+
+stages:
+ - check
+ - build
env:
global:
@@ -18,6 +21,7 @@ cache:
matrix:
include:
- name: Static checks (clang-format)
+ stage: check
env: STATIC_CHECKS=yes
os: linux
compiler: gcc
@@ -29,6 +33,7 @@ matrix:
- clang-format-8
- name: Linux editor (debug, GCC 9, with Mono)
+ stage: build
env: PLATFORM=x11 TOOLS=yes TARGET=debug CACHE_NAME=${PLATFORM}-tools-mono-gcc-9 MATRIX_EVAL="CC=gcc-9 && CXX=g++-9" EXTRA_ARGS="module_mono_enabled=yes mono_glue=no warnings=extra werror=yes"
os: linux
compiler: gcc-9
@@ -52,6 +57,7 @@ matrix:
branch_pattern: coverity_scan
- name: Linux export template (release, Clang)
+ stage: build
env: PLATFORM=x11 TOOLS=no TARGET=release CACHE_NAME=${PLATFORM}-clang EXTRA_ARGS="warnings=extra werror=yes"
os: linux
compiler: clang
@@ -61,22 +67,26 @@ matrix:
- *linux_deps
- name: Android export template (release_debug, Clang)
+ stage: build
env: PLATFORM=android TOOLS=no TARGET=release_debug CACHE_NAME=${PLATFORM}-clang EXTRA_ARGS="warnings=extra werror=yes"
os: linux
compiler: clang
- name: macOS editor (debug, Clang)
+ stage: build
env: PLATFORM=osx TOOLS=yes TARGET=debug CACHE_NAME=${PLATFORM}-tools-clang
os: osx
compiler: clang
- name: iOS export template (debug, Clang)
+ stage: build
env: PLATFORM=iphone TOOLS=no TARGET=debug CACHE_NAME=${PLATFORM}-clang
os: osx
compiler: clang
- - name: Linux headless editor (release_debug, GCC 9)
- env: PLATFORM=server TOOLS=yes TARGET=release_debug CACHE_NAME=${PLATFORM}-tools-gcc-9 MATRIX_EVAL="CC=gcc-9 && CXX=g++-9" EXTRA_ARGS="warnings=extra werror=yes"
+ - name: Linux headless editor (release_debug, GCC 9, testing project exporting and script running)
+ stage: build
+ env: PLATFORM=server TOOLS=yes TARGET=release_debug CACHE_NAME=${PLATFORM}-tools-gcc-9 MATRIX_EVAL="CC=gcc-9 && CXX=g++-9" EXTRA_ARGS="warnings=extra werror=yes" TEST_PROJECT=yes
os: linux
compiler: gcc-9
addons:
@@ -88,6 +98,7 @@ matrix:
- *linux_deps
- name: Linux export template (release_debug, GCC 5, without 3D support)
+ stage: build
env: PLATFORM=x11 TOOLS=no TARGET=release_debug CACHE_NAME=${PLATFORM}-gcc-5 EXTRA_ARGS="disable_3d=yes"
os: linux
compiler: gcc
@@ -124,5 +135,10 @@ script:
- if [ "$STATIC_CHECKS" = "yes" ]; then
sh ./misc/travis/clang-format.sh;
else
- scons -j2 CC=$CC CXX=$CXX platform=$PLATFORM tools=$TOOLS target=$TARGET $OPTIONS $EXTRA_ARGS;
+ scons -j2 CC=$CC CXX=$CXX platform=$PLATFORM tools=$TOOLS target=$TARGET $OPTIONS $EXTRA_ARGS &&
+ if [ "$TEST_PROJECT" = "yes" ]; then
+ git clone --depth 1 "https://github.com/godotengine/godot-tests.git";
+ sed -i "s:custom_template/release=\"\":custom_template/release=\"$(readlink -e bin/godot_server.x11.opt.tools.64)\":" godot-tests/tests/project_export/export_presets.cfg;
+ godot-tests/tests/project_export/test_project.sh "bin/godot_server.x11.opt.tools.64";
+ fi
fi
diff --git a/core/SCsub b/core/SCsub
index 85e5f1b089..ed9a0a231d 100644
--- a/core/SCsub
+++ b/core/SCsub
@@ -159,6 +159,7 @@ env.CommandNoCache('#core/license.gen.h', ["../COPYRIGHT.txt", "../LICENSE.txt"]
# Chain load SCsubs
SConscript('os/SCsub')
SConscript('math/SCsub')
+SConscript('crypto/SCsub')
SConscript('io/SCsub')
SConscript('bind/SCsub')
diff --git a/core/array.cpp b/core/array.cpp
index a334af2c04..108d9f7386 100644
--- a/core/array.cpp
+++ b/core/array.cpp
@@ -133,18 +133,12 @@ void Array::erase(const Variant &p_value) {
}
Variant Array::front() const {
- if (_p->array.size() == 0) {
- ERR_EXPLAIN("Can't take value from empty array");
- ERR_FAIL_V(Variant());
- }
+ ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
return operator[](0);
}
Variant Array::back() const {
- if (_p->array.size() == 0) {
- ERR_EXPLAIN("Can't take value from empty array");
- ERR_FAIL_V(Variant());
- }
+ ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
return operator[](_p->array.size() - 1);
}
diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp
index b41b84ab1e..b5e84d49a0 100644
--- a/core/bind/core_bind.cpp
+++ b/core/bind/core_bind.cpp
@@ -30,11 +30,11 @@
#include "core_bind.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/file_access_compressed.h"
#include "core/io/file_access_encrypted.h"
#include "core/io/json.h"
#include "core/io/marshalls.h"
-#include "core/math/crypto_core.h"
#include "core/math/geometry.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
@@ -73,10 +73,7 @@ RES _ResourceLoader::load(const String &p_path, const String &p_type_hint, bool
Error err = OK;
RES ret = ResourceLoader::load(p_path, p_type_hint, p_no_cache, &err);
- if (err != OK) {
- ERR_EXPLAIN("Error loading resource: '" + p_path + "'");
- ERR_FAIL_V(ret);
- }
+ ERR_FAIL_COND_V_MSG(err != OK, ret, "Error loading resource: '" + p_path + "'.");
return ret;
}
@@ -148,10 +145,7 @@ _ResourceLoader::_ResourceLoader() {
}
Error _ResourceSaver::save(const String &p_path, const RES &p_resource, SaverFlags p_flags) {
- if (p_resource.is_null()) {
- ERR_EXPLAIN("Can't save empty resource to path: " + String(p_path))
- ERR_FAIL_V(ERR_INVALID_PARAMETER);
- }
+ ERR_FAIL_COND_V_MSG(p_resource.is_null(), ERR_INVALID_PARAMETER, "Can't save empty resource to path: " + String(p_path) + ".");
return ResourceSaver::save(p_path, p_resource, p_flags);
}
@@ -191,10 +185,31 @@ _ResourceSaver::_ResourceSaver() {
/////////////////OS
+void _OS::global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta) {
+
+ OS::get_singleton()->global_menu_add_item(p_menu, p_label, p_signal, p_meta);
+}
+
+void _OS::global_menu_add_separator(const String &p_menu) {
+
+ OS::get_singleton()->global_menu_add_separator(p_menu);
+}
+
+void _OS::global_menu_remove_item(const String &p_menu, int p_idx) {
+
+ OS::get_singleton()->global_menu_remove_item(p_menu, p_idx);
+}
+
+void _OS::global_menu_clear(const String &p_menu) {
+
+ OS::get_singleton()->global_menu_clear(p_menu);
+}
+
Point2 _OS::get_mouse_position() const {
return OS::get_singleton()->get_mouse_position();
}
+
void _OS::set_window_title(const String &p_title) {
OS::get_singleton()->set_window_title(p_title);
@@ -208,6 +223,7 @@ int _OS::get_mouse_button_state() const {
String _OS::get_unique_id() const {
return OS::get_singleton()->get_unique_id();
}
+
bool _OS::has_touchscreen_ui_hint() const {
return OS::get_singleton()->has_touchscreen_ui_hint();
@@ -217,6 +233,7 @@ void _OS::set_clipboard(const String &p_text) {
OS::get_singleton()->set_clipboard(p_text);
}
+
String _OS::get_clipboard() const {
return OS::get_singleton()->get_clipboard();
@@ -263,12 +280,14 @@ void _OS::set_video_mode(const Size2 &p_size, bool p_fullscreen, bool p_resizeab
vm.resizable = p_resizeable;
OS::get_singleton()->set_video_mode(vm, p_screen);
}
+
Size2 _OS::get_video_mode(int p_screen) const {
OS::VideoMode vm;
vm = OS::get_singleton()->get_video_mode(p_screen);
return Size2(vm.width, vm.height);
}
+
bool _OS::is_video_mode_fullscreen(int p_screen) const {
OS::VideoMode vm;
@@ -727,22 +746,16 @@ int64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};
- ERR_EXPLAIN("Invalid second value of: " + itos(second));
- ERR_FAIL_COND_V(second > 59, 0);
+ ERR_FAIL_COND_V_MSG(second > 59, 0, "Invalid second value of: " + itos(second) + ".");
- ERR_EXPLAIN("Invalid minute value of: " + itos(minute));
- ERR_FAIL_COND_V(minute > 59, 0);
+ ERR_FAIL_COND_V_MSG(minute > 59, 0, "Invalid minute value of: " + itos(minute) + ".");
- ERR_EXPLAIN("Invalid hour value of: " + itos(hour));
- ERR_FAIL_COND_V(hour > 23, 0);
+ ERR_FAIL_COND_V_MSG(hour > 23, 0, "Invalid hour value of: " + itos(hour) + ".");
- ERR_EXPLAIN("Invalid month value of: " + itos(month));
- ERR_FAIL_COND_V(month > 12 || month == 0, 0);
+ ERR_FAIL_COND_V_MSG(month > 12 || month == 0, 0, "Invalid month value of: " + itos(month) + ".");
// Do this check after month is tested as valid
- ERR_EXPLAIN("Invalid day value of: " + itos(day) + " which is larger than " + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1]) + " or 0");
- ERR_FAIL_COND_V(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1] || day == 0, 0);
-
+ ERR_FAIL_COND_V_MSG(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1] || day == 0, 0, "Invalid day value of: " + itos(day) + " which is larger than " + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month - 1]) + " or 0.");
// Calculate all the seconds from months past in this year
uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month - 1] * SECONDS_PER_DAY;
@@ -1137,6 +1150,11 @@ void _OS::_bind_methods() {
//ClassDB::bind_method(D_METHOD("is_video_mode_resizable","screen"),&_OS::is_video_mode_resizable,DEFVAL(0));
//ClassDB::bind_method(D_METHOD("get_fullscreen_mode_list","screen"),&_OS::get_fullscreen_mode_list,DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("global_menu_add_item", "menu", "label", "id", "meta"), &_OS::global_menu_add_item);
+ ClassDB::bind_method(D_METHOD("global_menu_add_separator", "menu"), &_OS::global_menu_add_separator);
+ ClassDB::bind_method(D_METHOD("global_menu_remove_item", "menu", "idx"), &_OS::global_menu_remove_item);
+ ClassDB::bind_method(D_METHOD("global_menu_clear", "menu"), &_OS::global_menu_clear);
+
ClassDB::bind_method(D_METHOD("get_video_driver_count"), &_OS::get_video_driver_count);
ClassDB::bind_method(D_METHOD("get_video_driver_name", "driver"), &_OS::get_video_driver_name);
ClassDB::bind_method(D_METHOD("get_current_video_driver"), &_OS::get_current_video_driver);
@@ -2621,8 +2639,7 @@ void _Thread::_start_func(void *ud) {
}
}
- ERR_EXPLAIN("Could not call function '" + t->target_method.operator String() + "'' starting thread ID: " + t->get_id() + " Reason: " + reason);
- ERR_FAIL();
+ ERR_FAIL_MSG("Could not call function '" + t->target_method.operator String() + "'' starting thread ID: " + t->get_id() + " Reason: " + reason + ".");
}
}
@@ -2704,10 +2721,7 @@ _Thread::_Thread() {
_Thread::~_Thread() {
- if (active) {
- ERR_EXPLAIN("Reference to a Thread object object was lost while the thread is still running...");
- }
- ERR_FAIL_COND(active);
+ ERR_FAIL_COND_MSG(active, "Reference to a Thread object object was lost while the thread is still running...");
}
/////////////////////////////////////
diff --git a/core/bind/core_bind.h b/core/bind/core_bind.h
index f0f86e003f..76ba2dc0a5 100644
--- a/core/bind/core_bind.h
+++ b/core/bind/core_bind.h
@@ -143,6 +143,11 @@ public:
MONTH_DECEMBER
};
+ void global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta);
+ void global_menu_add_separator(const String &p_menu);
+ void global_menu_remove_item(const String &p_menu, int p_idx);
+ void global_menu_clear(const String &p_menu);
+
Point2 get_mouse_position() const;
void set_window_title(const String &p_title);
int get_mouse_button_state() const;
diff --git a/core/class_db.cpp b/core/class_db.cpp
index 49e3f94d8f..3ad59bc309 100644
--- a/core/class_db.cpp
+++ b/core/class_db.cpp
@@ -836,10 +836,7 @@ void ClassDB::add_signal(StringName p_class, const MethodInfo &p_signal) {
#ifdef DEBUG_METHODS_ENABLED
ClassInfo *check = type;
while (check) {
- if (check->signal_map.has(sname)) {
- ERR_EXPLAIN("Type " + String(p_class) + " already has signal: " + String(sname));
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(check->signal_map.has(sname), "Type " + String(p_class) + " already has signal: " + String(sname) + ".");
check = check->inherits_ptr;
}
#endif
@@ -924,16 +921,11 @@ void ClassDB::add_property(StringName p_class, const PropertyInfo &p_pinfo, cons
if (p_setter) {
mb_set = get_method(p_class, p_setter);
#ifdef DEBUG_METHODS_ENABLED
- if (!mb_set) {
- ERR_EXPLAIN("Invalid Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name);
- ERR_FAIL();
- } else {
- int exp_args = 1 + (p_index >= 0 ? 1 : 0);
- if (mb_set->get_argument_count() != exp_args) {
- ERR_EXPLAIN("Invalid Function for Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name);
- ERR_FAIL();
- }
- }
+
+ ERR_FAIL_COND_MSG(!mb_set, "Invalid setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name + ".");
+
+ int exp_args = 1 + (p_index >= 0 ? 1 : 0);
+ ERR_FAIL_COND_MSG(mb_set->get_argument_count() != exp_args, "Invalid function for setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name + ".");
#endif
}
@@ -943,25 +935,15 @@ void ClassDB::add_property(StringName p_class, const PropertyInfo &p_pinfo, cons
mb_get = get_method(p_class, p_getter);
#ifdef DEBUG_METHODS_ENABLED
- if (!mb_get) {
- ERR_EXPLAIN("Invalid Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name);
- ERR_FAIL();
- } else {
+ ERR_FAIL_COND_MSG(!mb_get, "Invalid getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name + ".");
- int exp_args = 0 + (p_index >= 0 ? 1 : 0);
- if (mb_get->get_argument_count() != exp_args) {
- ERR_EXPLAIN("Invalid Function for Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name);
- ERR_FAIL();
- }
- }
+ int exp_args = 0 + (p_index >= 0 ? 1 : 0);
+ ERR_FAIL_COND_MSG(mb_get->get_argument_count() != exp_args, "Invalid function for getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name + ".");
#endif
}
#ifdef DEBUG_METHODS_ENABLED
- if (type->property_setget.has(p_pinfo.name)) {
- ERR_EXPLAIN("Object " + p_class + " already has property: " + p_pinfo.name);
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(type->property_setget.has(p_pinfo.name), "Object " + p_class + " already has property: " + p_pinfo.name + ".");
#endif
OBJTYPE_WLOCK
@@ -1240,32 +1222,26 @@ MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const c
#ifdef DEBUG_ENABLED
- if (has_method(instance_type, mdname)) {
- ERR_EXPLAIN("Class " + String(instance_type) + " already has a method " + String(mdname));
- ERR_FAIL_V(NULL);
- }
+ ERR_FAIL_COND_V_MSG(has_method(instance_type, mdname), NULL, "Class " + String(instance_type) + " already has a method " + String(mdname) + ".");
#endif
ClassInfo *type = classes.getptr(instance_type);
if (!type) {
- ERR_PRINTS("Couldn't bind method '" + mdname + "' for instance: " + instance_type);
memdelete(p_bind);
- ERR_FAIL_V(NULL);
+ ERR_FAIL_V_MSG(NULL, "Couldn't bind method '" + mdname + "' for instance: " + instance_type + ".");
}
if (type->method_map.has(mdname)) {
memdelete(p_bind);
// overloading not supported
- ERR_EXPLAIN("Method already bound: " + instance_type + "::" + mdname);
- ERR_FAIL_V(NULL);
+ ERR_FAIL_V_MSG(NULL, "Method already bound: " + instance_type + "::" + mdname + ".");
}
#ifdef DEBUG_METHODS_ENABLED
if (method_name.args.size() > p_bind->get_argument_count()) {
memdelete(p_bind);
- ERR_EXPLAIN("Method definition provides more arguments than the method actually has: " + instance_type + "::" + mdname);
- ERR_FAIL_V(NULL);
+ ERR_FAIL_V_MSG(NULL, "Method definition provides more arguments than the method actually has: " + instance_type + "::" + mdname + ".");
}
p_bind->set_argument_names(method_name.args);
diff --git a/core/class_db.h b/core/class_db.h
index 3864522be4..092469beb7 100644
--- a/core/class_db.h
+++ b/core/class_db.h
@@ -306,8 +306,7 @@ public:
if (type->method_map.has(p_name)) {
memdelete(bind);
// overloading not supported
- ERR_EXPLAIN("Method already bound: " + instance_type + "::" + p_name);
- ERR_FAIL_V(NULL);
+ ERR_FAIL_V_MSG(NULL, "Method already bound: " + instance_type + "::" + p_name + ".");
}
type->method_map[p_name] = bind;
#ifdef DEBUG_METHODS_ENABLED
diff --git a/core/color.cpp b/core/color.cpp
index 1843532124..a54a3115cc 100644
--- a/core/color.cpp
+++ b/core/color.cpp
@@ -335,36 +335,23 @@ Color Color::html(const String &p_color) {
} else if (color.length() == 6) {
alpha = false;
} else {
- ERR_EXPLAIN("Invalid Color Code: " + p_color);
- ERR_FAIL_V(Color());
+ ERR_FAIL_V_MSG(Color(), "Invalid color code: " + p_color + ".");
}
int a = 255;
if (alpha) {
a = _parse_col(color, 0);
- if (a < 0) {
- ERR_EXPLAIN("Invalid Color Code: " + p_color);
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_COND_V_MSG(a < 0, Color(), "Invalid color code: " + p_color + ".");
}
int from = alpha ? 2 : 0;
int r = _parse_col(color, from + 0);
- if (r < 0) {
- ERR_EXPLAIN("Invalid Color Code: " + p_color);
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_COND_V_MSG(r < 0, Color(), "Invalid color code: " + p_color + ".");
int g = _parse_col(color, from + 2);
- if (g < 0) {
- ERR_EXPLAIN("Invalid Color Code: " + p_color);
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_COND_V_MSG(g < 0, Color(), "Invalid color code: " + p_color + ".");
int b = _parse_col(color, from + 4);
- if (b < 0) {
- ERR_EXPLAIN("Invalid Color Code: " + p_color);
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_COND_V_MSG(b < 0, Color(), "Invalid color code: " + p_color + ".");
return Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
}
@@ -425,12 +412,8 @@ Color Color::named(const String &p_name) {
name = name.to_lower();
const Map<String, Color>::Element *color = _named_colors.find(name);
- if (color) {
- return color->value();
- } else {
- ERR_EXPLAIN("Invalid Color Name: " + p_name);
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_NULL_V_MSG(color, Color(), "Invalid color name: " + p_name + ".");
+ return color->value();
}
String _to_hex(float p_val) {
@@ -523,8 +506,7 @@ Color Color::from_hsv(float p_h, float p_s, float p_v, float p_a) const {
// FIXME: Remove once Godot 3.1 has been released
float Color::gray() const {
- ERR_EXPLAIN("Color.gray() is deprecated and will be removed in a future version. Use Color.get_v() for a better grayscale approximation.");
- WARN_DEPRECATED;
+ WARN_DEPRECATED_MSG("Color.gray() is deprecated and will be removed in a future version. Use Color.get_v() for a better grayscale approximation.");
return (r + g + b) / 3.0;
}
diff --git a/core/crypto/SCsub b/core/crypto/SCsub
new file mode 100644
index 0000000000..0a3f05d87a
--- /dev/null
+++ b/core/crypto/SCsub
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+
+Import('env')
+
+env_crypto = env.Clone()
+
+is_builtin = env["builtin_mbedtls"]
+has_module = env["module_mbedtls_enabled"]
+
+if is_builtin or not has_module:
+ # Use our headers for builtin or if the module is not going to be compiled.
+ # We decided not to depend on system mbedtls just for these few files that can
+ # be easily extracted.
+ env_crypto.Prepend(CPPPATH=["#thirdparty/mbedtls/include"])
+
+# MbedTLS core functions (for CryptoCore).
+# If the mbedtls module is compiled we don't need to add the .c files with our
+# custom config since they will be built by the module itself.
+# Only if the module is not enabled, we must compile here the required sources
+# to make a "light" build with only the necessary mbedtls files.
+if not has_module:
+ env_thirdparty = env_crypto.Clone()
+ env_thirdparty.disable_warnings()
+ # Custom config file
+ env_thirdparty.Append(CPPDEFINES=[('MBEDTLS_CONFIG_FILE', '\\"thirdparty/mbedtls/include/godot_core_mbedtls_config.h\\"')])
+ thirdparty_mbedtls_dir = "#thirdparty/mbedtls/library/"
+ thirdparty_mbedtls_sources = [
+ "aes.c",
+ "base64.c",
+ "md5.c",
+ "sha1.c",
+ "sha256.c",
+ "godot_core_mbedtls_platform.c"
+ ]
+ thirdparty_mbedtls_sources = [thirdparty_mbedtls_dir + file for file in thirdparty_mbedtls_sources]
+ env_thirdparty.add_source_files(env.core_sources, thirdparty_mbedtls_sources)
+
+env_crypto.add_source_files(env.core_sources, "*.cpp")
diff --git a/core/crypto/crypto.cpp b/core/crypto/crypto.cpp
new file mode 100644
index 0000000000..925a01b36a
--- /dev/null
+++ b/core/crypto/crypto.cpp
@@ -0,0 +1,170 @@
+/*************************************************************************/
+/* crypto.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "crypto.h"
+
+#include "core/engine.h"
+#include "core/io/certs_compressed.gen.h"
+#include "core/io/compression.h"
+
+/// Resources
+
+CryptoKey *(*CryptoKey::_create)() = NULL;
+CryptoKey *CryptoKey::create() {
+ if (_create)
+ return _create();
+ return NULL;
+}
+
+void CryptoKey::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("save", "path"), &CryptoKey::save);
+ ClassDB::bind_method(D_METHOD("load", "path"), &CryptoKey::load);
+}
+
+X509Certificate *(*X509Certificate::_create)() = NULL;
+X509Certificate *X509Certificate::create() {
+ if (_create)
+ return _create();
+ return NULL;
+}
+
+void X509Certificate::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("save", "path"), &X509Certificate::save);
+ ClassDB::bind_method(D_METHOD("load", "path"), &X509Certificate::load);
+}
+
+/// Crypto
+
+void (*Crypto::_load_default_certificates)(String p_path) = NULL;
+Crypto *(*Crypto::_create)() = NULL;
+Crypto *Crypto::create() {
+ if (_create)
+ return _create();
+ return memnew(Crypto);
+}
+
+void Crypto::load_default_certificates(String p_path) {
+
+ if (_load_default_certificates)
+ _load_default_certificates(p_path);
+}
+
+void Crypto::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("generate_random_bytes", "size"), &Crypto::generate_random_bytes);
+ ClassDB::bind_method(D_METHOD("generate_rsa", "size"), &Crypto::generate_rsa);
+ ClassDB::bind_method(D_METHOD("generate_self_signed_certificate", "key", "issuer_name", "not_before", "not_after"), &Crypto::generate_self_signed_certificate, DEFVAL("CN=myserver,O=myorganisation,C=IT"), DEFVAL("20140101000000"), DEFVAL("20340101000000"));
+}
+
+PoolByteArray Crypto::generate_random_bytes(int p_bytes) {
+ ERR_FAIL_V_MSG(PoolByteArray(), "generate_random_bytes is not available when mbedtls module is disabled.");
+}
+
+Ref<CryptoKey> Crypto::generate_rsa(int p_bytes) {
+ ERR_FAIL_V_MSG(NULL, "generate_rsa is not available when mbedtls module is disabled.");
+}
+
+Ref<X509Certificate> Crypto::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) {
+ ERR_FAIL_V_MSG(NULL, "generate_self_signed_certificate is not available when mbedtls module is disabled.");
+}
+
+Crypto::Crypto() {
+}
+
+/// Resource loader/saver
+
+RES ResourceFormatLoaderCrypto::load(const String &p_path, const String &p_original_path, Error *r_error) {
+
+ String el = p_path.get_extension().to_lower();
+ if (el == "crt") {
+ X509Certificate *cert = X509Certificate::create();
+ if (cert)
+ cert->load(p_path);
+ return cert;
+ } else if (el == "key") {
+ CryptoKey *key = CryptoKey::create();
+ if (key)
+ key->load(p_path);
+ return key;
+ }
+ return NULL;
+}
+
+void ResourceFormatLoaderCrypto::get_recognized_extensions(List<String> *p_extensions) const {
+
+ p_extensions->push_back("crt");
+ p_extensions->push_back("key");
+}
+
+bool ResourceFormatLoaderCrypto::handles_type(const String &p_type) const {
+
+ return p_type == "X509Certificate" || p_type == "CryptoKey";
+}
+
+String ResourceFormatLoaderCrypto::get_resource_type(const String &p_path) const {
+
+ String el = p_path.get_extension().to_lower();
+ if (el == "crt")
+ return "X509Certificate";
+ else if (el == "key")
+ return "CryptoKey";
+ return "";
+}
+
+Error ResourceFormatSaverCrypto::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
+
+ Error err;
+ Ref<X509Certificate> cert = p_resource;
+ Ref<CryptoKey> key = p_resource;
+ if (cert.is_valid()) {
+ err = cert->save(p_path);
+ } else if (key.is_valid()) {
+ err = key->save(p_path);
+ } else {
+ ERR_FAIL_V(ERR_INVALID_PARAMETER);
+ }
+ ERR_FAIL_COND_V(err != OK, err);
+ return OK;
+}
+
+void ResourceFormatSaverCrypto::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
+
+ const X509Certificate *cert = Object::cast_to<X509Certificate>(*p_resource);
+ const CryptoKey *key = Object::cast_to<CryptoKey>(*p_resource);
+ if (cert) {
+ p_extensions->push_back("crt");
+ }
+ if (key) {
+ p_extensions->push_back("key");
+ }
+}
+bool ResourceFormatSaverCrypto::recognize(const RES &p_resource) const {
+
+ return Object::cast_to<X509Certificate>(*p_resource) || Object::cast_to<CryptoKey>(*p_resource);
+}
diff --git a/core/crypto/crypto.h b/core/crypto/crypto.h
new file mode 100644
index 0000000000..2de81f5b57
--- /dev/null
+++ b/core/crypto/crypto.h
@@ -0,0 +1,105 @@
+/*************************************************************************/
+/* crypto.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef CRYPTO_H
+#define CRYPTO_H
+
+#include "core/reference.h"
+#include "core/resource.h"
+
+#include "core/io/resource_loader.h"
+#include "core/io/resource_saver.h"
+
+class CryptoKey : public Resource {
+ GDCLASS(CryptoKey, Resource);
+
+protected:
+ static void _bind_methods();
+ static CryptoKey *(*_create)();
+
+public:
+ static CryptoKey *create();
+ virtual Error load(String p_path) = 0;
+ virtual Error save(String p_path) = 0;
+};
+
+class X509Certificate : public Resource {
+ GDCLASS(X509Certificate, Resource);
+
+protected:
+ static void _bind_methods();
+ static X509Certificate *(*_create)();
+
+public:
+ static X509Certificate *create();
+ virtual Error load(String p_path) = 0;
+ virtual Error load_from_memory(const uint8_t *p_buffer, int p_len) = 0;
+ virtual Error save(String p_path) = 0;
+};
+
+class Crypto : public Reference {
+ GDCLASS(Crypto, Reference);
+
+protected:
+ static void _bind_methods();
+ static Crypto *(*_create)();
+ static void (*_load_default_certificates)(String p_path);
+
+public:
+ static Crypto *create();
+ static void load_default_certificates(String p_path);
+
+ virtual PoolByteArray generate_random_bytes(int p_bytes);
+ virtual Ref<CryptoKey> generate_rsa(int p_bytes);
+ virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
+
+ Crypto();
+};
+
+class ResourceFormatLoaderCrypto : public ResourceFormatLoader {
+ GDCLASS(ResourceFormatLoaderCrypto, ResourceFormatLoader);
+
+public:
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
+ virtual void get_recognized_extensions(List<String> *p_extensions) const;
+ virtual bool handles_type(const String &p_type) const;
+ virtual String get_resource_type(const String &p_path) const;
+};
+
+class ResourceFormatSaverCrypto : public ResourceFormatSaver {
+ GDCLASS(ResourceFormatSaverCrypto, ResourceFormatSaver);
+
+public:
+ virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
+ virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
+ virtual bool recognize(const RES &p_resource) const;
+};
+
+#endif // CRYPTO_H
diff --git a/core/math/crypto_core.cpp b/core/crypto/crypto_core.cpp
index d7ba54e469..51c2e3c9e5 100644
--- a/core/math/crypto_core.cpp
+++ b/core/crypto/crypto_core.cpp
@@ -52,7 +52,7 @@ Error CryptoCore::MD5Context::start() {
return ret ? FAILED : OK;
}
-Error CryptoCore::MD5Context::update(uint8_t *p_src, size_t p_len) {
+Error CryptoCore::MD5Context::update(const uint8_t *p_src, size_t p_len) {
int ret = mbedtls_md5_update_ret((mbedtls_md5_context *)ctx, p_src, p_len);
return ret ? FAILED : OK;
}
@@ -62,6 +62,32 @@ Error CryptoCore::MD5Context::finish(unsigned char r_hash[16]) {
return ret ? FAILED : OK;
}
+// SHA1
+CryptoCore::SHA1Context::SHA1Context() {
+ ctx = memalloc(sizeof(mbedtls_sha1_context));
+ mbedtls_sha1_init((mbedtls_sha1_context *)ctx);
+}
+
+CryptoCore::SHA1Context::~SHA1Context() {
+ mbedtls_sha1_free((mbedtls_sha1_context *)ctx);
+ memfree((mbedtls_sha1_context *)ctx);
+}
+
+Error CryptoCore::SHA1Context::start() {
+ int ret = mbedtls_sha1_starts_ret((mbedtls_sha1_context *)ctx);
+ return ret ? FAILED : OK;
+}
+
+Error CryptoCore::SHA1Context::update(const uint8_t *p_src, size_t p_len) {
+ int ret = mbedtls_sha1_update_ret((mbedtls_sha1_context *)ctx, p_src, p_len);
+ return ret ? FAILED : OK;
+}
+
+Error CryptoCore::SHA1Context::finish(unsigned char r_hash[20]) {
+ int ret = mbedtls_sha1_finish_ret((mbedtls_sha1_context *)ctx, r_hash);
+ return ret ? FAILED : OK;
+}
+
// SHA256
CryptoCore::SHA256Context::SHA256Context() {
ctx = memalloc(sizeof(mbedtls_sha256_context));
@@ -78,12 +104,12 @@ Error CryptoCore::SHA256Context::start() {
return ret ? FAILED : OK;
}
-Error CryptoCore::SHA256Context::update(uint8_t *p_src, size_t p_len) {
+Error CryptoCore::SHA256Context::update(const uint8_t *p_src, size_t p_len) {
int ret = mbedtls_sha256_update_ret((mbedtls_sha256_context *)ctx, p_src, p_len);
return ret ? FAILED : OK;
}
-Error CryptoCore::SHA256Context::finish(unsigned char r_hash[16]) {
+Error CryptoCore::SHA256Context::finish(unsigned char r_hash[32]) {
int ret = mbedtls_sha256_finish_ret((mbedtls_sha256_context *)ctx, r_hash);
return ret ? FAILED : OK;
}
diff --git a/core/math/crypto_core.h b/core/crypto/crypto_core.h
index e28cb5a792..c859d612d4 100644
--- a/core/math/crypto_core.h
+++ b/core/crypto/crypto_core.h
@@ -46,10 +46,24 @@ public:
~MD5Context();
Error start();
- Error update(uint8_t *p_src, size_t p_len);
+ Error update(const uint8_t *p_src, size_t p_len);
Error finish(unsigned char r_hash[16]);
};
+ class SHA1Context {
+
+ private:
+ void *ctx; // To include, or not to include...
+
+ public:
+ SHA1Context();
+ ~SHA1Context();
+
+ Error start();
+ Error update(const uint8_t *p_src, size_t p_len);
+ Error finish(unsigned char r_hash[20]);
+ };
+
class SHA256Context {
private:
@@ -60,8 +74,8 @@ public:
~SHA256Context();
Error start();
- Error update(uint8_t *p_src, size_t p_len);
- Error finish(unsigned char r_hash[16]);
+ Error update(const uint8_t *p_src, size_t p_len);
+ Error finish(unsigned char r_hash[32]);
};
class AESContext {
diff --git a/core/crypto/hashing_context.cpp b/core/crypto/hashing_context.cpp
new file mode 100644
index 0000000000..bdccb258dd
--- /dev/null
+++ b/core/crypto/hashing_context.cpp
@@ -0,0 +1,137 @@
+/*************************************************************************/
+/* hashing_context.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "hashing_context.h"
+
+#include "core/crypto/crypto_core.h"
+
+Error HashingContext::start(HashType p_type) {
+ ERR_FAIL_COND_V(ctx != NULL, ERR_ALREADY_IN_USE);
+ _create_ctx(p_type);
+ ERR_FAIL_COND_V(ctx == NULL, ERR_UNAVAILABLE);
+ switch (type) {
+ case HASH_MD5:
+ return ((CryptoCore::MD5Context *)ctx)->start();
+ case HASH_SHA1:
+ return ((CryptoCore::SHA1Context *)ctx)->start();
+ case HASH_SHA256:
+ return ((CryptoCore::SHA256Context *)ctx)->start();
+ }
+ return ERR_UNAVAILABLE;
+}
+
+Error HashingContext::update(PoolByteArray p_chunk) {
+ ERR_FAIL_COND_V(ctx == NULL, ERR_UNCONFIGURED);
+ size_t len = p_chunk.size();
+ PoolByteArray::Read r = p_chunk.read();
+ switch (type) {
+ case HASH_MD5:
+ return ((CryptoCore::MD5Context *)ctx)->update(&r[0], len);
+ case HASH_SHA1:
+ return ((CryptoCore::SHA1Context *)ctx)->update(&r[0], len);
+ case HASH_SHA256:
+ return ((CryptoCore::SHA256Context *)ctx)->update(&r[0], len);
+ }
+ return ERR_UNAVAILABLE;
+}
+
+PoolByteArray HashingContext::finish() {
+ ERR_FAIL_COND_V(ctx == NULL, PoolByteArray());
+ PoolByteArray out;
+ Error err = FAILED;
+ switch (type) {
+ case HASH_MD5:
+ out.resize(16);
+ err = ((CryptoCore::MD5Context *)ctx)->finish(out.write().ptr());
+ break;
+ case HASH_SHA1:
+ out.resize(20);
+ err = ((CryptoCore::SHA1Context *)ctx)->finish(out.write().ptr());
+ break;
+ case HASH_SHA256:
+ out.resize(32);
+ err = ((CryptoCore::SHA256Context *)ctx)->finish(out.write().ptr());
+ break;
+ }
+ _delete_ctx();
+ ERR_FAIL_COND_V(err != OK, PoolByteArray());
+ return out;
+}
+
+void HashingContext::_create_ctx(HashType p_type) {
+ type = p_type;
+ switch (type) {
+ case HASH_MD5:
+ ctx = memnew(CryptoCore::MD5Context);
+ break;
+ case HASH_SHA1:
+ ctx = memnew(CryptoCore::SHA1Context);
+ break;
+ case HASH_SHA256:
+ ctx = memnew(CryptoCore::SHA256Context);
+ break;
+ default:
+ ctx = NULL;
+ }
+}
+
+void HashingContext::_delete_ctx() {
+ return;
+ switch (type) {
+ case HASH_MD5:
+ memdelete((CryptoCore::MD5Context *)ctx);
+ break;
+ case HASH_SHA1:
+ memdelete((CryptoCore::SHA1Context *)ctx);
+ break;
+ case HASH_SHA256:
+ memdelete((CryptoCore::SHA256Context *)ctx);
+ break;
+ }
+ ctx = NULL;
+}
+
+void HashingContext::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("start", "type"), &HashingContext::start);
+ ClassDB::bind_method(D_METHOD("update", "chunk"), &HashingContext::update);
+ ClassDB::bind_method(D_METHOD("finish"), &HashingContext::finish);
+ BIND_ENUM_CONSTANT(HASH_MD5);
+ BIND_ENUM_CONSTANT(HASH_SHA1);
+ BIND_ENUM_CONSTANT(HASH_SHA256);
+}
+
+HashingContext::HashingContext() {
+ ctx = NULL;
+}
+
+HashingContext::~HashingContext() {
+ if (ctx != NULL)
+ _delete_ctx();
+}
diff --git a/core/crypto/hashing_context.h b/core/crypto/hashing_context.h
new file mode 100644
index 0000000000..aa69636f2c
--- /dev/null
+++ b/core/crypto/hashing_context.h
@@ -0,0 +1,66 @@
+/*************************************************************************/
+/* hashing_context.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef HASHING_CONTEXT_H
+#define HASHING_CONTEXT_H
+
+#include "core/reference.h"
+
+class HashingContext : public Reference {
+ GDCLASS(HashingContext, Reference);
+
+public:
+ enum HashType {
+ HASH_MD5,
+ HASH_SHA1,
+ HASH_SHA256
+ };
+
+private:
+ void *ctx;
+ HashType type;
+
+protected:
+ static void _bind_methods();
+ void _create_ctx(HashType p_type);
+ void _delete_ctx();
+
+public:
+ Error start(HashType p_type);
+ Error update(PoolByteArray p_chunk);
+ PoolByteArray finish();
+
+ HashingContext();
+ ~HashingContext();
+};
+
+VARIANT_ENUM_CAST(HashingContext::HashType);
+
+#endif // HASHING_CONTEXT_H
diff --git a/core/engine.cpp b/core/engine.cpp
index 0dd0459403..937439faaf 100644
--- a/core/engine.cpp
+++ b/core/engine.cpp
@@ -197,10 +197,7 @@ void Engine::add_singleton(const Singleton &p_singleton) {
Object *Engine::get_singleton_object(const String &p_name) const {
const Map<StringName, Object *>::Element *E = singleton_ptrs.find(p_name);
- if (!E) {
- ERR_EXPLAIN("Failed to retrieve non-existent singleton '" + p_name + "'");
- ERR_FAIL_V(NULL);
- }
+ ERR_FAIL_COND_V_MSG(!E, NULL, "Failed to retrieve non-existent singleton '" + p_name + "'.");
return E->get();
};
diff --git a/core/hash_map.h b/core/hash_map.h
index 1513d7a65b..81ddc376d0 100644
--- a/core/hash_map.h
+++ b/core/hash_map.h
@@ -151,11 +151,7 @@ private:
return;
Element **new_hash_table = memnew_arr(Element *, ((uint64_t)1 << new_hash_table_power));
- if (!new_hash_table) {
-
- ERR_PRINT("Out of Memory");
- return;
- }
+ ERR_FAIL_COND_MSG(!new_hash_table, "Out of memory.");
for (int i = 0; i < (1 << new_hash_table_power); i++) {
@@ -208,10 +204,7 @@ private:
/* if element doesn't exist, create it */
Element *e = memnew(Element);
- if (!e) {
- ERR_EXPLAIN("Out of memory");
- ERR_FAIL_V(NULL);
- }
+ ERR_FAIL_COND_V_MSG(!e, NULL, "Out of memory.");
uint32_t hash = Hasher::hash(p_key);
uint32_t index = hash & ((1 << hash_table_power) - 1);
e->next = hash_table[index];
@@ -498,10 +491,7 @@ public:
} else { /* get the next key */
const Element *e = get_element(*p_key);
- if (!e) {
- ERR_EXPLAIN("Invalid key supplied")
- ERR_FAIL_V(NULL);
- }
+ ERR_FAIL_COND_V_MSG(!e, NULL, "Invalid key supplied.");
if (e->next) {
/* if there is a "next" in the list, return that */
return &e->next->pair.key;
diff --git a/core/image.cpp b/core/image.cpp
index 6211c06ebe..900efb0eb0 100644
--- a/core/image.cpp
+++ b/core/image.cpp
@@ -423,8 +423,7 @@ void Image::convert(Format p_new_format) {
if (format > FORMAT_RGBE9995 || p_new_format > FORMAT_RGBE9995) {
- ERR_EXPLAIN("Cannot convert to <-> from compressed formats. Use compress() and decompress() instead.");
- ERR_FAIL();
+ ERR_FAIL_MSG("Cannot convert to <-> from compressed formats. Use compress() and decompress() instead.");
} else if (format > FORMAT_RGBA8 || p_new_format > FORMAT_RGBA8) {
@@ -864,10 +863,7 @@ bool Image::is_size_po2() const {
void Image::resize_to_po2(bool p_square) {
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot resize in indexed, compressed or custom image formats.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
int w = next_power_of_2(width);
int h = next_power_of_2(height);
@@ -883,15 +879,9 @@ void Image::resize_to_po2(bool p_square) {
void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
- if (data.size() == 0) {
- ERR_EXPLAIN("Cannot resize image before creating it, use create() or create_from_data() first.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(data.size() == 0, "Cannot resize image before creating it, use create() or create_from_data() first.");
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot resize in indexed, compressed or custom image formats.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */;
@@ -1104,10 +1094,8 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
void Image::crop_from_point(int p_x, int p_y, int p_width, int p_height) {
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot crop in indexed, compressed or custom image formats.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot crop in compressed or custom image formats.");
+
ERR_FAIL_COND(p_x < 0);
ERR_FAIL_COND(p_y < 0);
ERR_FAIL_COND(p_width <= 0);
@@ -1161,10 +1149,7 @@ void Image::crop(int p_width, int p_height) {
void Image::flip_y() {
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot flip_y in indexed, compressed or custom image formats.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_y in compressed or custom image formats.");
bool used_mipmaps = has_mipmaps();
if (used_mipmaps) {
@@ -1197,10 +1182,7 @@ void Image::flip_y() {
void Image::flip_x() {
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot flip_x in indexed, compressed or custom image formats.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_x in compressed or custom image formats.");
bool used_mipmaps = has_mipmaps();
if (used_mipmaps) {
@@ -1459,15 +1441,9 @@ void Image::normalize() {
Error Image::generate_mipmaps(bool p_renormalize) {
- if (!_can_modify(format)) {
- ERR_EXPLAIN("Cannot generate mipmaps in indexed, compressed or custom image formats.");
- ERR_FAIL_V(ERR_UNAVAILABLE);
- }
+ ERR_FAIL_COND_V_MSG(!_can_modify(format), ERR_UNAVAILABLE, "Cannot generate mipmaps in compressed or custom image formats.");
- if (width == 0 || height == 0) {
- ERR_EXPLAIN("Cannot generate mipmaps with width or height equal to 0.");
- ERR_FAIL_V(ERR_UNCONFIGURED);
- }
+ ERR_FAIL_COND_V_MSG(width == 0 || height == 0, ERR_UNCONFIGURED, "Cannot generate mipmaps with width or height equal to 0.");
int mmcount;
@@ -1618,10 +1594,7 @@ void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_forma
int mm;
int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
- if (size != p_data.size()) {
- ERR_EXPLAIN("Expected data size of " + itos(size) + " bytes in Image::create(), got instead " + itos(p_data.size()) + " bytes.");
- ERR_FAIL_COND(p_data.size() != size);
- }
+ ERR_FAIL_COND_MSG(p_data.size() != size, "Expected data size of " + itos(size) + " bytes in Image::create(), got instead " + itos(p_data.size()) + " bytes.");
height = p_height;
width = p_width;
@@ -2411,10 +2384,7 @@ Color Image::get_pixel(int p_x, int p_y) const {
uint8_t *ptr = write_lock.ptr();
#ifdef DEBUG_ENABLED
- if (!ptr) {
- ERR_EXPLAIN("Image must be locked with 'lock()' before using get_pixel()");
- ERR_FAIL_V(Color());
- }
+ ERR_FAIL_COND_V_MSG(!ptr, Color(), "Image must be locked with 'lock()' before using get_pixel().");
ERR_FAIL_INDEX_V(p_x, width, Color());
ERR_FAIL_INDEX_V(p_y, height, Color());
@@ -2530,8 +2500,7 @@ Color Image::get_pixel(int p_x, int p_y) const {
return Color::from_rgbe9995(((uint32_t *)ptr)[ofs]);
}
default: {
- ERR_EXPLAIN("Can't get_pixel() on compressed image, sorry.");
- ERR_FAIL_V(Color());
+ ERR_FAIL_V_MSG(Color(), "Can't get_pixel() on compressed image, sorry.");
}
}
}
@@ -2544,10 +2513,7 @@ void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
uint8_t *ptr = write_lock.ptr();
#ifdef DEBUG_ENABLED
- if (!ptr) {
- ERR_EXPLAIN("Image must be locked with 'lock()' before using set_pixel()");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!ptr, "Image must be locked with 'lock()' before using set_pixel().");
ERR_FAIL_INDEX(p_x, width);
ERR_FAIL_INDEX(p_y, height);
@@ -2659,8 +2625,7 @@ void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
} break;
default: {
- ERR_EXPLAIN("Can't set_pixel() on compressed image, sorry.");
- ERR_FAIL();
+ ERR_FAIL_MSG("Can't set_pixel() on compressed image, sorry.");
}
}
}
diff --git a/core/image.h b/core/image.h
index d17571399d..f29a30cda0 100644
--- a/core/image.h
+++ b/core/image.h
@@ -220,9 +220,7 @@ public:
/**
* Resize the image, using the preferred interpolation method.
- * Indexed-Color images always use INTERPOLATE_NEAREST.
*/
-
void resize_to_po2(bool p_square = false);
void resize(int p_width, int p_height, Interpolation p_interpolation = INTERPOLATE_BILINEAR);
void shrink_x2();
diff --git a/core/input_map.cpp b/core/input_map.cpp
index 165999f081..2a8ac435fe 100644
--- a/core/input_map.cpp
+++ b/core/input_map.cpp
@@ -192,10 +192,7 @@ bool InputMap::event_is_action(const Ref<InputEvent> &p_event, const StringName
bool InputMap::event_get_action_status(const Ref<InputEvent> &p_event, const StringName &p_action, bool *p_pressed, float *p_strength) const {
Map<StringName, Action>::Element *E = input_map.find(p_action);
- if (!E) {
- ERR_EXPLAIN("Request for nonexistent InputMap action: " + String(p_action));
- ERR_FAIL_V(false);
- }
+ ERR_FAIL_COND_V_MSG(!E, false, "Request for nonexistent InputMap action: " + String(p_action) + ".");
Ref<InputEventAction> input_event_action = p_event;
if (input_event_action.is_valid()) {
diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp
index f7fb72c089..9063e028be 100644
--- a/core/io/config_file.cpp
+++ b/core/io/config_file.cpp
@@ -86,10 +86,7 @@ void ConfigFile::set_value(const String &p_section, const String &p_key, const V
Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const {
if (!values.has(p_section) || !values[p_section].has(p_key)) {
- if (p_default.get_type() == Variant::NIL) {
- ERR_EXPLAIN("Couldn't find the given section/key and no default was given");
- ERR_FAIL_V(p_default);
- }
+ ERR_FAIL_COND_V_MSG(p_default.get_type() == Variant::NIL, p_default, "Couldn't find the given section/key and no default was given.");
return p_default;
}
return values[p_section][p_key];
@@ -204,7 +201,7 @@ Error ConfigFile::load(const String &p_path) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
- return ERR_CANT_OPEN;
+ return err;
return _internal_load(p_path, f);
}
@@ -271,7 +268,7 @@ Error ConfigFile::_internal_load(const String &p_path, FileAccess *f) {
memdelete(f);
return OK;
} else if (err != OK) {
- ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text);
+ ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text + ".");
memdelete(f);
return err;
}
diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp
index 15523a49a9..f72ad61da6 100644
--- a/core/io/file_access_buffered.cpp
+++ b/core/io/file_access_buffered.cpp
@@ -87,10 +87,8 @@ bool FileAccessBuffered::eof_reached() const {
}
uint8_t FileAccessBuffered::get_8() const {
- if (!file.open) {
- ERR_EXPLAIN("Can't get data, when file is not opened.");
- ERR_FAIL_V(0);
- }
+
+ ERR_FAIL_COND_V_MSG(!file.open, 0, "Can't get data, when file is not opened.");
uint8_t byte = 0;
if (cache_data_left() >= 1) {
@@ -104,10 +102,8 @@ uint8_t FileAccessBuffered::get_8() const {
}
int FileAccessBuffered::get_buffer(uint8_t *p_dest, int p_length) const {
- if (!file.open) {
- ERR_EXPLAIN("Can't get buffer, when file is not opened.");
- ERR_FAIL_V(-1);
- }
+
+ ERR_FAIL_COND_V_MSG(!file.open, -1, "Can't get buffer, when file is not opened.");
if (p_length > cache_size) {
diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h
index 6e806e7b3f..c8cee04208 100644
--- a/core/io/file_access_buffered_fa.h
+++ b/core/io/file_access_buffered_fa.h
@@ -40,10 +40,7 @@ class FileAccessBufferedFA : public FileAccessBuffered {
int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const {
- if (!f.is_open()) {
- ERR_EXPLAIN("Can't read data block, when file is not opened.");
- ERR_FAIL_V(-1);
- }
+ ERR_FAIL_COND_V_MSG(!f.is_open(), -1, "Can't read data block when file is not opened.");
((T *)&f)->seek(p_offset);
diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp
index ccee6aeb15..77decc107d 100644
--- a/core/io/file_access_encrypted.cpp
+++ b/core/io/file_access_encrypted.cpp
@@ -30,7 +30,7 @@
#include "file_access_encrypted.h"
-#include "core/math/crypto_core.h"
+#include "core/crypto/crypto_core.h"
#include "core/os/copymem.h"
#include "core/print_string.h"
#include "core/variant.h"
@@ -94,8 +94,7 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8
unsigned char hash[16];
ERR_FAIL_COND_V(CryptoCore::md5(data.ptr(), data.size(), hash) != OK, ERR_BUG);
- ERR_EXPLAIN("The MD5 sum of the decrypted file does not match the expected value. It could be that the file is corrupt, or that the provided decryption key is invalid.");
- ERR_FAIL_COND_V(String::md5(hash) != String::md5(md5d), ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V_MSG(String::md5(hash) != String::md5(md5d), ERR_FILE_CORRUPT, "The MD5 sum of the decrypted file does not match the expected value. It could be that the file is corrupt, or that the provided decryption key is invalid.");
file = p_base;
}
@@ -298,7 +297,7 @@ uint32_t FileAccessEncrypted::_get_unix_permissions(const String &p_file) {
}
Error FileAccessEncrypted::_set_unix_permissions(const String &p_file, uint32_t p_permissions) {
- ERR_PRINT("Setting UNIX permissions on encrypted files is not implemented yet");
+ ERR_PRINT("Setting UNIX permissions on encrypted files is not implemented yet.");
return ERR_UNAVAILABLE;
}
diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp
index ca66b34e17..d49d36c2b9 100644
--- a/core/io/file_access_pack.cpp
+++ b/core/io/file_access_pack.cpp
@@ -90,7 +90,7 @@ void PackedData::add_path(const String &pkg_path, const String &path, uint64_t o
}
}
String filename = path.get_file();
- // Don't add as a file if the path points to a directoryy
+ // Don't add as a file if the path points to a directory
if (!filename.empty()) {
cd->files.insert(filename);
}
@@ -171,10 +171,8 @@ bool PackedSourcePCK::try_open_pack(const String &p_path) {
uint32_t ver_minor = f->get_32();
f->get_32(); // ver_rev
- ERR_EXPLAIN("Pack version unsupported: " + itos(version));
- ERR_FAIL_COND_V(version != PACK_VERSION, false);
- ERR_EXPLAIN("Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor));
- ERR_FAIL_COND_V(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), false);
+ ERR_FAIL_COND_V_MSG(version != PACK_VERSION, false, "Pack version unsupported: " + itos(version) + ".");
+ ERR_FAIL_COND_V_MSG(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), false, "Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + ".");
for (int i = 0; i < 16; i++) {
//reserved
@@ -322,10 +320,9 @@ bool FileAccessPack::file_exists(const String &p_name) {
FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) :
pf(p_file),
f(FileAccess::open(pf.pack, FileAccess::READ)) {
- if (!f) {
- ERR_EXPLAIN("Can't open pack-referenced file: " + String(pf.pack));
- ERR_FAIL_COND(!f);
- }
+
+ ERR_FAIL_COND_MSG(!f, "Can't open pack-referenced file: " + String(pf.pack) + ".");
+
f->seek(pf.offset);
pos = 0;
eof = false;
@@ -463,11 +460,15 @@ String DirAccessPack::get_current_dir() {
bool DirAccessPack::file_exists(String p_file) {
+ p_file = fix_path(p_file);
+
return current->files.has(p_file);
}
bool DirAccessPack::dir_exists(String p_dir) {
+ p_dir = fix_path(p_dir);
+
return current->subdirs.has(p_dir);
}
diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp
index 9305afac5f..df4be9b9fd 100644
--- a/core/io/ip_address.cpp
+++ b/core/io/ip_address.cpp
@@ -81,8 +81,7 @@ static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) {
} else if (c == ':') {
break;
} else {
- ERR_EXPLAIN("Invalid character in ipv6 address: " + p_string);
- ERR_FAIL();
+ ERR_FAIL_MSG("Invalid character in IPv6 address: " + p_string + ".");
};
ret = ret << 4;
ret += n;
@@ -126,9 +125,7 @@ void IP_Address::_parse_ipv6(const String &p_string) {
++parts_count;
};
} else {
-
- ERR_EXPLAIN("Invalid character in IPv6 address: " + p_string);
- ERR_FAIL();
+ ERR_FAIL_MSG("Invalid character in IPv6 address: " + p_string + ".");
};
};
@@ -166,10 +163,7 @@ void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret
};
int slices = ip.get_slice_count(".");
- if (slices != 4) {
- ERR_EXPLAIN("Invalid IP Address String: " + ip);
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(slices != 4, "Invalid IP address string: " + ip + ".");
for (int i = 0; i < 4; i++) {
p_ret[i] = ip.get_slicec('.', i).to_int();
}
@@ -229,7 +223,7 @@ IP_Address::IP_Address(const String &p_string) {
valid = true;
} else {
- ERR_PRINT("Invalid IP address");
+ ERR_PRINT("Invalid IP address.");
}
}
diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp
index dc5581ea01..b386feb14c 100644
--- a/core/io/marshalls.cpp
+++ b/core/io/marshalls.cpp
@@ -377,11 +377,6 @@ Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int
}
} break;
- /*case Variant::RESOURCE: {
-
- ERR_EXPLAIN("Can't marshallize resources");
- ERR_FAIL_V(ERR_INVALID_DATA); //no, i'm sorry, no go
- } break;*/
case Variant::_RID: {
r_variant = RID();
@@ -1066,11 +1061,6 @@ Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bo
r_len += 4 * 4;
} break;
- /*case Variant::RESOURCE: {
-
- ERR_EXPLAIN("Can't marshallize resources");
- ERR_FAIL_V(ERR_INVALID_DATA); //no, i'm sorry, no go
- } break;*/
case Variant::_RID: {
} break;
diff --git a/core/io/multiplayer_api.cpp b/core/io/multiplayer_api.cpp
index 33dc4dbde4..d20133642b 100644
--- a/core/io/multiplayer_api.cpp
+++ b/core/io/multiplayer_api.cpp
@@ -146,8 +146,7 @@ void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_pee
network_peer = p_peer;
- ERR_EXPLAIN("Supplied NetworkedNetworkPeer must be connecting or connected.");
- ERR_FAIL_COND(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED);
+ ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Supplied NetworkedNetworkPeer must be connecting or connected.");
if (network_peer.is_valid()) {
network_peer->connect("peer_connected", this, "_add_peer");
@@ -164,10 +163,8 @@ Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
- ERR_EXPLAIN("Multiplayer root node was not initialized. If you are using custom multiplayer, remember to set the root node via MultiplayerAPI.set_root_node before using it");
- ERR_FAIL_COND(root_node == NULL);
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_packet_len < 1);
+ ERR_FAIL_COND_MSG(root_node == NULL, "Multiplayer root node was not initialized. If you are using custom multiplayer, remember to set the root node via MultiplayerAPI.set_root_node before using it.");
+ ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
uint8_t packet_type = p_packet[0];
@@ -186,13 +183,11 @@ void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_
case NETWORK_COMMAND_REMOTE_CALL:
case NETWORK_COMMAND_REMOTE_SET: {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_packet_len < 6);
+ ERR_FAIL_COND_MSG(p_packet_len < 6, "Invalid packet received. Size too small.");
Node *node = _process_get_node(p_from, p_packet, p_packet_len);
- ERR_EXPLAIN("Invalid packet received. Requested node was not found.");
- ERR_FAIL_COND(node == NULL);
+ ERR_FAIL_COND_MSG(node == NULL, "Invalid packet received. Requested node was not found.");
// Detect cstring end.
int len_end = 5;
@@ -202,8 +197,7 @@ void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_
}
}
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(len_end >= p_packet_len);
+ ERR_FAIL_COND_MSG(len_end >= p_packet_len, "Invalid packet received. Size too small.");
StringName name = String::utf8((const char *)&p_packet[5]);
@@ -235,8 +229,7 @@ Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int
int ofs = target & 0x7FFFFFFF;
- ERR_EXPLAIN("Invalid packet received. Size smaller than declared.");
- ERR_FAIL_COND_V(ofs >= p_packet_len, NULL);
+ ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, NULL, "Invalid packet received. Size smaller than declared.");
String paths;
paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
@@ -246,33 +239,30 @@ Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int
node = root_node->get_node(np);
if (!node)
- ERR_PRINTS("Failed to get path from RPC: " + String(np));
+ ERR_PRINTS("Failed to get path from RPC: " + String(np) + ".");
} else {
// Use cached path.
int id = target;
Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
- ERR_EXPLAIN("Invalid packet received. Requests invalid peer cache.");
- ERR_FAIL_COND_V(!E, NULL);
+ ERR_FAIL_COND_V_MSG(!E, NULL, "Invalid packet received. Requests invalid peer cache.");
Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
- ERR_EXPLAIN("Invalid packet received. Unabled to find requested cached node.");
- ERR_FAIL_COND_V(!F, NULL);
+ ERR_FAIL_COND_V_MSG(!F, NULL, "Invalid packet received. Unabled to find requested cached node.");
PathGetCache::NodeInfo *ni = &F->get();
// Do proper caching later.
node = root_node->get_node(ni->path);
if (!node)
- ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path));
+ ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path) + ".");
}
return node;
}
void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_offset >= p_packet_len);
+ ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
// Check that remote can call the RPC on this node.
RPCMode rpc_mode = RPC_MODE_DISABLED;
@@ -284,8 +274,7 @@ void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_
}
bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
- ERR_EXPLAIN("RPC '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
- ERR_FAIL_COND(!can_call);
+ ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
int argc = p_packet[p_offset];
Vector<Variant> args;
@@ -297,13 +286,11 @@ void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_
for (int i = 0; i < argc; i++) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_offset >= p_packet_len);
+ ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
int vlen;
Error err = decode_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen, allow_object_decoding || network_peer->is_object_decoding_allowed());
- ERR_EXPLAIN("Invalid packet received. Unable to decode RPC argument.");
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
argp.write[i] = &args[i];
p_offset += vlen;
@@ -321,8 +308,7 @@ void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_
void MultiplayerAPI::_process_rset(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_offset >= p_packet_len);
+ ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
// Check that remote can call the RSET on this node.
RPCMode rset_mode = RPC_MODE_DISABLED;
@@ -334,28 +320,25 @@ void MultiplayerAPI::_process_rset(Node *p_node, const StringName &p_name, int p
}
bool can_call = _can_call_mode(p_node, rset_mode, p_from);
- ERR_EXPLAIN("RSET '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
- ERR_FAIL_COND(!can_call);
+ ERR_FAIL_COND_MSG(!can_call, "RSET '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
Variant value;
Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
- ERR_EXPLAIN("Invalid packet received. Unable to decode RSET value.");
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
bool valid;
p_node->set(p_name, value, &valid);
if (!valid) {
- String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class();
+ String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class() + ".";
ERR_PRINTS(error);
}
}
void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_packet_len < 5);
+ ERR_FAIL_COND_MSG(p_packet_len < 5, "Invalid packet received. Size too small.");
int id = decode_uint32(&p_packet[1]);
String paths;
@@ -390,8 +373,7 @@ void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet,
void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_packet_len < 2);
+ ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
String paths;
paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
@@ -399,12 +381,10 @@ void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet,
NodePath path = paths;
PathSentCache *psc = path_send_cache.getptr(path);
- ERR_EXPLAIN("Invalid packet received. Tries to confirm a path which was not found in cache.");
- ERR_FAIL_COND(!psc);
+ ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
- ERR_EXPLAIN("Invalid packet received. Source peer was not found in cache for the given path.");
- ERR_FAIL_COND(!E);
+ ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
E->get() = true;
}
@@ -460,39 +440,22 @@ bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int
void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
- if (network_peer.is_null()) {
- ERR_EXPLAIN("Attempt to remote call/set when networking is not active in SceneTree.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
- if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
- ERR_EXPLAIN("Attempt to remote call/set when networking is not connected yet in SceneTree.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree.");
- if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
- ERR_EXPLAIN("Attempt to remote call/set when networking is disconnected.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
- if (p_argcount > 255) {
- ERR_EXPLAIN("Too many arguments >255.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
- if (p_to == network_peer->get_unique_id()) {
- ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()));
- } else {
- ERR_EXPLAIN("Attempt to remote call unexisting ID: " + itos(p_to));
- }
+ ERR_FAIL_COND_MSG(p_to == network_peer->get_unique_id(), "Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()) + ".");
- ERR_FAIL();
+ ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
}
NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
- ERR_EXPLAIN("Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
- ERR_FAIL_COND(from_path.is_empty());
+ ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
// See if the path is cached.
PathSentCache *psc = path_send_cache.getptr(from_path);
@@ -530,8 +493,7 @@ void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p
if (p_set) {
// Set argument.
Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
- ERR_EXPLAIN("Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
MAKE_ROOM(ofs + len);
encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
ofs += len;
@@ -543,8 +505,7 @@ void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p
ofs += 1;
for (int i = 0; i < p_argcount; i++) {
Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
- ERR_EXPLAIN("Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
MAKE_ROOM(ofs + len);
encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
ofs += len;
@@ -626,12 +587,9 @@ void MultiplayerAPI::_server_disconnected() {
void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
- ERR_EXPLAIN("Trying to call an RPC while no network peer is active.");
- ERR_FAIL_COND(!network_peer.is_valid());
- ERR_EXPLAIN("Trying to call an RPC on a node which is not inside SceneTree.");
- ERR_FAIL_COND(!p_node->is_inside_tree());
- ERR_EXPLAIN("Trying to call an RPC via a network peer which is not connected.");
- ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
+ ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
+ ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
+ ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected.");
int node_id = network_peer->get_unique_id();
bool skip_rpc = node_id == p_peer_id;
@@ -668,7 +626,7 @@ void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const
rpc_sender_id = temp_id;
if (ce.error != Variant::CallError::CALL_OK) {
String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
- error = "rpc() aborted in local call: - " + error;
+ error = "rpc() aborted in local call: - " + error + ".";
ERR_PRINTS(error);
return;
}
@@ -683,24 +641,20 @@ void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const
rpc_sender_id = temp_id;
if (ce.error != Variant::CallError::CALL_OK) {
String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
- error = "rpc() aborted in script local call: - " + error;
+ error = "rpc() aborted in script local call: - " + error + ".";
ERR_PRINTS(error);
return;
}
}
- ERR_EXPLAIN("RPC '" + p_method + "' on yourself is not allowed by selected mode");
- ERR_FAIL_COND(skip_rpc && !(call_local_native || call_local_script));
+ ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
}
void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
- ERR_EXPLAIN("Trying to RSET while no network peer is active.");
- ERR_FAIL_COND(!network_peer.is_valid());
- ERR_EXPLAIN("Trying to RSET on a node which is not inside SceneTree.");
- ERR_FAIL_COND(!p_node->is_inside_tree());
- ERR_EXPLAIN("Trying to send an RSET via a network peer which is not connected.");
- ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
+ ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
+ ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
+ ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to send an RSET via a network peer which is not connected.");
int node_id = network_peer->get_unique_id();
bool is_master = p_node->is_network_master();
@@ -724,7 +678,7 @@ void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const
rpc_sender_id = temp_id;
if (!valid) {
- String error = "rset() aborted in local set, property not found: - " + String(p_property);
+ String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
ERR_PRINTS(error);
return;
}
@@ -742,7 +696,7 @@ void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const
rpc_sender_id = temp_id;
if (!valid) {
- String error = "rset() aborted in local script set, property not found: - " + String(p_property);
+ String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
ERR_PRINTS(error);
return;
}
@@ -751,8 +705,7 @@ void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const
}
if (skip_rset) {
- ERR_EXPLAIN("RSET for '" + p_property + "' on yourself is not allowed by selected mode");
- ERR_FAIL_COND(!set_local);
+ ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
return;
}
@@ -763,12 +716,9 @@ void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const
Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
- ERR_EXPLAIN("Trying to send an empty raw packet.");
- ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA);
- ERR_EXPLAIN("Trying to send a raw packet while no network peer is active.");
- ERR_FAIL_COND_V(!network_peer.is_valid(), ERR_UNCONFIGURED);
- ERR_EXPLAIN("Trying to send a raw packet via a network peer which is not connected.");
- ERR_FAIL_COND_V(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
+ ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
+ ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
MAKE_ROOM(p_data.size() + 1);
PoolVector<uint8_t>::Read r = p_data.read();
@@ -783,8 +733,7 @@ Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, Networked
void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
- ERR_EXPLAIN("Invalid packet received. Size too small.");
- ERR_FAIL_COND(p_packet_len < 2);
+ ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
PoolVector<uint8_t> out;
int len = p_packet_len - 1;
@@ -798,37 +747,32 @@ void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_pac
int MultiplayerAPI::get_network_unique_id() const {
- ERR_EXPLAIN("No network peer is assigned. Unable to get unique network ID.");
- ERR_FAIL_COND_V(!network_peer.is_valid(), 0);
+ ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
return network_peer->get_unique_id();
}
bool MultiplayerAPI::is_network_server() const {
// XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
- ERR_EXPLAIN("No network peer is assigned. I can't be a server.");
- ERR_FAIL_COND_V(!network_peer.is_valid(), false);
+ ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
return network_peer->is_server();
}
void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
- ERR_EXPLAIN("No network peer is assigned. Unable to set 'refuse_new_connections'.");
- ERR_FAIL_COND(!network_peer.is_valid());
+ ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
network_peer->set_refuse_new_connections(p_refuse);
}
bool MultiplayerAPI::is_refusing_new_network_connections() const {
- ERR_EXPLAIN("No network peer is assigned. Unable to get 'refuse_new_connections'.");
- ERR_FAIL_COND_V(!network_peer.is_valid(), false);
+ ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
return network_peer->is_refusing_new_connections();
}
Vector<int> MultiplayerAPI::get_network_connected_peers() const {
- ERR_EXPLAIN("No network peer is assigned. Assume no peers are connected.");
- ERR_FAIL_COND_V(!network_peer.is_valid(), Vector<int>());
+ ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
Vector<int> ret;
for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp
index 1e4ea715b3..1c792c43d1 100644
--- a/core/io/packet_peer.cpp
+++ b/core/io/packet_peer.cpp
@@ -280,8 +280,7 @@ Ref<StreamPeer> PacketPeerStream::get_stream_peer() const {
void PacketPeerStream::set_input_buffer_max_size(int p_max_size) {
//warning may lose packets
- ERR_EXPLAIN("Buffer in use, resizing would cause loss of data");
- ERR_FAIL_COND(ring_buffer.data_left());
+ ERR_FAIL_COND_MSG(ring_buffer.data_left(), "Buffer in use, resizing would cause loss of data.");
ring_buffer.resize(nearest_shift(p_max_size + 4));
input_buffer.resize(next_power_of_2(p_max_size + 4));
}
diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp
index c16d89d695..1c89bc6268 100644
--- a/core/io/pck_packer.cpp
+++ b/core/io/pck_packer.cpp
@@ -64,10 +64,7 @@ Error PCKPacker::pck_start(const String &p_file, int p_alignment) {
file = FileAccess::open(p_file, FileAccess::WRITE);
- if (!file) {
- ERR_EXPLAIN("Can't open file to write: " + String(p_file));
- ERR_FAIL_V(ERR_CANT_CREATE);
- }
+ ERR_FAIL_COND_V_MSG(!file, ERR_CANT_CREATE, "Can't open file to write: " + String(p_file) + ".");
alignment = p_alignment;
diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp
index 146480e5a2..de10fe1376 100644
--- a/core/io/resource_format_binary.cpp
+++ b/core/io/resource_format_binary.cpp
@@ -490,8 +490,7 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) {
#endif
} else {
- ERR_EXPLAIN("Vector2 size is NOT 8!");
- ERR_FAIL_V(ERR_UNAVAILABLE);
+ ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Vector2 size is NOT 8!");
}
w.release();
r_v = array;
@@ -518,8 +517,7 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) {
#endif
} else {
- ERR_EXPLAIN("Vector3 size is NOT 12!");
- ERR_FAIL_V(ERR_UNAVAILABLE);
+ ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Vector3 size is NOT 12!");
}
w.release();
r_v = array;
@@ -546,8 +544,7 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) {
#endif
} else {
- ERR_EXPLAIN("Color size is NOT 16!");
- ERR_FAIL_V(ERR_UNAVAILABLE);
+ ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Color size is NOT 16!");
}
w.release();
r_v = array;
@@ -571,7 +568,7 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) {
const uint32_t current_version = 0;
if (format_version > current_version) {
- ERR_PRINT("Format version for encoded binary image is too new");
+ ERR_PRINT("Format version for encoded binary image is too new.");
return ERR_PARSE_ERROR;
}
@@ -655,8 +652,7 @@ Error ResourceInteractiveLoaderBinary::poll() {
} else {
error = ERR_FILE_MISSING_DEPENDENCIES;
- ERR_EXPLAIN("Can't load dependency: " + path);
- ERR_FAIL_V(error);
+ ERR_FAIL_V_MSG(error, "Can't load dependency: " + path + ".");
}
} else {
@@ -711,16 +707,15 @@ Error ResourceInteractiveLoaderBinary::poll() {
Object *obj = ClassDB::instance(t);
if (!obj) {
error = ERR_FILE_CORRUPT;
- ERR_EXPLAIN(local_path + ":Resource of unrecognized type in file: " + t);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, local_path + ":Resource of unrecognized type in file: " + t + ".");
}
Resource *r = Object::cast_to<Resource>(obj);
if (!r) {
+ String obj_class = obj->get_class();
error = ERR_FILE_CORRUPT;
- ERR_EXPLAIN(local_path + ":Resource type in resource field not a resource, type is: " + obj->get_class());
memdelete(obj); //bye
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, local_path + ":Resource type in resource field not a resource, type is: " + obj_class + ".");
}
RES res = RES(r);
@@ -850,8 +845,7 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
//not normal
error = ERR_FILE_UNRECOGNIZED;
- ERR_EXPLAIN("Unrecognized binary resource file: " + local_path);
- ERR_FAIL();
+ ERR_FAIL_MSG("Unrecognized binary resource file: " + local_path + ".");
}
bool big_endian = f->get_32();
@@ -877,8 +871,7 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) {
f->close();
- ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a new engine version: " + local_path);
- ERR_FAIL();
+ ERR_FAIL_MSG("File format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a new engine version: " + local_path + ".");
}
type = get_unicode_string();
@@ -926,8 +919,7 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
if (f->eof_reached()) {
error = ERR_FILE_CORRUPT;
- ERR_EXPLAIN("Premature End Of File: " + local_path);
- ERR_FAIL();
+ ERR_FAIL_MSG("Premature end of file (EOF): " + local_path + ".");
}
}
@@ -1084,8 +1076,7 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons
//error=ERR_FILE_UNRECOGNIZED;
memdelete(f);
- ERR_EXPLAIN("Unrecognized binary resource file: " + local_path);
- ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Unrecognized binary resource file: " + local_path + ".");
} else {
fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
if (!fw) {
@@ -1122,7 +1113,7 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons
memdelete(da);
//use the old approach
- WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data());
+ WARN_PRINTS("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path + ".");
Error err;
f = FileAccess::open(p_path, FileAccess::READ, &err);
@@ -1153,8 +1144,7 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons
memdelete(f);
memdelete(fw);
- ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a new engine version: " + local_path);
- ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "File format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a new engine version: " + local_path + ".");
}
// Since we're not actually converting the file contents, leave the version
@@ -1477,7 +1467,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(FileAccess *f, const Varia
case Variant::_RID: {
f->store_32(VARIANT_RID);
- WARN_PRINT("Can't save RIDs");
+ WARN_PRINT("Can't save RIDs.");
RID val = p_property;
f->store_32(val.get_id());
} break;
@@ -1497,8 +1487,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(FileAccess *f, const Varia
if (!resource_set.has(res)) {
f->store_32(OBJECT_EMPTY);
- ERR_EXPLAIN("Resource was not pre cached for the resource section, most likely due to circular refedence.");
- ERR_FAIL();
+ ERR_FAIL_MSG("Resource was not pre cached for the resource section, most likely due to circular reference.");
}
f->store_32(OBJECT_INTERNAL_RESOURCE);
@@ -1629,8 +1618,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(FileAccess *f, const Varia
} break;
default: {
- ERR_EXPLAIN("Invalid variant");
- ERR_FAIL();
+ ERR_FAIL_MSG("Invalid variant.");
}
}
}
diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp
index 35af58ad07..9e954890bc 100644
--- a/core/io/resource_loader.cpp
+++ b/core/io/resource_loader.cpp
@@ -275,12 +275,9 @@ RES ResourceLoader::_load(const String &p_path, const String &p_original_path, c
return res;
}
- if (found) {
- ERR_EXPLAIN("Failed loading resource: " + p_path);
- } else {
- ERR_EXPLAIN("No loader found for resource: " + p_path);
- }
- ERR_FAIL_V(RES());
+ ERR_FAIL_COND_V_MSG(found, RES(), "Failed loading resource: " + p_path + ".");
+
+ ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
}
bool ResourceLoader::_add_to_loading_map(const String &p_path) {
@@ -355,10 +352,7 @@ RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p
{
bool success = _add_to_loading_map(local_path);
- if (!success) {
- ERR_EXPLAIN("Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
- ERR_FAIL_V(RES());
- }
+ ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
}
//lock first if possible
@@ -395,8 +389,7 @@ RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p
if (!p_no_cache) {
_remove_from_loading_map(local_path);
}
- ERR_EXPLAIN("Remapping '" + local_path + "'failed.");
- ERR_FAIL_V(RES());
+ ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
}
print_verbose("Loading resource: " + path);
@@ -479,10 +472,7 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_
if (!p_no_cache) {
bool success = _add_to_loading_map(local_path);
- if (!success) {
- ERR_EXPLAIN("Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
- ERR_FAIL_V(RES());
- }
+ ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
if (ResourceCache::has(local_path)) {
@@ -503,8 +493,7 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_
if (!p_no_cache) {
_remove_from_loading_map(local_path);
}
- ERR_EXPLAIN("Remapping '" + local_path + "'failed.");
- ERR_FAIL_V(RES());
+ ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
}
print_verbose("Loading resource: " + path);
@@ -534,12 +523,9 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_
_remove_from_loading_map(local_path);
}
- if (found) {
- ERR_EXPLAIN("Failed loading resource: " + path);
- } else {
- ERR_EXPLAIN("No loader found for resource: " + path);
- }
- ERR_FAIL_V(Ref<ResourceInteractiveLoader>());
+ ERR_FAIL_COND_V_MSG(found, Ref<ResourceInteractiveLoader>(), "Failed loading resource: " + path + ".");
+
+ ERR_FAIL_V_MSG(Ref<ResourceInteractiveLoader>(), "No loader found for resource: " + path + ".");
}
void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
@@ -801,7 +787,7 @@ String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_rem
if (err == ERR_FILE_EOF) {
break;
} else if (err != OK) {
- ERR_PRINTS("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text);
+ ERR_PRINTS("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
break;
}
@@ -932,13 +918,11 @@ bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
Ref<Script> s = res;
StringName ibt = s->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
- ERR_EXPLAIN("Script does not inherit a CustomResourceLoader: " + script_path);
- ERR_FAIL_COND_V(!valid_type, false);
+ ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
Object *obj = ClassDB::instance(ibt);
- ERR_EXPLAIN("Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt));
- ERR_FAIL_COND_V(obj == NULL, false);
+ ERR_FAIL_COND_V_MSG(obj == NULL, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
ResourceFormatLoader *crl = Object::cast_to<ResourceFormatLoader>(obj);
crl->set_script(s.get_ref_ptr());
diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp
index 369cd93442..a9ad62afe6 100644
--- a/core/io/resource_saver.cpp
+++ b/core/io/resource_saver.cpp
@@ -214,13 +214,11 @@ bool ResourceSaver::add_custom_resource_format_saver(String script_path) {
Ref<Script> s = res;
StringName ibt = s->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatSaver");
- ERR_EXPLAIN("Script does not inherit a CustomResourceSaver: " + script_path);
- ERR_FAIL_COND_V(!valid_type, false);
+ ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceSaver: " + script_path + ".");
Object *obj = ClassDB::instance(ibt);
- ERR_EXPLAIN("Cannot instance script as custom resource saver, expected 'ResourceFormatSaver' inheritance, got: " + String(ibt));
- ERR_FAIL_COND_V(obj == NULL, false);
+ ERR_FAIL_COND_V_MSG(obj == NULL, false, "Cannot instance script as custom resource saver, expected 'ResourceFormatSaver' inheritance, got: " + String(ibt) + ".");
ResourceFormatSaver *crl = Object::cast_to<ResourceFormatSaver>(obj);
crl->set_script(s.get_ref_ptr());
diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp
index ccce48ccd7..f2eaf57acc 100644
--- a/core/io/stream_peer_ssl.cpp
+++ b/core/io/stream_peer_ssl.cpp
@@ -30,10 +30,7 @@
#include "stream_peer_ssl.h"
-#include "core/io/certs_compressed.gen.h"
-#include "core/io/compression.h"
-#include "core/os/file_access.h"
-#include "core/project_settings.h"
+#include "core/engine.h"
StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL;
@@ -44,22 +41,8 @@ StreamPeerSSL *StreamPeerSSL::create() {
return NULL;
}
-StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL;
bool StreamPeerSSL::available = false;
-void StreamPeerSSL::load_certs_from_memory(const PoolByteArray &p_memory) {
- if (load_certs_func)
- load_certs_func(p_memory);
-}
-
-void StreamPeerSSL::load_certs_from_file(String p_path) {
- if (p_path != "") {
- PoolByteArray certs = get_cert_file_as_array(p_path);
- if (certs.size() > 0)
- load_certs_func(certs);
- }
-}
-
bool StreamPeerSSL::is_available() {
return available;
}
@@ -72,56 +55,11 @@ bool StreamPeerSSL::is_blocking_handshake_enabled() const {
return blocking_handshake;
}
-PoolByteArray StreamPeerSSL::get_cert_file_as_array(String p_path) {
-
- PoolByteArray out;
- FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
- if (f) {
- int flen = f->get_len();
- out.resize(flen + 1);
- PoolByteArray::Write w = out.write();
- f->get_buffer(w.ptr(), flen);
- w[flen] = 0; // Make sure it ends with string terminator
- memdelete(f);
-#ifdef DEBUG_ENABLED
- print_verbose(vformat("Loaded certs from '%s'.", p_path));
-#endif
- }
-
- return out;
-}
-
-PoolByteArray StreamPeerSSL::get_project_cert_array() {
-
- PoolByteArray out;
- String certs_path = GLOBAL_DEF("network/ssl/certificates", "");
- ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt"));
-
- if (certs_path != "") {
- // Use certs defined in project settings.
- return get_cert_file_as_array(certs_path);
- }
-#ifdef BUILTIN_CERTS_ENABLED
- else {
- // Use builtin certs only if user did not override it in project settings.
- out.resize(_certs_uncompressed_size + 1);
- PoolByteArray::Write w = out.write();
- Compression::decompress(w.ptr(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
- w[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
-#ifdef DEBUG_ENABLED
- print_verbose("Loaded builtin certs");
-#endif
- }
-#endif
-
- return out;
-}
-
void StreamPeerSSL::_bind_methods() {
ClassDB::bind_method(D_METHOD("poll"), &StreamPeerSSL::poll);
- ClassDB::bind_method(D_METHOD("accept_stream", "base"), &StreamPeerSSL::accept_stream);
- ClassDB::bind_method(D_METHOD("connect_to_stream", "stream", "validate_certs", "for_hostname"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("accept_stream", "stream", "private_key", "certificate", "chain"), &StreamPeerSSL::accept_stream, DEFVAL(Ref<X509Certificate>()));
+ ClassDB::bind_method(D_METHOD("connect_to_stream", "stream", "validate_certs", "for_hostname", "valid_certificate"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String()), DEFVAL(Ref<X509Certificate>()));
ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerSSL::get_status);
ClassDB::bind_method(D_METHOD("disconnect_from_stream"), &StreamPeerSSL::disconnect_from_stream);
ClassDB::bind_method(D_METHOD("set_blocking_handshake_enabled", "enabled"), &StreamPeerSSL::set_blocking_handshake_enabled);
diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h
index 482576c4c6..dedc35b9ac 100644
--- a/core/io/stream_peer_ssl.h
+++ b/core/io/stream_peer_ssl.h
@@ -31,19 +31,16 @@
#ifndef STREAM_PEER_SSL_H
#define STREAM_PEER_SSL_H
+#include "core/crypto/crypto.h"
#include "core/io/stream_peer.h"
class StreamPeerSSL : public StreamPeer {
GDCLASS(StreamPeerSSL, StreamPeer);
-public:
- typedef void (*LoadCertsFromMemory)(const PoolByteArray &p_certs);
-
protected:
static StreamPeerSSL *(*_create)();
static void _bind_methods();
- static LoadCertsFromMemory load_certs_func;
static bool available;
bool blocking_handshake;
@@ -61,18 +58,14 @@ public:
bool is_blocking_handshake_enabled() const;
virtual void poll() = 0;
- virtual Error accept_stream(Ref<StreamPeer> p_base) = 0;
- virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0;
+ virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>()) = 0;
+ virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>()) = 0;
virtual Status get_status() const = 0;
virtual void disconnect_from_stream() = 0;
static StreamPeerSSL *create();
- static PoolByteArray get_cert_file_as_array(String p_path);
- static PoolByteArray get_project_cert_array();
- static void load_certs_from_file(String p_path);
- static void load_certs_from_memory(const PoolByteArray &p_memory);
static bool is_available();
StreamPeerSSL();
diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp
index 67a0a905bd..e8e71c10ca 100644
--- a/core/io/translation_loader_po.cpp
+++ b/core/io/translation_loader_po.cpp
@@ -67,8 +67,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
if (status == STATUS_READING_ID) {
memdelete(f);
- ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
- ERR_FAIL_V(RES());
+ ERR_FAIL_V_MSG(RES(), p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
} else {
break;
}
@@ -79,8 +78,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
if (status == STATUS_READING_ID) {
memdelete(f);
- ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
- ERR_FAIL_V(RES());
+ ERR_FAIL_V_MSG(RES(), p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
}
if (msg_id != "") {
@@ -102,8 +100,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
if (status != STATUS_READING_ID) {
memdelete(f);
- ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
- ERR_FAIL_V(RES());
+ ERR_FAIL_V_MSG(RES(), p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
}
l = l.substr(6, l.length()).strip_edges();
@@ -118,11 +115,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
continue; //nothing to read or comment
}
- if (!l.begins_with("\"") || status == STATUS_NONE) {
- //not a string? failure!
- ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
- ERR_FAIL_V(RES());
- }
+ ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, RES(), p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
l = l.substr(1, l.length());
//find final quote
@@ -135,10 +128,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
}
}
- if (end_pos == -1) {
- ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
- ERR_FAIL_V(RES());
- }
+ ERR_FAIL_COND_V_MSG(end_pos == -1, RES(), p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
l = l.substr(0, end_pos);
l = l.c_unescape();
@@ -163,10 +153,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
config = msg_str;
}
- if (config == "") {
- ERR_EXPLAIN("No config found in file: " + p_path);
- ERR_FAIL_V(RES());
- }
+ ERR_FAIL_COND_V_MSG(config == "", RES(), "No config found in file: " + p_path + ".");
Vector<String> configs = config.split("\n");
for (int i = 0; i < configs.size(); i++) {
diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp
index 82527d3f38..9487947365 100644
--- a/core/io/xml_parser.cpp
+++ b/core/io/xml_parser.cpp
@@ -443,10 +443,8 @@ String XMLParser::get_attribute_value(const String &p_name) const {
}
}
- if (idx < 0) {
- ERR_EXPLAIN("Attribute not found: " + p_name);
- }
- ERR_FAIL_COND_V(idx < 0, "");
+ ERR_FAIL_COND_V_MSG(idx < 0, "", "Attribute not found: " + p_name + ".");
+
return attributes[idx].value;
}
diff --git a/core/math/SCsub b/core/math/SCsub
index 0995298a4b..be438fcfbe 100644
--- a/core/math/SCsub
+++ b/core/math/SCsub
@@ -2,37 +2,6 @@
Import('env')
-env_math = env.Clone() # Maybe make one specific for crypto?
-
-is_builtin = env["builtin_mbedtls"]
-has_module = env["module_mbedtls_enabled"]
-
-if is_builtin or not has_module:
- # Use our headers for builtin or if the module is not going to be compiled.
- # We decided not to depend on system mbedtls just for these few files that can
- # be easily extracted.
- env_math.Prepend(CPPPATH=["#thirdparty/mbedtls/include"])
-
-# MbedTLS core functions (for CryptoCore).
-# If the mbedtls module is compiled we don't need to add the .c files with our
-# custom config since they will be built by the module itself.
-# Only if the module is not enabled, we must compile here the required sources
-# to make a "light" build with only the necessary mbedtls files.
-if not has_module:
- env_thirdparty = env_math.Clone()
- env_thirdparty.disable_warnings()
- # Custom config file
- env_thirdparty.Append(CPPDEFINES=[('MBEDTLS_CONFIG_FILE', '\\"thirdparty/mbedtls/include/godot_core_mbedtls_config.h\\"')])
- thirdparty_mbedtls_dir = "#thirdparty/mbedtls/library/"
- thirdparty_mbedtls_sources = [
- "aes.c",
- "base64.c",
- "md5.c",
- "sha1.c",
- "sha256.c",
- "godot_core_mbedtls_platform.c"
- ]
- thirdparty_mbedtls_sources = [thirdparty_mbedtls_dir + file for file in thirdparty_mbedtls_sources]
- env_thirdparty.add_source_files(env.core_sources, thirdparty_mbedtls_sources)
+env_math = env.Clone()
env_math.add_source_files(env.core_sources, "*.cpp")
diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp
index b61119d8df..60b7326c29 100644
--- a/core/math/a_star.cpp
+++ b/core/math/a_star.cpp
@@ -40,7 +40,17 @@ int AStar::get_available_point_id() const {
return 1;
}
- return points.back()->key() + 1;
+ // calculate our new next available point id if bigger than before or next id already contained in set of points.
+ if (points.has(last_free_id)) {
+ int cur_new_id = last_free_id;
+ while (points.has(cur_new_id)) {
+ cur_new_id++;
+ }
+ int &non_const = const_cast<int &>(last_free_id);
+ non_const = cur_new_id;
+ }
+
+ return last_free_id;
}
void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) {
@@ -48,7 +58,10 @@ void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) {
ERR_FAIL_COND(p_id < 0);
ERR_FAIL_COND(p_weight_scale < 1);
- if (!points.has(p_id)) {
+ Point *found_pt;
+ bool p_exists = points.lookup(p_id, found_pt);
+
+ if (!p_exists) {
Point *pt = memnew(Point);
pt->id = p_id;
pt->pos = p_pos;
@@ -57,84 +70,98 @@ void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) {
pt->open_pass = 0;
pt->closed_pass = 0;
pt->enabled = true;
- points[p_id] = pt;
+ points.set(p_id, pt);
} else {
- points[p_id]->pos = p_pos;
- points[p_id]->weight_scale = p_weight_scale;
+ found_pt->pos = p_pos;
+ found_pt->weight_scale = p_weight_scale;
}
}
Vector3 AStar::get_point_position(int p_id) const {
- ERR_FAIL_COND_V(!points.has(p_id), Vector3());
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND_V(!p_exists, Vector3());
- return points[p_id]->pos;
+ return p->pos;
}
void AStar::set_point_position(int p_id, const Vector3 &p_pos) {
- ERR_FAIL_COND(!points.has(p_id));
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND(!p_exists);
- points[p_id]->pos = p_pos;
+ p->pos = p_pos;
}
real_t AStar::get_point_weight_scale(int p_id) const {
- ERR_FAIL_COND_V(!points.has(p_id), 0);
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND_V(!p_exists, 0);
- return points[p_id]->weight_scale;
+ return p->weight_scale;
}
void AStar::set_point_weight_scale(int p_id, real_t p_weight_scale) {
- ERR_FAIL_COND(!points.has(p_id));
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND(!p_exists);
ERR_FAIL_COND(p_weight_scale < 1);
- points[p_id]->weight_scale = p_weight_scale;
+ p->weight_scale = p_weight_scale;
}
void AStar::remove_point(int p_id) {
- ERR_FAIL_COND(!points.has(p_id));
-
- Point *p = points[p_id];
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND(!p_exists);
- for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) {
+ for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) {
- Segment s(p_id, E->get()->id);
+ Segment s(p_id, (*it.key));
segments.erase(s);
- E->get()->neighbours.erase(p);
- E->get()->unlinked_neighbours.erase(p);
+ (*it.value)->neighbours.remove(p->id);
+ (*it.value)->unlinked_neighbours.remove(p->id);
}
- for (Set<Point *>::Element *E = p->unlinked_neighbours.front(); E; E = E->next()) {
+ for (OAHashMap<int, Point *>::Iterator it = p->unlinked_neighbours.iter(); it.valid; it = p->unlinked_neighbours.next_iter(it)) {
- Segment s(p_id, E->get()->id);
+ Segment s(p_id, (*it.key));
segments.erase(s);
- E->get()->neighbours.erase(p);
- E->get()->unlinked_neighbours.erase(p);
+ (*it.value)->neighbours.remove(p->id);
+ (*it.value)->unlinked_neighbours.remove(p->id);
}
memdelete(p);
- points.erase(p_id);
+ points.remove(p_id);
+ last_free_id = p_id;
}
void AStar::connect_points(int p_id, int p_with_id, bool bidirectional) {
- ERR_FAIL_COND(!points.has(p_id));
- ERR_FAIL_COND(!points.has(p_with_id));
ERR_FAIL_COND(p_id == p_with_id);
- Point *a = points[p_id];
- Point *b = points[p_with_id];
- a->neighbours.insert(b);
+ Point *a;
+ bool from_exists = points.lookup(p_id, a);
+ ERR_FAIL_COND(!from_exists);
+
+ Point *b;
+ bool to_exists = points.lookup(p_with_id, b);
+ ERR_FAIL_COND(!to_exists);
- if (bidirectional)
- b->neighbours.insert(a);
- else
- b->unlinked_neighbours.insert(a);
+ a->neighbours.set(b->id, b);
+
+ if (bidirectional) {
+ b->neighbours.set(a->id, a);
+ } else {
+ b->unlinked_neighbours.set(a->id, a);
+ }
Segment s(p_id, p_with_id);
if (s.from == p_id) {
@@ -147,6 +174,7 @@ void AStar::connect_points(int p_id, int p_with_id, bool bidirectional) {
segments.insert(s);
}
+
void AStar::disconnect_points(int p_id, int p_with_id) {
Segment s(p_id, p_with_id);
@@ -154,12 +182,18 @@ void AStar::disconnect_points(int p_id, int p_with_id) {
segments.erase(s);
- Point *a = points[p_id];
- Point *b = points[p_with_id];
- a->neighbours.erase(b);
- a->unlinked_neighbours.erase(b);
- b->neighbours.erase(a);
- b->unlinked_neighbours.erase(a);
+ Point *a;
+ bool a_exists = points.lookup(p_id, a);
+ CRASH_COND(!a_exists);
+
+ Point *b;
+ bool b_exists = points.lookup(p_with_id, b);
+ CRASH_COND(!b_exists);
+
+ a->neighbours.remove(b->id);
+ a->unlinked_neighbours.remove(b->id);
+ b->neighbours.remove(a->id);
+ b->unlinked_neighbours.remove(a->id);
}
bool AStar::has_point(int p_id) const {
@@ -171,8 +205,8 @@ Array AStar::get_points() {
Array point_list;
- for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) {
- point_list.push_back(E->key());
+ for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) {
+ point_list.push_back(*(it.key));
}
return point_list;
@@ -180,14 +214,14 @@ Array AStar::get_points() {
PoolVector<int> AStar::get_point_connections(int p_id) {
- ERR_FAIL_COND_V(!points.has(p_id), PoolVector<int>());
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND_V(!p_exists, PoolVector<int>());
PoolVector<int> point_list;
- Point *p = points[p_id];
-
- for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) {
- point_list.push_back(E->get()->id);
+ for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) {
+ point_list.push_back((*it.key));
}
return point_list;
@@ -201,27 +235,41 @@ bool AStar::are_points_connected(int p_id, int p_with_id) const {
void AStar::clear() {
- for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) {
-
- memdelete(E->get());
+ last_free_id = 0;
+ for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) {
+ memdelete(*(it.value));
}
segments.clear();
points.clear();
}
+int AStar::get_point_count() const {
+ return points.get_num_elements();
+}
+
+int AStar::get_point_capacity() const {
+ return points.get_capacity();
+}
+
+void AStar::reserve_space(int p_num_nodes) {
+ ERR_FAIL_COND_MSG(p_num_nodes <= 0, "New capacity must be greater than 0, was: " + itos(p_num_nodes) + ".");
+ ERR_FAIL_COND_MSG((uint32_t)p_num_nodes < points.get_capacity(), "New capacity must be greater than current capacity: " + itos(points.get_capacity()) + ", new was: " + itos(p_num_nodes) + ".");
+ points.reserve(p_num_nodes);
+}
+
int AStar::get_closest_point(const Vector3 &p_point) const {
int closest_id = -1;
real_t closest_dist = 1e20;
- for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) {
+ for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) {
+
+ if (!(*it.value)->enabled) continue; // Disabled points should not be considered.
- if (!E->get()->enabled)
- continue; //Disabled points should not be considered
- real_t d = p_point.distance_squared_to(E->get()->pos);
+ real_t d = p_point.distance_squared_to((*it.value)->pos);
if (closest_id < 0 || d < closest_dist) {
closest_dist = d;
- closest_id = E->key();
+ closest_id = *(it.key);
}
}
@@ -230,8 +278,8 @@ int AStar::get_closest_point(const Vector3 &p_point) const {
Vector3 AStar::get_closest_position_in_segment(const Vector3 &p_point) const {
- real_t closest_dist = 1e20;
bool found = false;
+ real_t closest_dist = 1e20;
Vector3 closest_point;
for (const Set<Segment>::Element *E = segments.front(); E; E = E->next()) {
@@ -262,8 +310,7 @@ bool AStar::_solve(Point *begin_point, Point *end_point) {
pass++;
- if (!end_point->enabled)
- return false;
+ if (!end_point->enabled) return false;
bool found_route = false;
@@ -272,13 +319,9 @@ bool AStar::_solve(Point *begin_point, Point *end_point) {
begin_point->g_score = 0;
begin_point->f_score = _estimate_cost(begin_point->id, end_point->id);
-
open_list.push_back(begin_point);
- while (true) {
-
- if (open_list.size() == 0) // No path found
- break;
+ while (!open_list.empty()) {
Point *p = open_list[0]; // The currently processed point
@@ -291,24 +334,23 @@ bool AStar::_solve(Point *begin_point, Point *end_point) {
open_list.remove(open_list.size() - 1);
p->closed_pass = pass; // Mark the point as closed
- for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) {
+ for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) {
- Point *e = E->get(); // The neighbour point
+ Point *e = *(it.value); // The neighbour point
- if (!e->enabled || e->closed_pass == pass)
+ if (!e->enabled || e->closed_pass == pass) {
continue;
+ }
real_t tentative_g_score = p->g_score + _compute_cost(p->id, e->id) * e->weight_scale;
bool new_point = false;
- if (e->open_pass != pass) { // The point wasn't inside the open list
-
+ if (e->open_pass != pass) { // The point wasn't inside the open list.
e->open_pass = pass;
open_list.push_back(e);
new_point = true;
- } else if (tentative_g_score >= e->g_score) { // The new path is worse than the previous
-
+ } else if (tentative_g_score >= e->g_score) { // The new path is worse than the previous.
continue;
}
@@ -316,10 +358,11 @@ bool AStar::_solve(Point *begin_point, Point *end_point) {
e->g_score = tentative_g_score;
e->f_score = e->g_score + _estimate_cost(e->id, end_point->id);
- if (new_point) // The position of the new points is already known
+ if (new_point) { // The position of the new points is already known.
sorter.push_heap(0, open_list.size() - 1, 0, e, open_list.ptrw());
- else
+ } else {
sorter.push_heap(0, open_list.find(e), 0, e, open_list.ptrw());
+ }
}
}
@@ -331,7 +374,15 @@ float AStar::_estimate_cost(int p_from_id, int p_to_id) {
if (get_script_instance() && get_script_instance()->has_method(SceneStringNames::get_singleton()->_estimate_cost))
return get_script_instance()->call(SceneStringNames::get_singleton()->_estimate_cost, p_from_id, p_to_id);
- return points[p_from_id]->pos.distance_to(points[p_to_id]->pos);
+ Point *from_point;
+ bool from_exists = points.lookup(p_from_id, from_point);
+ CRASH_COND(!from_exists);
+
+ Point *to_point;
+ bool to_exists = points.lookup(p_to_id, to_point);
+ CRASH_COND(!to_exists);
+
+ return from_point->pos.distance_to(to_point->pos);
}
float AStar::_compute_cost(int p_from_id, int p_to_id) {
@@ -339,16 +390,26 @@ float AStar::_compute_cost(int p_from_id, int p_to_id) {
if (get_script_instance() && get_script_instance()->has_method(SceneStringNames::get_singleton()->_compute_cost))
return get_script_instance()->call(SceneStringNames::get_singleton()->_compute_cost, p_from_id, p_to_id);
- return points[p_from_id]->pos.distance_to(points[p_to_id]->pos);
+ Point *from_point;
+ bool from_exists = points.lookup(p_from_id, from_point);
+ CRASH_COND(!from_exists);
+
+ Point *to_point;
+ bool to_exists = points.lookup(p_to_id, to_point);
+ CRASH_COND(!to_exists);
+
+ return from_point->pos.distance_to(to_point->pos);
}
PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) {
- ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<Vector3>());
- ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<Vector3>());
+ Point *a;
+ bool from_exists = points.lookup(p_from_id, a);
+ ERR_FAIL_COND_V(!from_exists, PoolVector<Vector3>());
- Point *a = points[p_from_id];
- Point *b = points[p_to_id];
+ Point *b;
+ bool to_exists = points.lookup(p_to_id, b);
+ ERR_FAIL_COND_V(!to_exists, PoolVector<Vector3>());
if (a == b) {
PoolVector<Vector3> ret;
@@ -360,11 +421,8 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) {
Point *end_point = b;
bool found_route = _solve(begin_point, end_point);
+ if (!found_route) return PoolVector<Vector3>();
- if (!found_route)
- return PoolVector<Vector3>();
-
- // Midpoints
Point *p = end_point;
int pc = 1; // Begin point
while (p != begin_point) {
@@ -393,11 +451,13 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) {
PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
- ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<int>());
- ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<int>());
+ Point *a;
+ bool from_exists = points.lookup(p_from_id, a);
+ ERR_FAIL_COND_V(!from_exists, PoolVector<int>());
- Point *a = points[p_from_id];
- Point *b = points[p_to_id];
+ Point *b;
+ bool to_exists = points.lookup(p_to_id, b);
+ ERR_FAIL_COND_V(!to_exists, PoolVector<int>());
if (a == b) {
PoolVector<int> ret;
@@ -409,11 +469,8 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
Point *end_point = b;
bool found_route = _solve(begin_point, end_point);
+ if (!found_route) return PoolVector<int>();
- if (!found_route)
- return PoolVector<int>();
-
- // Midpoints
Point *p = end_point;
int pc = 1; // Begin point
while (p != begin_point) {
@@ -442,16 +499,20 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
void AStar::set_point_disabled(int p_id, bool p_disabled) {
- ERR_FAIL_COND(!points.has(p_id));
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND(!p_exists);
- points[p_id]->enabled = !p_disabled;
+ p->enabled = !p_disabled;
}
bool AStar::is_point_disabled(int p_id) const {
- ERR_FAIL_COND_V(!points.has(p_id), false);
+ Point *p;
+ bool p_exists = points.lookup(p_id, p);
+ ERR_FAIL_COND_V(!p_exists, false);
- return !points[p_id]->enabled;
+ return !p->enabled;
}
void AStar::_bind_methods() {
@@ -474,6 +535,9 @@ void AStar::_bind_methods() {
ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar::disconnect_points);
ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar::are_points_connected);
+ ClassDB::bind_method(D_METHOD("get_point_count"), &AStar::get_point_count);
+ ClassDB::bind_method(D_METHOD("get_point_capacity"), &AStar::get_point_capacity);
+ ClassDB::bind_method(D_METHOD("reserve_space", "num_nodes"), &AStar::reserve_space);
ClassDB::bind_method(D_METHOD("clear"), &AStar::clear);
ClassDB::bind_method(D_METHOD("get_closest_point", "to_position"), &AStar::get_closest_point);
@@ -487,13 +551,11 @@ void AStar::_bind_methods() {
}
AStar::AStar() {
-
+ last_free_id = 0;
pass = 1;
}
AStar::~AStar() {
-
- pass = 1;
clear();
}
@@ -560,10 +622,22 @@ bool AStar2D::are_points_connected(int p_id, int p_with_id) const {
return astar.are_points_connected(p_id, p_with_id);
}
+int AStar2D::get_point_count() const {
+ return astar.get_point_count();
+}
+
+int AStar2D::get_point_capacity() const {
+ return astar.get_point_capacity();
+}
+
void AStar2D::clear() {
astar.clear();
}
+void AStar2D::reserve_space(int p_num_nodes) {
+ astar.reserve_space(p_num_nodes);
+}
+
int AStar2D::get_closest_point(const Vector2 &p_point) const {
return astar.get_closest_point(Vector3(p_point.x, p_point.y, 0));
}
@@ -614,6 +688,9 @@ void AStar2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar2D::disconnect_points);
ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar2D::are_points_connected);
+ ClassDB::bind_method(D_METHOD("get_point_count"), &AStar2D::get_point_count);
+ ClassDB::bind_method(D_METHOD("get_point_capacity"), &AStar2D::get_point_capacity);
+ ClassDB::bind_method(D_METHOD("reserve_space", "num_nodes"), &AStar2D::reserve_space);
ClassDB::bind_method(D_METHOD("clear"), &AStar2D::clear);
ClassDB::bind_method(D_METHOD("get_closest_point", "to_position"), &AStar2D::get_closest_point);
diff --git a/core/math/a_star.h b/core/math/a_star.h
index cbabcce974..ec2a06f07f 100644
--- a/core/math/a_star.h
+++ b/core/math/a_star.h
@@ -31,6 +31,7 @@
#ifndef ASTAR_H
#define ASTAR_H
+#include "core/oa_hash_map.h"
#include "core/reference.h"
/**
@@ -43,19 +44,21 @@ class AStar : public Reference {
GDCLASS(AStar, Reference);
- uint64_t pass;
-
struct Point {
+ Point() :
+ neighbours(4u),
+ unlinked_neighbours(4u) {}
+
int id;
Vector3 pos;
real_t weight_scale;
bool enabled;
- Set<Point *> neighbours;
- Set<Point *> unlinked_neighbours;
+ OAHashMap<int, Point *> neighbours;
+ OAHashMap<int, Point *> unlinked_neighbours;
- // Used for pathfinding
+ // Used for pathfinding.
Point *prev_point;
real_t g_score;
real_t f_score;
@@ -63,16 +66,15 @@ class AStar : public Reference {
uint64_t closed_pass;
};
- Map<int, Point *> points;
-
struct SortPoints {
- _FORCE_INLINE_ bool operator()(const Point *A, const Point *B) const { // Returns true when the Point A is worse than Point B
- if (A->f_score > B->f_score)
+ _FORCE_INLINE_ bool operator()(const Point *A, const Point *B) const { // Returns true when the Point A is worse than Point B.
+ if (A->f_score > B->f_score) {
return true;
- else if (A->f_score < B->f_score)
+ } else if (A->f_score < B->f_score) {
return false;
- else
- return A->g_score < B->g_score; // If the f_costs are the same then prioritize the points that are further away from the start
+ } else {
+ return A->g_score < B->g_score; // If the f_costs are the same then prioritize the points that are further away from the start.
+ }
}
};
@@ -100,6 +102,10 @@ class AStar : public Reference {
}
};
+ int last_free_id;
+ uint64_t pass;
+
+ OAHashMap<int, Point *> points;
Set<Segment> segments;
bool _solve(Point *begin_point, Point *end_point);
@@ -130,6 +136,9 @@ public:
void disconnect_points(int p_id, int p_with_id);
bool are_points_connected(int p_id, int p_with_id) const;
+ int get_point_count() const;
+ int get_point_capacity() const;
+ void reserve_space(int p_num_nodes);
void clear();
int get_closest_point(const Vector3 &p_point) const;
@@ -169,6 +178,9 @@ public:
void disconnect_points(int p_id, int p_with_id);
bool are_points_connected(int p_id, int p_with_id) const;
+ int get_point_count() const;
+ int get_point_capacity() const;
+ void reserve_space(int p_num_nodes);
void clear();
int get_closest_point(const Vector2 &p_point) const;
diff --git a/core/math/basis.cpp b/core/math/basis.cpp
index 400f342018..2985959113 100644
--- a/core/math/basis.cpp
+++ b/core/math/basis.cpp
@@ -618,10 +618,7 @@ Basis::operator String() const {
Quat Basis::get_quat() const {
#ifdef MATH_CHECKS
- if (!is_rotation()) {
- ERR_EXPLAIN("Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quat() or call orthonormalized() instead.");
- ERR_FAIL_V(Quat());
- }
+ ERR_FAIL_COND_V_MSG(!is_rotation(), Quat(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quat() or call orthonormalized() instead.");
#endif
/* Allow getting a quaternion from an unnormalized transform */
Basis m = *this;
diff --git a/core/math/delaunay.h b/core/math/delaunay.h
index ed52c506db..3f8013a3e6 100644
--- a/core/math/delaunay.h
+++ b/core/math/delaunay.h
@@ -80,11 +80,11 @@ public:
}
static bool edge_compare(const Vector<Vector2> &p_vertices, const Edge &p_a, const Edge &p_b) {
- if (Math::is_zero_approx(p_vertices[p_a.edge[0]].distance_to(p_vertices[p_b.edge[0]])) && Math::is_zero_approx(p_vertices[p_a.edge[1]].distance_to(p_vertices[p_b.edge[1]]))) {
+ if (p_vertices[p_a.edge[0]] == p_vertices[p_b.edge[0]] && p_vertices[p_a.edge[1]] == p_vertices[p_b.edge[1]]) {
return true;
}
- if (Math::is_zero_approx(p_vertices[p_a.edge[0]].distance_to(p_vertices[p_b.edge[1]])) && Math::is_zero_approx(p_vertices[p_a.edge[1]].distance_to(p_vertices[p_b.edge[0]]))) {
+ if (p_vertices[p_a.edge[0]] == p_vertices[p_b.edge[1]] && p_vertices[p_a.edge[1]] == p_vertices[p_b.edge[0]]) {
return true;
}
diff --git a/core/math/expression.cpp b/core/math/expression.cpp
index 15eea1d308..46f81ce5c3 100644
--- a/core/math/expression.cpp
+++ b/core/math/expression.cpp
@@ -2161,10 +2161,8 @@ Error Expression::parse(const String &p_expression, const Vector<String> &p_inpu
}
Variant Expression::execute(Array p_inputs, Object *p_base, bool p_show_error) {
- if (error_set) {
- ERR_EXPLAIN("There was previously a parse error: " + error_str);
- ERR_FAIL_V(Variant());
- }
+
+ ERR_FAIL_COND_V_MSG(error_set, Variant(), "There was previously a parse error: " + error_str + ".");
execution_error = false;
Variant output;
@@ -2173,10 +2171,7 @@ Variant Expression::execute(Array p_inputs, Object *p_base, bool p_show_error) {
if (err) {
execution_error = true;
error_str = error_txt;
- if (p_show_error) {
- ERR_EXPLAIN(error_str);
- ERR_FAIL_V(Variant());
- }
+ ERR_FAIL_COND_V_MSG(p_show_error, Variant(), error_str);
}
return output;
diff --git a/core/math/geometry.h b/core/math/geometry.h
index a32ed2f56b..82d9884e9b 100644
--- a/core/math/geometry.h
+++ b/core/math/geometry.h
@@ -834,8 +834,7 @@ public:
static Vector<Vector<Point2> > offset_polyline_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
- ERR_EXPLAIN("Attempt to offset a polyline like a polygon (use offset_polygon_2d instead).");
- ERR_FAIL_COND_V(p_end_type == END_POLYGON, Vector<Vector<Point2> >());
+ ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2> >(), "Attempt to offset a polyline like a polygon (use offset_polygon_2d instead).");
return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
}
diff --git a/core/math/octree.h b/core/math/octree.h
index e752e10abc..db15c8a1f8 100644
--- a/core/math/octree.h
+++ b/core/math/octree.h
@@ -564,10 +564,7 @@ void Octree<T, use_pairs, AL>::_ensure_valid_root(const AABB &p_aabb) {
while (!base.encloses(p_aabb)) {
- if (base.size.x > OCTREE_SIZE_LIMIT) {
- ERR_EXPLAIN("Octree upper size limit reeached, does the AABB supplied contain NAN?");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(base.size.x > OCTREE_SIZE_LIMIT, "Octree upper size limit reached, does the AABB supplied contain NAN?");
Octant *gp = memnew_allocator(Octant, AL);
octant_count++;
diff --git a/core/math/vector2.cpp b/core/math/vector2.cpp
index 779a28be66..972bccc0ac 100644
--- a/core/math/vector2.cpp
+++ b/core/math/vector2.cpp
@@ -98,6 +98,11 @@ real_t Vector2::cross(const Vector2 &p_other) const {
return x * p_other.y - y * p_other.x;
}
+Vector2 Vector2::sign() const {
+
+ return Vector2(SGN(x), SGN(y));
+}
+
Vector2 Vector2::floor() const {
return Vector2(Math::floor(x), Math::floor(y));
@@ -121,6 +126,14 @@ Vector2 Vector2::rotated(real_t p_by) const {
return v;
}
+Vector2 Vector2::posmod(const real_t p_mod) const {
+ return Vector2(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod));
+}
+
+Vector2 Vector2::posmodv(const Vector2 &p_modv) const {
+ return Vector2(Math::fposmod(x, p_modv.x), Math::fposmod(y, p_modv.y));
+}
+
Vector2 Vector2::project(const Vector2 &p_b) const {
return p_b * (dot(p_b) / p_b.length_squared());
}
diff --git a/core/math/vector2.h b/core/math/vector2.h
index 78a1641c1e..1a73831891 100644
--- a/core/math/vector2.h
+++ b/core/math/vector2.h
@@ -38,6 +38,11 @@ struct Vector2i;
struct Vector2 {
+ enum Axis {
+ AXIS_X,
+ AXIS_Y,
+ };
+
union {
real_t x;
real_t width;
@@ -69,6 +74,8 @@ struct Vector2 {
real_t dot(const Vector2 &p_other) const;
real_t cross(const Vector2 &p_other) const;
+ Vector2 posmod(const real_t p_mod) const;
+ Vector2 posmodv(const Vector2 &p_modv) const;
Vector2 project(const Vector2 &p_b) const;
Vector2 plane_project(real_t p_d, const Vector2 &p_vec) const;
@@ -107,8 +114,10 @@ struct Vector2 {
bool operator==(const Vector2 &p_vec2) const;
bool operator!=(const Vector2 &p_vec2) const;
- bool operator<(const Vector2 &p_vec2) const { return (Math::is_equal_approx(x, p_vec2.x)) ? (y < p_vec2.y) : (x < p_vec2.x); }
- bool operator<=(const Vector2 &p_vec2) const { return (Math::is_equal_approx(x, p_vec2.x)) ? (y <= p_vec2.y) : (x < p_vec2.x); }
+ bool operator<(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); }
+ bool operator>(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y > p_vec2.y) : (x > p_vec2.x); }
+ bool operator<=(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y <= p_vec2.y) : (x < p_vec2.x); }
+ bool operator>=(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y >= p_vec2.y) : (x > p_vec2.x); }
real_t angle() const;
@@ -129,6 +138,7 @@ struct Vector2 {
return Vector2(y, -x);
}
+ Vector2 sign() const;
Vector2 floor() const;
Vector2 ceil() const;
Vector2 round() const;
@@ -141,10 +151,7 @@ struct Vector2 {
x = p_x;
y = p_y;
}
- _FORCE_INLINE_ Vector2() {
- x = 0;
- y = 0;
- }
+ _FORCE_INLINE_ Vector2() { x = y = 0; }
};
_FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2 &p_vec) const {
@@ -262,6 +269,11 @@ typedef Vector2 Point2;
struct Vector2i {
+ enum Axis {
+ AXIS_X,
+ AXIS_Y,
+ };
+
union {
int x;
int width;
diff --git a/core/math/vector3.h b/core/math/vector3.h
index 45bdfee487..597d3c22a8 100644
--- a/core/math/vector3.h
+++ b/core/math/vector3.h
@@ -31,9 +31,7 @@
#ifndef VECTOR3_H
#define VECTOR3_H
-#include "core/math/math_defs.h"
#include "core/math/math_funcs.h"
-#include "core/typedefs.h"
#include "core/ustring.h"
class Basis;
@@ -110,6 +108,8 @@ struct Vector3 {
_FORCE_INLINE_ real_t distance_to(const Vector3 &p_b) const;
_FORCE_INLINE_ real_t distance_squared_to(const Vector3 &p_b) const;
+ _FORCE_INLINE_ Vector3 posmod(const real_t p_mod) const;
+ _FORCE_INLINE_ Vector3 posmodv(const Vector3 &p_modv) const;
_FORCE_INLINE_ Vector3 project(const Vector3 &p_b) const;
_FORCE_INLINE_ real_t angle_to(const Vector3 &p_b) const;
@@ -141,15 +141,17 @@ struct Vector3 {
_FORCE_INLINE_ bool operator!=(const Vector3 &p_v) const;
_FORCE_INLINE_ bool operator<(const Vector3 &p_v) const;
_FORCE_INLINE_ bool operator<=(const Vector3 &p_v) const;
+ _FORCE_INLINE_ bool operator>(const Vector3 &p_v) const;
+ _FORCE_INLINE_ bool operator>=(const Vector3 &p_v) const;
operator String() const;
- _FORCE_INLINE_ Vector3() { x = y = z = 0; }
_FORCE_INLINE_ Vector3(real_t p_x, real_t p_y, real_t p_z) {
x = p_x;
y = p_y;
z = p_z;
}
+ _FORCE_INLINE_ Vector3() { x = y = z = 0; }
};
// Should be included after class definition, otherwise we get circular refs
@@ -233,6 +235,14 @@ real_t Vector3::distance_squared_to(const Vector3 &p_b) const {
return (p_b - *this).length_squared();
}
+Vector3 Vector3::posmod(const real_t p_mod) const {
+ return Vector3(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod), Math::fposmod(z, p_mod));
+}
+
+Vector3 Vector3::posmodv(const Vector3 &p_modv) const {
+ return Vector3(Math::fposmod(x, p_modv.x), Math::fposmod(y, p_modv.y), Math::fposmod(z, p_modv.z));
+}
+
Vector3 Vector3::project(const Vector3 &p_b) const {
return p_b * (dot(p_b) / p_b.length_squared());
}
@@ -357,6 +367,18 @@ bool Vector3::operator<(const Vector3 &p_v) const {
}
}
+bool Vector3::operator>(const Vector3 &p_v) const {
+
+ if (x == p_v.x) {
+ if (y == p_v.y)
+ return z > p_v.z;
+ else
+ return y > p_v.y;
+ } else {
+ return x > p_v.x;
+ }
+}
+
bool Vector3::operator<=(const Vector3 &p_v) const {
if (Math::is_equal_approx(x, p_v.x)) {
@@ -369,6 +391,18 @@ bool Vector3::operator<=(const Vector3 &p_v) const {
}
}
+bool Vector3::operator>=(const Vector3 &p_v) const {
+
+ if (x == p_v.x) {
+ if (y == p_v.y)
+ return z >= p_v.z;
+ else
+ return y > p_v.y;
+ } else {
+ return x > p_v.x;
+ }
+}
+
_FORCE_INLINE_ Vector3 vec3_cross(const Vector3 &p_a, const Vector3 &p_b) {
return p_a.cross(p_b);
diff --git a/core/message_queue.cpp b/core/message_queue.cpp
index 32d2b805f6..390989ac91 100644
--- a/core/message_queue.cpp
+++ b/core/message_queue.cpp
@@ -52,8 +52,7 @@ Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const V
type = ObjectDB::get_instance(p_id)->get_class();
print_line("Failed method: " + type + ":" + p_method + " target ID: " + itos(p_id));
statistics();
- ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
+ ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
@@ -103,8 +102,7 @@ Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Vari
type = ObjectDB::get_instance(p_id)->get_class();
print_line("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id));
statistics();
- ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
+ ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
@@ -136,8 +134,7 @@ Error MessageQueue::push_notification(ObjectID p_id, int p_notification) {
type = ObjectDB::get_instance(p_id)->get_class();
print_line("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id));
statistics();
- ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
+ ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings.");
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
@@ -256,7 +253,7 @@ void MessageQueue::_call_function(Object *p_target, const StringName &p_func, co
p_target->call(p_func, argptrs, p_argcount, ce);
if (p_show_error && ce.error != Variant::CallError::CALL_OK) {
- ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));
+ ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce) + ".");
}
}
diff --git a/core/node_path.cpp b/core/node_path.cpp
index a4b7cbe2eb..8244785d84 100644
--- a/core/node_path.cpp
+++ b/core/node_path.cpp
@@ -375,8 +375,7 @@ NodePath::NodePath(const String &p_path) {
if (str == "") {
if (path[i] == 0) continue; // Allow end-of-path :
- ERR_EXPLAIN("Invalid NodePath: " + p_path);
- ERR_FAIL();
+ ERR_FAIL_MSG("Invalid NodePath: " + p_path + ".");
}
subpath.push_back(str);
diff --git a/core/oa_hash_map.h b/core/oa_hash_map.h
index e52d36a859..5ea6d8b0d4 100644
--- a/core/oa_hash_map.h
+++ b/core/oa_hash_map.h
@@ -62,7 +62,7 @@ private:
static const uint32_t EMPTY_HASH = 0;
static const uint32_t DELETED_HASH_BIT = 1 << 31;
- _FORCE_INLINE_ uint32_t _hash(const TKey &p_key) {
+ _FORCE_INLINE_ uint32_t _hash(const TKey &p_key) const {
uint32_t hash = Hasher::hash(p_key);
if (hash == EMPTY_HASH) {
@@ -74,12 +74,11 @@ private:
return hash;
}
- _FORCE_INLINE_ uint32_t _get_probe_length(uint32_t p_pos, uint32_t p_hash) {
+ _FORCE_INLINE_ uint32_t _get_probe_length(uint32_t p_pos, uint32_t p_hash) const {
p_hash = p_hash & ~DELETED_HASH_BIT; // we don't care if it was deleted or not
uint32_t original_pos = p_hash % capacity;
-
- return p_pos - original_pos;
+ return (p_pos - original_pos) % capacity;
}
_FORCE_INLINE_ void _construct(uint32_t p_pos, uint32_t p_hash, const TKey &p_key, const TValue &p_value) {
@@ -90,7 +89,7 @@ private:
num_elements++;
}
- bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) {
+ bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
uint32_t hash = _hash(p_key);
uint32_t pos = hash % capacity;
uint32_t distance = 0;
@@ -151,17 +150,17 @@ private:
distance++;
}
}
- void _resize_and_rehash() {
+
+ void _resize_and_rehash(uint32_t p_new_capacity) {
+
+ uint32_t old_capacity = capacity;
+ capacity = p_new_capacity;
TKey *old_keys = keys;
TValue *old_values = values;
uint32_t *old_hashes = hashes;
- uint32_t old_capacity = capacity;
-
- capacity = old_capacity * 2;
num_elements = 0;
-
keys = memnew_arr(TKey, capacity);
values = memnew_arr(TValue, capacity);
hashes = memnew_arr(uint32_t, capacity);
@@ -186,10 +185,38 @@ private:
memdelete_arr(old_hashes);
}
+ void _resize_and_rehash() {
+ _resize_and_rehash(capacity * 2);
+ }
+
public:
_FORCE_INLINE_ uint32_t get_capacity() const { return capacity; }
_FORCE_INLINE_ uint32_t get_num_elements() const { return num_elements; }
+ bool empty() const {
+ return num_elements == 0;
+ }
+
+ void clear() {
+
+ for (uint32_t i = 0; i < capacity; i++) {
+
+ if (hashes[i] == EMPTY_HASH) {
+ continue;
+ }
+
+ if (hashes[i] & DELETED_HASH_BIT) {
+ continue;
+ }
+
+ hashes[i] = EMPTY_HASH;
+ values[i].~TValue();
+ keys[i].~TKey();
+ }
+
+ num_elements = 0;
+ }
+
void insert(const TKey &p_key, const TValue &p_value) {
if ((float)num_elements / (float)capacity > 0.9) {
@@ -219,7 +246,7 @@ public:
* if r_data is not NULL then the value will be written to the object
* it points to.
*/
- bool lookup(const TKey &p_key, TValue &r_data) {
+ bool lookup(const TKey &p_key, TValue &r_data) const {
uint32_t pos = 0;
bool exists = _lookup_pos(p_key, pos);
@@ -232,7 +259,7 @@ public:
return false;
}
- _FORCE_INLINE_ bool has(const TKey &p_key) {
+ _FORCE_INLINE_ bool has(const TKey &p_key) const {
uint32_t _pos = 0;
return _lookup_pos(p_key, _pos);
}
@@ -251,6 +278,16 @@ public:
num_elements--;
}
+ /**
+ * reserves space for a number of elements, useful to avoid many resizes and rehashes
+ * if adding a known (possibly large) number of elements at once, must be larger than old
+ * capacity.
+ **/
+ void reserve(uint32_t p_new_capacity) {
+ ERR_FAIL_COND(p_new_capacity < capacity);
+ _resize_and_rehash(p_new_capacity);
+ }
+
struct Iterator {
bool valid;
@@ -302,6 +339,9 @@ public:
return it;
}
+ OAHashMap(const OAHashMap &) = delete; // Delete the copy constructor so we don't get unexpected copies and dangling pointers.
+ OAHashMap &operator=(const OAHashMap &) = delete; // Same for assignment operator.
+
OAHashMap(uint32_t p_initial_capacity = 64) {
capacity = p_initial_capacity;
@@ -312,7 +352,7 @@ public:
hashes = memnew_arr(uint32_t, p_initial_capacity);
for (uint32_t i = 0; i < p_initial_capacity; i++) {
- hashes[i] = 0;
+ hashes[i] = EMPTY_HASH;
}
}
diff --git a/core/object.cpp b/core/object.cpp
index 3367d6b6c3..62bfa31480 100644
--- a/core/object.cpp
+++ b/core/object.cpp
@@ -709,20 +709,17 @@ static void _test_call_error(const StringName &p_func, const Variant::CallError
break;
case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: {
- ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Invalid type for argument " + itos(error.argument) + ", expected " + Variant::get_type_name(error.expected));
- ERR_FAIL();
+ ERR_FAIL_MSG("Error calling function: " + String(p_func) + " - Invalid type for argument " + itos(error.argument) + ", expected " + Variant::get_type_name(error.expected) + ".");
break;
}
case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
- ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too many arguments, expected " + itos(error.argument));
- ERR_FAIL();
+ ERR_FAIL_MSG("Error calling function: " + String(p_func) + " - Too many arguments, expected " + itos(error.argument) + ".");
break;
}
case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
- ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too few arguments, expected " + itos(error.argument));
- ERR_FAIL();
+ ERR_FAIL_MSG("Error calling function: " + String(p_func) + " - Too few arguments, expected " + itos(error.argument) + ".");
break;
}
case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL:
@@ -739,15 +736,9 @@ void Object::call_multilevel(const StringName &p_method, const Variant **p_args,
if (p_method == CoreStringNames::get_singleton()->_free) {
#ifdef DEBUG_ENABLED
- if (Object::cast_to<Reference>(this)) {
- ERR_EXPLAIN("Can't 'free' a reference.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(Object::cast_to<Reference>(this), "Can't 'free' a reference.");
- if (_lock_index.get() > 1) {
- ERR_EXPLAIN("Object is locked and can't be freed.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(_lock_index.get() > 1, "Object is locked and can't be freed.");
#endif
//must be here, must be before everything,
@@ -835,8 +826,7 @@ Variant Object::callv(const StringName &p_method, const Array &p_args) {
Variant::CallError ce;
Variant ret = call(p_method, argptrs, p_args.size(), ce);
if (ce.error != Variant::CallError::CALL_OK) {
- ERR_EXPLAIN("Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce));
- ERR_FAIL_V(Variant());
+ ERR_FAIL_V_MSG(Variant(), "Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce) + ".");
}
return ret;
}
@@ -888,15 +878,13 @@ Variant Object::call(const StringName &p_method, const Variant **p_args, int p_a
if (Object::cast_to<Reference>(this)) {
r_error.argument = 0;
r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
- ERR_EXPLAIN("Can't 'free' a reference.");
- ERR_FAIL_V(Variant());
+ ERR_FAIL_V_MSG(Variant(), "Can't 'free' a reference.");
}
if (_lock_index.get() > 1) {
r_error.argument = 0;
r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
- ERR_EXPLAIN("Object is locked and can't be freed.");
- ERR_FAIL_V(Variant());
+ ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
}
#endif
@@ -1172,10 +1160,7 @@ Error Object::emit_signal(const StringName &p_name, const Variant **p_args, int
#ifdef DEBUG_ENABLED
bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
//check in script
- if (!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name)) {
- ERR_EXPLAIN("Can't emit non-existing signal " + String("\"") + p_name + "\".");
- ERR_FAIL_V(ERR_UNAVAILABLE);
- }
+ ERR_FAIL_COND_V_MSG(!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name), ERR_UNAVAILABLE, "Can't emit non-existing signal " + String("\"") + p_name + "\".");
#endif
//not connected? just return
return ERR_UNAVAILABLE;
@@ -1240,7 +1225,7 @@ Error Object::emit_signal(const StringName &p_name, const Variant **p_args, int
if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
//most likely object is not initialized yet, do not throw error.
} else {
- ERR_PRINTS("Error calling method from signal '" + String(p_name) + "': " + Variant::get_call_error_text(target, c.method, args, argc, ce));
+ ERR_PRINTS("Error calling method from signal '" + String(p_name) + "': " + Variant::get_call_error_text(target, c.method, args, argc, ce) + ".");
err = ERR_METHOD_NOT_FOUND;
}
}
@@ -1415,8 +1400,9 @@ void Object::get_signal_connection_list(const StringName &p_signal, List<Connect
p_connections->push_back(s->slot_map.getv(i).conn);
}
-bool Object::has_persistent_signal_connections() const {
+int Object::get_persistent_signal_connection_count() const {
+ int count = 0;
const StringName *S = NULL;
while ((S = signal_map.next(S))) {
@@ -1424,13 +1410,13 @@ bool Object::has_persistent_signal_connections() const {
const Signal *s = &signal_map[*S];
for (int i = 0; i < s->slot_map.size(); i++) {
-
- if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST)
- return true;
+ if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST) {
+ count += 1;
+ }
}
}
- return false;
+ return count;
}
void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
@@ -1463,10 +1449,8 @@ Error Object::connect(const StringName &p_signal, Object *p_to_object, const Str
#endif
}
- if (!signal_is_valid) {
- ERR_EXPLAIN("In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to method '" + p_to_object->get_class() + "." + p_to_method + "'");
- ERR_FAIL_V(ERR_INVALID_PARAMETER);
- }
+ ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, "In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to method '" + p_to_object->get_class() + "." + p_to_method + "'.");
+
signal_map[p_signal] = Signal();
s = &signal_map[p_signal];
}
@@ -1477,8 +1461,7 @@ Error Object::connect(const StringName &p_signal, Object *p_to_object, const Str
s->slot_map[target].reference_count++;
return OK;
} else {
- ERR_EXPLAIN("Signal '" + p_signal + "' is already connected to given method '" + p_to_method + "' in that object.");
- ERR_FAIL_V(ERR_INVALID_PARAMETER);
+ ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given method '" + p_to_method + "' in that object.");
}
}
@@ -1514,8 +1497,7 @@ bool Object::is_connected(const StringName &p_signal, Object *p_to_object, const
if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal))
return false;
- ERR_EXPLAIN("Nonexistent signal: " + p_signal);
- ERR_FAIL_V(false);
+ ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + ".");
}
Signal::Target target(p_to_object->get_instance_id(), p_to_method);
@@ -1533,21 +1515,13 @@ void Object::_disconnect(const StringName &p_signal, Object *p_to_object, const
ERR_FAIL_NULL(p_to_object);
Signal *s = signal_map.getptr(p_signal);
- if (!s) {
- ERR_EXPLAIN("Nonexistent signal: " + p_signal);
- ERR_FAIL();
- }
- if (s->lock > 0) {
- ERR_EXPLAIN("Attempt to disconnect signal '" + p_signal + "' while emitting (locks: " + itos(s->lock) + ")");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!s, "Nonexistent signal: " + p_signal + ".");
+
+ ERR_FAIL_COND_MSG(s->lock > 0, "Attempt to disconnect signal '" + p_signal + "' while emitting (locks: " + itos(s->lock) + ").");
Signal::Target target(p_to_object->get_instance_id(), p_to_method);
- if (!s->slot_map.has(target)) {
- ERR_EXPLAIN("Disconnecting nonexistent signal '" + p_signal + "', slot: " + itos(target._id) + ":" + target.method);
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!s->slot_map.has(target), "Disconnecting nonexistent signal '" + p_signal + "', slot: " + itos(target._id) + ":" + target.method + ".");
Signal::Slot *slot = &s->slot_map[target];
@@ -1974,10 +1948,7 @@ Object::~Object() {
Signal *s = &signal_map[*S];
- if (s->lock) {
- ERR_EXPLAIN("Attempt to delete an object in the middle of a signal emission from it");
- ERR_CONTINUE(s->lock > 0);
- }
+ ERR_CONTINUE_MSG(s->lock > 0, "Attempt to delete an object in the middle of a signal emission from it.");
//brute force disconnect for performance
int slot_count = s->slot_map.size();
diff --git a/core/object.h b/core/object.h
index 15c3ab94c5..ac8620757c 100644
--- a/core/object.h
+++ b/core/object.h
@@ -707,7 +707,7 @@ public:
void get_signal_list(List<MethodInfo> *p_signals) const;
void get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const;
void get_all_signal_connections(List<Connection> *p_connections) const;
- bool has_persistent_signal_connections() const;
+ int get_persistent_signal_connection_count() const;
void get_signals_connected_to_this(List<Connection> *p_connections) const;
Error connect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds = Vector<Variant>(), uint32_t p_flags = 0);
diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp
index 7509050b2b..9a8315a3bb 100644
--- a/core/os/file_access.cpp
+++ b/core/os/file_access.cpp
@@ -30,9 +30,9 @@
#include "file_access.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/file_access_pack.h"
#include "core/io/marshalls.h"
-#include "core/math/crypto_core.h"
#include "core/os/os.h"
#include "core/project_settings.h"
@@ -599,8 +599,7 @@ Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path, Error *r_err
if (r_error) { // if error requested, do not throw error
return Vector<uint8_t>();
}
- ERR_EXPLAIN("Can't open file from path: " + String(p_path));
- ERR_FAIL_V(Vector<uint8_t>());
+ ERR_FAIL_V_MSG(Vector<uint8_t>(), "Can't open file from path: " + String(p_path) + ".");
}
Vector<uint8_t> data;
data.resize(f->get_len());
@@ -620,8 +619,7 @@ String FileAccess::get_file_as_string(const String &p_path, Error *r_error) {
if (r_error) {
return String();
}
- ERR_EXPLAIN("Can't get file as string from path: " + String(p_path));
- ERR_FAIL_V(String());
+ ERR_FAIL_V_MSG(String(), "Can't get file as string from path: " + String(p_path) + ".");
}
String ret;
diff --git a/core/os/input.cpp b/core/os/input.cpp
index f04d4a1b3e..51cb41b184 100644
--- a/core/os/input.cpp
+++ b/core/os/input.cpp
@@ -80,6 +80,7 @@ void Input::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_joy_axis_index_from_string", "axis"), &Input::get_joy_axis_index_from_string);
ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
+ ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
diff --git a/core/os/input.h b/core/os/input.h
index de04f239e6..a12ded176b 100644
--- a/core/os/input.h
+++ b/core/os/input.h
@@ -100,6 +100,7 @@ public:
virtual uint64_t get_joy_vibration_timestamp(int p_device) = 0;
virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration = 0) = 0;
virtual void stop_joy_vibration(int p_device) = 0;
+ virtual void vibrate_handheld(int p_duration_ms = 500) = 0;
virtual Point2 get_mouse_position() const = 0;
virtual Point2 get_last_mouse_speed() const = 0;
diff --git a/core/os/main_loop.cpp b/core/os/main_loop.cpp
index 9946ced2f3..eca3b2a7f4 100644
--- a/core/os/main_loop.cpp
+++ b/core/os/main_loop.cpp
@@ -49,6 +49,8 @@ void MainLoop::_bind_methods() {
BIND_VMETHOD(MethodInfo("_drop_files", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "from_screen")));
BIND_VMETHOD(MethodInfo("_finalize"));
+ BIND_VMETHOD(MethodInfo("_global_menu_action", PropertyInfo(Variant::NIL, "id"), PropertyInfo(Variant::NIL, "meta")));
+
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_ENTER);
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_EXIT);
BIND_CONSTANT(NOTIFICATION_WM_FOCUS_IN);
@@ -115,6 +117,12 @@ void MainLoop::drop_files(const Vector<String> &p_files, int p_from_screen) {
get_script_instance()->call("_drop_files", p_files, p_from_screen);
}
+void MainLoop::global_menu_action(const Variant &p_id, const Variant &p_meta) {
+
+ if (get_script_instance())
+ get_script_instance()->call("_global_menu_action", p_id, p_meta);
+}
+
void MainLoop::finish() {
if (get_script_instance()) {
diff --git a/core/os/main_loop.h b/core/os/main_loop.h
index 6ddaf5bee7..54e61fd2fa 100644
--- a/core/os/main_loop.h
+++ b/core/os/main_loop.h
@@ -71,6 +71,7 @@ public:
virtual void finish();
virtual void drop_files(const Vector<String> &p_files, int p_from_screen = 0);
+ virtual void global_menu_action(const Variant &p_id, const Variant &p_meta);
void set_init_script(const Ref<Script> &p_init_script);
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 925154af7d..7531900480 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -186,6 +186,11 @@ int OS::get_process_id() const {
return -1;
};
+void OS::vibrate_handheld(int p_duration_ms) {
+
+ WARN_PRINTS("vibrate_handheld() only works with Android and iOS");
+}
+
bool OS::is_stdout_verbose() const {
return _verbose_stdout;
@@ -268,8 +273,7 @@ void OS::print_all_resources(String p_to_file) {
_OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
if (err != OK) {
_OSPRF = NULL;
- ERR_EXPLAIN("Can't print all resources to file: " + String(p_to_file));
- ERR_FAIL();
+ ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + ".");
}
}
@@ -487,10 +491,7 @@ void OS::_ensure_user_data_dir() {
da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
Error err = da->make_dir_recursive(dd);
- if (err != OK) {
- ERR_EXPLAIN("Error attempting to create data dir: " + dd);
- }
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
memdelete(da);
}
diff --git a/core/os/os.h b/core/os/os.h
index c0c346e9aa..9b46b43081 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -143,6 +143,11 @@ public:
static OS *get_singleton();
+ virtual void global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta){};
+ virtual void global_menu_add_separator(const String &p_menu){};
+ virtual void global_menu_remove_item(const String &p_menu, int p_idx){};
+ virtual void global_menu_clear(const String &p_menu){};
+
void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, Logger::ErrorType p_type = Logger::ERR_ERROR);
void print(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3;
void printerr(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3;
@@ -265,6 +270,7 @@ public:
virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL, bool read_stderr = false, Mutex *p_pipe_mutex = NULL) = 0;
virtual Error kill(const ProcessID &p_pid) = 0;
virtual int get_process_id() const;
+ virtual void vibrate_handheld(int p_duration_ms = 500);
virtual Error shell_open(String p_uri);
virtual Error set_cwd(const String &p_cwd);
diff --git a/core/pool_allocator.cpp b/core/pool_allocator.cpp
index 48a30f6702..6c1f2756f2 100644
--- a/core/pool_allocator.cpp
+++ b/core/pool_allocator.cpp
@@ -204,10 +204,8 @@ PoolAllocator::ID PoolAllocator::alloc(int p_size) {
/* Then search again */
if (!find_hole(&new_entry_indices_pos, size_to_alloc)) {
-
mt_unlock();
- ERR_EXPLAIN("Memory can't be compacted further");
- ERR_FAIL_V(POOL_ALLOCATOR_INVALID_ID);
+ ERR_FAIL_V_MSG(POOL_ALLOCATOR_INVALID_ID, "Memory can't be compacted further.");
}
}
@@ -217,8 +215,7 @@ PoolAllocator::ID PoolAllocator::alloc(int p_size) {
if (!found_free_entry) {
mt_unlock();
- ERR_EXPLAIN("No free entry found in PoolAllocator");
- ERR_FAIL_V(POOL_ALLOCATOR_INVALID_ID);
+ ERR_FAIL_V_MSG(POOL_ALLOCATOR_INVALID_ID, "No free entry found in PoolAllocator.");
}
/* move all entry indices up, make room for this one */
diff --git a/core/pool_vector.cpp b/core/pool_vector.cpp
index b9d2316315..50ea898bef 100644
--- a/core/pool_vector.cpp
+++ b/core/pool_vector.cpp
@@ -66,6 +66,5 @@ void MemoryPool::cleanup() {
memdelete_arr(allocs);
memdelete(alloc_mutex);
- ERR_EXPLAINC("There are still MemoryPool allocs in use at exit!");
- ERR_FAIL_COND(allocs_used > 0);
+ ERR_FAIL_COND_MSG(allocs_used > 0, "There are still MemoryPool allocs in use at exit!");
}
diff --git a/core/pool_vector.h b/core/pool_vector.h
index 39a8eccc51..957a72483c 100644
--- a/core/pool_vector.h
+++ b/core/pool_vector.h
@@ -98,8 +98,7 @@ class PoolVector {
MemoryPool::alloc_mutex->lock();
if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex->unlock();
- ERR_EXPLAINC("All memory pool allocations are in use, can't COW.");
- ERR_FAIL();
+ ERR_FAIL_MSG("All memory pool allocations are in use, can't COW.");
}
MemoryPool::Alloc *old_alloc = alloc;
@@ -520,8 +519,7 @@ Error PoolVector<T>::resize(int p_size) {
MemoryPool::alloc_mutex->lock();
if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex->unlock();
- ERR_EXPLAINC("All memory pool allocations are in use.");
- ERR_FAIL_V(ERR_OUT_OF_MEMORY);
+ ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "All memory pool allocations are in use.");
}
//take one from the free list
diff --git a/core/project_settings.cpp b/core/project_settings.cpp
index c1d4967f55..eb88143db3 100644
--- a/core/project_settings.cpp
+++ b/core/project_settings.cpp
@@ -500,8 +500,7 @@ Error ProjectSettings::_load_settings_binary(const String &p_path) {
if (hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G') {
memdelete(f);
- ERR_EXPLAIN("Corrupted header in binary project.binary (not ECFG)");
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Corrupted header in binary project.binary (not ECFG).");
}
uint32_t count = f->get_32();
@@ -522,8 +521,7 @@ Error ProjectSettings::_load_settings_binary(const String &p_path) {
f->get_buffer(d.ptrw(), vlen);
Variant value;
err = decode_variant(value, d.ptr(), d.size(), NULL, true);
- ERR_EXPLAIN("Error decoding property: " + key);
- ERR_CONTINUE(err != OK);
+ ERR_CONTINUE_MSG(err != OK, "Error decoding property: " + key + ".");
set(key, value);
}
@@ -577,8 +575,7 @@ Error ProjectSettings::_load_settings_text(const String &p_path) {
config_version = value;
if (config_version > CONFIG_VERSION) {
memdelete(f);
- ERR_EXPLAIN(vformat("Can't open project at '%s', its `config_version` (%d) is from a more recent and incompatible version of the engine. Expected config version: %d.", p_path, config_version, CONFIG_VERSION));
- ERR_FAIL_V(ERR_FILE_CANT_OPEN);
+ ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, vformat("Can't open project at '%s', its `config_version` (%d) is from a more recent and incompatible version of the engine. Expected config version: %d.", p_path, config_version, CONFIG_VERSION));
}
} else {
if (section == String()) {
@@ -645,11 +642,7 @@ Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<Str
Error err;
FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
- if (err != OK) {
-
- ERR_EXPLAIN("Couldn't save project.binary at " + p_file);
- ERR_FAIL_COND_V(err, err);
- }
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Couldn't save project.binary at " + p_file + ".");
uint8_t hdr[4] = { 'E', 'C', 'F', 'G' };
file->store_buffer(hdr, 4);
@@ -738,10 +731,7 @@ Error ProjectSettings::_save_settings_text(const String &p_file, const Map<Strin
Error err;
FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
- if (err) {
- ERR_EXPLAIN("Couldn't save project.godot - " + p_file);
- ERR_FAIL_COND_V(err, err);
- }
+ ERR_FAIL_COND_V_MSG(err != OK, err, "Couldn't save project.godot - " + p_file + ".");
file->store_line("; Engine configuration file.");
file->store_line("; It's best edited using the editor UI and not directly,");
@@ -872,8 +862,7 @@ Error ProjectSettings::save_custom(const String &p_path, const CustomMap &p_cust
return _save_settings_binary(p_path, props, p_custom, custom_features);
else {
- ERR_EXPLAIN("Unknown config file format: " + p_path);
- ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Unknown config file format: " + p_path + ".");
}
}
@@ -1030,6 +1019,9 @@ ProjectSettings::ProjectSettings() {
GLOBAL_DEF("editor/search_in_file_extensions", extensions);
custom_prop_info["editor/search_in_file_extensions"] = PropertyInfo(Variant::POOL_STRING_ARRAY, "editor/search_in_file_extensions");
+ GLOBAL_DEF("editor/script_templates_search_path", "res://script_templates");
+ custom_prop_info["editor/script_templates_search_path"] = PropertyInfo(Variant::STRING, "editor/script_templates_search_path", PROPERTY_HINT_DIR);
+
action = Dictionary();
action["deadzone"] = Variant(0.5f);
events = Array();
diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp
index e442546124..efc77bde48 100644
--- a/core/register_core_types.cpp
+++ b/core/register_core_types.cpp
@@ -34,6 +34,8 @@
#include "core/class_db.h"
#include "core/compressed_translation.h"
#include "core/core_string_names.h"
+#include "core/crypto/crypto.h"
+#include "core/crypto/hashing_context.h"
#include "core/engine.h"
#include "core/func_ref.h"
#include "core/input_map.h"
@@ -70,6 +72,8 @@ static Ref<ResourceFormatLoaderBinary> resource_loader_binary;
static Ref<ResourceFormatImporter> resource_format_importer;
static Ref<ResourceFormatLoaderImage> resource_format_image;
static Ref<TranslationLoaderPO> resource_format_po;
+static Ref<ResourceFormatSaverCrypto> resource_format_saver_crypto;
+static Ref<ResourceFormatLoaderCrypto> resource_format_loader_crypto;
static _ResourceLoader *_resource_loader = NULL;
static _ResourceSaver *_resource_saver = NULL;
@@ -151,7 +155,19 @@ void register_core_types() {
ClassDB::register_class<StreamPeerTCP>();
ClassDB::register_class<TCP_Server>();
ClassDB::register_class<PacketPeerUDP>();
+
+ // Crypto
+ ClassDB::register_class<HashingContext>();
+ ClassDB::register_custom_instance_class<X509Certificate>();
+ ClassDB::register_custom_instance_class<CryptoKey>();
+ ClassDB::register_custom_instance_class<Crypto>();
ClassDB::register_custom_instance_class<StreamPeerSSL>();
+
+ resource_format_saver_crypto.instance();
+ ResourceSaver::add_resource_format_saver(resource_format_saver_crypto);
+ resource_format_loader_crypto.instance();
+ ResourceLoader::add_resource_format_loader(resource_format_loader_crypto);
+
ClassDB::register_virtual_class<IP>();
ClassDB::register_virtual_class<PacketPeer>();
ClassDB::register_class<PacketPeerStream>();
@@ -211,6 +227,9 @@ void register_core_settings() {
ProjectSettings::get_singleton()->set_custom_property_info("network/limits/tcp/connect_timeout_seconds", PropertyInfo(Variant::INT, "network/limits/tcp/connect_timeout_seconds", PROPERTY_HINT_RANGE, "1,1800,1"));
GLOBAL_DEF_RST("network/limits/packet_peer_stream/max_buffer_po2", (16));
ProjectSettings::get_singleton()->set_custom_property_info("network/limits/packet_peer_stream/max_buffer_po2", PropertyInfo(Variant::INT, "network/limits/packet_peer_stream/max_buffer_po2", PROPERTY_HINT_RANGE, "0,64,1,or_greater"));
+
+ GLOBAL_DEF("network/ssl/certificates", "");
+ ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt"));
}
void register_core_singletons() {
@@ -272,6 +291,11 @@ void unregister_core_types() {
ResourceLoader::remove_resource_format_loader(resource_format_po);
resource_format_po.unref();
+ ResourceSaver::remove_resource_format_saver(resource_format_saver_crypto);
+ resource_format_saver_crypto.unref();
+ ResourceLoader::remove_resource_format_loader(resource_format_loader_crypto);
+ resource_format_loader_crypto.unref();
+
if (ip)
memdelete(ip);
diff --git a/core/resource.cpp b/core/resource.cpp
index 74e2c1ed6b..5a5efa4644 100644
--- a/core/resource.cpp
+++ b/core/resource.cpp
@@ -75,8 +75,7 @@ void Resource::set_path(const String &p_path, bool p_take_over) {
bool exists = ResourceCache::resources.has(p_path);
ResourceCache::lock->read_unlock();
- ERR_EXPLAIN("Another resource is loaded from path: " + p_path + " (possible cyclic resource inclusion)");
- ERR_FAIL_COND(exists);
+ ERR_FAIL_COND_MSG(exists, "Another resource is loaded from path: " + p_path + " (possible cyclic resource inclusion).");
}
}
path_cache = p_path;
@@ -277,8 +276,7 @@ void Resource::notify_change_to_owners() {
for (Set<ObjectID>::Element *E = owners.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->get());
- ERR_EXPLAIN("Object was deleted, while still owning a resource");
- ERR_CONTINUE(!obj); //wtf
+ ERR_CONTINUE_MSG(!obj, "Object was deleted, while still owning a resource."); //wtf
//TODO store string
obj->call("resource_changed", RES(this));
}
@@ -427,7 +425,7 @@ Resource::~Resource() {
ResourceCache::lock->write_unlock();
}
if (owners.size()) {
- WARN_PRINT("Resource is still owned");
+ WARN_PRINT("Resource is still owned.");
}
}
diff --git a/core/script_debugger_remote.cpp b/core/script_debugger_remote.cpp
index 6dd9054aaa..2a061f0947 100644
--- a/core/script_debugger_remote.cpp
+++ b/core/script_debugger_remote.cpp
@@ -89,7 +89,7 @@ Error ScriptDebuggerRemote::connect_to_host(const String &p_host, uint16_t p_por
if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
- ERR_PRINTS("Remote Debugger: Unable to connect. Status: " + String::num(tcp_client->get_status()));
+ ERR_PRINTS("Remote Debugger: Unable to connect. Status: " + String::num(tcp_client->get_status()) + ".");
return FAILED;
};
@@ -110,7 +110,7 @@ void ScriptDebuggerRemote::_put_variable(const String &p_name, const Variant &p_
int len = 0;
Error err = encode_variant(var, NULL, len, true);
if (err != OK)
- ERR_PRINT("Failed to encode variant");
+ ERR_PRINT("Failed to encode variant.");
if (len > packet_peer_stream->get_output_buffer_max_size()) { //limit to max size
packet_peer_stream->put_var(Variant());
@@ -134,10 +134,7 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script, bool p_can_continue)
//this function is called when there is a debugger break (bug on script)
//or when execution is paused from editor
- if (!tcp_client->is_connected_to_host()) {
- ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway.");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!tcp_client->is_connected_to_host(), "Script Debugger failed to connect, but being used anyway.");
packet_peer_stream->put_var("debug_enter");
packet_peer_stream->put_var(2);
diff --git a/core/translation.cpp b/core/translation.cpp
index a3ff971f45..a0902d71fc 100644
--- a/core/translation.cpp
+++ b/core/translation.cpp
@@ -848,8 +848,7 @@ void Translation::set_locale(const String &p_locale) {
if (!TranslationServer::is_locale_valid(univ_locale)) {
String trimmed_locale = get_trimmed_locale(univ_locale);
- ERR_EXPLAIN("Invalid locale: " + trimmed_locale);
- ERR_FAIL_COND(!TranslationServer::is_locale_valid(trimmed_locale));
+ ERR_FAIL_COND_MSG(!TranslationServer::is_locale_valid(trimmed_locale), "Invalid locale: " + trimmed_locale + ".");
locale = trimmed_locale;
} else {
diff --git a/core/ustring.cpp b/core/ustring.cpp
index ed401c3763..3f5e198281 100644
--- a/core/ustring.cpp
+++ b/core/ustring.cpp
@@ -31,7 +31,7 @@
#include "ustring.h"
#include "core/color.h"
-#include "core/math/crypto_core.h"
+#include "core/crypto/crypto_core.h"
#include "core/math/math_funcs.h"
#include "core/os/memory.h"
#include "core/print_string.h"
@@ -40,6 +40,7 @@
#include "core/variant.h"
#include <wchar.h>
+#include <cstdint>
#ifndef NO_USE_STDLIB
#include <stdio.h>
@@ -1668,6 +1669,7 @@ int String::hex_to_int(bool p_with_prefix) const {
return 0;
}
+ ERR_FAIL_COND_V_MSG(hex > INT32_MAX / 16, sign == 1 ? INT32_MAX : INT32_MIN, "Cannot represent " + *this + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
hex *= 16;
hex += n;
s++;
@@ -1709,6 +1711,7 @@ int64_t String::hex_to_int64(bool p_with_prefix) const {
return 0;
}
+ ERR_FAIL_COND_V_MSG(hex > INT64_MAX / 16, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
hex *= 16;
hex += n;
s++;
@@ -1748,6 +1751,7 @@ int64_t String::bin_to_int64(bool p_with_prefix) const {
return 0;
}
+ ERR_FAIL_COND_V_MSG(binary > INT64_MAX / 2, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
binary *= 2;
binary += n;
s++;
@@ -1771,6 +1775,7 @@ int String::to_int() const {
CharType c = operator[](i);
if (c >= '0' && c <= '9') {
+ ERR_FAIL_COND_V_MSG(integer > INT32_MAX / 10, sign == 1 ? INT32_MAX : INT32_MIN, "Cannot represent " + *this + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
integer *= 10;
integer += c - '0';
@@ -1798,6 +1803,7 @@ int64_t String::to_int64() const {
CharType c = operator[](i);
if (c >= '0' && c <= '9') {
+ ERR_FAIL_COND_V_MSG(integer > INT64_MAX / 10, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
integer *= 10;
integer += c - '0';
@@ -1828,6 +1834,7 @@ int String::to_int(const char *p_str, int p_len) {
char c = p_str[i];
if (c >= '0' && c <= '9') {
+ ERR_FAIL_COND_V_MSG(integer > INT32_MAX / 10, sign == 1 ? INT32_MAX : INT32_MIN, "Cannot represent " + String(p_str).substr(0, to) + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
integer *= 10;
integer += c - '0';
@@ -2140,6 +2147,14 @@ int64_t String::to_int(const CharType *p_str, int p_len) {
if (c >= '0' && c <= '9') {
+ if (integer > INT32_MAX / 10) {
+ String number("");
+ str = p_str;
+ while (*str && str != limit) {
+ number += *(str++);
+ }
+ ERR_FAIL_V_MSG(sign == 1 ? INT32_MAX : INT32_MIN, "Cannot represent " + number + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
+ }
integer *= 10;
integer += c - '0';
} else {
diff --git a/core/variant.cpp b/core/variant.cpp
index 1574af5239..e7d0e58367 100644
--- a/core/variant.cpp
+++ b/core/variant.cpp
@@ -1740,10 +1740,7 @@ Variant::operator RID() const {
} else if (type == OBJECT && _get_obj().obj) {
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton()) {
- if (!ObjectDB::instance_validate(_get_obj().obj)) {
- ERR_EXPLAIN("Invalid pointer (object was deleted)");
- ERR_FAIL_V(RID());
- };
+ ERR_FAIL_COND_V_MSG(!ObjectDB::instance_validate(_get_obj().obj), RID(), "Invalid pointer (object was deleted).");
};
#endif
Variant::CallError ce;
diff --git a/core/variant_call.cpp b/core/variant_call.cpp
index eca5d0567b..05ef51cecd 100644
--- a/core/variant_call.cpp
+++ b/core/variant_call.cpp
@@ -32,8 +32,8 @@
#include "core/color_names.inc"
#include "core/core_string_names.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/compression.h"
-#include "core/math/crypto_core.h"
#include "core/object.h"
#include "core/os/os.h"
#include "core/script_language.h"
@@ -347,6 +347,8 @@ struct _VariantCall {
VCALL_LOCALMEM0R(Vector2, is_normalized);
VCALL_LOCALMEM1R(Vector2, distance_to);
VCALL_LOCALMEM1R(Vector2, distance_squared_to);
+ VCALL_LOCALMEM1R(Vector2, posmod);
+ VCALL_LOCALMEM1R(Vector2, posmodv);
VCALL_LOCALMEM1R(Vector2, project);
VCALL_LOCALMEM1R(Vector2, angle_to);
VCALL_LOCALMEM1R(Vector2, angle_to_point);
@@ -370,6 +372,7 @@ struct _VariantCall {
VCALL_LOCALMEM1R(Vector2, cross);
VCALL_LOCALMEM0R(Vector2, abs);
VCALL_LOCALMEM1R(Vector2, clamped);
+ VCALL_LOCALMEM0R(Vector2, sign);
VCALL_LOCALMEM0R(Rect2, get_area);
VCALL_LOCALMEM1R(Rect2, intersects);
@@ -407,12 +410,15 @@ struct _VariantCall {
VCALL_LOCALMEM0R(Vector3, round);
VCALL_LOCALMEM1R(Vector3, distance_to);
VCALL_LOCALMEM1R(Vector3, distance_squared_to);
+ VCALL_LOCALMEM1R(Vector3, posmod);
+ VCALL_LOCALMEM1R(Vector3, posmodv);
VCALL_LOCALMEM1R(Vector3, project);
VCALL_LOCALMEM1R(Vector3, angle_to);
VCALL_LOCALMEM1R(Vector3, direction_to);
VCALL_LOCALMEM1R(Vector3, slide);
VCALL_LOCALMEM1R(Vector3, bounce);
VCALL_LOCALMEM1R(Vector3, reflect);
+ VCALL_LOCALMEM0R(Vector3, sign);
VCALL_LOCALMEM0R(Plane, normalized);
VCALL_LOCALMEM0R(Plane, center);
@@ -584,8 +590,7 @@ struct _VariantCall {
if (buffer_size < 0) {
r_ret = decompressed;
- ERR_EXPLAIN("Decompression buffer size is less than zero");
- ERR_FAIL();
+ ERR_FAIL_MSG("Decompression buffer size is less than zero.");
}
decompressed.resize(buffer_size);
@@ -597,13 +602,10 @@ struct _VariantCall {
r_ret = decompressed;
}
- static void _call_PoolByteArray_sha256_string(Variant &r_ret, Variant &p_self, const Variant **p_args) {
+ static void _call_PoolByteArray_hex_encode(Variant &r_ret, Variant &p_self, const Variant **p_args) {
PoolByteArray *ba = reinterpret_cast<PoolByteArray *>(p_self._data._mem);
PoolByteArray::Read r = ba->read();
- String s;
- unsigned char hash[32];
- CryptoCore::sha256((unsigned char *)r.ptr(), ba->size(), hash);
- s = String::hex_encode_buffer(hash, 32);
+ String s = String::hex_encode_buffer(&r[0], ba->size());
r_ret = s;
}
@@ -1591,6 +1593,8 @@ void register_variant_methods() {
ADDFUNC1R(VECTOR2, VECTOR2, Vector2, direction_to, VECTOR2, "b", varray());
ADDFUNC1R(VECTOR2, REAL, Vector2, distance_to, VECTOR2, "to", varray());
ADDFUNC1R(VECTOR2, REAL, Vector2, distance_squared_to, VECTOR2, "to", varray());
+ ADDFUNC1R(VECTOR2, VECTOR2, Vector2, posmod, REAL, "mod", varray());
+ ADDFUNC1R(VECTOR2, VECTOR2, Vector2, posmodv, VECTOR2, "modv", varray());
ADDFUNC1R(VECTOR2, VECTOR2, Vector2, project, VECTOR2, "b", varray());
ADDFUNC1R(VECTOR2, REAL, Vector2, angle_to, VECTOR2, "to", varray());
ADDFUNC1R(VECTOR2, REAL, Vector2, angle_to_point, VECTOR2, "to", varray());
@@ -1612,6 +1616,7 @@ void register_variant_methods() {
ADDFUNC1R(VECTOR2, REAL, Vector2, cross, VECTOR2, "with", varray());
ADDFUNC0R(VECTOR2, VECTOR2, Vector2, abs, varray());
ADDFUNC1R(VECTOR2, VECTOR2, Vector2, clamped, REAL, "length", varray());
+ ADDFUNC0R(VECTOR2, VECTOR2, Vector2, sign, varray());
ADDFUNC0R(RECT2, REAL, Rect2, get_area, varray());
ADDFUNC1R(RECT2, BOOL, Rect2, intersects, RECT2, "b", varray());
@@ -1650,11 +1655,14 @@ void register_variant_methods() {
ADDFUNC0R(VECTOR3, VECTOR3, Vector3, round, varray());
ADDFUNC1R(VECTOR3, REAL, Vector3, distance_to, VECTOR3, "b", varray());
ADDFUNC1R(VECTOR3, REAL, Vector3, distance_squared_to, VECTOR3, "b", varray());
+ ADDFUNC1R(VECTOR3, VECTOR3, Vector3, posmod, REAL, "mod", varray());
+ ADDFUNC1R(VECTOR3, VECTOR3, Vector3, posmodv, VECTOR3, "modv", varray());
ADDFUNC1R(VECTOR3, VECTOR3, Vector3, project, VECTOR3, "b", varray());
ADDFUNC1R(VECTOR3, REAL, Vector3, angle_to, VECTOR3, "to", varray());
ADDFUNC1R(VECTOR3, VECTOR3, Vector3, slide, VECTOR3, "n", varray());
ADDFUNC1R(VECTOR3, VECTOR3, Vector3, bounce, VECTOR3, "n", varray());
ADDFUNC1R(VECTOR3, VECTOR3, Vector3, reflect, VECTOR3, "n", varray());
+ ADDFUNC0R(VECTOR3, VECTOR3, Vector3, sign, varray());
ADDFUNC0R(PLANE, PLANE, Plane, normalized, varray());
ADDFUNC0R(PLANE, VECTOR3, Plane, center, varray());
@@ -1763,7 +1771,7 @@ void register_variant_methods() {
ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_ascii, varray());
ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_utf8, varray());
- ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, sha256_string, varray());
+ ADDFUNC0R(POOL_BYTE_ARRAY, STRING, PoolByteArray, hex_encode, varray());
ADDFUNC1R(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, compress, INT, "compression_mode", varray(0));
ADDFUNC2R(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, decompress, INT, "buffer_size", INT, "compression_mode", varray(0));
@@ -1947,6 +1955,9 @@ void register_variant_methods() {
_VariantCall::add_variant_constant(Variant::VECTOR3, "FORWARD", Vector3(0, 0, -1));
_VariantCall::add_variant_constant(Variant::VECTOR3, "BACK", Vector3(0, 0, 1));
+ _VariantCall::add_constant(Variant::VECTOR2, "AXIS_X", Vector2::AXIS_X);
+ _VariantCall::add_constant(Variant::VECTOR2, "AXIS_Y", Vector2::AXIS_Y);
+
_VariantCall::add_variant_constant(Variant::VECTOR2, "ZERO", Vector2(0, 0));
_VariantCall::add_variant_constant(Variant::VECTOR2, "ONE", Vector2(1, 1));
_VariantCall::add_variant_constant(Variant::VECTOR2, "INF", Vector2(Math_INF, Math_INF));
diff --git a/doc/classes/AStar.xml b/doc/classes/AStar.xml
index 6d7adc9935..9ca09371dd 100644
--- a/doc/classes/AStar.xml
+++ b/doc/classes/AStar.xml
@@ -157,6 +157,13 @@
If you change the 2nd point's weight to 3, then the result will be [code][1, 4, 3][/code] instead, because now even though the distance is longer, it's "easier" to get through point 4 than through point 2.
</description>
</method>
+ <method name="get_point_capacity" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ Returns the capacity of the structure backing the points, useful in conjunction with [code]reserve_space[/code].
+ </description>
+ </method>
<method name="get_point_connections">
<return type="PoolIntArray">
</return>
@@ -178,6 +185,13 @@
[/codeblock]
</description>
</method>
+ <method name="get_point_count" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ Returns the number of points currently in the points pool.
+ </description>
+ </method>
<method name="get_point_path">
<return type="PoolVector3Array">
</return>
@@ -241,6 +255,15 @@
Removes the point associated with the given [code]id[/code] from the points pool.
</description>
</method>
+ <method name="reserve_space">
+ <return type="void">
+ </return>
+ <argument index="0" name="num_nodes" type="int">
+ </argument>
+ <description>
+ Reserves space internally for [code]num_nodes[/code] points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity.
+ </description>
+ </method>
<method name="set_point_disabled">
<return type="void">
</return>
diff --git a/doc/classes/AStar2D.xml b/doc/classes/AStar2D.xml
index 9d51330139..0eff2bd560 100644
--- a/doc/classes/AStar2D.xml
+++ b/doc/classes/AStar2D.xml
@@ -134,6 +134,13 @@
If you change the 2nd point's weight to 3, then the result will be [code][1, 4, 3][/code] instead, because now even though the distance is longer, it's "easier" to get through point 4 than through point 2.
</description>
</method>
+ <method name="get_point_capacity" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ Returns the capacity of the structure backing the points, useful in conjunction with [code]reserve_space[/code].
+ </description>
+ </method>
<method name="get_point_connections">
<return type="PoolIntArray">
</return>
@@ -155,6 +162,13 @@
[/codeblock]
</description>
</method>
+ <method name="get_point_count" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ Returns the number of points currently in the points pool.
+ </description>
+ </method>
<method name="get_point_path">
<return type="PoolVector2Array">
</return>
@@ -218,6 +232,15 @@
Removes the point associated with the given [code]id[/code] from the points pool.
</description>
</method>
+ <method name="reserve_space">
+ <return type="void">
+ </return>
+ <argument index="0" name="num_nodes" type="int">
+ </argument>
+ <description>
+ Reserves space internally for [code]num_nodes[/code] points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity.
+ </description>
+ </method>
<method name="set_point_disabled">
<return type="void">
</return>
diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml
index b4c44fe8eb..e510603281 100644
--- a/doc/classes/AnimationPlayer.xml
+++ b/doc/classes/AnimationPlayer.xml
@@ -165,6 +165,7 @@
</argument>
<description>
Queues an animation for playback once the current one is done.
+ [b]Note:[/b] If a looped animation is currently playing, the queued animation will never play unless the looped animation is stopped somehow.
</description>
</method>
<method name="remove_animation">
diff --git a/doc/classes/ClassDB.xml b/doc/classes/ClassDB.xml
index b7b77bc02a..fd08643dd5 100644
--- a/doc/classes/ClassDB.xml
+++ b/doc/classes/ClassDB.xml
@@ -134,7 +134,7 @@
<argument index="2" name="no_inheritance" type="bool" default="false">
</argument>
<description>
- Returns whether [code]class[/code] (or its ancestry if [code]no_inheritance[/code] is false) has a method called [code]method[/code] or not.
+ Returns whether [code]class[/code] (or its ancestry if [code]no_inheritance[/code] is [code]false[/code]) has a method called [code]method[/code] or not.
</description>
</method>
<method name="class_has_signal" qualifiers="const">
@@ -201,7 +201,7 @@
<argument index="0" name="class" type="String">
</argument>
<description>
- Returns whether this class is enabled or not.
+ Returns whether this [code]class[/code] is enabled or not.
</description>
</method>
<method name="is_parent_class" qualifiers="const">
diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml
index acceffb3bf..f263c12821 100644
--- a/doc/classes/Control.xml
+++ b/doc/classes/Control.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Control" inherits="CanvasItem" category="Core" version="3.2">
<brief_description>
- All User Interface nodes inherit from Control. A control's anchors and margins adapt its position and size relative to its parent.
+ All user interface nodes inherit from Control. A control's anchors and margins adapt its position and size relative to its parent.
</brief_description>
<description>
Base class for all UI-related nodes. [Control] features a bounding rectangle that defines its extents, an anchor position relative to its parent control or the current viewport, and margins that represent an offset to the anchor. The margins update automatically when the node, any of its parents, or the screen size change.
@@ -49,10 +49,10 @@
[/codeblock]
The event won't trigger if:
* clicking outside the control (see [method has_point]);
- * control has [member mouse_filter] set to [member MOUSE_FILTER_IGNORE];
- * control is obstructed by another [Control] on top of it, which doesn't have [member mouse_filter] set to [member MOUSE_FILTER_IGNORE];
- * control's parent has [member mouse_filter] set to [member MOUSE_FILTER_STOP] or has accepted the event;
- * it happens outside parent's rectangle and the parent has either [member rect_clip_content] or [member _clips_input] enabled.
+ * control has [member mouse_filter] set to [constant MOUSE_FILTER_IGNORE];
+ * control is obstructed by another [Control] on top of it, which doesn't have [member mouse_filter] set to [constant MOUSE_FILTER_IGNORE];
+ * control's parent has [member mouse_filter] set to [constant MOUSE_FILTER_STOP] or has accepted the event;
+ * it happens outside parent's rectangle and the parent has either [member rect_clip_content] or [method _clips_input] enabled.
</description>
</method>
<method name="_make_custom_tooltip" qualifiers="virtual">
@@ -63,7 +63,7 @@
<description>
Virtual method to be implemented by the user. Returns a [Control] node that should be used as a tooltip instead of the default one. Use [code]for_text[/code] parameter to determine what text the tooltip should contain (likely the contents of [member hint_tooltip]).
The returned node must be of type [Control] or Control-derieved. It can have child nodes of any type. It is freed when the tooltip disappears, so make sure you always provide a new instance, not e.g. a node from scene. When null or non-Control node is returned, the default tooltip will be used instead.
- [b]Note:[/b] The tooltip is shrunk to miminal size. If you want to ensure it's fully visible, you might want to set its [member rect_min_size] to some non-zero value.
+ [b]Note:[/b] The tooltip is shrunk to minimal size. If you want to ensure it's fully visible, you might want to set its [member rect_min_size] to some non-zero value.
Example of usage with custom-constructed node:
[codeblock]
func _make_custom_tooltip(for_text):
@@ -388,7 +388,7 @@
<argument index="0" name="at_position" type="Vector2" default="Vector2( 0, 0 )">
</argument>
<description>
- Returns the tooltip, which will appear when the cursor is resting over this control. See [member]hint_tooltip[/member].
+ Returns the tooltip, which will appear when the cursor is resting over this control. See [member hint_tooltip].
</description>
</method>
<method name="grab_click_focus">
diff --git a/doc/classes/Crypto.xml b/doc/classes/Crypto.xml
new file mode 100644
index 0000000000..bb852f5fff
--- /dev/null
+++ b/doc/classes/Crypto.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="Crypto" inherits="Reference" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="generate_random_bytes">
+ <return type="PoolByteArray">
+ </return>
+ <argument index="0" name="size" type="int">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="generate_rsa">
+ <return type="CryptoKey">
+ </return>
+ <argument index="0" name="size" type="int">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="generate_self_signed_certificate">
+ <return type="X509Certificate">
+ </return>
+ <argument index="0" name="key" type="CryptoKey">
+ </argument>
+ <argument index="1" name="issuer_name" type="String" default="&quot;CN=myserver,O=myorganisation,C=IT&quot;">
+ </argument>
+ <argument index="2" name="not_before" type="String" default="&quot;20140101000000&quot;">
+ </argument>
+ <argument index="3" name="not_after" type="String" default="&quot;20340101000000&quot;">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/CryptoKey.xml b/doc/classes/CryptoKey.xml
new file mode 100644
index 0000000000..d3cd485a5f
--- /dev/null
+++ b/doc/classes/CryptoKey.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="CryptoKey" inherits="Resource" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="load">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="save">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/Directory.xml b/doc/classes/Directory.xml
index 9294a515d2..8aae85563a 100644
--- a/doc/classes/Directory.xml
+++ b/doc/classes/Directory.xml
@@ -127,8 +127,8 @@
</argument>
<description>
Initializes the stream used to list all files and directories using the [method get_next] function, closing the current opened stream if needed. Once the stream has been processed, it should typically be closed with [method list_dir_end].
- If you pass [code]skip_navigational[/code], then [code].[/code] and [code]..[/code] would be filtered out.
- If you pass [code]skip_hidden[/code], then hidden files would be filtered out.
+ If [code]skip_navigational[/code] is [code]true[/code], [code].[/code] and [code]..[/code] are filtered out.
+ If [code]skip_hidden[/code] is [code]true[/code], hidden files are filtered out.
</description>
</method>
<method name="list_dir_end">
diff --git a/doc/classes/FileDialog.xml b/doc/classes/FileDialog.xml
index e78f21b274..4f1e8cc309 100644
--- a/doc/classes/FileDialog.xml
+++ b/doc/classes/FileDialog.xml
@@ -134,6 +134,8 @@
</theme_item>
<theme_item name="folder" type="Texture">
</theme_item>
+ <theme_item name="folder_icon_modulate" type="Color" default="Color( 1, 1, 1, 1 )">
+ </theme_item>
<theme_item name="parent_folder" type="Texture">
</theme_item>
<theme_item name="reload" type="Texture">
diff --git a/doc/classes/GeometryInstance.xml b/doc/classes/GeometryInstance.xml
index b108e1be7c..02f2c27043 100644
--- a/doc/classes/GeometryInstance.xml
+++ b/doc/classes/GeometryInstance.xml
@@ -46,22 +46,26 @@
</member>
<member name="lod_max_distance" type="float" setter="set_lod_max_distance" getter="get_lod_max_distance" default="0.0">
The GeometryInstance's max LOD distance.
+ [b]Note:[/b] This property currently has no effect.
</member>
<member name="lod_max_hysteresis" type="float" setter="set_lod_max_hysteresis" getter="get_lod_max_hysteresis" default="0.0">
The GeometryInstance's max LOD margin.
+ [b]Note:[/b] This property currently has no effect.
</member>
<member name="lod_min_distance" type="float" setter="set_lod_min_distance" getter="get_lod_min_distance" default="0.0">
The GeometryInstance's min LOD distance.
+ [b]Note:[/b] This property currently has no effect.
</member>
<member name="lod_min_hysteresis" type="float" setter="set_lod_min_hysteresis" getter="get_lod_min_hysteresis" default="0.0">
The GeometryInstance's min LOD margin.
+ [b]Note:[/b] This property currently has no effect.
</member>
<member name="material_override" type="Material" setter="set_material_override" getter="get_material_override">
The material override for the whole geometry.
- If there is a material in [code]material_override[/code], it will be used instead of any material set in any material slot of the mesh.
+ If a material is assigned to this property, it will be used instead of any material set in any material slot of the mesh.
</member>
<member name="use_in_baked_light" type="bool" setter="set_flag" getter="get_flag" default="false">
- If [code]true[/code], this GeometryInstance will be used when baking lights using a [GIProbe] and/or any other form of baked lighting.
+ If [code]true[/code], this GeometryInstance will be used when baking lights using a [GIProbe] or [BakedLightmap].
</member>
</members>
<constants>
@@ -78,10 +82,10 @@
</constant>
<constant name="SHADOW_CASTING_SETTING_SHADOWS_ONLY" value="3" enum="ShadowCastingSetting">
Will only show the shadows casted from this object.
- In other words: The actual mesh will not be visible, only the shadows casted from the mesh.
+ In other words, the actual mesh will not be visible, only the shadows casted from the mesh will be.
</constant>
<constant name="FLAG_USE_BAKED_LIGHT" value="0" enum="Flags">
- Will allow the GeometryInstance to be used when baking lights using a [GIProbe] and/or any other form of baked lighting.
+ Will allow the GeometryInstance to be used when baking lights using a [GIProbe] or [BakedLightmap].
</constant>
<constant name="FLAG_DRAW_NEXT_FRAME_IF_VISIBLE" value="1" enum="Flags">
Unused in this class, exposed for consistency with [enum VisualServer.InstanceFlags].
diff --git a/doc/classes/HashingContext.xml b/doc/classes/HashingContext.xml
new file mode 100644
index 0000000000..552a74eba4
--- /dev/null
+++ b/doc/classes/HashingContext.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="HashingContext" inherits="Reference" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="finish">
+ <return type="PoolByteArray">
+ </return>
+ <description>
+ </description>
+ </method>
+ <method name="start">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="type" type="int" enum="HashingContext.HashType">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="update">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="chunk" type="PoolByteArray">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="HASH_MD5" value="0" enum="HashType">
+ </constant>
+ <constant name="HASH_SHA1" value="1" enum="HashType">
+ </constant>
+ <constant name="HASH_SHA256" value="2" enum="HashType">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/Input.xml b/doc/classes/Input.xml
index 91ebcd52f6..5fd5e8c3c0 100644
--- a/doc/classes/Input.xml
+++ b/doc/classes/Input.xml
@@ -20,6 +20,7 @@
<description>
This will simulate pressing the specified action.
The strength can be used for non-boolean actions, it's ranged between 0 and 1 representing the intensity of the given action.
+ [b]Note:[/b] This method will not cause any [method Node._input] calls. It is intended to be used with [method is_action_pressed] and [method is_action_just_pressed]. If you want to simulate [code]_input[/code], use [method parse_input_event] instead.
</description>
</method>
<method name="action_release">
@@ -283,7 +284,14 @@
<argument index="0" name="event" type="InputEvent">
</argument>
<description>
- Feeds an [InputEvent] to the game. Can be used to artificially trigger input events from code.
+ Feeds an [InputEvent] to the game. Can be used to artificially trigger input events from code. Also generates [method Node._input] calls.
+ Example:
+ [codeblock]
+ var a = InputEventAction.new()
+ a.action = "ui_cancel"
+ a.pressed = true
+ Input.parse_input_event(a)
+ [/codeblock]
</description>
</method>
<method name="remove_joy_mapping">
@@ -364,6 +372,16 @@
Stops the vibration of the joypad.
</description>
</method>
+ <method name="vibrate_handheld">
+ <return type="void">
+ </return>
+ <argument index="0" name="duration_ms" type="int" default="500">
+ </argument>
+ <description>
+ Vibrate Android and iOS devices.
+ [b]Note:[/b] It needs VIBRATE permission for Android at export settings. iOS does not support duration.
+ </description>
+ </method>
<method name="warp_mouse_position">
<return type="void">
</return>
diff --git a/doc/classes/MainLoop.xml b/doc/classes/MainLoop.xml
index f5bf12a876..181a99590a 100644
--- a/doc/classes/MainLoop.xml
+++ b/doc/classes/MainLoop.xml
@@ -4,7 +4,7 @@
Abstract base class for the game's main loop.
</brief_description>
<description>
- [MainLoop] is the abstract base class for a Godot project's game loop. It in inherited by [SceneTree], which is the default game loop implementation used in Godot projects, though it is also possible to write and use one's own [MainLoop] subclass instead of the scene tree.
+ [MainLoop] is the abstract base class for a Godot project's game loop. It is inherited by [SceneTree], which is the default game loop implementation used in Godot projects, though it is also possible to write and use one's own [MainLoop] subclass instead of the scene tree.
Upon the application start, a [MainLoop] implementation must be provided to the OS; otherwise, the application will exit. This happens automatically (and a [SceneTree] is created) unless a main [Script] is provided from the command line (with e.g. [code]godot -s my_loop.gd[/code], which should then be a [MainLoop] implementation.
Here is an example script implementing a simple [MainLoop]:
[codeblock]
@@ -61,6 +61,16 @@
Called before the program exits.
</description>
</method>
+ <method name="_global_menu_action" qualifiers="virtual">
+ <return type="void">
+ </return>
+ <argument index="0" name="id" type="Variant">
+ </argument>
+ <argument index="1" name="meta" type="Variant">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="_idle" qualifiers="virtual">
<return type="bool">
</return>
diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index c770e78c7c..938777a36b 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -497,6 +497,50 @@
Returns unobscured area of the window where interactive controls should be rendered.
</description>
</method>
+ <method name="global_menu_add_item">
+ <return type="void">
+ </return>
+ <argument index="0" name="menu" type="String">
+ </argument>
+ <argument index="1" name="label" type="String">
+ </argument>
+ <argument index="2" name="id" type="Variant">
+ </argument>
+ <argument index="3" name="meta" type="Variant">
+ </argument>
+ <description>
+ Add a new item with text "label" to global menu. Use "_dock" menu to add item to the macOS dock icon menu.
+ </description>
+ </method>
+ <method name="global_menu_add_separator">
+ <return type="void">
+ </return>
+ <argument index="0" name="menu" type="String">
+ </argument>
+ <description>
+ Add a separator between items. Separators also occupy an index.
+ </description>
+ </method>
+ <method name="global_menu_clear">
+ <return type="void">
+ </return>
+ <argument index="0" name="menu" type="String">
+ </argument>
+ <description>
+ Clear the global menu, in effect removing all items.
+ </description>
+ </method>
+ <method name="global_menu_remove_item">
+ <return type="void">
+ </return>
+ <argument index="0" name="menu" type="String">
+ </argument>
+ <argument index="1" name="idx" type="int">
+ </argument>
+ <description>
+ Removes the item at index "idx" from the global menu. Note that the indexes of items after the removed item are going to be shifted by one.
+ </description>
+ </method>
<method name="has_environment" qualifiers="const">
<return type="bool">
</return>
diff --git a/doc/classes/PoolByteArray.xml b/doc/classes/PoolByteArray.xml
index 08848e789b..21bf078017 100644
--- a/doc/classes/PoolByteArray.xml
+++ b/doc/classes/PoolByteArray.xml
@@ -67,6 +67,12 @@
Returns a copy of the array's contents as [String]. Slower than [method get_string_from_ascii] but supports UTF-8 encoded data. Use this function if you are unsure about the source of the data. For user input this function should always be preferred.
</description>
</method>
+ <method name="hex_encode">
+ <return type="String">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="insert">
<return type="int">
</return>
@@ -113,13 +119,6 @@
Changes the byte at the given index.
</description>
</method>
- <method name="sha256_string">
- <return type="String">
- </return>
- <description>
- Returns SHA-256 string of the PoolByteArray.
- </description>
- </method>
<method name="size">
<return type="int">
</return>
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 9f18eea0d4..bf1835594b 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -664,6 +664,8 @@
</member>
<member name="network/limits/tcp/connect_timeout_seconds" type="int" setter="" getter="" default="30">
</member>
+ <member name="network/limits/webrtc/max_channel_in_buffer_kb" type="int" setter="" getter="" default="64">
+ </member>
<member name="network/limits/websocket_client/max_in_buffer_kb" type="int" setter="" getter="" default="64">
</member>
<member name="network/limits/websocket_client/max_in_packets" type="int" setter="" getter="" default="1024">
@@ -686,6 +688,8 @@
<member name="network/remote_fs/page_size" type="int" setter="" getter="" default="65536">
Page size used by remote filesystem (in bytes).
</member>
+ <member name="network/ssl/certificates" type="String" setter="" getter="" default="&quot;&quot;">
+ </member>
<member name="node/name_casing" type="int" setter="" getter="" default="0">
When creating node names automatically, set the type of casing in this project. This is mostly an editor setting.
</member>
diff --git a/doc/classes/ResourceFormatLoaderCrypto.xml b/doc/classes/ResourceFormatLoaderCrypto.xml
new file mode 100644
index 0000000000..8bc7d50c75
--- /dev/null
+++ b/doc/classes/ResourceFormatLoaderCrypto.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="ResourceFormatLoaderCrypto" inherits="ResourceFormatLoader" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/ResourceFormatSaverCrypto.xml b/doc/classes/ResourceFormatSaverCrypto.xml
new file mode 100644
index 0000000000..2f7d224dab
--- /dev/null
+++ b/doc/classes/ResourceFormatSaverCrypto.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="ResourceFormatSaverCrypto" inherits="ResourceFormatSaver" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/RigidBody2D.xml b/doc/classes/RigidBody2D.xml
index f280dc81c2..32a1634f77 100644
--- a/doc/classes/RigidBody2D.xml
+++ b/doc/classes/RigidBody2D.xml
@@ -154,7 +154,7 @@
Multiplies the gravity applied to the body. The body's gravity is calculated from the [b]Default Gravity[/b] value in [b]Project &gt; Project Settings &gt; Physics &gt; 2d[/b] and/or any additional gravity vector applied by [Area2D]s.
</member>
<member name="inertia" type="float" setter="set_inertia" getter="get_inertia">
- The body's moment of inertia. This is like mass, but for rotation: it determines how much torque it takes to rotate the body. The moment of inertia is usually computed automatically from the mass and the shapes, but this function allows you to set a custom value. Set 0 (or negative) inertia to return to automatically computing it.
+ The body's moment of inertia. This is like mass, but for rotation: it determines how much torque it takes to rotate the body. The moment of inertia is usually computed automatically from the mass and the shapes, but this function allows you to set a custom value. Set 0 inertia to return to automatically computing it.
</member>
<member name="linear_damp" type="float" setter="set_linear_damp" getter="get_linear_damp" default="-1.0">
Damps the body's [member linear_velocity]. If [code]-1[/code], the body will use the [b]Default Linear Damp[/b] in [b]Project &gt; Project Settings &gt; Physics &gt; 2d[/b].
diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml
index 1302c1e6bf..ed43f83f05 100644
--- a/doc/classes/SceneTree.xml
+++ b/doc/classes/SceneTree.xml
@@ -324,6 +324,15 @@
Emitted when files are dragged from the OS file manager and dropped in the game window. The arguments are a list of file paths and the identifier of the screen where the drag originated.
</description>
</signal>
+ <signal name="global_menu_action">
+ <argument index="0" name="id" type="Nil">
+ </argument>
+ <argument index="1" name="meta" type="Nil">
+ </argument>
+ <description>
+ Emitted whenever global menu item is clicked.
+ </description>
+ </signal>
<signal name="idle_frame">
<description>
Emitted immediately before [method Node._process] is called on every node in the [SceneTree].
diff --git a/doc/classes/StreamPeerSSL.xml b/doc/classes/StreamPeerSSL.xml
index 9b5f4e7580..c960a794e2 100644
--- a/doc/classes/StreamPeerSSL.xml
+++ b/doc/classes/StreamPeerSSL.xml
@@ -13,7 +13,13 @@
<method name="accept_stream">
<return type="int" enum="Error">
</return>
- <argument index="0" name="base" type="StreamPeer">
+ <argument index="0" name="stream" type="StreamPeer">
+ </argument>
+ <argument index="1" name="private_key" type="CryptoKey">
+ </argument>
+ <argument index="2" name="certificate" type="X509Certificate">
+ </argument>
+ <argument index="3" name="chain" type="X509Certificate" default="null">
</argument>
<description>
</description>
@@ -27,6 +33,8 @@
</argument>
<argument index="2" name="for_hostname" type="String" default="&quot;&quot;">
</argument>
+ <argument index="3" name="valid_certificate" type="X509Certificate" default="null">
+ </argument>
<description>
Connects to a peer using an underlying [StreamPeer] [code]stream[/code]. If [code]validate_certs[/code] is [code]true[/code], [StreamPeerSSL] will validate that the certificate presented by the peer matches the [code]for_hostname[/code].
</description>
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index 22c769330d..fb5f20361b 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -418,6 +418,10 @@
<member name="highlight_current_line" type="bool" setter="set_highlight_current_line" getter="is_highlight_current_line_enabled" default="false">
If [code]true[/code], the line containing the cursor is highlighted.
</member>
+ <member name="minimap_draw" type="bool" setter="draw_minimap" getter="is_drawing_minimap" default="false">
+ </member>
+ <member name="minimap_width" type="int" setter="set_minimap_width" getter="get_minimap_width" default="80">
+ </member>
<member name="override_selected_font_color" type="bool" setter="set_override_selected_font_color" getter="is_overriding_selected_font_color" default="false">
</member>
<member name="readonly" type="bool" setter="set_readonly" getter="is_readonly" default="false">
diff --git a/doc/classes/Tree.xml b/doc/classes/Tree.xml
index 62a7147e08..51d56c758e 100644
--- a/doc/classes/Tree.xml
+++ b/doc/classes/Tree.xml
@@ -16,7 +16,7 @@
var subchild1 = tree.create_item(child1)
subchild1.set_text(0, "Subchild1")
[/codeblock]
- To iterate over all the [TreeItem] objects in a [Tree] object, use [method TreeItem.get_next] and [method TreeItem.get_children] after getting the root through [get_root].
+ To iterate over all the [TreeItem] objects in a [Tree] object, use [method TreeItem.get_next] and [method TreeItem.get_children] after getting the root through [method get_root].
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/TreeItem.xml b/doc/classes/TreeItem.xml
index 56b4b21525..04deae6bf5 100644
--- a/doc/classes/TreeItem.xml
+++ b/doc/classes/TreeItem.xml
@@ -136,6 +136,15 @@
Returns the column's icon's maximum width.
</description>
</method>
+ <method name="get_icon_modulate" qualifiers="const">
+ <return type="Color">
+ </return>
+ <argument index="0" name="column" type="int">
+ </argument>
+ <description>
+ Returns the [Color] modulating the column's icon.
+ </description>
+ </method>
<method name="get_icon_region" qualifiers="const">
<return type="Rect2">
</return>
@@ -464,6 +473,17 @@
Sets the given column's icon's maximum width.
</description>
</method>
+ <method name="set_icon_modulate">
+ <return type="void">
+ </return>
+ <argument index="0" name="column" type="int">
+ </argument>
+ <argument index="1" name="modulate" type="Color">
+ </argument>
+ <description>
+ Modulates the given column's icon with [code]modulate[/code].
+ </description>
+ </method>
<method name="set_icon_region">
<return type="void">
</return>
diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml
index 237b596fad..66c4849358 100644
--- a/doc/classes/Vector2.xml
+++ b/doc/classes/Vector2.xml
@@ -203,6 +203,24 @@
Returns the vector scaled to unit length. Equivalent to [code]v / v.length()[/code].
</description>
</method>
+ <method name="posmod">
+ <return type="Vector2">
+ </return>
+ <argument index="0" name="mod" type="float">
+ </argument>
+ <description>
+ Returns a vector composed of the [code]fposmod[/code] of this vector's components and [code]mod[/code].
+ </description>
+ </method>
+ <method name="posmodv">
+ <return type="Vector2">
+ </return>
+ <argument index="0" name="mod" type="float">
+ </argument>
+ <description>
+ Returns a vector composed of the [code]fposmod[/code] of this vector's components and [code]modv[/code]'s components.
+ </description>
+ </method>
<method name="project">
<return type="Vector2">
</return>
@@ -237,6 +255,13 @@
Returns the vector with all components rounded to the nearest integer, with halfway cases rounded away from zero.
</description>
</method>
+ <method name="sign">
+ <return type="Vector2">
+ </return>
+ <description>
+ Returns the vector with each component set to one or negative one, depending on the signs of the components.
+ </description>
+ </method>
<method name="slerp">
<return type="Vector2">
</return>
@@ -284,6 +309,12 @@
</member>
</members>
<constants>
+ <constant name="AXIS_X" value="0">
+ Enumerated value for the X axis. Returned by [method max_axis] and [method min_axis].
+ </constant>
+ <constant name="AXIS_Y" value="1">
+ Enumerated value for the Y axis.
+ </constant>
<constant name="ZERO" value="Vector2( 0, 0 )">
Zero vector.
</constant>
@@ -291,7 +322,7 @@
One vector.
</constant>
<constant name="INF" value="Vector2( inf, inf )">
- Infinite vector.
+ Infinity vector.
</constant>
<constant name="LEFT" value="Vector2( -1, 0 )">
Left unit vector.
diff --git a/doc/classes/Vector3.xml b/doc/classes/Vector3.xml
index 3e1083ab69..4631eb7300 100644
--- a/doc/classes/Vector3.xml
+++ b/doc/classes/Vector3.xml
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Vector3" category="Built-In Types" version="3.2">
<brief_description>
- Vector class, which performs basic 3D vector math operations.
+ Vector used for 3D math.
</brief_description>
<description>
- Vector3 is one of the core classes of the engine, and includes several built-in helper functions to perform basic vector math operations.
+ 3-element structure that can be used to represent positions in 3D space or any other pair of numeric values.
</description>
<tutorials>
<link>https://docs.godotengine.org/en/latest/tutorials/math/index.html</link>
@@ -202,6 +202,24 @@
Returns the outer product with [code]b[/code].
</description>
</method>
+ <method name="posmod">
+ <return type="Vector3">
+ </return>
+ <argument index="0" name="mod" type="float">
+ </argument>
+ <description>
+ Returns a vector composed of the [code]fposmod[/code] of this vector's components and [code]mod[/code].
+ </description>
+ </method>
+ <method name="posmodv">
+ <return type="Vector3">
+ </return>
+ <argument index="0" name="mod" type="float">
+ </argument>
+ <description>
+ Returns a vector composed of the [code]fposmod[/code] of this vector's components and [code]modv[/code]'s components.
+ </description>
+ </method>
<method name="project">
<return type="Vector3">
</return>
@@ -238,6 +256,13 @@
Returns the vector with all components rounded to the nearest integer, with halfway cases rounded away from zero.
</description>
</method>
+ <method name="sign">
+ <return type="Vector3">
+ </return>
+ <description>
+ Returns the vector with each component set to one or negative one, depending on the signs of the components.
+ </description>
+ </method>
<method name="slerp">
<return type="Vector3">
</return>
@@ -304,7 +329,7 @@
One vector.
</constant>
<constant name="INF" value="Vector3( inf, inf, inf )">
- Infinite vector.
+ Infinity vector.
</constant>
<constant name="LEFT" value="Vector3( -1, 0, 0 )">
Left unit vector.
diff --git a/doc/classes/VisualShaderNodeCustom.xml b/doc/classes/VisualShaderNodeCustom.xml
index d4a1732364..9067097f0b 100644
--- a/doc/classes/VisualShaderNodeCustom.xml
+++ b/doc/classes/VisualShaderNodeCustom.xml
@@ -22,14 +22,6 @@
Override this method to define the category of the associated custom node in the Visual Shader Editor's members dialog.
Defining this method is [b]optional[/b]. If not overridden, the node will be filed under the "Custom" category.
</description>
- </method>
- <method name="_get_description" qualifiers="virtual">
- <return type="String">
- </return>
- <description>
- Override this method to define the description of the associated custom node in the Visual Shader Editor's members dialog.
- Defining this method is [b]optional[/b].
- </description>
</method>
<method name="_get_code" qualifiers="virtual">
<return type="String">
@@ -38,9 +30,9 @@
</argument>
<argument index="1" name="output_vars" type="Array">
</argument>
- <argument index="2" name="mode" type="int" enum="Shader.Mode">
- </argument>
- <argument index="3" name="type" type="int" enum="VisualShader.Type">
+ <argument index="2" name="mode" type="int">
+ </argument>
+ <argument index="3" name="type" type="int">
</argument>
<description>
Override this method to define the actual shader code of the associated custom node. The shader code should be returned as a string, which can have multiple lines (the [code]"""[/code] multiline string construct can be used for convenience).
@@ -50,10 +42,18 @@
Defining this method is [b]required[/b].
</description>
</method>
+ <method name="_get_description" qualifiers="virtual">
+ <return type="String">
+ </return>
+ <description>
+ Override this method to define the description of the associated custom node in the Visual Shader Editor's members dialog.
+ Defining this method is [b]optional[/b].
+ </description>
+ </method>
<method name="_get_global_code" qualifiers="virtual">
<return type="String">
</return>
- <argument index="0" name="mode" type="int" enum="Shader.Mode">
+ <argument index="0" name="mode" type="int">
</argument>
<description>
Override this method to add shader code on top of the global shader, to define your own standard library of reusable methods, varyings, constants, uniforms, etc. The shader code should be returned as a string, which can have multiple lines (the [code]"""[/code] multiline string construct can be used for convenience).
@@ -81,7 +81,7 @@
</description>
</method>
<method name="_get_input_port_type" qualifiers="virtual">
- <return type="int" enum="VisualShaderNode.PortType">
+ <return type="int">
</return>
<argument index="0" name="port" type="int">
</argument>
@@ -117,7 +117,7 @@
</description>
</method>
<method name="_get_output_port_type" qualifiers="virtual">
- <return type="int" enum="VisualShaderNode.PortType">
+ <return type="int">
</return>
<argument index="0" name="port" type="int">
</argument>
@@ -127,7 +127,7 @@
</description>
</method>
<method name="_get_return_icon_type" qualifiers="virtual">
- <return type="int" enum="VisualShaderNode.PortType">
+ <return type="int">
</return>
<description>
Override this method to define the return icon of the associated custom node in the Visual Shader Editor's members dialog.
diff --git a/doc/classes/VisualShaderNodeGlobalExpression.xml b/doc/classes/VisualShaderNodeGlobalExpression.xml
new file mode 100644
index 0000000000..3c5a26bf47
--- /dev/null
+++ b/doc/classes/VisualShaderNodeGlobalExpression.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeGlobalExpression" inherits="VisualShaderNodeExpression" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeGroupBase.xml b/doc/classes/VisualShaderNodeGroupBase.xml
index c2e9b9503b..d32a63d605 100644
--- a/doc/classes/VisualShaderNodeGroupBase.xml
+++ b/doc/classes/VisualShaderNodeGroupBase.xml
@@ -208,6 +208,10 @@
</description>
</method>
</methods>
+ <members>
+ <member name="editable" type="bool" setter="set_editable" getter="is_editable" default="false">
+ </member>
+ </members>
<constants>
</constants>
</class>
diff --git a/doc/classes/X509Certificate.xml b/doc/classes/X509Certificate.xml
new file mode 100644
index 0000000000..013f768843
--- /dev/null
+++ b/doc/classes/X509Certificate.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="X509Certificate" inherits="Resource" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="load">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="save">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp
index 4716b29e03..6be48a4c58 100644
--- a/drivers/gles2/rasterizer_canvas_gles2.cpp
+++ b/drivers/gles2/rasterizer_canvas_gles2.cpp
@@ -1265,14 +1265,11 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur
void RasterizerCanvasGLES2::_copy_screen(const Rect2 &p_rect) {
if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) {
- ERR_PRINT_ONCE("Cannot use screen texture copying in render target set to render direct to screen");
+ ERR_PRINT_ONCE("Cannot use screen texture copying in render target set to render direct to screen.");
return;
}
- if (storage->frame.current_rt->copy_screen_effect.color == 0) {
- ERR_EXPLAIN("Can't use screen texture copying in a render target configured without copy buffers");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(storage->frame.current_rt->copy_screen_effect.color == 0, "Can't use screen texture copying in a render target configured without copy buffers.");
glDisable(GL_BLEND);
diff --git a/drivers/gles2/rasterizer_scene_gles2.cpp b/drivers/gles2/rasterizer_scene_gles2.cpp
index 453abeb853..cc414c26af 100644
--- a/drivers/gles2/rasterizer_scene_gles2.cpp
+++ b/drivers/gles2/rasterizer_scene_gles2.cpp
@@ -882,8 +882,7 @@ RID RasterizerSceneGLES2::light_instance_create(RID p_light) {
if (!light_instance->light_ptr) {
memdelete(light_instance);
- ERR_EXPLAIN("Condition ' !light_instance->light_ptr ' is true.");
- ERR_FAIL_V(RID());
+ ERR_FAIL_V_MSG(RID(), "Condition ' !light_instance->light_ptr ' is true.");
}
light_instance->self = light_instance_owner.make_rid(light_instance);
diff --git a/drivers/gles2/rasterizer_storage_gles2.cpp b/drivers/gles2/rasterizer_storage_gles2.cpp
index a30af87516..5c02d8096d 100644
--- a/drivers/gles2/rasterizer_storage_gles2.cpp
+++ b/drivers/gles2/rasterizer_storage_gles2.cpp
@@ -1570,7 +1570,7 @@ void RasterizerStorageGLES2::shader_get_param_list(RID p_shader, List<PropertyIn
if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
pi.hint = PROPERTY_HINT_RANGE;
- pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]);
+ pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
}
} break;
@@ -2171,8 +2171,7 @@ void RasterizerStorageGLES2::mesh_add_surface(RID p_mesh, uint32_t p_format, VS:
//must have index and bones, both.
{
uint32_t bones_weight = VS::ARRAY_FORMAT_BONES | VS::ARRAY_FORMAT_WEIGHTS;
- ERR_EXPLAIN("Array must have both bones and weights in format or none.");
- ERR_FAIL_COND((p_format & bones_weight) && (p_format & bones_weight) != bones_weight);
+ ERR_FAIL_COND_MSG((p_format & bones_weight) && (p_format & bones_weight) != bones_weight, "Array must have both bones and weights in format or none.");
}
//bool has_morph = p_blend_shapes.size();
@@ -3497,6 +3496,8 @@ RID RasterizerStorageGLES2::skeleton_create() {
Skeleton *skeleton = memnew(Skeleton);
+ glGenTextures(1, &skeleton->tex_id);
+
return skeleton_owner.make_rid(skeleton);
}
@@ -3514,7 +3515,6 @@ void RasterizerStorageGLES2::skeleton_allocate(RID p_skeleton, int p_bones, bool
skeleton->use_2d = p_2d_skeleton;
if (config.float_texture_supported) {
- glGenTextures(1, &skeleton->tex_id);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, skeleton->tex_id);
diff --git a/drivers/gles2/shader_compiler_gles2.cpp b/drivers/gles2/shader_compiler_gles2.cpp
index 9c9a8e9717..ab0ee7c24f 100644
--- a/drivers/gles2/shader_compiler_gles2.cpp
+++ b/drivers/gles2/shader_compiler_gles2.cpp
@@ -758,11 +758,13 @@ String ShaderCompilerGLES2::_dump_node_code(SL::Node *p_node, int p_level, Gener
} break;
case SL::OP_SELECT_IF: {
+ code += "(";
code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += " ? ";
code += _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += " : ";
code += _dump_node_code(op_node->arguments[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
+ code += ")";
} break;
case SL::OP_MOD: {
@@ -802,6 +804,15 @@ String ShaderCompilerGLES2::_dump_node_code(SL::Node *p_node, int p_level, Gener
code += "else\n";
code += _dump_node_code(cf_node->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
}
+ } else if (cf_node->flow_op == SL::FLOW_OP_SWITCH) {
+ code += _mktab(p_level) + "switch (" + _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";
+ code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
+ } else if (cf_node->flow_op == SL::FLOW_OP_CASE) {
+ code += _mktab(p_level) + "case " + _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ":\n";
+ code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
+ } else if (cf_node->flow_op == SL::FLOW_OP_DEFAULT) {
+ code += _mktab(p_level) + "default:\n";
+ code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cf_node->flow_op == SL::FLOW_OP_DO) {
code += _mktab(p_level);
code += "do";
@@ -955,6 +966,7 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() {
actions[VS::SHADER_CANVAS_ITEM].usage_defines["outerProduct"] = "#define OUTER_PRODUCT_USED\n";
actions[VS::SHADER_CANVAS_ITEM].usage_defines["round"] = "#define ROUND_USED\n";
actions[VS::SHADER_CANVAS_ITEM].usage_defines["roundEven"] = "#define ROUND_EVEN_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["inverse"] = "#define INVERSE_USED\n";
actions[VS::SHADER_CANVAS_ITEM].usage_defines["isinf"] = "#define IS_INF_USED\n";
actions[VS::SHADER_CANVAS_ITEM].usage_defines["isnan"] = "#define IS_NAN_USED\n";
actions[VS::SHADER_CANVAS_ITEM].usage_defines["trunc"] = "#define TRUNC_USED\n";
@@ -1064,6 +1076,7 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() {
actions[VS::SHADER_SPATIAL].usage_defines["outerProduct"] = "#define OUTER_PRODUCT_USED\n";
actions[VS::SHADER_SPATIAL].usage_defines["round"] = "#define ROUND_USED\n";
actions[VS::SHADER_SPATIAL].usage_defines["roundEven"] = "#define ROUND_EVEN_USED\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["inverse"] = "#define INVERSE_USED\n";
actions[VS::SHADER_SPATIAL].usage_defines["isinf"] = "#define IS_INF_USED\n";
actions[VS::SHADER_SPATIAL].usage_defines["isnan"] = "#define IS_NAN_USED\n";
actions[VS::SHADER_SPATIAL].usage_defines["trunc"] = "#define TRUNC_USED\n";
diff --git a/drivers/gles2/shaders/stdlib.glsl b/drivers/gles2/shaders/stdlib.glsl
index 96421fcb4a..9c74418743 100644
--- a/drivers/gles2/shaders/stdlib.glsl
+++ b/drivers/gles2/shaders/stdlib.glsl
@@ -299,6 +299,81 @@ highp float determinant(highp mat4 m) {
#endif
+#if defined(INVERSE_USED)
+
+highp mat2 inverse(highp mat2 m) {
+ highp float d = 1.0 / (m[0].x * m[1].y - m[1].x * m[0].y);
+ return mat2(
+ vec2(m[1].y * d, -m[0].y * d),
+ vec2(-m[1].x * d, m[0].x * d));
+}
+
+highp mat3 inverse(highp mat3 m) {
+ highp float d = 1.0 / (m[0].x * (m[1].y * m[2].z - m[2].y * m[1].z) - m[1].x * (m[0].y * m[2].z - m[2].y * m[0].z) + m[2].x * (m[0].y * m[1].z - m[1].y * m[0].z));
+ return mat3(
+ vec3((m[1].y * m[2].z - m[2].y * m[1].z), -(m[1].x * m[2].z - m[2].x * m[1].z), (m[1].x * m[2].y - m[2].x * m[1].y)) * d,
+ vec3(-(m[0].y * m[2].z - m[2].y * m[0].z), (m[0].x * m[2].z - m[2].x * m[0].z), -(m[0].x * m[2].y - m[2].x * m[0].y)) * d,
+ vec3((m[0].y * m[1].z - m[1].y * m[0].z), -(m[0].x * m[1].z - m[1].x * m[0].z), (m[0].x * m[1].y - m[1].x * m[0].y)) * d);
+}
+
+highp mat4 inverse(highp mat4 m) {
+ highp float c00 = m[2].z * m[3].w - m[3].z * m[2].w;
+ highp float c02 = m[1].z * m[3].w - m[3].z * m[1].w;
+ highp float c03 = m[1].z * m[2].w - m[2].z * m[1].w;
+
+ highp float c04 = m[2].y * m[3].w - m[3].y * m[2].w;
+ highp float c06 = m[1].y * m[3].w - m[3].y * m[1].w;
+ highp float c07 = m[1].y * m[2].w - m[2].y * m[1].w;
+
+ highp float c08 = m[2].y * m[3].z - m[3].y * m[2].z;
+ highp float c10 = m[1].y * m[3].z - m[3].y * m[1].z;
+ highp float c11 = m[1].y * m[2].z - m[2].y * m[1].z;
+
+ highp float c12 = m[2].x * m[3].w - m[3].x * m[2].w;
+ highp float c14 = m[1].x * m[3].w - m[3].x * m[1].w;
+ highp float c15 = m[1].x * m[2].w - m[2].x * m[1].w;
+
+ highp float c16 = m[2].x * m[3].z - m[3].x * m[2].z;
+ highp float c18 = m[1].x * m[3].z - m[3].x * m[1].z;
+ highp float c19 = m[1].x * m[2].z - m[2].x * m[1].z;
+
+ highp float c20 = m[2].x * m[3].y - m[3].x * m[2].y;
+ highp float c22 = m[1].x * m[3].y - m[3].x * m[1].y;
+ highp float c23 = m[1].x * m[2].y - m[2].x * m[1].y;
+
+ vec4 f0 = vec4(c00, c00, c02, c03);
+ vec4 f1 = vec4(c04, c04, c06, c07);
+ vec4 f2 = vec4(c08, c08, c10, c11);
+ vec4 f3 = vec4(c12, c12, c14, c15);
+ vec4 f4 = vec4(c16, c16, c18, c19);
+ vec4 f5 = vec4(c20, c20, c22, c23);
+
+ vec4 v0 = vec4(m[1].x, m[0].x, m[0].x, m[0].x);
+ vec4 v1 = vec4(m[1].y, m[0].y, m[0].y, m[0].y);
+ vec4 v2 = vec4(m[1].z, m[0].z, m[0].z, m[0].z);
+ vec4 v3 = vec4(m[1].w, m[0].w, m[0].w, m[0].w);
+
+ vec4 inv0 = vec4(v1 * f0 - v2 * f1 + v3 * f2);
+ vec4 inv1 = vec4(v0 * f0 - v2 * f3 + v3 * f4);
+ vec4 inv2 = vec4(v0 * f1 - v1 * f3 + v3 * f5);
+ vec4 inv3 = vec4(v0 * f2 - v1 * f4 + v2 * f5);
+
+ vec4 sa = vec4(+1, -1, +1, -1);
+ vec4 sb = vec4(-1, +1, -1, +1);
+
+ mat4 inv = mat4(inv0 * sa, inv1 * sb, inv2 * sa, inv3 * sb);
+
+ vec4 r0 = vec4(inv[0].x, inv[1].x, inv[2].x, inv[3].x);
+ vec4 d0 = vec4(m[0] * r0);
+
+ highp float d1 = (d0.x + d0.y) + (d0.z + d0.w);
+ highp float d = 1.0 / d1;
+
+ return inv * d;
+}
+
+#endif
+
#ifndef USE_GLES_OVER_GL
#if defined(TRANSPOSE_USED)
diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp
index 1a97225e6b..edffe852a2 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.cpp
+++ b/drivers/gles3/rasterizer_canvas_gles3.cpp
@@ -1156,10 +1156,7 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item, Item *cur
void RasterizerCanvasGLES3::_copy_texscreen(const Rect2 &p_rect) {
- if (storage->frame.current_rt->effects.mip_maps[0].sizes.size() == 0) {
- ERR_EXPLAIN("Can't use screen texture copying in a render target configured without copy buffers");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(storage->frame.current_rt->effects.mip_maps[0].sizes.size() == 0, "Can't use screen texture copying in a render target configured without copy buffers.");
glDisable(GL_BLEND);
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index 048f3c114e..1472954ebc 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -1008,8 +1008,7 @@ RID RasterizerSceneGLES3::light_instance_create(RID p_light) {
if (!light_instance->light_ptr) {
memdelete(light_instance);
- ERR_EXPLAIN("Condition ' !light_instance->light_ptr ' is true.");
- ERR_FAIL_V(RID());
+ ERR_FAIL_V_MSG(RID(), "Condition ' !light_instance->light_ptr ' is true.");
}
light_instance->self = light_instance_owner.make_rid(light_instance);
diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp
index c7040c232b..5f4acbc2de 100644
--- a/drivers/gles3/rasterizer_storage_gles3.cpp
+++ b/drivers/gles3/rasterizer_storage_gles3.cpp
@@ -2247,7 +2247,7 @@ void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyIn
pi.type = Variant::INT;
if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
pi.hint = PROPERTY_HINT_RANGE;
- pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]);
+ pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
}
} break;
@@ -3191,8 +3191,7 @@ void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS:
//must have index and bones, both.
{
uint32_t bones_weight = VS::ARRAY_FORMAT_BONES | VS::ARRAY_FORMAT_WEIGHTS;
- ERR_EXPLAIN("Array must have both bones and weights in format or none.");
- ERR_FAIL_COND((p_format & bones_weight) && (p_format & bones_weight) != bones_weight);
+ ERR_FAIL_COND_MSG((p_format & bones_weight) && (p_format & bones_weight) != bones_weight, "Array must have both bones and weights in format or none.");
}
//bool has_morph = p_blend_shapes.size();
diff --git a/drivers/gles3/shader_compiler_gles3.cpp b/drivers/gles3/shader_compiler_gles3.cpp
index 6b477ec78b..0121d88f4d 100644
--- a/drivers/gles3/shader_compiler_gles3.cpp
+++ b/drivers/gles3/shader_compiler_gles3.cpp
@@ -772,11 +772,13 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
} break;
case SL::OP_SELECT_IF: {
+ code += "(";
code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += "?";
code += _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
code += ":";
code += _dump_node_code(onode->arguments[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);
+ code += ")";
} break;
@@ -799,6 +801,15 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
code += _mktab(p_level) + "else\n";
code += _dump_node_code(cfnode->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
}
+ } else if (cfnode->flow_op == SL::FLOW_OP_SWITCH) {
+ code += _mktab(p_level) + "switch (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";
+ code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
+ } else if (cfnode->flow_op == SL::FLOW_OP_CASE) {
+ code += _mktab(p_level) + "case " + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ":\n";
+ code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
+ } else if (cfnode->flow_op == SL::FLOW_OP_DEFAULT) {
+ code += _mktab(p_level) + "default:\n";
+ code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
} else if (cfnode->flow_op == SL::FLOW_OP_DO) {
code += _mktab(p_level) + "do";
code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);
diff --git a/drivers/gles3/shaders/copy.glsl b/drivers/gles3/shaders/copy.glsl
index 232b9ce7c0..1952e201aa 100644
--- a/drivers/gles3/shaders/copy.glsl
+++ b/drivers/gles3/shaders/copy.glsl
@@ -165,11 +165,11 @@ void main() {
#elif defined(USE_ASYM_PANO)
// When an asymmetrical projection matrix is used (applicable for stereoscopic rendering i.e. VR) we need to do this calculation per fragment to get a perspective correct result.
- // Note that we're ignoring the x-offset for IPD, with Z sufficiently in the distance it becomes neglectible, as a result we could probably just set cube_normal.z to -1.
+ // Asymmetrical projection means the center of projection is no longer in the center of the screen but shifted.
// The Matrix[2][0] (= asym_proj.x) and Matrix[2][1] (= asym_proj.z) values are what provide the right shift in the image.
vec3 cube_normal;
- cube_normal.z = -1000000.0;
+ cube_normal.z = -1.0;
cube_normal.x = (cube_normal.z * (-uv_interp.x - asym_proj.x)) / asym_proj.y;
cube_normal.y = (cube_normal.z * (-uv_interp.y - asym_proj.z)) / asym_proj.a;
cube_normal = mat3(sky_transform) * mat3(pano_transform) * cube_normal;
diff --git a/drivers/png/png_driver_common.cpp b/drivers/png/png_driver_common.cpp
index 0e849bf2fe..7deac1d118 100644
--- a/drivers/png/png_driver_common.cpp
+++ b/drivers/png/png_driver_common.cpp
@@ -97,7 +97,7 @@ Error png_to_image(const uint8_t *p_source, size_t p_size, Ref<Image> p_image) {
break;
default:
png_image_free(&png_img); // only required when we return before finish_read
- ERR_PRINT("Unsupported png format");
+ ERR_PRINT("Unsupported png format.");
return ERR_UNAVAILABLE;
}
@@ -179,10 +179,9 @@ Error image_to_png(const Ref<Image> &p_image, PoolVector<uint8_t> &p_buffer) {
ERR_FAIL_COND_V(check_error(png_img), FAILED);
}
if (!success) {
- if (compressed_size <= png_size_estimate) {
- // buffer was big enough, must be some other error
- ERR_FAIL_V(FAILED);
- }
+
+ // buffer was big enough, must be some other error
+ ERR_FAIL_COND_V(compressed_size <= png_size_estimate, FAILED);
// write failed due to buffer size, resize and retry
Error err = p_buffer.resize(buffer_offset + compressed_size);
diff --git a/drivers/png/resource_saver_png.cpp b/drivers/png/resource_saver_png.cpp
index 43a30f055b..7a2eeafdc3 100644
--- a/drivers/png/resource_saver_png.cpp
+++ b/drivers/png/resource_saver_png.cpp
@@ -39,9 +39,8 @@ Error ResourceSaverPNG::save(const String &p_path, const RES &p_resource, uint32
Ref<ImageTexture> texture = p_resource;
- ERR_FAIL_COND_V(!texture.is_valid(), ERR_INVALID_PARAMETER);
- ERR_EXPLAIN("Can't save empty texture as PNG");
- ERR_FAIL_COND_V(!texture->get_width() || !texture->get_height(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V_MSG(!texture.is_valid(), ERR_INVALID_PARAMETER, "Can't save invalid texture as PNG.");
+ ERR_FAIL_COND_V_MSG(!texture->get_width(), ERR_INVALID_PARAMETER, "Can't save empty texture as PNG.");
Ref<Image> img = texture->get_data();
diff --git a/drivers/unix/file_access_unix.cpp b/drivers/unix/file_access_unix.cpp
index a285b3b65f..071734eb48 100644
--- a/drivers/unix/file_access_unix.cpp
+++ b/drivers/unix/file_access_unix.cpp
@@ -38,6 +38,8 @@
#include <sys/stat.h>
#include <sys/types.h>
+#include <errno.h>
+
#if defined(UNIX_ENABLED)
#include <unistd.h>
#endif
@@ -112,8 +114,15 @@ Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) {
f = fopen(path.utf8().get_data(), mode_string);
if (f == NULL) {
- last_error = ERR_FILE_CANT_OPEN;
- return ERR_FILE_CANT_OPEN;
+ switch (errno) {
+ case ENOENT: {
+ last_error = ERR_FILE_NOT_FOUND;
+ } break;
+ default: {
+ last_error = ERR_FILE_CANT_OPEN;
+ } break;
+ }
+ return last_error;
} else {
last_error = OK;
flags = p_mode_flags;
@@ -288,8 +297,7 @@ uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
if (!err) {
return flags.st_mtime;
} else {
- ERR_EXPLAIN("Failed to get modified time for: " + p_file);
- ERR_FAIL_V(0);
+ ERR_FAIL_V_MSG(0, "Failed to get modified time for: " + p_file + ".");
};
}
@@ -302,8 +310,7 @@ uint32_t FileAccessUnix::_get_unix_permissions(const String &p_file) {
if (!err) {
return flags.st_mode & 0x7FF; //only permissions
} else {
- ERR_EXPLAIN("Failed to get unix permissions for: " + p_file);
- ERR_FAIL_V(0);
+ ERR_FAIL_V_MSG(0, "Failed to get unix permissions for: " + p_file + ".");
};
}
diff --git a/drivers/unix/ip_unix.cpp b/drivers/unix/ip_unix.cpp
index ce66f07a19..ac7195abc1 100644
--- a/drivers/unix/ip_unix.cpp
+++ b/drivers/unix/ip_unix.cpp
@@ -184,9 +184,7 @@ void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) co
continue; // will go back and alloc the right size
};
- ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err));
- ERR_FAIL();
- return;
+ ERR_FAIL_MSG("Call to GetAdaptersAddresses failed with error " + itos(err) + ".");
};
IP_ADAPTER_ADDRESSES *adapter = addrs;
diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp
index aa61cf5dcc..ab5590dba4 100644
--- a/drivers/unix/os_unix.cpp
+++ b/drivers/unix/os_unix.cpp
@@ -72,8 +72,7 @@ static double _clock_scale = 0;
static void _setup_clock() {
mach_timebase_info_data_t info;
kern_return_t ret = mach_timebase_info(&info);
- ERR_EXPLAIN("OS CLOCK IS NOT WORKING!");
- ERR_FAIL_COND(ret != 0);
+ ERR_FAIL_COND_MSG(ret != 0, "OS CLOCK IS NOT WORKING!");
_clock_scale = ((double)info.numer / (double)info.denom) / 1000.0;
_clock_start = mach_absolute_time() * _clock_scale;
}
@@ -85,8 +84,7 @@ static void _setup_clock() {
#endif
static void _setup_clock() {
struct timespec tv_now = { 0, 0 };
- ERR_EXPLAIN("OS CLOCK IS NOT WORKING!");
- ERR_FAIL_COND(clock_gettime(GODOT_CLOCK, &tv_now) != 0);
+ ERR_FAIL_COND_MSG(clock_gettime(GODOT_CLOCK, &tv_now) != 0, "OS CLOCK IS NOT WORKING!");
_clock_start = ((uint64_t)tv_now.tv_nsec / 1000L) + (uint64_t)tv_now.tv_sec * 1000000L;
}
#endif
@@ -420,10 +418,7 @@ Error OS_Unix::open_dynamic_library(const String p_path, void *&p_library_handle
}
p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
- if (!p_library_handle) {
- ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
- ERR_FAIL_V(ERR_CANT_OPEN);
- }
+ ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
return OK;
}
@@ -442,12 +437,9 @@ Error OS_Unix::get_dynamic_library_symbol_handle(void *p_library_handle, const S
error = dlerror();
if (error != NULL) {
- if (!p_optional) {
- ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + error);
- ERR_FAIL_V(ERR_CANT_RESOLVE);
- } else {
- return ERR_CANT_RESOLVE;
- }
+ ERR_FAIL_COND_V_MSG(!p_optional, ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ". Error: " + error + ".");
+
+ return ERR_CANT_RESOLVE;
}
return OK;
}
diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp
index b0f102f1a3..adc3cc8d65 100644
--- a/drivers/wasapi/audio_driver_wasapi.cpp
+++ b/drivers/wasapi/audio_driver_wasapi.cpp
@@ -296,8 +296,7 @@ Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_c
}
hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_capture ? REFTIMES_PER_SEC : 0, 0, pwfex, NULL);
- ERR_EXPLAIN("WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16));
- ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
+ ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");
if (p_capture) {
hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
diff --git a/drivers/windows/file_access_windows.cpp b/drivers/windows/file_access_windows.cpp
index 646e744248..fb21c0c5a1 100644
--- a/drivers/windows/file_access_windows.cpp
+++ b/drivers/windows/file_access_windows.cpp
@@ -38,6 +38,7 @@
#include <shlwapi.h>
#include <windows.h>
+#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <tchar.h>
@@ -114,17 +115,25 @@ Error FileAccessWindows::_open(const String &p_path, int p_mode_flags) {
path = path + ".tmp";
}
- _wfopen_s(&f, path.c_str(), mode_string);
+ errno_t errcode = _wfopen_s(&f, path.c_str(), mode_string);
if (f == NULL) {
- last_error = ERR_FILE_CANT_OPEN;
- return ERR_FILE_CANT_OPEN;
+ switch (errcode) {
+ case ENOENT: {
+ last_error = ERR_FILE_NOT_FOUND;
+ } break;
+ default: {
+ last_error = ERR_FILE_CANT_OPEN;
+ } break;
+ }
+ return last_error;
} else {
last_error = OK;
flags = p_mode_flags;
return OK;
}
}
+
void FileAccessWindows::close() {
if (!f)
@@ -167,13 +176,11 @@ void FileAccessWindows::close() {
if (close_fail_notify) {
close_fail_notify(save_path);
}
-
- ERR_EXPLAIN("Safe save failed. This may be a permissions problem, but also may happen because you are running a paranoid antivirus. If this is the case, please switch to Windows Defender or disable the 'safe save' option in editor settings. This makes it work, but increases the risk of file corruption in a crash.");
}
save_path = "";
- ERR_FAIL_COND(rename_error);
+ ERR_FAIL_COND_MSG(rename_error, "Safe save failed. This may be a permissions problem, but also may happen because you are running a paranoid antivirus. If this is the case, please switch to Windows Defender or disable the 'safe save' option in editor settings. This makes it work, but increases the risk of file corruption in a crash.");
}
}
@@ -334,8 +341,7 @@ uint64_t FileAccessWindows::_get_modified_time(const String &p_file) {
return st.st_mtime;
} else {
- ERR_EXPLAIN("Failed to get modified time for: " + file);
- ERR_FAIL_V(0);
+ ERR_FAIL_V_MSG(0, "Failed to get modified time for: " + file + ".");
}
}
diff --git a/drivers/xaudio2/audio_driver_xaudio2.cpp b/drivers/xaudio2/audio_driver_xaudio2.cpp
index 8674d24af6..6d729c50ab 100644
--- a/drivers/xaudio2/audio_driver_xaudio2.cpp
+++ b/drivers/xaudio2/audio_driver_xaudio2.cpp
@@ -63,15 +63,10 @@ Error AudioDriverXAudio2::init() {
HRESULT hr;
hr = XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR);
- if (hr != S_OK) {
- ERR_EXPLAIN("Error creating XAudio2 engine.");
- ERR_FAIL_V(ERR_UNAVAILABLE);
- }
+ ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_UNAVAILABLE, "Error creating XAudio2 engine.");
+
hr = xaudio->CreateMasteringVoice(&mastering_voice);
- if (hr != S_OK) {
- ERR_EXPLAIN("Error creating XAudio2 mastering voice.");
- ERR_FAIL_V(ERR_UNAVAILABLE);
- }
+ ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_UNAVAILABLE, "Error creating XAudio2 mastering voice.");
wave_format.nChannels = channels;
wave_format.cbSize = 0;
@@ -82,10 +77,7 @@ Error AudioDriverXAudio2::init() {
wave_format.nAvgBytesPerSec = mix_rate * wave_format.nBlockAlign;
hr = xaudio->CreateSourceVoice(&source_voice, &wave_format, 0, XAUDIO2_MAX_FREQ_RATIO, &voice_callback);
- if (hr != S_OK) {
- ERR_EXPLAIN("Error creating XAudio2 source voice. " + itos(hr));
- ERR_FAIL_V(ERR_UNAVAILABLE);
- }
+ ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_UNAVAILABLE, "Error creating XAudio2 source voice. Error code: " + itos(hr) + ".");
mutex = Mutex::create();
thread = Thread::create(AudioDriverXAudio2::thread_func, this);
@@ -140,10 +132,7 @@ void AudioDriverXAudio2::start() {
active = true;
HRESULT hr = source_voice->Start(0);
- if (hr != S_OK) {
- ERR_EXPLAIN("XAudio2 start error " + itos(hr));
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(hr != S_OK, "Error starting XAudio2 driver. Error code: " + itos(hr) + ".");
}
int AudioDriverXAudio2::get_mix_rate() const {
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 014bb08144..c93dc2b340 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -1748,7 +1748,11 @@ void AnimationTimelineEdit::_play_position_draw() {
if (px >= get_name_limit() && px < (play_position->get_size().width - get_buttons_width())) {
Color color = get_color("accent_color", "Editor");
- play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(EDSCALE));
+ play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(2 * EDSCALE));
+ play_position->draw_texture(
+ get_icon("TimelineIndicator", "EditorIcons"),
+ Point2(px - get_icon("TimelineIndicator", "EditorIcons")->get_width() * 0.5, 0),
+ color);
}
}
@@ -2438,7 +2442,7 @@ void AnimationTrackEdit::_play_position_draw() {
if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) {
Color color = get_color("accent_color", "Editor");
- play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(EDSCALE));
+ play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(2 * EDSCALE));
}
}
@@ -3184,7 +3188,7 @@ void AnimationTrackEditGroup::_notification(int p_what) {
if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) {
Color accent = get_color("accent_color", "Editor");
- draw_line(Point2(px, 0), Point2(px, get_size().height), accent, Math::round(EDSCALE));
+ draw_line(Point2(px, 0), Point2(px, get_size().height), accent, Math::round(2 * EDSCALE));
}
}
}
@@ -5050,10 +5054,9 @@ float AnimationTrackEditor::get_moving_selection_offset() const {
void AnimationTrackEditor::_box_selection_draw() {
- Color color = get_color("accent_color", "Editor");
- color.a = 0.2;
- Rect2 rect = Rect2(Point2(), box_selection->get_size());
- box_selection->draw_rect(rect, color);
+ const Rect2 selection_rect = Rect2(Point2(), box_selection->get_size());
+ box_selection->draw_rect(selection_rect, get_color("box_selection_fill_color", "Editor"));
+ box_selection->draw_rect(selection_rect, get_color("box_selection_stroke_color", "Editor"), false, Math::round(EDSCALE));
}
void AnimationTrackEditor::_scroll_input(const Ref<InputEvent> &p_event) {
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index 33af5927b3..61adff7c9c 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -908,6 +908,8 @@ void CodeTextEditor::update_editor_settings() {
text_editor->set_hiding_enabled(EditorSettings::get_singleton()->get("text_editor/line_numbers/code_folding"));
text_editor->set_draw_fold_gutter(EditorSettings::get_singleton()->get("text_editor/line_numbers/code_folding"));
text_editor->set_wrap_enabled(EditorSettings::get_singleton()->get("text_editor/line_numbers/word_wrap"));
+ text_editor->set_draw_minimap(EditorSettings::get_singleton()->get("text_editor/line_numbers/draw_minimap"));
+ text_editor->set_minimap_width(EditorSettings::get_singleton()->get("text_editor/line_numbers/minimap_width"));
text_editor->set_draw_info_gutter(EditorSettings::get_singleton()->get("text_editor/line_numbers/show_info_gutter"));
text_editor->cursor_set_block_mode(EditorSettings::get_singleton()->get("text_editor/cursor/block_caret"));
text_editor->set_smooth_scroll_enabled(EditorSettings::get_singleton()->get("text_editor/open_scripts/smooth_scrolling"));
diff --git a/editor/collada/collada.cpp b/editor/collada/collada.cpp
index edd59f3057..aea7f461f1 100644
--- a/editor/collada/collada.cpp
+++ b/editor/collada/collada.cpp
@@ -1903,8 +1903,7 @@ void Collada::_parse_animation(XMLParser &parser) {
Vector<float> &output = float_sources[output_id];
- ERR_EXPLAIN("Wrong number of keys in output");
- ERR_CONTINUE((output.size() / stride) != key_count);
+ ERR_CONTINUE_MSG((output.size() / stride) != key_count, "Wrong number of keys in output.");
for (int j = 0; j < key_count; j++) {
track.keys.write[j].data.resize(output_len);
@@ -2447,8 +2446,7 @@ void Collada::_find_morph_nodes(VisualScene *p_vscene, Node *p_node) {
state.morph_ownership_map[base] = nj->id;
break;
} else {
- ERR_EXPLAIN("Invalid scene");
- ERR_FAIL();
+ ERR_FAIL_MSG("Invalid scene.");
}
}
}
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index 48bc409b73..c5b81c4685 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -881,7 +881,6 @@ void ConnectionsDock::update_tree() {
icon = get_icon(scr->get_class(), "EditorIcons");
}
}
-
} else {
ClassDB::get_signal_list(base, &node_signals2, true);
@@ -891,6 +890,10 @@ void ConnectionsDock::update_tree() {
name = base;
}
+ if (!icon.is_valid()) {
+ icon = get_icon("Object", "EditorIcons");
+ }
+
TreeItem *pitem = NULL;
if (node_signals2.size()) {
@@ -939,7 +942,7 @@ void ConnectionsDock::update_tree() {
item->set_metadata(0, sinfo);
item->set_icon(0, get_icon("Signal", "EditorIcons"));
- // Set tooltip with the signal's documentation
+ // Set tooltip with the signal's documentation.
{
String descr;
bool found = false;
diff --git a/editor/doc/doc_data.cpp b/editor/doc/doc_data.cpp
index 5b8c8fffb8..0f99e2ba1e 100644
--- a/editor/doc/doc_data.cpp
+++ b/editor/doc/doc_data.cpp
@@ -720,8 +720,7 @@ static Error _parse_methods(Ref<XMLParser> &parser, Vector<DocData::MethodDoc> &
methods.push_back(method);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + parser->get_node_name());
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + parser->get_node_name() + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == section)
@@ -841,8 +840,7 @@ Error DocData::_load(Ref<XMLParser> parser) {
if (parser->get_node_type() == XMLParser::NODE_TEXT)
c.tutorials.push_back(parser->get_node_data().strip_edges());
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + name3);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + name3 + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "tutorials")
break; //end of <tutorials>
@@ -883,8 +881,7 @@ Error DocData::_load(Ref<XMLParser> parser) {
prop2.description = parser->get_node_data();
c.properties.push_back(prop2);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + name3);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + name3 + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "members")
@@ -912,8 +909,7 @@ Error DocData::_load(Ref<XMLParser> parser) {
prop2.description = parser->get_node_data();
c.theme_properties.push_back(prop2);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + name3);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + name3 + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "theme_items")
@@ -943,8 +939,7 @@ Error DocData::_load(Ref<XMLParser> parser) {
constant2.description = parser->get_node_data();
c.constants.push_back(constant2);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + name3);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + name3 + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "constants")
@@ -953,8 +948,7 @@ Error DocData::_load(Ref<XMLParser> parser) {
} else {
- ERR_EXPLAIN("Invalid tag in doc file: " + name2);
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Invalid tag in doc file: " + name2 + ".");
}
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "class")
@@ -991,10 +985,8 @@ Error DocData::save_classes(const String &p_default_path, const Map<String, Stri
Error err;
String save_file = save_path.plus_file(c.name + ".xml");
FileAccessRef f = FileAccess::open(save_file, FileAccess::WRITE, &err);
- if (err) {
- ERR_EXPLAIN("Can't write doc file: " + save_file);
- ERR_CONTINUE(err);
- }
+
+ ERR_CONTINUE_MSG(err != OK, "Can't write doc file: " + save_file + ".");
_write_string(f, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
diff --git a/editor/editor_about.cpp b/editor/editor_about.cpp
index bea1980b09..b2567249d8 100644
--- a/editor/editor_about.cpp
+++ b/editor/editor_about.cpp
@@ -181,14 +181,14 @@ EditorAbout::EditorAbout() {
// Thirdparty License
VBoxContainer *license_thirdparty = memnew(VBoxContainer);
- license_thirdparty->set_name(TTR("Thirdparty License"));
+ license_thirdparty->set_name(TTR("Third-party Licenses"));
license_thirdparty->set_h_size_flags(Control::SIZE_EXPAND_FILL);
tc->add_child(license_thirdparty);
Label *tpl_label = memnew(Label);
tpl_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
tpl_label->set_autowrap(true);
- tpl_label->set_text(TTR("Godot Engine relies on a number of thirdparty free and open source libraries, all compatible with the terms of its MIT license. The following is an exhaustive list of all such thirdparty components with their respective copyright statements and license terms."));
+ tpl_label->set_text(TTR("Godot Engine relies on a number of third-party free and open source libraries, all compatible with the terms of its MIT license. The following is an exhaustive list of all such third-party components with their respective copyright statements and license terms."));
tpl_label->set_size(Size2(630, 1) * EDSCALE);
license_thirdparty->add_child(tpl_label);
diff --git a/editor/editor_asset_installer.cpp b/editor/editor_asset_installer.cpp
index b706f2cae6..98e670f952 100644
--- a/editor/editor_asset_installer.cpp
+++ b/editor/editor_asset_installer.cpp
@@ -90,7 +90,7 @@ void EditorAssetInstaller::open(const String &p_path, int p_depth) {
unzFile pkg = unzOpen2(p_path.utf8().get_data(), &io);
if (!pkg) {
- error->set_text(TTR("Error opening package file, not in zip format."));
+ error->set_text(TTR("Error opening package file, not in ZIP format."));
return;
}
@@ -217,7 +217,7 @@ void EditorAssetInstaller::ok_pressed() {
unzFile pkg = unzOpen2(package_path.utf8().get_data(), &io);
if (!pkg) {
- error->set_text(TTR("Error opening package file, not in zip format."));
+ error->set_text(TTR("Error opening package file, not in ZIP format."));
return;
}
diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp
index 7210211d90..f44e1b7b14 100644
--- a/editor/editor_autoload_settings.cpp
+++ b/editor/editor_autoload_settings.cpp
@@ -315,8 +315,7 @@ void EditorAutoloadSettings::_autoload_file_callback(const String &p_path) {
Node *EditorAutoloadSettings::_create_autoload(const String &p_path) {
RES res = ResourceLoader::load(p_path);
- ERR_EXPLAIN("Can't autoload: " + p_path);
- ERR_FAIL_COND_V(res.is_null(), NULL);
+ ERR_FAIL_COND_V_MSG(res.is_null(), NULL, "Can't autoload: " + p_path + ".");
Node *n = NULL;
if (res->is_class("PackedScene")) {
Ref<PackedScene> ps = res;
@@ -325,20 +324,17 @@ Node *EditorAutoloadSettings::_create_autoload(const String &p_path) {
Ref<Script> s = res;
StringName ibt = s->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "Node");
- ERR_EXPLAIN("Script does not inherit a Node: " + p_path);
- ERR_FAIL_COND_V(!valid_type, NULL);
+ ERR_FAIL_COND_V_MSG(!valid_type, NULL, "Script does not inherit a Node: " + p_path + ".");
Object *obj = ClassDB::instance(ibt);
- ERR_EXPLAIN("Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt));
- ERR_FAIL_COND_V(obj == NULL, NULL);
+ ERR_FAIL_COND_V_MSG(obj == NULL, NULL, "Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt) + ".");
n = Object::cast_to<Node>(obj);
n->set_script(s.get_ref_ptr());
}
- ERR_EXPLAIN("Path in autoload not a node or script: " + p_path);
- ERR_FAIL_COND_V(!n, NULL);
+ ERR_FAIL_COND_V_MSG(!n, NULL, "Path in autoload not a node or script: " + p_path + ".");
return n;
}
@@ -443,11 +439,11 @@ void EditorAutoloadSettings::update_autoload() {
}
if (info.in_editor) {
ERR_CONTINUE(!info.node);
- get_tree()->get_root()->remove_child(info.node);
+ get_tree()->get_root()->call_deferred("remove_child", info.node);
}
if (info.node) {
- memdelete(info.node);
+ info.node->queue_delete();
info.node = NULL;
}
}
diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp
index f5846c10f6..c98635d16b 100644
--- a/editor/editor_data.cpp
+++ b/editor/editor_data.cpp
@@ -537,6 +537,7 @@ int EditorData::add_edited_scene(int p_at_pos) {
p_at_pos = edited_scene.size();
EditedScene es;
es.root = NULL;
+ es.path = String();
es.history_current = -1;
es.version = 0;
es.live_edit_root = NodePath(String("/root"));
@@ -653,6 +654,8 @@ bool EditorData::check_and_update_scene(int p_idx) {
memdelete(edited_scene[p_idx].root);
edited_scene.write[p_idx].root = new_scene;
+ if (new_scene->get_filename() != "")
+ edited_scene.write[p_idx].path = new_scene->get_filename();
edited_scene.write[p_idx].selection = new_selection;
return true;
@@ -684,6 +687,12 @@ void EditorData::set_edited_scene_root(Node *p_root) {
ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
edited_scene.write[current_edited_scene].root = p_root;
+ if (p_root) {
+ if (p_root->get_filename() != "")
+ edited_scene.write[current_edited_scene].path = p_root->get_filename();
+ else
+ p_root->set_filename(edited_scene[current_edited_scene].path);
+ }
}
int EditorData::get_edited_scene_count() const {
@@ -773,6 +782,7 @@ String EditorData::get_scene_title(int p_idx) const {
void EditorData::set_scene_path(int p_idx, const String &p_path) {
ERR_FAIL_INDEX(p_idx, edited_scene.size());
+ edited_scene.write[p_idx].path = p_path;
if (!edited_scene[p_idx].root)
return;
@@ -783,9 +793,14 @@ String EditorData::get_scene_path(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), String());
- if (!edited_scene[p_idx].root)
- return "";
- return edited_scene[p_idx].root->get_filename();
+ if (edited_scene[p_idx].root) {
+ if (edited_scene[p_idx].root->get_filename() == "")
+ edited_scene[p_idx].root->set_filename(edited_scene[p_idx].path);
+ else
+ return edited_scene[p_idx].root->get_filename();
+ }
+
+ return edited_scene[p_idx].path;
}
void EditorData::set_edited_scene_live_edit_root(const NodePath &p_root) {
diff --git a/editor/editor_data.h b/editor/editor_data.h
index 845878e070..df83135942 100644
--- a/editor/editor_data.h
+++ b/editor/editor_data.h
@@ -117,6 +117,7 @@ public:
struct EditedScene {
Node *root;
+ String path;
Dictionary editor_states;
List<Node *> selection;
Vector<EditorHistory::History> history_stored;
diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp
index e1f2635275..e58c7c992a 100644
--- a/editor/editor_export.cpp
+++ b/editor/editor_export.cpp
@@ -30,11 +30,11 @@
#include "editor_export.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/config_file.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/io/zip_io.h"
-#include "core/math/crypto_core.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/project_settings.h"
@@ -148,6 +148,12 @@ String EditorExportPreset::get_include_filter() const {
void EditorExportPreset::set_export_path(const String &p_path) {
export_path = p_path;
+ /* NOTE(SonerSound): if there is a need to implement a PropertyHint that specifically indicates a relative path,
+ * this should be removed. */
+ if (export_path.is_abs_path()) {
+ String res_path = OS::get_singleton()->get_resource_dir();
+ export_path = res_path.path_to_file(export_path);
+ }
EditorExport::singleton->save_presets();
}
@@ -1011,7 +1017,7 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, c
if (!ftmp) {
memdelete(f);
DirAccess::remove_file_or_error(tmppath);
- ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Can't open file to read from path: " + String(tmppath));
+ ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Can't open file to read from path: " + String(tmppath) + ".");
}
const int bufsize = 16384;
diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp
index 1f43740858..80aeeef868 100644
--- a/editor/editor_file_dialog.cpp
+++ b/editor/editor_file_dialog.cpp
@@ -257,6 +257,7 @@ void EditorFileDialog::_post_popup() {
if (is_visible_in_tree()) {
Ref<Texture> folder = get_icon("folder", "FileDialog");
+ const Color folder_color = get_color("folder_icon_modulate", "FileDialog");
recent->clear();
bool res = access == ACCESS_RESOURCES;
@@ -274,6 +275,7 @@ void EditorFileDialog::_post_popup() {
recent->add_item(name, folder);
recent->set_item_metadata(recent->get_item_count() - 1, recentd[i]);
+ recent->set_item_icon_modulate(recent->get_item_count() - 1, folder_color);
}
local_history.clear();
@@ -734,6 +736,7 @@ void EditorFileDialog::update_file_list() {
dir_access->list_dir_begin();
Ref<Texture> folder = get_icon("folder", "FileDialog");
+ const Color folder_color = get_color("folder_icon_modulate", "FileDialog");
List<String> files;
List<String> dirs;
@@ -774,6 +777,7 @@ void EditorFileDialog::update_file_list() {
d["dir"] = true;
item_list->set_item_metadata(item_list->get_item_count() - 1, d);
+ item_list->set_item_icon_modulate(item_list->get_item_count() - 1, folder_color);
dirs.pop_front();
}
@@ -1200,6 +1204,7 @@ void EditorFileDialog::_update_favorites() {
String current = get_current_dir();
Ref<Texture> folder_icon = get_icon("Folder", "EditorIcons");
+ const Color folder_color = get_color("folder_icon_modulate", "FileDialog");
favorites->clear();
favorite->set_pressed(false);
@@ -1230,6 +1235,7 @@ void EditorFileDialog::_update_favorites() {
}
favorites->set_item_metadata(favorites->get_item_count() - 1, favorited[i]);
+ favorites->set_item_icon_modulate(favorites->get_item_count() - 1, folder_color);
if (setthis) {
favorite->set_pressed(true);
diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index be3df2815e..6d3377a85b 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -1930,8 +1930,7 @@ void EditorFileSystem::reimport_files(const Vector<String> &p_files) {
Error err = da->make_dir(".import");
if (err) {
memdelete(da);
- ERR_EXPLAIN("Failed to create 'res://.import' folder.");
- ERR_FAIL();
+ ERR_FAIL_MSG("Failed to create 'res://.import' folder.");
}
}
memdelete(da);
diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp
index 385b6924df..2e8f8ec646 100644
--- a/editor/editor_help.cpp
+++ b/editor/editor_help.cpp
@@ -164,6 +164,17 @@ void EditorHelp::_class_desc_select(const String &p_select) {
void EditorHelp::_class_desc_input(const Ref<InputEvent> &p_input) {
}
+void EditorHelp::_class_desc_resized() {
+ // Add extra horizontal margins for better readability.
+ // The margins increase as the width of the editor help container increases.
+ const int display_margin = MAX(30 * EDSCALE, get_parent_anchorable_rect().size.width - 900 * EDSCALE) * 0.5;
+
+ Ref<StyleBox> class_desc_stylebox = EditorNode::get_singleton()->get_theme_base()->get_stylebox("normal", "RichTextLabel")->duplicate();
+ class_desc_stylebox->set_default_margin(MARGIN_LEFT, display_margin);
+ class_desc_stylebox->set_default_margin(MARGIN_RIGHT, display_margin);
+ class_desc->add_style_override("normal", class_desc_stylebox);
+}
+
void EditorHelp::_add_type(const String &p_type, const String &p_enum) {
String t = p_type;
@@ -1488,6 +1499,7 @@ void EditorHelp::_bind_methods() {
ClassDB::bind_method("_class_list_select", &EditorHelp::_class_list_select);
ClassDB::bind_method("_class_desc_select", &EditorHelp::_class_desc_select);
ClassDB::bind_method("_class_desc_input", &EditorHelp::_class_desc_input);
+ ClassDB::bind_method("_class_desc_resized", &EditorHelp::_class_desc_resized);
ClassDB::bind_method("_request_help", &EditorHelp::_request_help);
ClassDB::bind_method("_unhandled_key_input", &EditorHelp::_unhandled_key_input);
ClassDB::bind_method("_search", &EditorHelp::_search);
@@ -1506,8 +1518,11 @@ EditorHelp::EditorHelp() {
add_child(class_desc);
class_desc->set_v_size_flags(SIZE_EXPAND_FILL);
class_desc->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4));
+
class_desc->connect("meta_clicked", this, "_class_desc_select");
class_desc->connect("gui_input", this, "_class_desc_input");
+ class_desc->connect("resized", this, "_class_desc_resized");
+ _class_desc_resized();
// Added second so it opens at the bottom so it won't offset the entire widget.
find_bar = memnew(FindBar);
diff --git a/editor/editor_help.h b/editor/editor_help.h
index 3824ba231e..1019cafffc 100644
--- a/editor/editor_help.h
+++ b/editor/editor_help.h
@@ -151,6 +151,7 @@ class EditorHelp : public VBoxContainer {
void _class_list_select(const String &p_select);
void _class_desc_select(const String &p_select);
void _class_desc_input(const Ref<InputEvent> &p_input);
+ void _class_desc_resized();
Error _goto_desc(const String &p_class, int p_vscr = -1);
//void _update_history_buttons();
diff --git a/editor/editor_help_search.cpp b/editor/editor_help_search.cpp
index fbfc999dbf..af79c21f85 100644
--- a/editor/editor_help_search.cpp
+++ b/editor/editor_help_search.cpp
@@ -354,7 +354,7 @@ bool EditorHelpSearch::Runner::_phase_match_classes() {
match.constants.push_back(const_cast<DocData::ConstantDoc *>(&class_doc.constants[i]));
if (search_flags & SEARCH_PROPERTIES)
for (int i = 0; i < class_doc.properties.size(); i++)
- if (_match_string(term, class_doc.properties[i].name))
+ if (_match_string(term, class_doc.properties[i].name) || _match_string(term, class_doc.properties[i].getter) || _match_string(term, class_doc.properties[i].setter))
match.properties.push_back(const_cast<DocData::PropertyDoc *>(&class_doc.properties[i]));
if (search_flags & SEARCH_THEME_ITEMS)
for (int i = 0; i < class_doc.theme_properties.size(); i++)
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 866a90ff10..635f6d4fc7 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -135,6 +135,8 @@ void EditorNode::_update_scene_tabs() {
bool show_rb = EditorSettings::get_singleton()->get("interface/scene_tabs/show_script_button");
+ OS::get_singleton()->global_menu_clear("_dock");
+
scene_tabs->clear_tabs();
Ref<Texture> script_icon = gui_base->get_icon("Script", "EditorIcons");
for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
@@ -149,11 +151,16 @@ void EditorNode::_update_scene_tabs() {
bool unsaved = (i == current) ? saved_version != editor_data.get_undo_redo().get_version() : editor_data.get_scene_version(i) != 0;
scene_tabs->add_tab(editor_data.get_scene_title(i) + (unsaved ? "(*)" : ""), icon);
+ OS::get_singleton()->global_menu_add_item("_dock", editor_data.get_scene_title(i) + (unsaved ? "(*)" : ""), GLOBAL_SCENE, i);
+
if (show_rb && editor_data.get_scene_root_script(i).is_valid()) {
scene_tabs->set_tab_right_button(i, script_icon);
}
}
+ OS::get_singleton()->global_menu_add_separator("_dock");
+ OS::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), GLOBAL_NEW_WINDOW, Variant());
+
scene_tabs->set_current_tab(editor_data.get_edited_scene());
if (scene_tabs->get_offset_buttons_visible()) {
@@ -290,6 +297,7 @@ void EditorNode::_notification(int p_what) {
get_tree()->get_root()->set_as_audio_listener_2d(false);
get_tree()->set_auto_accept_quit(false);
get_tree()->connect("files_dropped", this, "_dropped_files");
+ get_tree()->connect("global_menu_action", this, "_global_menu_action");
/* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
} break;
@@ -1926,10 +1934,7 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
switch (p_option) {
case FILE_NEW_SCENE: {
- int idx = editor_data.add_edited_scene(-1);
- _scene_tab_changed(idx);
- editor_data.clear_editor_states();
- _update_scene_tabs();
+ new_scene();
} break;
case FILE_NEW_INHERITED_SCENE:
@@ -2798,8 +2803,7 @@ void EditorNode::select_editor_by_name(const String &p_name) {
}
}
- ERR_EXPLAIN("The editor name '" + p_name + "' was not found.");
- ERR_FAIL();
+ ERR_FAIL_MSG("The editor name '" + p_name + "' was not found.");
}
void EditorNode::add_editor_plugin(EditorPlugin *p_editor, bool p_config_changed) {
@@ -2925,36 +2929,39 @@ void EditorNode::set_addon_plugin_enabled(const String &p_addon, bool p_enabled,
return;
}
- String path = cf->get_value("plugin", "script");
- path = String("res://addons").plus_file(p_addon).plus_file(path);
+ String script_path = cf->get_value("plugin", "script");
+ Ref<Script> script; // We need to save it for creating "ep" below.
- Ref<Script> script = ResourceLoader::load(path);
+ // Only try to load the script if it has a name. Else, the plugin has no init script.
+ if (script_path.length() > 0) {
+ script_path = String("res://addons").plus_file(p_addon).plus_file(script_path);
+ script = ResourceLoader::load(script_path);
- if (script.is_null()) {
- show_warning(vformat(TTR("Unable to load addon script from path: '%s'."), path));
- return;
- }
+ if (script.is_null()) {
+ show_warning(vformat(TTR("Unable to load addon script from path: '%s'."), script_path));
+ return;
+ }
- //errors in the script cause the base_type to be ""
- if (String(script->get_instance_base_type()) == "") {
- show_warning(vformat(TTR("Unable to load addon script from path: '%s' There seems to be an error in the code, please check the syntax."), path));
- return;
- }
+ // Errors in the script cause the base_type to be an empty string.
+ if (String(script->get_instance_base_type()) == "") {
+ show_warning(vformat(TTR("Unable to load addon script from path: '%s' There seems to be an error in the code, please check the syntax."), script_path));
+ return;
+ }
- //could check inheritance..
- if (String(script->get_instance_base_type()) != "EditorPlugin") {
- show_warning(vformat(TTR("Unable to load addon script from path: '%s' Base type is not EditorPlugin."), path));
- return;
- }
+ // Plugin init scripts must inherit from EditorPlugin and be tools.
+ if (String(script->get_instance_base_type()) != "EditorPlugin") {
+ show_warning(vformat(TTR("Unable to load addon script from path: '%s' Base type is not EditorPlugin."), script_path));
+ return;
+ }
- if (!script->is_tool()) {
- show_warning(vformat(TTR("Unable to load addon script from path: '%s' Script is not in tool mode."), path));
- return;
+ if (!script->is_tool()) {
+ show_warning(vformat(TTR("Unable to load addon script from path: '%s' Script is not in tool mode."), script_path));
+ return;
+ }
}
EditorPlugin *ep = memnew(EditorPlugin);
ep->set_script(script.get_ref_ptr());
- ep->set_dir_cache(p_addon);
plugin_addons[p_addon] = ep;
add_editor_plugin(ep, p_config_changed);
@@ -3162,6 +3169,14 @@ void EditorNode::fix_dependencies(const String &p_for_file) {
dependency_fixer->edit(p_for_file);
}
+int EditorNode::new_scene() {
+ int idx = editor_data.add_edited_scene(-1);
+ _scene_tab_changed(idx);
+ editor_data.clear_editor_states();
+ _update_scene_tabs();
+ return idx;
+}
+
Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_clear_errors, bool p_force_open_imported) {
if (!is_inside_tree()) {
@@ -3820,9 +3835,13 @@ void EditorNode::show_accept(const String &p_text, const String &p_title) {
void EditorNode::show_warning(const String &p_text, const String &p_title) {
- warning->set_text(p_text);
- warning->set_title(p_title);
- warning->popup_centered_minsize();
+ if (warning->is_inside_tree()) {
+ warning->set_text(p_text);
+ warning->set_title(p_title);
+ warning->popup_centered_minsize();
+ } else {
+ WARN_PRINTS(p_title + " " + p_text);
+ }
}
void EditorNode::_copy_warning(const String &p_str) {
@@ -4792,8 +4811,7 @@ void EditorNode::remove_control_from_dock(Control *p_control) {
}
}
- ERR_EXPLAIN("Control was not in dock");
- ERR_FAIL_COND(!dock);
+ ERR_FAIL_COND_MSG(!dock, "Control was not in dock.");
dock->remove_child(p_control);
_update_dock_slots_visibility();
@@ -4931,6 +4949,23 @@ void EditorNode::remove_tool_menu_item(const String &p_name) {
}
}
+void EditorNode::_global_menu_action(const Variant &p_id, const Variant &p_meta) {
+
+ int id = (int)p_id;
+ if (id == GLOBAL_NEW_WINDOW) {
+ if (OS::get_singleton()->get_main_loop()) {
+ List<String> args;
+ String exec = OS::get_singleton()->get_executable_path();
+
+ OS::ProcessID pid = 0;
+ OS::get_singleton()->execute(exec, args, false, &pid);
+ }
+ } else if (id == GLOBAL_SCENE) {
+ int idx = (int)p_meta;
+ scene_tabs->set_current_tab(idx);
+ }
+}
+
void EditorNode::_dropped_files(const Vector<String> &p_files, int p_screen) {
String to_path = ProjectSettings::get_singleton()->globalize_path(get_filesystem_dock()->get_selected_path());
@@ -5312,6 +5347,7 @@ void EditorNode::_bind_methods() {
ClassDB::bind_method("_clear_undo_history", &EditorNode::_clear_undo_history);
ClassDB::bind_method("_dropped_files", &EditorNode::_dropped_files);
+ ClassDB::bind_method(D_METHOD("_global_menu_action"), &EditorNode::_global_menu_action, DEFVAL(Variant()));
ClassDB::bind_method("_toggle_distraction_free_mode", &EditorNode::_toggle_distraction_free_mode);
ClassDB::bind_method("edit_item_resource", &EditorNode::edit_item_resource);
@@ -5505,6 +5541,9 @@ EditorNode::EditorNode() {
}
}
+ // Define a minimum window size to prevent UI elements from overlapping or being cut off
+ OS::get_singleton()->set_min_window_size(Size2(1024, 600) * EDSCALE);
+
ResourceLoader::set_abort_on_missing_resources(false);
FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
EditorFileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
diff --git a/editor/editor_node.h b/editor/editor_node.h
index 10ad2d691e..61bbb7b86d 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -207,6 +207,9 @@ private:
SET_VIDEO_DRIVER_SAVE_AND_RESTART,
+ GLOBAL_NEW_WINDOW,
+ GLOBAL_SCENE,
+
IMPORT_PLUGIN_BASE = 100,
TOOL_MENU_BASE = 1000
@@ -504,6 +507,7 @@ private:
void _add_to_recent_scenes(const String &p_scene);
void _update_recent_scenes();
void _open_recent_scene(int p_idx);
+ void _global_menu_action(const Variant &p_id, const Variant &p_meta);
void _dropped_files(const Vector<String> &p_files, int p_screen);
void _add_dropped_files_recursive(const Vector<String> &p_files, String to_path);
String _recent_scene;
@@ -745,6 +749,7 @@ public:
void fix_dependencies(const String &p_for_file);
void clear_scene() { _cleanup_scene(); }
+ int new_scene();
Error load_scene(const String &p_scene, bool p_ignore_broken_deps = false, bool p_set_inherited = false, bool p_clear_errors = true, bool p_force_open_imported = false);
Error load_resource(const String &p_resource, bool p_ignore_broken_deps = false);
diff --git a/editor/editor_path.cpp b/editor/editor_path.cpp
index 12510e27de..23d28261d1 100644
--- a/editor/editor_path.cpp
+++ b/editor/editor_path.cpp
@@ -78,6 +78,9 @@ void EditorPath::_about_to_show() {
}
void EditorPath::update_path() {
+ set_text("");
+ set_tooltip("");
+ set_icon(NULL);
for (int i = 0; i < history->get_path_size(); i++) {
diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp
index 4b6afcbb86..e27f1ab9eb 100644
--- a/editor/editor_plugin.cpp
+++ b/editor/editor_plugin.cpp
@@ -324,13 +324,6 @@ void EditorPlugin::remove_autoload_singleton(const String &p_name) {
EditorNode::get_singleton()->get_project_settings()->get_autoload_settings()->autoload_remove(p_name);
}
-Ref<ConfigFile> EditorPlugin::get_config() {
- Ref<ConfigFile> cf = memnew(ConfigFile);
- Error err = cf->load(_dir_cache.plus_file("plugin.cfg"));
- ERR_FAIL_COND_V(err != OK, cf);
- return cf;
-}
-
ToolButton *EditorPlugin::add_control_to_bottom_panel(Control *p_control, const String &p_title) {
ERR_FAIL_NULL_V(p_control, NULL);
return EditorNode::get_singleton()->add_bottom_panel_item(p_title, p_control);
diff --git a/editor/editor_plugin.h b/editor/editor_plugin.h
index 7b6f55e93d..8941dfa28c 100644
--- a/editor/editor_plugin.h
+++ b/editor/editor_plugin.h
@@ -117,7 +117,6 @@ class EditorPlugin : public Node {
bool force_draw_over_forwarding_enabled;
String last_main_screen_name;
- String _dir_cache;
protected:
static void _bind_methods();
@@ -236,10 +235,6 @@ public:
void add_autoload_singleton(const String &p_name, const String &p_path);
void remove_autoload_singleton(const String &p_name);
- void set_dir_cache(const String &p_dir) { _dir_cache = p_dir; }
- String get_dir_cache() { return _dir_cache; }
- Ref<ConfigFile> get_config();
-
void enable_plugin();
void disable_plugin();
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index 20ba07c102..378dd34e39 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -209,13 +209,7 @@ EditorPropertyTextEnum::EditorPropertyTextEnum() {
void EditorPropertyPath::_path_selected(const String &p_path) {
- String final_path = p_path;
- if (final_path.is_abs_path()) {
- String res_path = OS::get_singleton()->get_resource_dir() + "/";
- final_path = res_path.path_to_file(final_path);
- }
-
- emit_changed(get_edited_property(), final_path);
+ emit_changed(get_edited_property(), p_path);
update_property();
}
void EditorPropertyPath::_path_pressed() {
@@ -228,13 +222,6 @@ void EditorPropertyPath::_path_pressed() {
}
String full_path = get_edited_object()->get(get_edited_property());
- if (full_path.is_rel_path()) {
-
- if (!DirAccess::exists(full_path.get_base_dir())) {
- DirAccessRef da(DirAccess::create(DirAccess::ACCESS_FILESYSTEM));
- da->make_dir_recursive(full_path.get_base_dir());
- }
- }
dialog->clear_filters();
diff --git a/editor/editor_resource_preview.cpp b/editor/editor_resource_preview.cpp
index 327e61cea3..4a7a9fb863 100644
--- a/editor/editor_resource_preview.cpp
+++ b/editor/editor_resource_preview.cpp
@@ -46,8 +46,7 @@ bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
if (get_script_instance() && get_script_instance()->has_method("handles")) {
return get_script_instance()->call("handles", p_type);
}
- ERR_EXPLAIN("EditorResourcePreviewGenerator::handles needs to be overridden");
- ERR_FAIL_V(false);
+ ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::handles needs to be overridden.");
}
Ref<Texture> EditorResourcePreviewGenerator::generate(const RES &p_from, const Size2 &p_size) const {
@@ -55,8 +54,7 @@ Ref<Texture> EditorResourcePreviewGenerator::generate(const RES &p_from, const S
if (get_script_instance() && get_script_instance()->has_method("generate")) {
return get_script_instance()->call("generate", p_from, p_size);
}
- ERR_EXPLAIN("EditorResourcePreviewGenerator::generate needs to be overridden");
- ERR_FAIL_V(Ref<Texture>());
+ ERR_FAIL_V_MSG(Ref<Texture>(), "EditorResourcePreviewGenerator::generate needs to be overridden.");
}
Ref<Texture> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size) const {
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index 2d2e53370d..ea6361665c 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -334,9 +334,9 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
hints["interface/editor/code_font"] = PropertyInfo(Variant::STRING, "interface/editor/code_font", PROPERTY_HINT_GLOBAL_FILE, "*.ttf,*.otf", PROPERTY_USAGE_DEFAULT);
_initial_set("interface/editor/dim_editor_on_dialog_popup", true);
_initial_set("interface/editor/low_processor_mode_sleep_usec", 6900); // ~144 FPS
- hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT);
+ hints["interface/editor/low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
_initial_set("interface/editor/unfocused_low_processor_mode_sleep_usec", 50000); // 20 FPS
- hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT);
+ hints["interface/editor/unfocused_low_processor_mode_sleep_usec"] = PropertyInfo(Variant::REAL, "interface/editor/unfocused_low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "1,100000,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
_initial_set("interface/editor/separate_distraction_mode", false);
_initial_set("interface/editor/automatically_open_screenshots", true);
_initial_set("interface/editor/hide_console_window", false);
@@ -448,6 +448,9 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_initial_set("text_editor/line_numbers/show_info_gutter", true);
_initial_set("text_editor/line_numbers/code_folding", true);
_initial_set("text_editor/line_numbers/word_wrap", false);
+ _initial_set("text_editor/line_numbers/draw_minimap", true);
+ _initial_set("text_editor/line_numbers/minimap_width", 80);
+ hints["text_editor/line_numbers/minimap_width"] = PropertyInfo(Variant::INT, "text_editor/line_numbers/minimap_width", PROPERTY_HINT_RANGE, "50,250,1");
_initial_set("text_editor/line_numbers/show_line_length_guideline", false);
_initial_set("text_editor/line_numbers/line_length_guideline_column", 80);
hints["text_editor/line_numbers/line_length_guideline_column"] = PropertyInfo(Variant::INT, "text_editor/line_numbers/line_length_guideline_column", PROPERTY_HINT_RANGE, "20, 160, 1");
@@ -561,6 +564,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
// 2D
_initial_set("editors/2d/grid_color", Color(1.0, 1.0, 1.0, 0.07));
_initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8));
+ _initial_set("editors/2d/smart_snapping_line_color", Color(0.9, 0.1, 0.1));
_initial_set("editors/2d/bone_width", 5);
_initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9));
_initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9));
@@ -608,6 +612,18 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_initial_set("run/output/always_open_output_on_play", true);
_initial_set("run/output/always_close_output_on_stop", false);
+ /* Network */
+
+ // Debug
+ _initial_set("network/debug/remote_host", "127.0.0.1"); // Hints provided in setup_network
+
+ _initial_set("network/debug/remote_port", 6007);
+ hints["network/debug/remote_port"] = PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1");
+
+ // SSL
+ _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH);
+ hints["network/ssl/editor_ssl_certificates"] = PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem");
+
/* Extra config */
_initial_set("project_manager/sorting_order", 0);
@@ -993,11 +1009,11 @@ void EditorSettings::setup_network() {
List<IP_Address> local_ip;
IP::get_singleton()->get_local_addresses(&local_ip);
- String lip = "127.0.0.1";
String hint;
String current = has_setting("network/debug/remote_host") ? get("network/debug/remote_host") : "";
- int port = has_setting("network/debug/remote_port") ? (int)get("network/debug/remote_port") : 6007;
+ String selected = "127.0.0.1";
+ // Check that current remote_host is a valid interface address and populate hints.
for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) {
String ip = E->get();
@@ -1008,22 +1024,18 @@ void EditorSettings::setup_network() {
// Same goes for IPv4 link-local (APIPA) addresses.
if (ip.begins_with("169.254.")) // 169.254.0.0/16
continue;
+ // Select current IP (found)
if (ip == current)
- lip = current; //so it saves
+ selected = ip;
if (hint != "")
hint += ",";
hint += ip;
}
- _initial_set("network/debug/remote_host", lip);
+ // Add hints with valid IP addresses to remote_host property.
add_property_hint(PropertyInfo(Variant::STRING, "network/debug/remote_host", PROPERTY_HINT_ENUM, hint));
-
- _initial_set("network/debug/remote_port", port);
- add_property_hint(PropertyInfo(Variant::INT, "network/debug/remote_port", PROPERTY_HINT_RANGE, "1,65535,1"));
-
- // Editor SSL certificates override
- _initial_set("network/ssl/editor_ssl_certificates", _SYSTEM_CERTS_PATH);
- add_property_hint(PropertyInfo(Variant::STRING, "network/ssl/editor_ssl_certificates", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"));
+ // Fix potentially invalid remote_host due to network change.
+ set("network/debug/remote_host", selected);
}
void EditorSettings::save() {
@@ -1197,6 +1209,11 @@ String EditorSettings::get_script_templates_dir() const {
return get_settings_dir().plus_file("script_templates");
}
+String EditorSettings::get_project_script_templates_dir() const {
+
+ return ProjectSettings::get_singleton()->get("editor/script_templates_search_path");
+}
+
// Cache directory
String EditorSettings::get_cache_dir() const {
@@ -1216,7 +1233,7 @@ void EditorSettings::set_project_metadata(const String &p_section, const String
String path = get_project_settings_dir().plus_file("project_metadata.cfg");
Error err;
err = cf->load(path);
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND(err != OK && err != ERR_FILE_NOT_FOUND);
cf->set_value(p_section, p_key, p_data);
err = cf->save(path);
ERR_FAIL_COND(err != OK);
@@ -1417,10 +1434,14 @@ bool EditorSettings::is_default_text_editor_theme() {
return _is_default_text_editor_theme(p_file.get_file().to_lower());
}
-Vector<String> EditorSettings::get_script_templates(const String &p_extension) {
+Vector<String> EditorSettings::get_script_templates(const String &p_extension, const String &p_custom_path) {
Vector<String> templates;
- DirAccess *d = DirAccess::open(get_script_templates_dir());
+ String template_dir = get_script_templates_dir();
+ if (!p_custom_path.empty()) {
+ template_dir = p_custom_path;
+ }
+ DirAccess *d = DirAccess::open(template_dir);
if (d) {
d->list_dir_begin();
String file = d->get_next();
@@ -1451,10 +1472,7 @@ void EditorSettings::add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcu
bool EditorSettings::is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const {
const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name);
- if (!E) {
- ERR_EXPLAIN("Unknown Shortcut: " + p_name);
- ERR_FAIL_V(false);
- }
+ ERR_FAIL_COND_V_MSG(!E, false, "Unknown Shortcut: " + p_name + ".");
return E->get()->is_shortcut(p_event);
}
@@ -1483,10 +1501,8 @@ Ref<ShortCut> ED_GET_SHORTCUT(const String &p_path) {
}
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path);
- if (!sc.is_valid()) {
- ERR_EXPLAIN("Used ED_GET_SHORTCUT with invalid shortcut: " + p_path);
- ERR_FAIL_COND_V(!sc.is_valid(), sc);
- }
+
+ ERR_FAIL_COND_V_MSG(!sc.is_valid(), sc, "Used ED_GET_SHORTCUT with invalid shortcut: " + p_path + ".");
return sc;
}
diff --git a/editor/editor_settings.h b/editor/editor_settings.h
index 890850629e..0738185e95 100644
--- a/editor/editor_settings.h
+++ b/editor/editor_settings.h
@@ -166,6 +166,7 @@ public:
String get_project_settings_dir() const;
String get_text_editor_themes_dir() const;
String get_script_templates_dir() const;
+ String get_project_script_templates_dir() const;
String get_cache_dir() const;
String get_feature_profiles_dir() const;
@@ -187,7 +188,7 @@ public:
bool save_text_editor_theme_as(String p_file);
bool is_default_text_editor_theme();
- Vector<String> get_script_templates(const String &p_extension);
+ Vector<String> get_script_templates(const String &p_extension, const String &p_custom_path = String());
String get_editor_layouts_config() const;
void add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcut);
diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp
index 379b8a2980..46a30b7554 100644
--- a/editor/editor_spin_slider.cpp
+++ b/editor/editor_spin_slider.cpp
@@ -47,42 +47,48 @@ void EditorSpinSlider::_gui_input(const Ref<InputEvent> &p_event) {
return;
Ref<InputEventMouseButton> mb = p_event;
- if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
+ if (mb.is_valid()) {
- if (mb->is_pressed()) {
+ if (mb->get_button_index() == BUTTON_LEFT) {
+ if (mb->is_pressed()) {
- if (updown_offset != -1 && mb->get_position().x > updown_offset) {
- //there is an updown, so use it.
- if (mb->get_position().y < get_size().height / 2) {
- set_value(get_value() + get_step());
+ if (updown_offset != -1 && mb->get_position().x > updown_offset) {
+ //there is an updown, so use it.
+ if (mb->get_position().y < get_size().height / 2) {
+ set_value(get_value() + get_step());
+ } else {
+ set_value(get_value() - get_step());
+ }
+ return;
} else {
- set_value(get_value() - get_step());
+
+ grabbing_spinner_attempt = true;
+ grabbing_spinner_dist_cache = 0;
+ pre_grab_value = get_value();
+ grabbing_spinner = false;
+ grabbing_spinner_mouse_pos = Input::get_singleton()->get_mouse_position();
}
- return;
} else {
- grabbing_spinner_attempt = true;
- grabbing_spinner_dist_cache = 0;
- pre_grab_value = get_value();
- grabbing_spinner = false;
- grabbing_spinner_mouse_pos = Input::get_singleton()->get_mouse_position();
- }
- } else {
+ if (grabbing_spinner_attempt) {
- if (grabbing_spinner_attempt) {
+ if (grabbing_spinner) {
- if (grabbing_spinner) {
+ Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
+ Input::get_singleton()->warp_mouse_position(grabbing_spinner_mouse_pos);
+ update();
+ } else {
+ _focus_entered();
+ }
- Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
- Input::get_singleton()->warp_mouse_position(grabbing_spinner_mouse_pos);
- update();
- } else {
- _focus_entered();
+ grabbing_spinner = false;
+ grabbing_spinner_attempt = false;
}
-
- grabbing_spinner = false;
- grabbing_spinner_attempt = false;
}
+ } else if (mb->get_button_index() == BUTTON_WHEEL_UP || mb->get_button_index() == BUTTON_WHEEL_DOWN) {
+
+ if (grabber->is_visible())
+ call_deferred("update");
}
}
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 97af0d08ea..56eed96e31 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -351,6 +351,8 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
theme->set_color("dark_color_3", "Editor", dark_color_3);
theme->set_color("contrast_color_1", "Editor", contrast_color_1);
theme->set_color("contrast_color_2", "Editor", contrast_color_2);
+ theme->set_color("box_selection_fill_color", "Editor", accent_color * Color(1, 1, 1, 0.3));
+ theme->set_color("box_selection_stroke_color", "Editor", accent_color * Color(1, 1, 1, 0.8));
theme->set_color("font_color", "Editor", font_color);
theme->set_color("highlighted_font_color", "Editor", font_color_hl);
@@ -1064,6 +1066,9 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
// FileDialog
theme->set_icon("folder", "FileDialog", theme->get_icon("Folder", "EditorIcons"));
+ // Use a different color for folder icons to make them easier to distinguish from files.
+ // On a light theme, the icon will be dark, so we need to lighten it before blending it with the accent color.
+ theme->set_color("folder_icon_modulate", "FileDialog", (dark_theme ? Color(1, 1, 1) : Color(5, 5, 5)).linear_interpolate(accent_color, 0.7));
theme->set_color("files_disabled", "FileDialog", font_color_disabled);
// color picker
diff --git a/editor/export_template_manager.cpp b/editor/export_template_manager.cpp
index 72a4b43737..1447a143d4 100644
--- a/editor/export_template_manager.cpp
+++ b/editor/export_template_manager.cpp
@@ -321,8 +321,7 @@ bool ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_
if (!f) {
ret = unzGoToNextFile(pkg);
fc++;
- ERR_EXPLAIN("Can't open file from path: " + String(to_write));
- ERR_CONTINUE(true);
+ ERR_CONTINUE_MSG(true, "Can't open file from path: " + String(to_write) + ".");
}
f->store_buffer(data.ptr(), data.size());
@@ -591,8 +590,7 @@ Error ExportTemplateManager::install_android_template() {
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(source_zip.utf8().get_data(), &io);
- ERR_EXPLAIN("Android sources not in zip format");
- ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
+ ERR_FAIL_COND_V_MSG(!pkg, ERR_CANT_OPEN, "Android sources not in ZIP format.");
int ret = unzGoToFirstFile(pkg);
diff --git a/editor/file_type_cache.cpp b/editor/file_type_cache.cpp
index 1bcbc45d3b..746d38f2b5 100644
--- a/editor/file_type_cache.cpp
+++ b/editor/file_type_cache.cpp
@@ -83,11 +83,8 @@ void FileTypeCache::save() {
GLOBAL_LOCK_FUNCTION
String project = ProjectSettings::get_singleton()->get_resource_path();
FileAccess *f = FileAccess::open(project + "/file_type_cache.cch", FileAccess::WRITE);
- if (!f) {
- ERR_EXPLAIN(TTR("Can't open file_type_cache.cch for writing, not saving file type cache!"));
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(!f, "Can't open file_type_cache.cch for writing, not saving file type cache!");
const String *K = NULL;
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index 8e332ad20e..a729befe8e 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -39,6 +39,7 @@
#include "editor_node.h"
#include "editor_settings.h"
#include "scene/main/viewport.h"
+#include "scene/resources/packed_scene.h"
Ref<Texture> FileSystemDock::_get_tree_item_icon(EditorFileSystemDirectory *p_dir, int p_idx) {
Ref<Texture> file_icon;
@@ -52,10 +53,9 @@ Ref<Texture> FileSystemDock::_get_tree_item_icon(EditorFileSystemDirectory *p_di
}
bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory *p_dir, Vector<String> &uncollapsed_paths, bool p_select_in_favorites) {
-
bool parent_should_expand = false;
- // Create a tree item for the subdirectory
+ // Create a tree item for the subdirectory.
TreeItem *subdirectory_item = tree->create_item(p_parent);
String dname = p_dir->get_name();
if (dname == "")
@@ -63,6 +63,7 @@ bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory
subdirectory_item->set_text(0, dname);
subdirectory_item->set_icon(0, get_icon("Folder", "EditorIcons"));
+ subdirectory_item->set_icon_modulate(0, get_color("folder_icon_modulate", "FileDialog"));
subdirectory_item->set_selectable(0, true);
String lpath = p_dir->get_path();
subdirectory_item->set_metadata(0, lpath);
@@ -79,28 +80,28 @@ bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory
parent_should_expand = true;
}
- // Create items for all subdirectories
+ // Create items for all subdirectories.
for (int i = 0; i < p_dir->get_subdir_count(); i++)
parent_should_expand = (_create_tree(subdirectory_item, p_dir->get_subdir(i), uncollapsed_paths, p_select_in_favorites) || parent_should_expand);
- // Create all items for the files in the subdirectory
+ // Create all items for the files in the subdirectory.
if (display_mode == DISPLAY_MODE_TREE_ONLY) {
for (int i = 0; i < p_dir->get_file_count(); i++) {
String file_type = p_dir->get_file_type(i);
if (_is_file_type_disabled_by_feature_profile(file_type)) {
- //if type is disabled, file won't be displayed.
+ // If type is disabled, file won't be displayed.
continue;
}
String file_name = p_dir->get_file(i);
if (searched_string.length() > 0) {
if (file_name.to_lower().find(searched_string) < 0) {
- // The searched string is not in the file name, we skip it
+ // The searched string is not in the file name, we skip it.
continue;
} else {
- // We expand all parents
+ // We expand all parents.
parent_should_expand = true;
}
}
@@ -133,7 +134,7 @@ bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory
}
Vector<String> FileSystemDock::_compute_uncollapsed_paths() {
- // Register currently collapsed paths
+ // Register currently collapsed paths.
Vector<String> uncollapsed_paths;
TreeItem *root = tree->get_root();
if (root) {
@@ -164,14 +165,13 @@ Vector<String> FileSystemDock::_compute_uncollapsed_paths() {
}
void FileSystemDock::_update_tree(const Vector<String> &p_uncollapsed_paths, bool p_uncollapse_root, bool p_select_in_favorites) {
-
- // Recreate the tree
+ // Recreate the tree.
tree->clear();
tree_update_id++;
updating_tree = true;
TreeItem *root = tree->create_item();
- // Handles the favorites
+ // Handles the favorites.
TreeItem *favorites = tree->create_item(root);
favorites->set_icon(0, get_icon("Favorites", "EditorIcons"));
favorites->set_text(0, TTR("Favorites:"));
@@ -185,15 +185,19 @@ void FileSystemDock::_update_tree(const Vector<String> &p_uncollapsed_paths, boo
continue;
Ref<Texture> folder_icon = get_icon("Folder", "EditorIcons");
+ const Color folder_color = get_color("folder_icon_modulate", "FileDialog");
String text;
Ref<Texture> icon;
+ Color color;
if (fave == "res://") {
text = "/";
icon = folder_icon;
+ color = folder_color;
} else if (fave.ends_with("/")) {
text = fave.substr(0, fave.length() - 1).get_file();
icon = folder_icon;
+ color = folder_color;
} else {
text = fave.get_file();
int index;
@@ -203,12 +207,14 @@ void FileSystemDock::_update_tree(const Vector<String> &p_uncollapsed_paths, boo
} else {
icon = get_icon("File", "EditorIcons");
}
+ color = Color(1, 1, 1);
}
if (searched_string.length() == 0 || text.to_lower().find(searched_string) >= 0) {
TreeItem *ti = tree->create_item(favorites);
ti->set_text(0, text);
ti->set_icon(0, icon);
+ ti->set_icon_modulate(0, color);
ti->set_tooltip(0, fave);
ti->set_selectable(0, true);
ti->set_metadata(0, fave);
@@ -230,7 +236,7 @@ void FileSystemDock::_update_tree(const Vector<String> &p_uncollapsed_paths, boo
uncollapsed_paths.push_back("res://");
}
- // Create the remaining of the tree
+ // Create the remaining of the tree.
_create_tree(root, EditorFileSystem::get_singleton()->get_filesystem(), uncollapsed_paths, p_select_in_favorites);
tree->ensure_cursor_is_visible();
updating_tree = false;
@@ -242,7 +248,7 @@ void FileSystemDock::set_display_mode(DisplayMode p_display_mode) {
}
void FileSystemDock::_update_display_mode(bool p_force) {
- // Compute the new display mode
+ // Compute the new display mode.
if (p_force || old_display_mode != display_mode) {
button_toggle_display_mode->set_pressed(display_mode == DISPLAY_MODE_SPLIT);
switch (display_mode) {
@@ -275,11 +281,8 @@ void FileSystemDock::_update_display_mode(bool p_force) {
}
void FileSystemDock::_notification(int p_what) {
-
switch (p_what) {
-
case NOTIFICATION_ENTER_TREE: {
-
if (initialized)
return;
initialized = true;
@@ -319,18 +322,15 @@ void FileSystemDock::_notification(int p_what) {
} else {
_update_tree(Vector<String>(), true);
}
-
} break;
+
case NOTIFICATION_PROCESS: {
if (EditorFileSystem::get_singleton()->is_scanning()) {
scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100);
}
} break;
- case NOTIFICATION_EXIT_TREE: {
- } break;
case NOTIFICATION_DRAG_BEGIN: {
-
Dictionary dd = get_viewport()->gui_get_drag_data();
if (tree->is_visible_in_tree() && dd.has("type")) {
if ((String(dd["type"]) == "files") || (String(dd["type"]) == "files_and_dirs") || (String(dd["type"]) == "resource")) {
@@ -339,20 +339,20 @@ void FileSystemDock::_notification(int p_what) {
tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN);
}
}
-
} break;
- case NOTIFICATION_DRAG_END: {
+ case NOTIFICATION_DRAG_END: {
tree->set_drop_mode_flags(0);
-
} break;
+
case NOTIFICATION_THEME_CHANGED: {
if (is_visible_in_tree()) {
_update_display_mode(true);
}
} break;
+
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
- // Update icons
+ // Update icons.
String ei = "EditorIcons";
button_reload->set_icon(get_icon("Reload", ei));
button_toggle_display_mode->set_icon(get_icon("Panels2", ei));
@@ -369,48 +369,47 @@ void FileSystemDock::_notification(int p_what) {
file_list_search_box->set_right_icon(get_icon("Search", ei));
file_list_search_box->set_clear_button_enabled(true);
- // Update always showfolders
+ // Update always show folders.
bool new_always_show_folders = bool(EditorSettings::get_singleton()->get("docks/filesystem/always_show_folders"));
if (new_always_show_folders != always_show_folders) {
always_show_folders = new_always_show_folders;
_update_file_list(true);
}
- // Change full tree mode
+ // Change full tree mode.
_update_display_mode();
-
} break;
}
}
void FileSystemDock::_tree_multi_selected(Object *p_item, int p_column, bool p_selected) {
- // Update the import dock
+ // Update the import dock.
import_dock_needs_update = true;
call_deferred("_update_import_dock");
- // Return if we don't select something new
+ // Return if we don't select something new.
if (!p_selected)
return;
- // Tree item selected
+ // Tree item selected.
TreeItem *selected = tree->get_selected();
if (!selected)
return;
TreeItem *favorites_item = tree->get_root()->get_children();
if (selected->get_parent() == favorites_item && !String(selected->get_metadata(0)).ends_with("/")) {
- // Go to the favorites if we click in the favorites and the path has changed
+ // Go to the favorites if we click in the favorites and the path has changed.
path = "Favorites";
} else {
path = selected->get_metadata(0);
- // Note: the "Favorites" item also leads to this path
+ // Note: the "Favorites" item also leads to this path.
}
- // Set the current path
+ // Set the current path.
_set_current_path_text(path);
_push_to_history();
- // Update the file list
+ // Update the file list.
if (!updating_tree && display_mode == DISPLAY_MODE_SPLIT) {
_update_file_list(false);
}
@@ -424,7 +423,6 @@ String FileSystemDock::get_selected_path() const {
}
String FileSystemDock::get_current_path() const {
-
return path;
}
@@ -452,8 +450,7 @@ void FileSystemDock::_navigate_to_path(const String &p_path, bool p_select_in_fa
path = target_path + "/";
} else {
memdelete(dirAccess);
- ERR_EXPLAIN(vformat(TTR("Cannot navigate to '%s' as it has not been found in the file system!"), p_path));
- ERR_FAIL();
+ ERR_FAIL_MSG(vformat("Cannot navigate to '%s' as it has not been found in the file system!", p_path));
}
memdelete(dirAccess);
}
@@ -484,7 +481,6 @@ void FileSystemDock::navigate_to_path(const String &p_path) {
}
void FileSystemDock::_file_list_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Ref<Texture> &p_small_preview, const Variant &p_udata) {
-
if ((file_list_vb->is_visible_in_tree() || path == p_path.get_base_dir()) && p_preview.is_valid()) {
Array uarr = p_udata;
int idx = uarr[0];
@@ -532,7 +528,6 @@ void FileSystemDock::_set_file_display(bool p_active) {
}
bool FileSystemDock::_is_file_type_disabled_by_feature_profile(const StringName &p_class) {
-
Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
if (profile.is_null()) {
return false;
@@ -552,7 +547,6 @@ bool FileSystemDock::_is_file_type_disabled_by_feature_profile(const StringName
}
void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items) {
-
if (matches->size() > p_max_items)
return;
@@ -570,10 +564,9 @@ void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *
fi.type = p_path->get_file_type(i);
fi.path = p_path->get_file_path(i);
fi.import_broken = !p_path->get_file_import_is_valid(i);
- fi.import_status = 0;
if (_is_file_type_disabled_by_feature_profile(fi.type)) {
- //this type is disabled, will not appear here
+ // This type is disabled, will not appear here.
continue;
}
@@ -585,8 +578,7 @@ void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *
}
void FileSystemDock::_update_file_list(bool p_keep_selection) {
-
- // Register the previously selected items
+ // Register the previously selected items.
Set<String> cselection;
if (p_keep_selection) {
for (int i = 0; i < files->get_item_count(); i++) {
@@ -612,7 +604,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
bool use_thumbnails = (file_list_display_mode == FILE_LIST_DISPLAY_THUMBNAILS);
if (use_thumbnails) {
- // Thumbnails mode
+ // Thumbnails mode.
files->set_max_columns(0);
files->set_icon_mode(ItemList::ICON_MODE_TOP);
files->set_fixed_column_width(thumbnail_size * 3 / 2);
@@ -629,8 +621,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
file_thumbnail_broken = get_icon("FileDeadBigThumb", ei);
}
} else {
-
- // No thumbnails
+ // No thumbnails.
files->set_icon_mode(ItemList::ICON_MODE_LEFT);
files->set_max_columns(1);
files->set_max_text_lines(1);
@@ -639,11 +630,12 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
}
Ref<Texture> folder_icon = (use_thumbnails) ? folder_thumbnail : get_icon("folder", "FileDialog");
+ const Color folder_color = get_color("folder_icon_modulate", "FileDialog");
- // Build the FileInfo list
+ // Build the FileInfo list.
List<FileInfo> filelist;
if (path == "Favorites") {
- // Display the favorites
+ // Display the favorites.
Vector<String> favorites = EditorSettings::get_singleton()->get_favorites();
for (int i = 0; i < favorites.size(); i++) {
String favorite = favorites[i];
@@ -677,7 +669,6 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
fi.type = "";
fi.import_broken = true;
}
- fi.import_status = 0;
if (searched_string.length() == 0 || fi.name.to_lower().find(searched_string) >= 0) {
filelist.push_back(fi);
@@ -685,8 +676,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
}
}
} else {
-
- // Get infos on the directory + file
+ // Get infos on the directory + file.
if (directory.ends_with("/") && directory != "res://") {
directory = directory.substr(0, directory.length() - 1);
}
@@ -700,13 +690,11 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
return;
if (searched_string.length() > 0) {
- // Display the search results
+ // Display the search results.
_search(EditorFileSystem::get_singleton()->get_filesystem(), &filelist, 128);
} else {
-
if (display_mode == DISPLAY_MODE_TREE_ONLY || always_show_folders) {
- // Display folders in the list
-
+ // Display folders in the list.
if (directory != "res://") {
files->add_item("..", folder_icon, true);
@@ -716,14 +704,15 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
files->set_item_metadata(files->get_item_count() - 1, bd);
files->set_item_selectable(files->get_item_count() - 1, false);
+ files->set_item_icon_modulate(files->get_item_count() - 1, folder_color);
}
for (int i = 0; i < efd->get_subdir_count(); i++) {
-
String dname = efd->get_subdir(i)->get_name();
files->add_item(dname, folder_icon, true);
files->set_item_metadata(files->get_item_count() - 1, directory.plus_file(dname) + "/");
+ files->set_item_icon_modulate(files->get_item_count() - 1, folder_color);
if (cselection.has(dname)) {
files->select(files->get_item_count() - 1, false);
@@ -731,15 +720,13 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
}
}
- // Display the folder content
+ // Display the folder content.
for (int i = 0; i < efd->get_file_count(); i++) {
-
FileInfo fi;
fi.name = efd->get_file(i);
fi.path = directory.plus_file(fi.name);
fi.type = efd->get_file_type(i);
fi.import_broken = !efd->get_file_import_is_valid(i);
- fi.import_status = 0;
filelist.push_back(fi);
}
@@ -747,7 +734,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
filelist.sort();
}
- // Fills the ItemList control node from the FileInfos
+ // Fills the ItemList control node from the FileInfos.
String oi = "Object";
for (List<FileInfo>::Element *E = filelist.front(); E; E = E->next()) {
FileInfo *finfo = &(E->get());
@@ -760,7 +747,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
String tooltip = fpath;
- // Select the icons
+ // Select the icons.
if (!finfo->import_broken) {
type_icon = (has_icon(ftype, ei)) ? get_icon(ftype, ei) : get_icon(oi, ei);
big_icon = file_thumbnail;
@@ -770,7 +757,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
tooltip += "\n" + TTR("Status: Import of file failed. Please fix file and reimport manually.");
}
- // Add the item to the ItemList
+ // Add the item to the ItemList.
int item_index;
if (use_thumbnails) {
files->add_item(fname, big_icon, true);
@@ -784,7 +771,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
files->set_item_metadata(item_index, fpath);
}
- // Generate the preview
+ // Generate the preview.
if (!finfo->import_broken) {
Array udata;
udata.resize(2);
@@ -793,7 +780,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
EditorResourcePreview::get_singleton()->queue_resource_preview(fpath, this, "_file_list_thumbnail_done", udata);
}
- // Select the items
+ // Select the items.
if (cselection.has(fname))
files->select(item_index, false);
@@ -802,7 +789,7 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
files->ensure_current_is_visible();
}
- // Tooltip
+ // Tooltip.
if (finfo->sources.size()) {
for (int j = 0; j < finfo->sources.size(); j++) {
tooltip += "\nSource: " + finfo->sources[j];
@@ -849,13 +836,12 @@ void FileSystemDock::_file_list_activate_file(int p_idx) {
}
void FileSystemDock::_preview_invalidated(const String &p_path) {
-
if (file_list_display_mode == FILE_LIST_DISPLAY_THUMBNAILS && p_path.get_base_dir() == path && searched_string.length() == 0 && file_list_vb->is_visible_in_tree()) {
for (int i = 0; i < files->get_item_count(); i++) {
if (files->get_item_metadata(i) == p_path) {
- //re-request preview
+ // Re-request preview.
Array udata;
udata.resize(2);
udata[0] = i;
@@ -868,7 +854,6 @@ void FileSystemDock::_preview_invalidated(const String &p_path) {
}
void FileSystemDock::_fs_changed() {
-
button_hist_prev->set_disabled(history_pos == 0);
button_hist_next->set_disabled(history_pos == history.size() - 1);
scanning_vb->hide();
@@ -886,7 +871,6 @@ void FileSystemDock::_fs_changed() {
}
void FileSystemDock::_set_scanning_mode() {
-
button_hist_prev->set_disabled(true);
button_hist_next->set_disabled(true);
split_box->hide();
@@ -900,7 +884,6 @@ void FileSystemDock::_set_scanning_mode() {
}
void FileSystemDock::_fw_history() {
-
if (history_pos < history.size() - 1)
history_pos++;
@@ -978,7 +961,7 @@ void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd, const Map<Str
void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_new_path,
Map<String, String> &p_file_renames, Map<String, String> &p_folder_renames) {
- //Ensure folder paths end with "/"
+ // Ensure folder paths end with "/".
String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/");
String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/");
@@ -988,12 +971,12 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root."));
return;
} else if (!p_item.is_file && new_path.begins_with(old_path)) {
- //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/"
+ // This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/".
EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n");
return;
}
- //Build a list of files which will have new paths as a result of this operation
+ // Build a list of files which will have new paths as a result of this operation.
Vector<String> file_changed_paths;
Vector<String> folder_changed_paths;
if (p_item.is_file) {
@@ -1007,8 +990,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
print_verbose("Moving " + old_path + " -> " + new_path);
Error err = da->rename(old_path, new_path);
if (err == OK) {
-
- //Move/Rename any corresponding import settings too
+ // Move/Rename any corresponding import settings too.
if (p_item.is_file && FileAccess::exists(old_path + ".import")) {
err = da->rename(old_path + ".import", new_path + ".import");
if (err != OK) {
@@ -1016,7 +998,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
}
}
- // update scene if it is open
+ // Update scene if it is open.
for (int i = 0; i < file_changed_paths.size(); ++i) {
String new_item_path = p_item.is_file ? new_path : file_changed_paths[i].replace_first(old_path, new_path);
if (ResourceLoader::get_resource_type(new_item_path) == "PackedScene" && editor->is_scene_open(file_changed_paths[i])) {
@@ -1031,7 +1013,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
}
}
- //Only treat as a changed dependency if it was successfully moved
+ // Only treat as a changed dependency if it was successfully moved.
for (int i = 0; i < file_changed_paths.size(); ++i) {
p_file_renames[file_changed_paths[i]] = file_changed_paths[i].replace_first(old_path, new_path);
print_verbose(" Remap: " + file_changed_paths[i] + " -> " + p_file_renames[file_changed_paths[i]]);
@@ -1048,7 +1030,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
}
void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const String &p_new_path) const {
- //Ensure folder paths end with "/"
+ // Ensure folder paths end with "/".
String old_path = (p_item.is_file || p_item.path.ends_with("/")) ? p_item.path : (p_item.path + "/");
String new_path = (p_item.is_file || p_new_path.ends_with("/")) ? p_new_path : (p_new_path + "/");
@@ -1058,7 +1040,7 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin
EditorNode::get_singleton()->add_io_error(TTR("Cannot move/rename resources root."));
return;
} else if (!p_item.is_file && new_path.begins_with(old_path)) {
- //This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/"
+ // This check doesn't erroneously catch renaming to a longer name as folder paths always end with "/".
EditorNode::get_singleton()->add_io_error(TTR("Cannot move a folder into itself.") + "\n" + old_path + "\n");
return;
}
@@ -1067,7 +1049,7 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin
print_verbose("Duplicating " + old_path + " -> " + new_path);
Error err = p_item.is_file ? da->copy(old_path, new_path) : da->copy_dir(old_path, new_path);
if (err == OK) {
- //Move/Rename any corresponding import settings too
+ // Move/Rename any corresponding import settings too.
if (p_item.is_file && FileAccess::exists(old_path + ".import")) {
err = da->copy(old_path + ".import", new_path + ".import");
if (err != OK) {
@@ -1081,13 +1063,11 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin
}
void FileSystemDock::_update_resource_paths_after_move(const Map<String, String> &p_renames) const {
-
- //Rename all resources loaded, be it subresources or actual resources
+ // Rename all resources loaded, be it subresources or actual resources.
List<Ref<Resource> > cached;
ResourceCache::get_cached_resources(&cached);
for (List<Ref<Resource> >::Element *E = cached.front(); E; E = E->next()) {
-
Ref<Resource> r = E->get();
String base_path = r->get_path();
@@ -1106,7 +1086,6 @@ void FileSystemDock::_update_resource_paths_after_move(const Map<String, String>
}
for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); i++) {
-
String path;
if (i == EditorNode::get_editor_data().get_edited_scene()) {
if (!get_tree()->get_edited_scene_root())
@@ -1114,7 +1093,6 @@ void FileSystemDock::_update_resource_paths_after_move(const Map<String, String>
path = get_tree()->get_edited_scene_root()->get_filename();
} else {
-
path = EditorNode::get_editor_data().get_scene_path(i);
}
@@ -1123,23 +1101,21 @@ void FileSystemDock::_update_resource_paths_after_move(const Map<String, String>
}
if (i == EditorNode::get_editor_data().get_edited_scene()) {
-
get_tree()->get_edited_scene_root()->set_filename(path);
} else {
-
EditorNode::get_editor_data().set_scene_path(i, path);
}
}
}
void FileSystemDock::_update_dependencies_after_move(const Map<String, String> &p_renames) const {
- //The following code assumes that the following holds:
+ // The following code assumes that the following holds:
// 1) EditorFileSystem contains the old paths/folder structure from before the rename/move.
// 2) ResourceLoader can use the new paths without needing to call rescan.
Vector<String> remaps;
_find_remaps(EditorFileSystem::get_singleton()->get_filesystem(), p_renames, remaps);
for (int i = 0; i < remaps.size(); ++i) {
- //Because we haven't called a rescan yet the found remap might still be an old path itself.
+ // Because we haven't called a rescan yet the found remap might still be an old path itself.
String file = p_renames.has(remaps[i]) ? p_renames[remaps[i]] : remaps[i];
print_verbose("Remapping dependencies for: " + file);
Error err = ResourceLoader::rename_dependencies(file, p_renames);
@@ -1153,8 +1129,7 @@ void FileSystemDock::_update_dependencies_after_move(const Map<String, String> &
}
void FileSystemDock::_update_project_settings_after_move(const Map<String, String> &p_renames) const {
-
- // Find all project settings of type FILE and replace them if needed
+ // Find all project settings of type FILE and replace them if needed.
const Map<StringName, PropertyInfo> prop_info = ProjectSettings::get_singleton()->get_custom_property_info();
for (const Map<StringName, PropertyInfo>::Element *E = prop_info.front(); E; E = E->next()) {
if (E->get().hint == PROPERTY_HINT_FILE) {
@@ -1185,7 +1160,6 @@ void FileSystemDock::_update_project_settings_after_move(const Map<String, Strin
}
void FileSystemDock::_update_favorites_list_after_move(const Map<String, String> &p_files_renames, const Map<String, String> &p_folders_renames) const {
-
Vector<String> favorites = EditorSettings::get_singleton()->get_favorites();
Vector<String> new_favorites;
@@ -1250,6 +1224,48 @@ void FileSystemDock::_make_dir_confirm() {
}
}
+void FileSystemDock::_make_scene_confirm() {
+ String scene_name = make_scene_dialog_text->get_text().strip_edges();
+
+ if (scene_name.length() == 0) {
+ EditorNode::get_singleton()->show_warning(TTR("No name provided."));
+ return;
+ }
+
+ String directory = path;
+ if (!directory.ends_with("/")) {
+ directory = directory.get_base_dir();
+ }
+
+ String extension = scene_name.get_extension();
+ List<String> extensions;
+ Ref<PackedScene> sd = memnew(PackedScene);
+ ResourceSaver::get_recognized_extensions(sd, &extensions);
+
+ bool extension_correct = false;
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ if (E->get() == extension) {
+ extension_correct = true;
+ break;
+ }
+ }
+ if (!extension_correct)
+ scene_name = scene_name.get_basename() + ".tscn";
+
+ scene_name = directory.plus_file(scene_name);
+
+ DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
+ if (da->file_exists(scene_name)) {
+ EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists."));
+ memdelete(da);
+ return;
+ }
+ memdelete(da);
+
+ int idx = editor->new_scene();
+ editor->get_editor_data().set_scene_path(idx, scene_name);
+}
+
void FileSystemDock::_file_deleted(String p_file) {
emit_signal("file_deleted", p_file);
}
@@ -1259,7 +1275,6 @@ void FileSystemDock::_folder_deleted(String p_folder) {
}
void FileSystemDock::_rename_operation_confirm() {
-
String new_name = rename_dialog_text->get_text().strip_edges();
if (new_name.length() == 0) {
EditorNode::get_singleton()->show_warning(TTR("No name provided."));
@@ -1279,10 +1294,10 @@ void FileSystemDock::_rename_operation_confirm() {
EditorFileSystem::get_singleton()->move_group_file(old_path, new_path);
}
- //Present a more user friendly warning for name conflict
+ // Present a more user friendly warning for name conflict.
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
#if defined(WINDOWS_ENABLED) || defined(UWP_ENABLED)
- // Workaround case insensitivity on Windows
+ // Workaround case insensitivity on Windows.
if ((da->file_exists(new_path) || da->dir_exists(new_path)) && new_path.to_lower() != old_path.to_lower()) {
#else
if (da->file_exists(new_path) || da->dir_exists(new_path)) {
@@ -1314,7 +1329,6 @@ void FileSystemDock::_rename_operation_confirm() {
}
void FileSystemDock::_duplicate_operation_confirm() {
-
String new_name = duplicate_dialog_text->get_text().strip_edges();
if (new_name.length() == 0) {
EditorNode::get_singleton()->show_warning(TTR("No name provided."));
@@ -1332,7 +1346,7 @@ void FileSystemDock::_duplicate_operation_confirm() {
String new_path = base_dir.plus_file(new_name);
- //Present a more user friendly warning for name conflict
+ // Present a more user friendly warning for name conflict
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
if (da->file_exists(new_path) || da->dir_exists(new_path)) {
EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists."));
@@ -1343,7 +1357,7 @@ void FileSystemDock::_duplicate_operation_confirm() {
_try_duplicate_item(to_duplicate, new_path);
- //Rescan everything
+ // Rescan everything.
print_verbose("FileSystem: calling rescan.");
_rescan();
}
@@ -1376,14 +1390,14 @@ void FileSystemDock::_move_operation_confirm(const String &p_to_path, bool overw
to_move_path = p_to_path;
bool can_move = _check_existing();
if (!can_move) {
- //ask to do something
+ // Ask to do something.
overwrite_dialog->popup_centered_minsize();
overwrite_dialog->grab_focus();
return;
}
}
- //check groups
+ // Check groups.
for (int i = 0; i < to_move.size(); i++) {
print_line("is group: " + to_move[i].path + ": " + itos(EditorFileSystem::get_singleton()->is_group_file(to_move[i].path)));
@@ -1424,7 +1438,7 @@ void FileSystemDock::_move_operation_confirm(const String &p_to_path, bool overw
}
Vector<String> FileSystemDock::_tree_get_selected(bool remove_self_inclusion) {
- // Build a list of selected items with the active one at the first position
+ // Build a list of selected items with the active one at the first position.
Vector<String> selected_strings;
TreeItem *favorites_item = tree->get_root()->get_children();
@@ -1442,8 +1456,15 @@ Vector<String> FileSystemDock::_tree_get_selected(bool remove_self_inclusion) {
selected = tree->get_next_selected(selected);
}
- // Remove paths or files that are included into another
- if (remove_self_inclusion && selected_strings.size() > 1) {
+ if (remove_self_inclusion) {
+ selected_strings = _remove_self_included_paths(selected_strings);
+ }
+ return selected_strings;
+}
+
+Vector<String> FileSystemDock::_remove_self_included_paths(Vector<String> selected_strings) {
+ // Remove paths or files that are included into another.
+ if (selected_strings.size() > 1) {
selected_strings.sort_custom<NaturalNoCaseComparator>();
String last_path = "";
for (int i = 0; i < selected_strings.size(); i++) {
@@ -1460,10 +1481,9 @@ Vector<String> FileSystemDock::_tree_get_selected(bool remove_self_inclusion) {
}
void FileSystemDock::_tree_rmb_option(int p_option) {
+ Vector<String> selected_strings = _tree_get_selected(false);
- Vector<String> selected_strings = _tree_get_selected();
-
- // Execute the current option
+ // Execute the current option.
switch (p_option) {
case FOLDER_EXPAND_ALL:
case FOLDER_COLLAPSE_ALL: {
@@ -1503,11 +1523,11 @@ void FileSystemDock::_file_list_rmb_option(int p_option) {
}
void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected) {
- // The first one should be the active item
+ // The first one should be the active item.
switch (p_option) {
case FILE_SHOW_IN_EXPLORER: {
- // Show the file / folder in the OS explorer
+ // Show the file/folder in the OS explorer.
String fpath = path;
if (path == "Favorites") {
fpath = p_selected[0];
@@ -1521,7 +1541,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_OPEN: {
- // Open folders
+ // Open folders.
TreeItem *selected = tree->get_root();
selected = tree->get_next_selected(selected);
while (selected) {
@@ -1530,21 +1550,21 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
}
selected = tree->get_next_selected(selected);
}
- // Open the file
+ // Open the file.
for (int i = 0; i < p_selected.size(); i++) {
_select_file(p_selected[i]);
}
} break;
case FILE_INHERIT: {
- // Create a new scene inherited from the selected one
+ // Create a new scene inherited from the selected one.
if (p_selected.size() == 1) {
emit_signal("inherit", p_selected[0]);
}
} break;
case FILE_INSTANCE: {
- // Instance all selected scenes
+ // Instance all selected scenes.
Vector<String> paths;
for (int i = 0; i < p_selected.size(); i++) {
String fpath = p_selected[i];
@@ -1558,7 +1578,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_ADD_FAVORITE: {
- // Add the files from favorites
+ // Add the files from favorites.
Vector<String> favorites = EditorSettings::get_singleton()->get_favorites();
for (int i = 0; i < p_selected.size(); i++) {
if (favorites.find(p_selected[i]) == -1) {
@@ -1570,7 +1590,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_REMOVE_FAVORITE: {
- // Remove the files from favorites
+ // Remove the files from favorites.
Vector<String> favorites = EditorSettings::get_singleton()->get_favorites();
for (int i = 0; i < p_selected.size(); i++) {
favorites.erase(p_selected[i]);
@@ -1582,7 +1602,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_DEPENDENCIES: {
- // Checkout the file dependencies
+ // Checkout the file dependencies.
if (!p_selected.empty()) {
String fpath = p_selected[0];
deps_editor->edit(fpath);
@@ -1590,7 +1610,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_OWNERS: {
- // Checkout the file owners
+ // Checkout the file owners.
if (!p_selected.empty()) {
String fpath = p_selected[0];
owners_editor->show(fpath);
@@ -1598,10 +1618,11 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_MOVE: {
- // Move the files to a given location
+ // Move the files to a given location.
to_move.clear();
- for (int i = 0; i < p_selected.size(); i++) {
- String fpath = p_selected[i];
+ Vector<String> collapsed_paths = _remove_self_included_paths(p_selected);
+ for (int i = collapsed_paths.size() - 1; i >= 0; i--) {
+ String fpath = collapsed_paths[i];
if (fpath != "res://") {
to_move.push_back(FileOrFolder(fpath, !fpath.ends_with("/")));
}
@@ -1612,7 +1633,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_RENAME: {
- // Rename the active file
+ // Rename the active file.
if (!p_selected.empty()) {
to_rename.path = p_selected[0];
if (to_rename.path != "res://") {
@@ -1635,12 +1656,13 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_REMOVE: {
- // Remove the selected files
+ // Remove the selected files.
Vector<String> remove_files;
Vector<String> remove_folders;
+ Vector<String> collapsed_paths = _remove_self_included_paths(p_selected);
- for (int i = 0; i < p_selected.size(); i++) {
- String fpath = p_selected[i];
+ for (int i = 0; i < collapsed_paths.size(); i++) {
+ String fpath = collapsed_paths[i];
if (fpath != "res://") {
if (fpath.ends_with("/")) {
remove_folders.push_back(fpath);
@@ -1656,7 +1678,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_DUPLICATE: {
- // Duplicate the selected files
+ // Duplicate the selected files.
for (int i = 0; i < p_selected.size(); i++) {
to_duplicate.path = p_selected[i];
to_duplicate.is_file = !to_duplicate.path.ends_with("/");
@@ -1681,7 +1703,7 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_REIMPORT: {
- // Reimport all selected files
+ // Reimport all selected files.
Vector<String> reimport;
for (int i = 0; i < p_selected.size(); i++) {
reimport.push_back(p_selected[i]);
@@ -1691,15 +1713,20 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_NEW_FOLDER: {
- // Create a new folder
make_dir_dialog_text->set_text("new folder");
make_dir_dialog_text->select_all();
make_dir_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE);
make_dir_dialog_text->grab_focus();
} break;
+ case FILE_NEW_SCENE: {
+ make_scene_dialog_text->set_text("new scene");
+ make_scene_dialog_text->select_all();
+ make_scene_dialog->popup_centered_minsize(Size2(250, 80) * EDSCALE);
+ make_scene_dialog_text->grab_focus();
+ } break;
+
case FILE_NEW_SCRIPT: {
- // Create a new script
String fpath = path;
if (!fpath.ends_with("/")) {
fpath = fpath.get_base_dir();
@@ -1709,7 +1736,6 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_COPY_PATH: {
- // Copy the file path
if (!p_selected.empty()) {
String fpath = p_selected[0];
OS::get_singleton()->set_clipboard(fpath);
@@ -1717,7 +1743,6 @@ void FileSystemDock::_file_option(int p_option, const Vector<String> &p_selected
} break;
case FILE_NEW_RESOURCE: {
- // Create a new resource
new_resource_dialog->popup_create(true);
} break;
}
@@ -1745,7 +1770,7 @@ void FileSystemDock::_resource_created() const {
void FileSystemDock::_search_changed(const String &p_text, const Control *p_from) {
if (searched_string.length() == 0 && p_text.length() > 0) {
- // Register the uncollapsed paths before they change
+ // Register the uncollapsed paths before they change.
uncollapsed_paths_before_search = _compute_uncollapsed_paths();
}
@@ -1753,7 +1778,7 @@ void FileSystemDock::_search_changed(const String &p_text, const Control *p_from
if (p_from == tree_search_box)
file_list_search_box->set_text(searched_string);
- else // file_list_search_box
+ else // File_list_search_box.
tree_search_box->set_text(searched_string);
switch (display_mode) {
@@ -1768,7 +1793,6 @@ void FileSystemDock::_search_changed(const String &p_text, const Control *p_from
}
void FileSystemDock::_rescan() {
-
_set_scanning_mode();
EditorFileSystem::get_singleton()->scan();
}
@@ -1783,12 +1807,10 @@ void FileSystemDock::fix_dependencies(const String &p_for_file) {
}
void FileSystemDock::focus_on_filter() {
-
file_list_search_box->grab_focus();
}
void FileSystemDock::set_file_list_display_mode(FileListDisplayMode p_mode) {
-
if (p_mode == file_list_display_mode)
return;
@@ -1802,12 +1824,12 @@ Variant FileSystemDock::get_drag_data_fw(const Point2 &p_point, Control *p_from)
Vector<String> paths;
if (p_from == tree) {
- // Check if the first selected is in favorite
+ // Check if the first selected is in favorite.
TreeItem *selected = tree->get_next_selected(tree->get_root());
while (selected) {
TreeItem *favorites_item = tree->get_root()->get_children();
if (selected == favorites_item) {
- // The "Favorites" item is not draggable
+ // The "Favorites" item is not draggable.
return Variant();
}
@@ -1845,12 +1867,11 @@ Variant FileSystemDock::get_drag_data_fw(const Point2 &p_point, Control *p_from)
}
bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
-
Dictionary drag_data = p_data;
if (drag_data.has("type") && String(drag_data["type"]) == "favorite") {
- // Moving favorite around
+ // Moving favorite around.
TreeItem *ti = tree->get_item_at_position(p_point);
if (!ti)
return false;
@@ -1861,20 +1882,20 @@ bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_da
TreeItem *resources_item = favorites_item->get_next();
if (ti == favorites_item) {
- return (drop_section == 1); // The parent, first fav
+ return (drop_section == 1); // The parent, first fav.
}
if (ti->get_parent() && favorites_item == ti->get_parent()) {
return true; // A favorite
}
if (ti == resources_item) {
- return (drop_section == -1); // The tree, last fav
+ return (drop_section == -1); // The tree, last fav.
}
return false;
}
if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
- // Move resources
+ // Move resources.
String to_dir;
bool favorite;
_get_drag_target_folder(to_dir, favorite, p_point, p_from);
@@ -1882,7 +1903,7 @@ bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) {
- // Move files or dir
+ // Move files or dir.
String to_dir;
bool favorite;
_get_drag_target_folder(to_dir, favorite, p_point, p_from);
@@ -1893,8 +1914,8 @@ bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_da
if (to_dir.empty())
return false;
- //Attempting to move a folder into itself will fail later
- //Rather than bring up a message don't try to do it in the first place
+ // Attempting to move a folder into itself will fail later,
+ // rather than bring up a message don't try to do it in the first place
to_dir = to_dir.ends_with("/") ? to_dir : (to_dir + "/");
Vector<String> fnames = drag_data["files"];
for (int i = 0; i < fnames.size(); ++i) {
@@ -1909,7 +1930,6 @@ bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_da
}
void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
-
if (!can_drop_data_fw(p_point, p_data, p_from))
return;
Dictionary drag_data = p_data;
@@ -1917,7 +1937,7 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
Vector<String> dirs = EditorSettings::get_singleton()->get_favorites();
if (drag_data.has("type") && String(drag_data["type"]) == "favorite") {
- // Moving favorite around
+ // Moving favorite around.
TreeItem *ti = tree->get_item_at_position(p_point);
if (!ti)
return;
@@ -1929,20 +1949,20 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
TreeItem *resources_item = favorites_item->get_next();
if (ti == favorites_item) {
- // Drop on the favorite folder
+ // Drop on the favorite folder.
drop_position = 0;
} else if (ti == resources_item) {
- // Drop on the resource item
+ // Drop on the resource item.
drop_position = dirs.size();
} else {
- // Drop in the list
+ // Drop in the list.
drop_position = dirs.find(ti->get_metadata(0));
if (drop_section == 1) {
drop_position++;
}
}
- // Remove dragged favorites
+ // Remove dragged favorites.
Vector<int> to_remove;
int offset = 0;
for (int i = 0; i < files.size(); i++) {
@@ -1958,7 +1978,7 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
dirs.remove(to_remove[i] - i);
}
- // Re-add them at the right position
+ // Re-add them at the right position.
for (int i = 0; i < files.size(); i++) {
dirs.insert(drop_position, files[i]);
drop_position++;
@@ -1973,7 +1993,7 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
}
if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
- // Moving resource
+ // Moving resource.
Ref<Resource> res = drag_data["resource"];
String to_dir;
bool favorite;
@@ -1985,7 +2005,7 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
}
if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) {
- // Move files or add to favorites
+ // Move files or add to favorites.
String to_dir;
bool favorite;
_get_drag_target_folder(to_dir, favorite, p_point, p_from);
@@ -2015,7 +2035,7 @@ void FileSystemDock::_get_drag_target_folder(String &target, bool &target_favori
target = String();
target_favorites = false;
- // In the file list
+ // In the file list.
if (p_from == files) {
int pos = files->get_item_at_position(p_point, true);
if (pos == -1) {
@@ -2027,12 +2047,12 @@ void FileSystemDock::_get_drag_target_folder(String &target, bool &target_favori
return;
}
- // In the tree
+ // In the tree.
if (p_from == tree) {
TreeItem *ti = tree->get_item_at_position(p_point);
int section = tree->get_drop_section_at_position(p_point);
if (ti) {
- // Check the favorites first
+ // Check the favorites first.
if (ti == tree->get_root()->get_children() && section >= 0) {
target_favorites = true;
return;
@@ -2043,13 +2063,13 @@ void FileSystemDock::_get_drag_target_folder(String &target, bool &target_favori
String fpath = ti->get_metadata(0);
if (section == 0) {
if (fpath.ends_with("/")) {
- // We drop on a folder
+ // We drop on a folder.
target = fpath;
return;
}
} else {
if (ti->get_parent() != tree->get_root()->get_children()) {
- // Not in the favorite section
+ // Not in the favorite section.
if (fpath != "res://") {
// We drop between two files
if (fpath.ends_with("/")) {
@@ -2066,7 +2086,7 @@ void FileSystemDock::_get_drag_target_folder(String &target, bool &target_favori
}
void FileSystemDock::_file_and_folders_fill_popup(PopupMenu *p_popup, Vector<String> p_paths, bool p_display_path_dependent_options) {
- // Add options for files and folders
+ // Add options for files and folders.
ERR_FAIL_COND(p_paths.empty());
Vector<String> filenames;
@@ -2090,7 +2110,7 @@ void FileSystemDock::_file_and_folders_fill_popup(PopupMenu *p_popup, Vector<Str
all_files_scenes &= (EditorFileSystem::get_singleton()->get_file_type(fpath) == "PackedScene");
}
- // Check if in favorites
+ // Check if in favorites.
bool found = false;
for (int j = 0; j < favorites.size(); j++) {
if (favorites[j] == fpath) {
@@ -2106,7 +2126,6 @@ void FileSystemDock::_file_and_folders_fill_popup(PopupMenu *p_popup, Vector<Str
}
if (all_files) {
-
if (all_files_scenes) {
if (filenames.size() == 1) {
p_popup->add_item(TTR("Open Scene"), FILE_OPEN);
@@ -2146,19 +2165,25 @@ void FileSystemDock::_file_and_folders_fill_popup(PopupMenu *p_popup, Vector<Str
if (p_paths.size() == 1) {
p_popup->add_item(TTR("Copy Path"), FILE_COPY_PATH);
- p_popup->add_item(TTR("Rename..."), FILE_RENAME);
- p_popup->add_item(TTR("Duplicate..."), FILE_DUPLICATE);
+ if (p_paths[0] != "res://") {
+ p_popup->add_item(TTR("Rename..."), FILE_RENAME);
+ p_popup->add_item(TTR("Duplicate..."), FILE_DUPLICATE);
+ }
}
- p_popup->add_item(TTR("Move To..."), FILE_MOVE);
- p_popup->add_item(TTR("Delete"), FILE_REMOVE);
+ if (p_paths.size() > 1 || p_paths[0] != "res://") {
+ p_popup->add_item(TTR("Move To..."), FILE_MOVE);
+ p_popup->add_item(TTR("Delete"), FILE_REMOVE);
+ }
if (p_paths.size() == 1) {
p_popup->add_separator();
if (p_display_path_dependent_options) {
p_popup->add_item(TTR("New Folder..."), FILE_NEW_FOLDER);
+ p_popup->add_item(TTR("New Scene..."), FILE_NEW_SCENE);
p_popup->add_item(TTR("New Script..."), FILE_NEW_SCRIPT);
p_popup->add_item(TTR("New Resource..."), FILE_NEW_RESOURCE);
+ p_popup->add_separator();
}
String fpath = p_paths[0];
@@ -2168,8 +2193,8 @@ void FileSystemDock::_file_and_folders_fill_popup(PopupMenu *p_popup, Vector<Str
}
void FileSystemDock::_tree_rmb_select(const Vector2 &p_pos) {
- // Right click is pressed in the tree
- Vector<String> paths = _tree_get_selected();
+ // Right click is pressed in the tree.
+ Vector<String> paths = _tree_get_selected(false);
if (paths.size() == 1) {
if (paths[0].ends_with("/")) {
@@ -2179,7 +2204,7 @@ void FileSystemDock::_tree_rmb_select(const Vector2 &p_pos) {
}
}
- // Popup
+ // Popup.
if (!paths.empty()) {
tree_popup->clear();
tree_popup->set_size(Size2(1, 1));
@@ -2190,11 +2215,12 @@ void FileSystemDock::_tree_rmb_select(const Vector2 &p_pos) {
}
void FileSystemDock::_tree_rmb_empty(const Vector2 &p_pos) {
- // Right click is pressed in the empty space of the tree
+ // Right click is pressed in the empty space of the tree.
path = "res://";
tree_popup->clear();
tree_popup->set_size(Size2(1, 1));
tree_popup->add_item(TTR("New Folder..."), FILE_NEW_FOLDER);
+ tree_popup->add_item(TTR("New Scene..."), FILE_NEW_SCENE);
tree_popup->add_item(TTR("New Script..."), FILE_NEW_SCRIPT);
tree_popup->add_item(TTR("New Resource..."), FILE_NEW_RESOURCE);
tree_popup->set_position(tree->get_global_position() + p_pos);
@@ -2206,7 +2232,7 @@ void FileSystemDock::_tree_empty_selected() {
}
void FileSystemDock::_file_list_rmb_select(int p_item, const Vector2 &p_pos) {
- // Right click is pressed in the file list
+ // Right click is pressed in the file list.
Vector<String> paths;
for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
@@ -2218,7 +2244,7 @@ void FileSystemDock::_file_list_rmb_select(int p_item, const Vector2 &p_pos) {
paths.push_back(files->get_item_metadata(i));
}
- // Popup
+ // Popup.
if (!paths.empty()) {
file_list_popup->clear();
file_list_popup->set_size(Size2(1, 1));
@@ -2229,7 +2255,7 @@ void FileSystemDock::_file_list_rmb_select(int p_item, const Vector2 &p_pos) {
}
void FileSystemDock::_file_list_rmb_pressed(const Vector2 &p_pos) {
- // Right click on empty space for file list
+ // Right click on empty space for file list.
if (searched_string.length() > 0)
return;
@@ -2237,21 +2263,21 @@ void FileSystemDock::_file_list_rmb_pressed(const Vector2 &p_pos) {
file_list_popup->set_size(Size2(1, 1));
file_list_popup->add_item(TTR("New Folder..."), FILE_NEW_FOLDER);
+ file_list_popup->add_item(TTR("New Scene..."), FILE_NEW_SCENE);
file_list_popup->add_item(TTR("New Script..."), FILE_NEW_SCRIPT);
file_list_popup->add_item(TTR("New Resource..."), FILE_NEW_RESOURCE);
- file_list_popup->add_item(TTR("Show in File Manager"), FILE_SHOW_IN_EXPLORER);
+ file_list_popup->add_separator();
+ file_list_popup->add_item(TTR("Open in File Manager"), FILE_SHOW_IN_EXPLORER);
file_list_popup->set_position(files->get_global_position() + p_pos);
file_list_popup->popup();
}
void FileSystemDock::select_file(const String &p_file) {
-
_navigate_to_path(p_file);
}
void FileSystemDock::_file_multi_selected(int p_index, bool p_selected) {
-
- // Set the path to the current focused item
+ // Set the path to the current focused item.
int current = files->get_current();
if (current == p_index) {
String fpath = files->get_item_metadata(current);
@@ -2263,15 +2289,14 @@ void FileSystemDock::_file_multi_selected(int p_index, bool p_selected) {
}
}
- // Update the import dock
+ // Update the import dock.
import_dock_needs_update = true;
call_deferred("_update_import_dock");
}
void FileSystemDock::_tree_gui_input(Ref<InputEvent> p_event) {
-
if (get_viewport()->get_modal_stack_top())
- return; //ignore because of modal window
+ return; // Ignore because of modal window.
Ref<InputEventKey> key = p_event;
if (key.is_valid() && key->is_pressed() && !key->is_echo()) {
@@ -2288,9 +2313,8 @@ void FileSystemDock::_tree_gui_input(Ref<InputEvent> p_event) {
}
void FileSystemDock::_file_list_gui_input(Ref<InputEvent> p_event) {
-
if (get_viewport()->get_modal_stack_top())
- return; //ignore because of modal window
+ return; // Ignore because of modal window.
Ref<InputEventKey> key = p_event;
if (key.is_valid() && key->is_pressed() && !key->is_echo()) {
@@ -2307,18 +2331,17 @@ void FileSystemDock::_file_list_gui_input(Ref<InputEvent> p_event) {
}
void FileSystemDock::_update_import_dock() {
-
if (!import_dock_needs_update)
return;
- // List selected
+ // List selected.
Vector<String> selected;
if (display_mode == DISPLAY_MODE_TREE_ONLY) {
// Use the tree
selected = _tree_get_selected();
} else {
- // Use the file list
+ // Use the file list.
for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
continue;
@@ -2327,7 +2350,7 @@ void FileSystemDock::_update_import_dock() {
}
}
- // Check import
+ // Check import.
Vector<String> imports;
String import_type;
for (int i = 0; i < selected.size(); i++) {
@@ -2354,7 +2377,7 @@ void FileSystemDock::_update_import_dock() {
if (import_type == "") {
import_type = type;
} else if (import_type != type) {
- //all should be the same type
+ // All should be the same type.
imports.clear();
break;
}
@@ -2373,12 +2396,10 @@ void FileSystemDock::_update_import_dock() {
}
void FileSystemDock::_feature_profile_changed() {
-
_update_display_mode(true);
}
void FileSystemDock::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("_file_list_gui_input"), &FileSystemDock::_file_list_gui_input);
ClassDB::bind_method(D_METHOD("_tree_gui_input"), &FileSystemDock::_tree_gui_input);
@@ -2411,6 +2432,7 @@ void FileSystemDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_fs_changed"), &FileSystemDock::_fs_changed);
ClassDB::bind_method(D_METHOD("_tree_multi_selected"), &FileSystemDock::_tree_multi_selected);
ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &FileSystemDock::_make_dir_confirm);
+ ClassDB::bind_method(D_METHOD("_make_scene_confirm"), &FileSystemDock::_make_scene_confirm);
ClassDB::bind_method(D_METHOD("_resource_created"), &FileSystemDock::_resource_created);
ClassDB::bind_method(D_METHOD("_move_operation_confirm", "to_path", "overwrite"), &FileSystemDock::_move_operation_confirm, DEFVAL(false));
ClassDB::bind_method(D_METHOD("_move_with_overwrite"), &FileSystemDock::_move_with_overwrite);
@@ -2442,7 +2464,6 @@ void FileSystemDock::_bind_methods() {
}
FileSystemDock::FileSystemDock(EditorNode *p_editor) {
-
set_name("FileSystem");
editor = p_editor;
path = "res://";
@@ -2523,7 +2544,6 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
tree->set_custom_minimum_size(Size2(0, 15 * EDSCALE));
split_box->add_child(tree);
- tree->connect("item_edited", this, "_favorite_toggled");
tree->connect("item_activated", this, "_tree_activate_file");
tree->connect("multi_selected", this, "_tree_multi_selected");
tree->connect("item_rmb_selected", this, "_tree_rmb_select");
@@ -2626,6 +2646,17 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
make_dir_dialog->register_text_enter(make_dir_dialog_text);
make_dir_dialog->connect("confirmed", this, "_make_dir_confirm");
+ make_scene_dialog = memnew(ConfirmationDialog);
+ make_scene_dialog->set_title(TTR("Create Scene"));
+ VBoxContainer *make_scene_dialog_vb = memnew(VBoxContainer);
+ make_scene_dialog->add_child(make_scene_dialog_vb);
+
+ make_scene_dialog_text = memnew(LineEdit);
+ make_scene_dialog_vb->add_margin_child(TTR("Name:"), make_scene_dialog_text);
+ add_child(make_scene_dialog);
+ make_scene_dialog->register_text_enter(make_scene_dialog_text);
+ make_scene_dialog->connect("confirmed", this, "_make_scene_confirm");
+
make_script_dialog_text = memnew(ScriptCreateDialog);
make_script_dialog_text->set_title(TTR("Create Script"));
add_child(make_script_dialog_text);
diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h
index 6de370ad29..49eb31e330 100644
--- a/editor/filesystem_dock.h
+++ b/editor/filesystem_dock.h
@@ -87,6 +87,7 @@ private:
FILE_INFO,
FILE_NEW_FOLDER,
FILE_NEW_SCRIPT,
+ FILE_NEW_SCENE,
FILE_SHOW_IN_EXPLORER,
FILE_COPY_PATH,
FILE_NEW_RESOURCE,
@@ -135,6 +136,8 @@ private:
LineEdit *duplicate_dialog_text;
ConfirmationDialog *make_dir_dialog;
LineEdit *make_dir_dialog_text;
+ ConfirmationDialog *make_scene_dialog;
+ LineEdit *make_scene_dialog_text;
ConfirmationDialog *overwrite_dialog;
ScriptCreateDialog *make_script_dialog_text;
CreateDialog *new_resource_dialog;
@@ -168,7 +171,7 @@ private:
bool updating_tree;
int tree_update_id;
- Tree *tree; //directories
+ Tree *tree;
ItemList *files;
bool import_dock_needs_update;
@@ -213,6 +216,7 @@ private:
void _resource_created() const;
void _make_dir_confirm();
+ void _make_scene_confirm();
void _rename_operation_confirm();
void _duplicate_operation_confirm();
void _move_with_overwrite();
@@ -246,7 +250,6 @@ private:
String name;
String path;
StringName type;
- int import_status; //0 not imported, 1 - ok, 2- must reimport, 3- broken
Vector<String> sources;
bool import_broken;
@@ -275,6 +278,7 @@ private:
bool _is_file_type_disabled_by_feature_profile(const StringName &p_class);
void _feature_profile_changed();
+ Vector<String> _remove_self_included_paths(Vector<String> selected_strings);
protected:
void _notification(int p_what);
diff --git a/editor/find_in_files.cpp b/editor/find_in_files.cpp
index cc2efb92ae..def22d07de 100644
--- a/editor/find_in_files.cpp
+++ b/editor/find_in_files.cpp
@@ -221,8 +221,8 @@ float FindInFiles::get_progress() const {
void FindInFiles::_scan_dir(String path, PoolStringArray &out_folders) {
- DirAccess *dir = DirAccess::open(path);
- if (dir == NULL) {
+ DirAccessRef dir = DirAccess::open(path);
+ if (!dir) {
print_verbose("Cannot open directory! " + path);
return;
}
@@ -253,8 +253,8 @@ void FindInFiles::_scan_dir(String path, PoolStringArray &out_folders) {
void FindInFiles::_scan_file(String fpath) {
- FileAccess *f = FileAccess::open(fpath, FileAccess::READ);
- if (f == NULL) {
+ FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
+ if (!f) {
print_verbose(String("Cannot open file ") + fpath);
return;
}
diff --git a/editor/icons/icon_editor_curve_handle.svg b/editor/icons/icon_editor_curve_handle.svg
new file mode 100644
index 0000000000..c405ceab9d
--- /dev/null
+++ b/editor/icons/icon_editor_curve_handle.svg
@@ -0,0 +1 @@
+<svg height="10" viewBox="0 0 10 10" width="10" xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="5" fill="#fefefe" r="2.75" stroke="#000" stroke-linecap="square"/></svg> \ No newline at end of file
diff --git a/editor/icons/icon_editor_path_sharp_handle.svg b/editor/icons/icon_editor_path_sharp_handle.svg
new file mode 100644
index 0000000000..db160dfeae
--- /dev/null
+++ b/editor/icons/icon_editor_path_sharp_handle.svg
@@ -0,0 +1 @@
+<svg height="10" viewBox="0 0 10 10" width="10" xmlns="http://www.w3.org/2000/svg"><path d="m-3.035534-10.106602h6.071068v6.071068h-6.071068z" fill="#fefefe" stroke="#000" stroke-linecap="square" transform="matrix(-.70710678 .70710678 -.70710678 -.70710678 0 0)"/></svg> \ No newline at end of file
diff --git a/editor/icons/icon_editor_path_smooth_handle.svg b/editor/icons/icon_editor_path_smooth_handle.svg
new file mode 100644
index 0000000000..34f3d290bd
--- /dev/null
+++ b/editor/icons/icon_editor_path_smooth_handle.svg
@@ -0,0 +1 @@
+<svg height="10" viewBox="0 0 10 10" width="10" xmlns="http://www.w3.org/2000/svg"><path d="m1.5-8.5h7v7h-7z" fill="#fefefe" stroke="#000" stroke-linecap="square" transform="rotate(90)"/></svg> \ No newline at end of file
diff --git a/editor/icons/icon_timeline_indicator.svg b/editor/icons/icon_timeline_indicator.svg
new file mode 100644
index 0000000000..fd18192705
--- /dev/null
+++ b/editor/icons/icon_timeline_indicator.svg
@@ -0,0 +1 @@
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m3 0h10l-4 4h-2z" fill="#fefefe"/></svg> \ No newline at end of file
diff --git a/editor/import/editor_import_collada.cpp b/editor/import/editor_import_collada.cpp
index 1c4a8c43a9..449124acec 100644
--- a/editor/import/editor_import_collada.cpp
+++ b/editor/import/editor_import_collada.cpp
@@ -692,16 +692,6 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<ArrayMesh> &p_me
pre_weights[w_i] = weights;
- /*
- for(Set<int>::Element *E=vertex_map[w_i].front();E;E=E->next()) {
-
- int dst = E->get();
- ERR_EXPLAIN("invalid vertex index in array");
- ERR_FAIL_INDEX_V(dst,vertex_array.size(),ERR_INVALID_DATA);
- vertex_array[dst].weights=weights;
-
- }*/
-
index_ofs += wstride * amount;
}
@@ -711,7 +701,6 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<ArrayMesh> &p_me
Set<Collada::Vertex> vertex_set; //vertex set will be the vertices
List<int> indices_list; //indices will be the indices
- //Map<int,Set<int> > vertex_map; //map vertices (for setting skinning/morph)
/**************************/
/* CREATE PRIMITIVE ARRAY */
@@ -834,9 +823,6 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<ArrayMesh> &p_me
vertex_set.insert(vertex);
}
- /* if (!vertex_map.has(vertex_index))
- vertex_map[vertex_index]=Set<int>();
- vertex_map[vertex_index].insert(index); //should be outside..*/
//build triangles if needed
if (j == 0)
prev2[0] = index;
@@ -1204,10 +1190,7 @@ Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compres
}
}
- if (ngsource != "") {
- ERR_EXPLAIN("Controller Instance Source '" + ngsource + "' is neither skin or morph!");
- ERR_FAIL_V(ERR_INVALID_DATA);
- }
+ ERR_FAIL_COND_V_MSG(ngsource != "", ERR_INVALID_DATA, "Controller instance source '" + ngsource + "' is neither skin or morph!");
} else {
meshid = ng2->source;
@@ -1608,7 +1591,7 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
}
if (xform_idx == -1) {
- WARN_PRINTS("Collada: Couldn't find matching node " + at.target + " xform for track " + at.param);
+ WARN_PRINTS("Collada: Couldn't find matching node " + at.target + " xform for track " + at.param + ".");
continue;
}
@@ -1630,8 +1613,7 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
} else if (data.size() == xf.data.size()) {
xf.data = data;
} else {
- ERR_EXPLAIN("Component " + at.component + " has datasize " + itos(data.size()) + ", xfdatasize " + itos(xf.data.size()));
- ERR_CONTINUE(data.size() != xf.data.size());
+ ERR_CONTINUE_MSG(data.size() != xf.data.size(), "Component " + at.component + " has datasize " + itos(data.size()) + ", xfdatasize " + itos(xf.data.size()) + ".");
}
}
diff --git a/editor/import/editor_scene_importer_gltf.cpp b/editor/import/editor_scene_importer_gltf.cpp
index c9c5b3818f..9ea7c86e0c 100644
--- a/editor/import/editor_scene_importer_gltf.cpp
+++ b/editor/import/editor_scene_importer_gltf.cpp
@@ -29,8 +29,8 @@
/*************************************************************************/
#include "editor_scene_importer_gltf.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/json.h"
-#include "core/math/crypto_core.h"
#include "core/math/math_defs.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
@@ -1544,8 +1544,7 @@ Error EditorSceneImporterGLTF::_parse_cameras(GLTFState &state) {
camera.fov_size = 10;
}
} else {
- ERR_EXPLAIN("Camera should be in 'orthographic' or 'perspective'");
- ERR_FAIL_V(ERR_PARSE_ERROR);
+ ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Camera should be in 'orthographic' or 'perspective'");
}
state.cameras.push_back(camera);
diff --git a/editor/import/resource_importer_csv_translation.cpp b/editor/import/resource_importer_csv_translation.cpp
index cfcdbc8de4..301422a25a 100644
--- a/editor/import/resource_importer_csv_translation.cpp
+++ b/editor/import/resource_importer_csv_translation.cpp
@@ -101,8 +101,7 @@ Error ResourceImporterCSVTranslation::import(const String &p_source_file, const
for (int i = 1; i < line.size(); i++) {
String locale = line[i];
- ERR_EXPLAIN("Error importing CSV translation: '" + locale + "' is not a valid locale");
- ERR_FAIL_COND_V(!TranslationServer::is_locale_valid(locale), ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V_MSG(!TranslationServer::is_locale_valid(locale), ERR_PARSE_ERROR, "Error importing CSV translation: '" + locale + "' is not a valid locale.");
locales.push_back(locale);
Ref<Translation> translation;
diff --git a/editor/import/resource_importer_obj.cpp b/editor/import/resource_importer_obj.cpp
index 868f67fd77..9061c92f6e 100644
--- a/editor/import/resource_importer_obj.cpp
+++ b/editor/import/resource_importer_obj.cpp
@@ -45,8 +45,7 @@ uint32_t EditorOBJImporter::get_import_flags() const {
static Error _parse_material_library(const String &p_path, Map<String, Ref<SpatialMaterial> > &material_map, List<String> *r_missing_deps) {
FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
- ERR_EXPLAIN(vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path));
- ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
+ ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path));
Ref<SpatialMaterial> current;
String current_name;
@@ -207,8 +206,7 @@ static Error _parse_material_library(const String &p_path, Map<String, Ref<Spati
static Error _parse_obj(const String &p_path, List<Ref<Mesh> > &r_meshes, bool p_single_mesh, bool p_generate_tangents, bool p_optimize, Vector3 p_scale_mesh, List<String> *r_missing_deps) {
FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
- ERR_EXPLAIN(vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path));
- ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
+ ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path));
Ref<ArrayMesh> mesh;
mesh.instance();
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index 8e6a56a929..64994e21b0 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -960,7 +960,7 @@ void ResourceImporterScene::_find_meshes(Node *p_node, Map<Ref<ArrayMesh>, Trans
}
}
-void ResourceImporterScene::_make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_keep_animations, bool p_make_materials, bool p_keep_materials, bool p_make_meshes, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes) {
+void ResourceImporterScene::_make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_animations_as_text, bool p_keep_animations, bool p_make_materials, bool p_materials_as_text, bool p_keep_materials, bool p_make_meshes, bool p_meshes_as_text, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes) {
List<PropertyInfo> pi;
@@ -982,7 +982,14 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
anim->track_set_imported(i, true);
}
- String ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".anim");
+ String ext_name;
+
+ if (p_animations_as_text) {
+ ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".tres");
+ } else {
+ ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".anim");
+ }
+
if (FileAccess::exists(ext_name) && p_keep_animations) {
//try to keep custom animation tracks
Ref<Animation> old_anim = ResourceLoader::load(ext_name, "Animation", true);
@@ -1017,7 +1024,14 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
if (!p_materials.has(mat)) {
- String ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
+ String ext_name;
+
+ if (p_materials_as_text) {
+ ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".tres");
+ } else {
+ ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
+ }
+
if (p_keep_materials && FileAccess::exists(ext_name)) {
//if exists, use it
p_materials[mat] = ResourceLoader::load(ext_name);
@@ -1045,7 +1059,13 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
if (!p_meshes.has(mesh)) {
//meshes are always overwritten, keeping them is not practical
- String ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
+ String ext_name;
+
+ if (p_meshes_as_text) {
+ ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".tres");
+ } else {
+ ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
+ }
ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
p_meshes[mesh] = ResourceLoader::load(ext_name);
@@ -1067,9 +1087,14 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
continue;
if (!p_materials.has(mat)) {
+ String ext_name;
+
+ if (p_materials_as_text) {
+ ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".tres");
+ } else {
+ ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
+ }
- String ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
- ;
if (p_keep_materials && FileAccess::exists(ext_name)) {
//if exists, use it
p_materials[mat] = ResourceLoader::load(ext_name);
@@ -1086,7 +1111,15 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
//re-save the mesh since a material is now assigned
if (p_make_meshes) {
- String ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
+
+ String ext_name;
+
+ if (p_meshes_as_text) {
+ ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".tres");
+ } else {
+ ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
+ }
+
ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
p_meshes[mesh] = ResourceLoader::load(ext_name);
}
@@ -1105,7 +1138,7 @@ void ResourceImporterScene::_make_external_resources(Node *p_node, const String
for (int i = 0; i < p_node->get_child_count(); i++) {
- _make_external_resources(p_node->get_child(i), p_base_path, p_make_animations, p_keep_animations, p_make_materials, p_keep_materials, p_make_meshes, p_animations, p_materials, p_meshes);
+ _make_external_resources(p_node->get_child(i), p_base_path, p_make_animations, p_animations_as_text, p_keep_animations, p_make_materials, p_materials_as_text, p_keep_materials, p_make_meshes, p_meshes_as_text, p_animations, p_materials, p_meshes);
}
}
@@ -1134,18 +1167,18 @@ void ResourceImporterScene::get_import_options(List<ImportOption> *r_options, in
r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/custom_script", PROPERTY_HINT_FILE, script_ext_hint), ""));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "nodes/storage", PROPERTY_HINT_ENUM, "Single Scene,Instanced Sub-Scenes"), scenes_out ? 1 : 0));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/location", PROPERTY_HINT_ENUM, "Node,Mesh"), (meshes_out || materials_out) ? 1 : 0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/storage", PROPERTY_HINT_ENUM, "Built-In,Files", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), materials_out ? 1 : 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.material),Files (.tres)", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), materials_out ? 1 : 0));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "materials/keep_on_reimport"), materials_out));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/compress"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/storage", PROPERTY_HINT_ENUM, "Built-In,Files"), meshes_out ? 1 : 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.mesh),Files (.tres)"), meshes_out ? 1 : 0));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/light_baking", PROPERTY_HINT_ENUM, "Disabled,Enable,Gen Lightmaps", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "meshes/lightmap_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.1));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "external_files/store_in_subdir"), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/fps", PROPERTY_HINT_RANGE, "1,120,1"), 15));
r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/filter_script", PROPERTY_HINT_MULTILINE_TEXT), ""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/storage", PROPERTY_HINT_ENUM, "Built-In,Files", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), animations_out));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.anim),Files (.tres)"), animations_out ? true : false));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/keep_custom_tracks"), animations_out));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_linear_error"), 0.05));
@@ -1367,10 +1400,13 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p
_filter_tracks(scene, animation_filter);
}
- bool external_animations = int(p_options["animation/storage"]) == 1;
+ bool external_animations = int(p_options["animation/storage"]) == 1 || int(p_options["animation/storage"]) == 2;
+ bool external_animations_as_text = int(p_options["animation/storage"]) == 2;
bool keep_custom_tracks = p_options["animation/keep_custom_tracks"];
- bool external_materials = p_options["materials/storage"];
- bool external_meshes = p_options["meshes/storage"];
+ bool external_materials = int(p_options["materials/storage"]) == 1 || int(p_options["materials/storage"]) == 2;
+ bool external_materials_as_text = int(p_options["materials/storage"]) == 2;
+ bool external_meshes = int(p_options["meshes/storage"]) == 1 || int(p_options["meshes/storage"]) == 2;
+ bool external_meshes_as_text = int(p_options["meshes/storage"]) == 2;
bool external_scenes = int(p_options["nodes/storage"]) == 1;
String base_path = p_source_file.get_base_dir();
@@ -1425,7 +1461,7 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p
bool keep_materials = bool(p_options["materials/keep_on_reimport"]);
- _make_external_resources(scene, base_path, external_animations, keep_custom_tracks, external_materials, keep_materials, external_meshes, anim_map, mat_map, mesh_map);
+ _make_external_resources(scene, base_path, external_animations, external_animations_as_text, keep_custom_tracks, external_materials, external_materials_as_text, keep_materials, external_meshes, external_meshes_as_text, anim_map, mat_map, mesh_map);
}
progress.step(TTR("Running Custom Script..."), 2);
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index 498e0f6fb8..ef9a77917f 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -144,7 +144,7 @@ public:
void _find_meshes(Node *p_node, Map<Ref<ArrayMesh>, Transform> &meshes);
- void _make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_keep_animations, bool p_make_materials, bool p_keep_materials, bool p_make_meshes, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes);
+ void _make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_animations_as_text, bool p_keep_animations, bool p_make_materials, bool p_materials_as_text, bool p_keep_materials, bool p_make_meshes, bool p_meshes_as_text, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes);
Node *_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, List<Ref<Shape> > > &collision_map, LightBakeMode p_light_bake_mode);
diff --git a/editor/import/resource_importer_wav.cpp b/editor/import/resource_importer_wav.cpp
index d267b29224..4fd4ab2f2e 100644
--- a/editor/import/resource_importer_wav.cpp
+++ b/editor/import/resource_importer_wav.cpp
@@ -123,8 +123,7 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s
file->close();
memdelete(file);
- ERR_EXPLAIN("Not a WAV file (no WAVE RIFF Header)");
- ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Not a WAV file (no WAVE RIFF header).");
}
int format_bits = 0;
@@ -166,16 +165,14 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s
if (compression_code != 1 && compression_code != 3) {
file->close();
memdelete(file);
- ERR_EXPLAIN("Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM instead.");
- ERR_FAIL_V(ERR_INVALID_DATA);
+ ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM instead.");
}
format_channels = file->get_16();
if (format_channels != 1 && format_channels != 2) {
file->close();
memdelete(file);
- ERR_EXPLAIN("Format not supported for WAVE file (not stereo or mono).");
- ERR_FAIL_V(ERR_INVALID_DATA);
+ ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Format not supported for WAVE file (not stereo or mono).");
}
format_freq = file->get_32(); //sampling rate
@@ -187,8 +184,7 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s
if (format_bits % 8 || format_bits == 0) {
file->close();
memdelete(file);
- ERR_EXPLAIN("Invalid amount of bits in the sample (should be one of 8, 16, 24 or 32).");
- ERR_FAIL_V(ERR_INVALID_DATA);
+ ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Invalid amount of bits in the sample (should be one of 8, 16, 24 or 32).");
}
/* Don't need anything else, continue */
@@ -258,8 +254,7 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s
if (file->eof_reached()) {
file->close();
memdelete(file);
- ERR_EXPLAIN("Premature end of file.");
- ERR_FAIL_V(ERR_FILE_CORRUPT);
+ ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Premature end of file.");
}
}
diff --git a/editor/node_dock.cpp b/editor/node_dock.cpp
index 1c0151ed0a..d6df3bd369 100644
--- a/editor/node_dock.cpp
+++ b/editor/node_dock.cpp
@@ -56,10 +56,7 @@ void NodeDock::_bind_methods() {
void NodeDock::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- connections_button->set_icon(get_icon("Signals", "EditorIcons"));
- groups_button->set_icon(get_icon("Groups", "EditorIcons"));
- } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
+ if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
connections_button->set_icon(get_icon("Signals", "EditorIcons"));
groups_button->set_icon(get_icon("Groups", "EditorIcons"));
}
@@ -131,7 +128,7 @@ NodeDock::NodeDock() {
groups->hide();
select_a_node = memnew(Label);
- select_a_node->set_text(TTR("Select a Node to edit Signals and Groups."));
+ select_a_node->set_text(TTR("Select a single node to edit its signals and groups."));
select_a_node->set_v_size_flags(SIZE_EXPAND_FILL);
select_a_node->set_valign(Label::VALIGN_CENTER);
select_a_node->set_align(Label::ALIGN_CENTER);
diff --git a/editor/plugins/abstract_polygon_2d_editor.cpp b/editor/plugins/abstract_polygon_2d_editor.cpp
index 574b47d770..7f023af848 100644
--- a/editor/plugins/abstract_polygon_2d_editor.cpp
+++ b/editor/plugins/abstract_polygon_2d_editor.cpp
@@ -571,7 +571,8 @@ void AbstractPolygon2DEditor::forward_canvas_draw_over_viewport(Control *p_overl
return;
Transform2D xform = canvas_item_editor->get_canvas_transform() * _get_node()->get_global_transform();
- const Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
+ // All polygon points are sharp, so use the sharp handle icon
+ const Ref<Texture> handle = get_icon("EditorPathSharpHandle", "EditorIcons");
const Vertex active_point = get_active_point();
const int n_polygons = _get_polygon_count();
diff --git a/editor/plugins/asset_library_editor_plugin.cpp b/editor/plugins/asset_library_editor_plugin.cpp
index 132bf3973e..fecab89d23 100644
--- a/editor/plugins/asset_library_editor_plugin.cpp
+++ b/editor/plugins/asset_library_editor_plugin.cpp
@@ -101,7 +101,7 @@ EditorAssetLibraryItem::EditorAssetLibraryItem() {
add_style_override("panel", border);
HBoxContainer *hb = memnew(HBoxContainer);
- // Add some spacing to visually separate the icon from the asset details
+ // Add some spacing to visually separate the icon from the asset details.
hb->add_constant_override("separation", 15 * EDSCALE);
add_child(hb);
@@ -118,25 +118,21 @@ EditorAssetLibraryItem::EditorAssetLibraryItem() {
vb->set_h_size_flags(SIZE_EXPAND_FILL);
title = memnew(LinkButton);
- title->set_text("My Awesome Addon");
title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed", this, "_asset_clicked");
vb->add_child(title);
category = memnew(LinkButton);
- category->set_text("Editor Tools");
category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
category->connect("pressed", this, "_category_clicked");
vb->add_child(category);
author = memnew(LinkButton);
- author->set_text("Johny Tolengo");
author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
author->connect("pressed", this, "_author_clicked");
vb->add_child(author);
price = memnew(Label);
- price->set_text(TTR("Free"));
vb->add_child(price);
set_custom_minimum_size(Size2(250, 100) * EDSCALE);
@@ -278,12 +274,8 @@ void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video, cons
EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() {
- VBoxContainer *vbox = memnew(VBoxContainer);
- add_child(vbox);
-
HBoxContainer *hbox = memnew(HBoxContainer);
- vbox->add_child(hbox);
- vbox->add_constant_override("separation", 15 * EDSCALE);
+ add_child(hbox);
VBoxContainer *desc_vbox = memnew(VBoxContainer);
hbox->add_child(desc_vbox);
hbox->add_constant_override("separation", 15 * EDSCALE);
@@ -298,17 +290,20 @@ EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() {
desc_bg->set_v_size_flags(SIZE_EXPAND_FILL);
description = memnew(RichTextLabel);
+ desc_bg->add_child(description);
description->connect("meta_clicked", this, "_link_click");
description->set_custom_minimum_size(Size2(440 * EDSCALE, 300 * EDSCALE));
- desc_bg->add_child(description);
VBoxContainer *previews_vbox = memnew(VBoxContainer);
hbox->add_child(previews_vbox);
previews_vbox->add_constant_override("separation", 15 * EDSCALE);
+ previews_vbox->set_v_size_flags(SIZE_EXPAND_FILL);
preview = memnew(TextureRect);
- preview->set_custom_minimum_size(Size2(640 * EDSCALE, 345 * EDSCALE));
previews_vbox->add_child(preview);
+ preview->set_expand(true);
+ preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
+ preview->set_custom_minimum_size(Size2(640 * EDSCALE, 345 * EDSCALE));
previews_bg = memnew(PanelContainer);
previews_vbox->add_child(previews_bg);
@@ -392,7 +387,7 @@ void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int
install->set_disabled(false);
status->set_text(TTR("Success!"));
- // Make the progress bar invisible but don't reflow other Controls around it
+ // Make the progress bar invisible but don't reflow other Controls around it.
progress->set_modulate(Color(0, 0, 0, 0));
set_process(false);
@@ -404,7 +399,7 @@ void EditorAssetLibraryItemDownload::configure(const String &p_title, int p_asse
icon->set_texture(p_preview);
asset_id = p_asset_id;
if (!p_preview.is_valid())
- icon->set_texture(get_icon("DefaultProjectIcon", "EditorIcons"));
+ icon->set_texture(get_icon("FileBrokenBigThumb", "EditorIcons"));
host = p_download_url;
sha256 = p_sha256_hash;
_make_request();
@@ -600,33 +595,15 @@ void EditorAssetLibrary::_notification(int p_what) {
case NOTIFICATION_PROCESS: {
HTTPClient::Status s = request->get_http_client_status();
- bool visible = s != HTTPClient::STATUS_DISCONNECTED;
-
- if (visible != load_status->is_visible()) {
- load_status->set_visible(visible);
- }
-
- if (visible) {
- switch (s) {
+ const bool loading = s != HTTPClient::STATUS_DISCONNECTED;
- case HTTPClient::STATUS_RESOLVING: {
- load_status->set_value(0.1);
- } break;
- case HTTPClient::STATUS_CONNECTING: {
- load_status->set_value(0.2);
- } break;
- case HTTPClient::STATUS_REQUESTING: {
- load_status->set_value(0.3);
- } break;
- case HTTPClient::STATUS_BODY: {
- load_status->set_value(0.4);
- } break;
- default: {
- }
- }
+ if (loading) {
+ library_scroll->set_modulate(Color(1, 1, 1, 0.5));
+ } else {
+ library_scroll->set_modulate(Color(1, 1, 1, 1));
}
- bool no_downloads = downloads_hb->get_child_count() == 0;
+ const bool no_downloads = downloads_hb->get_child_count() == 0;
if (no_downloads == downloads_scroll->is_visible()) {
downloads_scroll->set_visible(!no_downloads);
}
@@ -679,7 +656,7 @@ const char *EditorAssetLibrary::sort_key[SORT_MAX] = {
const char *EditorAssetLibrary::sort_text[SORT_MAX] = {
"Downloads",
"Name",
- "License", // "cost" stores the SPDX license name in the Godot Asset Library
+ "License", // "cost" stores the SPDX license name in the Godot Asset Library.
"Updated"
};
@@ -691,7 +668,7 @@ const char *EditorAssetLibrary::support_key[SUPPORT_MAX] = {
void EditorAssetLibrary::_select_author(int p_id) {
- // Open author window
+ // Open author window.
}
void EditorAssetLibrary::_select_category(int p_id) {
@@ -788,7 +765,7 @@ void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PoolByt
}
if (!image_set && final) {
- obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("DefaultProjectIcon", "EditorIcons"));
+ obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("FileBrokenBigThumb", "EditorIcons"));
}
}
}
@@ -833,7 +810,7 @@ void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, cons
WARN_PRINTS("Error getting image file from URL: " + image_queue[p_queue_id].image_url);
Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
if (obj) {
- obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("DefaultProjectIcon", "EditorIcons"));
+ obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("FileBrokenBigThumb", "EditorIcons"));
}
}
@@ -845,7 +822,7 @@ void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, cons
void EditorAssetLibrary::_update_image_queue() {
- int max_images = 2;
+ const int max_images = 6;
int current_images = 0;
List<int> to_delete;
@@ -1157,6 +1134,10 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const
_search();
} break;
case REQUESTING_SEARCH: {
+
+ // The loading text only needs to be displayed before the first page is loaded
+ library_loading->hide();
+
if (asset_items) {
memdelete(asset_items);
}
@@ -1359,7 +1340,6 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
library_main->add_child(search_hb);
library_main->add_constant_override("separation", 10 * EDSCALE);
- search_hb->add_child(memnew(Label(TTR("Search:") + " ")));
filter = memnew(LineEdit);
search_hb->add_child(filter);
filter->set_h_size_flags(SIZE_EXPAND_FILL);
@@ -1372,12 +1352,12 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
search_hb->add_child(memnew(VSeparator));
Button *open_asset = memnew(Button);
- open_asset->set_text(TTR("Import"));
+ open_asset->set_text(TTR("Import..."));
search_hb->add_child(open_asset);
open_asset->connect("pressed", this, "_asset_open");
Button *plugins = memnew(Button);
- plugins->set_text(TTR("Plugins"));
+ plugins->set_text(TTR("Plugins..."));
search_hb->add_child(plugins);
plugins->connect("pressed", this, "_manage_plugins");
@@ -1434,7 +1414,7 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
support = memnew(MenuButton);
search_hb2->add_child(support);
- support->set_text(TTR("Support..."));
+ support->set_text(TTR("Support"));
support->get_popup()->add_check_item(TTR("Official"), SUPPORT_OFFICIAL);
support->get_popup()->add_check_item(TTR("Community"), SUPPORT_COMMUNITY);
support->get_popup()->add_check_item(TTR("Testing"), SUPPORT_TESTING);
@@ -1472,6 +1452,10 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
library_vb_border->add_child(library_vb);
+ library_loading = memnew(Label(TTR("Loading...")));
+ library_loading->set_align(Label::ALIGN_CENTER);
+ library_vb->add_child(library_loading);
+
asset_top_page = memnew(HBoxContainer);
library_vb->add_child(asset_top_page);
@@ -1494,12 +1478,6 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
library_vb->add_constant_override("separation", 20 * EDSCALE);
- load_status = memnew(ProgressBar);
- load_status->set_min(0);
- load_status->set_max(1);
- load_status->set_step(0.001);
- library_main->add_child(load_status);
-
error_hb = memnew(HBoxContainer);
library_main->add_child(error_hb);
error_label = memnew(Label);
diff --git a/editor/plugins/asset_library_editor_plugin.h b/editor/plugins/asset_library_editor_plugin.h
index 81288ae831..d81606c284 100644
--- a/editor/plugins/asset_library_editor_plugin.h
+++ b/editor/plugins/asset_library_editor_plugin.h
@@ -186,13 +186,13 @@ class EditorAssetLibrary : public PanelContainer {
PanelContainer *library_scroll_bg;
ScrollContainer *library_scroll;
VBoxContainer *library_vb;
+ Label *library_loading;
LineEdit *filter;
OptionButton *categories;
OptionButton *repository;
OptionButton *sort;
ToolButton *reverse;
Button *search;
- ProgressBar *load_status;
HBoxContainer *error_hb;
TextureRect *error_tr;
Label *error_label;
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 98c2f21e45..2daee70474 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -174,15 +174,6 @@ public:
}
};
-void CanvasItemEditor::_snap_if_closer_float(float p_value, float p_target_snap, float &r_current_snap, bool &r_snapped, float p_radius) {
- float radius = p_radius / zoom;
- float dist = Math::abs(p_value - p_target_snap);
- if ((p_radius < 0 || dist < radius) && (!r_snapped || dist < Math::abs(r_current_snap - p_value))) {
- r_current_snap = p_target_snap;
- r_snapped = true;
- }
-}
-
bool CanvasItemEditor::_is_node_locked(const Node *p_node) {
return p_node->has_meta("_edit_lock_") && p_node->get_meta("_edit_lock_");
}
@@ -200,108 +191,174 @@ bool CanvasItemEditor::_is_node_movable(const Node *p_node, bool p_popup_warning
return true;
}
-void CanvasItemEditor::_snap_if_closer_point(Point2 p_value, Point2 p_target_snap, Point2 &r_current_snap, bool (&r_snapped)[2], real_t rotation, float p_radius) {
+void CanvasItemEditor::_snap_if_closer_float(
+ float p_value,
+ float &r_current_snap, SnapTarget &r_current_snap_target,
+ float p_target_value, SnapTarget p_snap_target,
+ float p_radius) {
+
+ float radius = p_radius / zoom;
+ float dist = Math::abs(p_value - p_target_value);
+ if ((p_radius < 0 || dist < radius) && (r_current_snap_target == SNAP_TARGET_NONE || dist < Math::abs(r_current_snap - p_value))) {
+ r_current_snap = p_target_value;
+ r_current_snap_target = p_snap_target;
+ }
+}
+
+void CanvasItemEditor::_snap_if_closer_point(
+ Point2 p_value,
+ Point2 &r_current_snap, SnapTarget (&r_current_snap_target)[2],
+ Point2 p_target_value, SnapTarget p_snap_target,
+ real_t rotation,
+ float p_radius) {
+
Transform2D rot_trans = Transform2D(rotation, Point2());
p_value = rot_trans.inverse().xform(p_value);
- p_target_snap = rot_trans.inverse().xform(p_target_snap);
+ p_target_value = rot_trans.inverse().xform(p_target_value);
r_current_snap = rot_trans.inverse().xform(r_current_snap);
- _snap_if_closer_float(p_value.x, p_target_snap.x, r_current_snap.x, r_snapped[0], p_radius);
- _snap_if_closer_float(p_value.y, p_target_snap.y, r_current_snap.y, r_snapped[1], p_radius);
+ _snap_if_closer_float(
+ p_value.x,
+ r_current_snap.x,
+ r_current_snap_target[0],
+ p_target_value.x,
+ p_snap_target,
+ p_radius);
+
+ _snap_if_closer_float(
+ p_value.y,
+ r_current_snap.y,
+ r_current_snap_target[1],
+ p_target_value.y,
+ p_snap_target,
+ p_radius);
r_current_snap = rot_trans.xform(r_current_snap);
}
-void CanvasItemEditor::_snap_other_nodes(Point2 p_value, Point2 &r_current_snap, bool (&r_snapped)[2], const Node *p_current, const CanvasItem *p_to_snap) {
+void CanvasItemEditor::_snap_other_nodes(
+ const Point2 p_value,
+ const Transform2D p_transform_to_snap,
+ Point2 &r_current_snap, SnapTarget (&r_current_snap_target)[2],
+ const SnapTarget p_snap_target, List<const CanvasItem *> p_exceptions,
+ const Node *p_current) {
const CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_current);
- if (canvas_item && (!p_to_snap || p_current != p_to_snap)) {
+
+ // Check if the element is in the exception
+ bool exception = false;
+ for (List<const CanvasItem *>::Element *E = p_exceptions.front(); E; E = E->next()) {
+ if (E->get() == p_current) {
+ exception = true;
+ break;
+ }
+ };
+
+ if (canvas_item && !exception) {
Transform2D ci_transform = canvas_item->get_global_transform_with_canvas();
- Transform2D to_snap_transform = p_to_snap ? p_to_snap->get_global_transform_with_canvas() : Transform2D();
- if (fmod(ci_transform.get_rotation() - to_snap_transform.get_rotation(), (real_t)360.0) == 0.0) {
+ if (fmod(ci_transform.get_rotation() - p_transform_to_snap.get_rotation(), (real_t)360.0) == 0.0) {
if (canvas_item->_edit_use_rect()) {
Point2 begin = ci_transform.xform(canvas_item->_edit_get_rect().get_position());
Point2 end = ci_transform.xform(canvas_item->_edit_get_rect().get_position() + canvas_item->_edit_get_rect().get_size());
- _snap_if_closer_point(p_value, begin, r_current_snap, r_snapped, ci_transform.get_rotation());
- _snap_if_closer_point(p_value, end, r_current_snap, r_snapped, ci_transform.get_rotation());
+
+ _snap_if_closer_point(p_value, r_current_snap, r_current_snap_target, begin, p_snap_target, ci_transform.get_rotation());
+ _snap_if_closer_point(p_value, r_current_snap, r_current_snap_target, end, p_snap_target, ci_transform.get_rotation());
} else {
Point2 position = ci_transform.xform(Point2());
- _snap_if_closer_point(p_value, position, r_current_snap, r_snapped, ci_transform.get_rotation());
+ _snap_if_closer_point(p_value, r_current_snap, r_current_snap_target, position, p_snap_target, ci_transform.get_rotation());
}
}
}
for (int i = 0; i < p_current->get_child_count(); i++) {
- _snap_other_nodes(p_value, r_current_snap, r_snapped, p_current->get_child(i), p_to_snap);
+ _snap_other_nodes(p_value, p_transform_to_snap, r_current_snap, r_current_snap_target, p_snap_target, p_exceptions, p_current->get_child(i));
}
}
-Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, const CanvasItem *p_canvas_item, unsigned int p_forced_modes) {
- bool snapped[2] = { false, false };
+Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, unsigned int p_forced_modes, const CanvasItem *p_self_canvas_item, List<CanvasItem *> p_other_nodes_exceptions) {
+
+ snap_target[0] = SNAP_TARGET_NONE;
+ snap_target[1] = SNAP_TARGET_NONE;
+
bool is_snap_active = snap_active ^ Input::get_singleton()->is_key_pressed(KEY_CONTROL);
// Smart snap using the canvas position
Vector2 output = p_target;
real_t rotation = 0.0;
- if (p_canvas_item) {
- rotation = p_canvas_item->get_global_transform_with_canvas().get_rotation();
+ if (p_self_canvas_item) {
+ rotation = p_self_canvas_item->get_global_transform_with_canvas().get_rotation();
// Parent sides and center
if ((is_snap_active && snap_node_parent && (p_modes & SNAP_NODE_PARENT)) || (p_forced_modes & SNAP_NODE_PARENT)) {
- if (const Control *c = Object::cast_to<Control>(p_canvas_item)) {
- Point2 begin = p_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(0, 0)));
- Point2 end = p_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(1, 1)));
- _snap_if_closer_point(p_target, begin, output, snapped, rotation);
- _snap_if_closer_point(p_target, (begin + end) / 2.0, output, snapped, rotation);
- _snap_if_closer_point(p_target, end, output, snapped, rotation);
- } else if (const CanvasItem *parent_ci = Object::cast_to<CanvasItem>(p_canvas_item->get_parent())) {
+ if (const Control *c = Object::cast_to<Control>(p_self_canvas_item)) {
+ Point2 begin = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(0, 0)));
+ Point2 end = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(1, 1)));
+ _snap_if_closer_point(p_target, output, snap_target, begin, SNAP_TARGET_PARENT, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, (begin + end) / 2.0, SNAP_TARGET_PARENT, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, end, SNAP_TARGET_PARENT, rotation);
+ } else if (const CanvasItem *parent_ci = Object::cast_to<CanvasItem>(p_self_canvas_item->get_parent())) {
if (parent_ci->_edit_use_rect()) {
- Point2 begin = p_canvas_item->get_transform().affine_inverse().xform(parent_ci->_edit_get_rect().get_position());
- Point2 end = p_canvas_item->get_transform().affine_inverse().xform(parent_ci->_edit_get_rect().get_position() + parent_ci->_edit_get_rect().get_size());
- _snap_if_closer_point(p_target, begin, output, snapped, rotation);
- _snap_if_closer_point(p_target, (begin + end) / 2.0, output, snapped, rotation);
- _snap_if_closer_point(p_target, end, output, snapped, rotation);
+ Point2 begin = p_self_canvas_item->get_transform().affine_inverse().xform(parent_ci->_edit_get_rect().get_position());
+ Point2 end = p_self_canvas_item->get_transform().affine_inverse().xform(parent_ci->_edit_get_rect().get_position() + parent_ci->_edit_get_rect().get_size());
+ _snap_if_closer_point(p_target, output, snap_target, begin, SNAP_TARGET_PARENT, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, (begin + end) / 2.0, SNAP_TARGET_PARENT, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, end, SNAP_TARGET_PARENT, rotation);
} else {
- Point2 position = p_canvas_item->get_transform().affine_inverse().xform(Point2());
- _snap_if_closer_point(p_target, position, output, snapped, rotation);
+ Point2 position = p_self_canvas_item->get_transform().affine_inverse().xform(Point2());
+ _snap_if_closer_point(p_target, output, snap_target, position, SNAP_TARGET_PARENT, rotation);
}
}
}
// Self anchors
if ((is_snap_active && snap_node_anchors && (p_modes & SNAP_NODE_ANCHORS)) || (p_forced_modes & SNAP_NODE_ANCHORS)) {
- if (const Control *c = Object::cast_to<Control>(p_canvas_item)) {
- Point2 begin = p_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_LEFT), c->get_anchor(MARGIN_TOP))));
- Point2 end = p_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_RIGHT), c->get_anchor(MARGIN_BOTTOM))));
- _snap_if_closer_point(p_target, begin, output, snapped, rotation);
- _snap_if_closer_point(p_target, end, output, snapped, rotation);
+ if (const Control *c = Object::cast_to<Control>(p_self_canvas_item)) {
+ Point2 begin = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_LEFT), c->get_anchor(MARGIN_TOP))));
+ Point2 end = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_RIGHT), c->get_anchor(MARGIN_BOTTOM))));
+ _snap_if_closer_point(p_target, output, snap_target, begin, SNAP_TARGET_SELF_ANCHORS, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, end, SNAP_TARGET_SELF_ANCHORS, rotation);
}
}
// Self sides
if ((is_snap_active && snap_node_sides && (p_modes & SNAP_NODE_SIDES)) || (p_forced_modes & SNAP_NODE_SIDES)) {
- if (p_canvas_item->_edit_use_rect()) {
- Point2 begin = p_canvas_item->get_global_transform_with_canvas().xform(p_canvas_item->_edit_get_rect().get_position());
- Point2 end = p_canvas_item->get_global_transform_with_canvas().xform(p_canvas_item->_edit_get_rect().get_position() + p_canvas_item->_edit_get_rect().get_size());
- _snap_if_closer_point(p_target, begin, output, snapped, rotation);
- _snap_if_closer_point(p_target, end, output, snapped, rotation);
+ if (p_self_canvas_item->_edit_use_rect()) {
+ Point2 begin = p_self_canvas_item->get_global_transform_with_canvas().xform(p_self_canvas_item->_edit_get_rect().get_position());
+ Point2 end = p_self_canvas_item->get_global_transform_with_canvas().xform(p_self_canvas_item->_edit_get_rect().get_position() + p_self_canvas_item->_edit_get_rect().get_size());
+ _snap_if_closer_point(p_target, output, snap_target, begin, SNAP_TARGET_SELF, rotation);
+ _snap_if_closer_point(p_target, output, snap_target, end, SNAP_TARGET_SELF, rotation);
}
}
// Self center
if ((is_snap_active && snap_node_center && (p_modes & SNAP_NODE_CENTER)) || (p_forced_modes & SNAP_NODE_CENTER)) {
- if (p_canvas_item->_edit_use_rect()) {
- Point2 center = p_canvas_item->get_global_transform_with_canvas().xform(p_canvas_item->_edit_get_rect().get_position() + p_canvas_item->_edit_get_rect().get_size() / 2.0);
- _snap_if_closer_point(p_target, center, output, snapped, rotation);
+ if (p_self_canvas_item->_edit_use_rect()) {
+ Point2 center = p_self_canvas_item->get_global_transform_with_canvas().xform(p_self_canvas_item->_edit_get_rect().get_position() + p_self_canvas_item->_edit_get_rect().get_size() / 2.0);
+ _snap_if_closer_point(p_target, output, snap_target, center, SNAP_TARGET_SELF, rotation);
} else {
- Point2 position = p_canvas_item->get_global_transform_with_canvas().xform(Point2());
- _snap_if_closer_point(p_target, position, output, snapped, rotation);
+ Point2 position = p_self_canvas_item->get_global_transform_with_canvas().xform(Point2());
+ _snap_if_closer_point(p_target, output, snap_target, position, SNAP_TARGET_SELF, rotation);
}
}
}
// Other nodes sides
if ((is_snap_active && snap_other_nodes && (p_modes & SNAP_OTHER_NODES)) || (p_forced_modes & SNAP_OTHER_NODES)) {
- _snap_other_nodes(p_target, output, snapped, get_tree()->get_edited_scene_root(), p_canvas_item);
+ Transform2D to_snap_transform = Transform2D();
+ List<const CanvasItem *> exceptions = List<const CanvasItem *>();
+ for (List<CanvasItem *>::Element *E = p_other_nodes_exceptions.front(); E; E = E->next()) {
+ exceptions.push_back(E->get());
+ }
+ if (p_self_canvas_item) {
+ exceptions.push_back(p_self_canvas_item);
+ to_snap_transform = p_self_canvas_item->get_global_transform_with_canvas();
+ }
+
+ _snap_other_nodes(
+ p_target, to_snap_transform,
+ output, snap_target,
+ SNAP_TARGET_OTHER_NODE,
+ exceptions,
+ get_tree()->get_edited_scene_root());
}
if (((is_snap_active && snap_guides && (p_modes & SNAP_GUIDES)) || (p_forced_modes & SNAP_GUIDES)) && fmod(rotation, (real_t)360.0) == 0.0) {
@@ -309,14 +366,14 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, const
if (EditorNode::get_singleton()->get_edited_scene() && EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_vertical_guides_")) {
Array vguides = EditorNode::get_singleton()->get_edited_scene()->get_meta("_edit_vertical_guides_");
for (int i = 0; i < vguides.size(); i++) {
- _snap_if_closer_float(p_target.x, vguides[i], output.x, snapped[0]);
+ _snap_if_closer_float(p_target.x, output.x, snap_target[0], vguides[i], SNAP_TARGET_GUIDE);
}
}
if (EditorNode::get_singleton()->get_edited_scene() && EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_horizontal_guides_")) {
Array hguides = EditorNode::get_singleton()->get_edited_scene()->get_meta("_edit_horizontal_guides_");
for (int i = 0; i < hguides.size(); i++) {
- _snap_if_closer_float(p_target.y, hguides[i], output.y, snapped[1]);
+ _snap_if_closer_float(p_target.y, output.y, snap_target[1], hguides[i], SNAP_TARGET_GUIDE);
}
}
}
@@ -335,7 +392,7 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, const
Point2 grid_output;
grid_output.x = Math::stepify(p_target.x - offset.x, grid_step.x * Math::pow(2.0, grid_step_multiplier)) + offset.x;
grid_output.y = Math::stepify(p_target.y - offset.y, grid_step.y * Math::pow(2.0, grid_step_multiplier)) + offset.y;
- _snap_if_closer_point(p_target, grid_output, output, snapped, 0.0, -1.0);
+ _snap_if_closer_point(p_target, output, snap_target, grid_output, SNAP_TARGET_GRID, 0.0, -1.0);
}
if (((snap_pixel && (p_modes & SNAP_PIXEL)) || (p_forced_modes & SNAP_PIXEL)) && rotation == 0.0) {
@@ -343,6 +400,8 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, const
output = output.snapped(Size2(1, 1));
}
+ snap_transform = Transform2D(rotation, output);
+
return output;
}
@@ -1205,10 +1264,11 @@ bool CanvasItemEditor::_gui_input_pivot(const Ref<InputEvent> &p_event) {
if (drag_selection.size() > 0) {
drag_from = transform.affine_inverse().xform((b.is_valid()) ? b->get_position() : viewport->get_local_mouse_position());
Vector2 new_pos;
- if (drag_selection.size() == 1)
- new_pos = snap_point(drag_from, SNAP_NODE_SIDES | SNAP_NODE_CENTER | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, drag_selection[0]);
- else
- new_pos = snap_point(drag_from, SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL);
+ if (drag_selection.size() == 1) {
+ new_pos = snap_point(drag_from, SNAP_NODE_SIDES | SNAP_NODE_CENTER | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, 0, drag_selection[0]);
+ } else {
+ new_pos = snap_point(drag_from, SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, 0, NULL, drag_selection);
+ }
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get();
canvas_item->_edit_set_pivot(canvas_item->get_global_transform_with_canvas().affine_inverse().xform(new_pos));
@@ -1228,7 +1288,7 @@ bool CanvasItemEditor::_gui_input_pivot(const Ref<InputEvent> &p_event) {
_restore_canvas_item_state(drag_selection);
Vector2 new_pos;
if (drag_selection.size() == 1)
- new_pos = snap_point(drag_to, SNAP_NODE_SIDES | SNAP_NODE_CENTER | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, drag_selection[0]);
+ new_pos = snap_point(drag_to, SNAP_NODE_SIDES | SNAP_NODE_CENTER | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, 0, drag_selection[0]);
else
new_pos = snap_point(drag_to, SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL);
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
@@ -1478,7 +1538,7 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) {
previous_anchor.y = (drag_type == DRAG_ANCHOR_TOP_LEFT || drag_type == DRAG_ANCHOR_TOP_RIGHT) ? control->get_anchor(MARGIN_TOP) : control->get_anchor(MARGIN_BOTTOM);
previous_anchor = xform.affine_inverse().xform(_anchor_to_position(control, previous_anchor));
- Vector2 new_anchor = xform.xform(snap_point(previous_anchor + (drag_to - drag_from), SNAP_GRID | SNAP_OTHER_NODES, control, SNAP_NODE_PARENT | SNAP_NODE_SIDES | SNAP_NODE_CENTER));
+ Vector2 new_anchor = xform.xform(snap_point(previous_anchor + (drag_to - drag_from), SNAP_GRID | SNAP_OTHER_NODES, SNAP_NODE_PARENT | SNAP_NODE_SIDES | SNAP_NODE_CENTER, control));
new_anchor = _position_to_anchor(control, new_anchor).snapped(Vector2(0.001, 0.001));
bool use_single_axis = m->get_shift();
@@ -1624,8 +1684,8 @@ bool CanvasItemEditor::_gui_input_resize(const Ref<InputEvent> &p_event) {
Transform2D xform = canvas_item->get_global_transform_with_canvas().affine_inverse();
- Point2 drag_to_snapped_begin = snap_point(xform.affine_inverse().xform(current_begin) + (drag_to - drag_from), SNAP_NODE_ANCHORS | SNAP_NODE_PARENT | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, canvas_item);
- Point2 drag_to_snapped_end = snap_point(xform.affine_inverse().xform(current_end) + (drag_to - drag_from), SNAP_NODE_ANCHORS | SNAP_NODE_PARENT | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, canvas_item);
+ Point2 drag_to_snapped_begin = snap_point(xform.affine_inverse().xform(current_begin) + (drag_to - drag_from), SNAP_NODE_ANCHORS | SNAP_NODE_PARENT | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, 0, canvas_item);
+ Point2 drag_to_snapped_end = snap_point(xform.affine_inverse().xform(current_end) + (drag_to - drag_from), SNAP_NODE_ANCHORS | SNAP_NODE_PARENT | SNAP_OTHER_NODES | SNAP_GRID | SNAP_PIXEL, 0, canvas_item);
Point2 drag_begin = xform.xform(drag_to_snapped_begin);
Point2 drag_end = xform.xform(drag_to_snapped_end);
@@ -1866,7 +1926,7 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
} else {
previous_pos = _get_encompassing_rect_from_list(drag_selection).position;
}
- Point2 new_pos = snap_point(previous_pos + (drag_to - drag_from), SNAP_GRID | SNAP_GUIDES | SNAP_PIXEL | SNAP_NODE_PARENT | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES);
+ Point2 new_pos = snap_point(previous_pos + (drag_to - drag_from), SNAP_GRID | SNAP_GUIDES | SNAP_PIXEL | SNAP_NODE_PARENT | SNAP_NODE_ANCHORS | SNAP_OTHER_NODES, 0, NULL, drag_selection);
bool single_axis = m->get_shift();
if (single_axis) {
if (ABS(new_pos.x - previous_pos.x) > ABS(new_pos.y - previous_pos.y)) {
@@ -2421,6 +2481,20 @@ void CanvasItemEditor::_draw_guides() {
}
}
+void CanvasItemEditor::_draw_smart_snapping() {
+ Color line_color = EditorSettings::get_singleton()->get("editors/2d/smart_snapping_line_color");
+ if (snap_target[0] != SNAP_TARGET_NONE && snap_target[0] != SNAP_TARGET_GRID) {
+ viewport->draw_set_transform_matrix(viewport->get_transform() * transform * snap_transform);
+ viewport->draw_line(Point2(0, -1.0e+10F), Point2(0, 1.0e+10F), line_color);
+ viewport->draw_set_transform_matrix(viewport->get_transform());
+ }
+ if (snap_target[1] != SNAP_TARGET_NONE && snap_target[1] != SNAP_TARGET_GRID) {
+ viewport->draw_set_transform_matrix(viewport->get_transform() * transform * snap_transform);
+ viewport->draw_line(Point2(-1.0e+10F, 0), Point2(1.0e+10F, 0), line_color);
+ viewport->draw_set_transform_matrix(viewport->get_transform());
+ }
+}
+
void CanvasItemEditor::_draw_rulers() {
Color bg_color = get_color("dark_color_2", "Editor");
Color graduation_color = get_color("font_color", "Editor").linear_interpolate(bg_color, 0.5);
@@ -2505,6 +2579,8 @@ void CanvasItemEditor::_draw_rulers() {
}
}
}
+
+ // Draw the top left corner
viewport->draw_rect(Rect2(Point2(), Size2(RULER_WIDTH, RULER_WIDTH)), graduation_color);
}
@@ -2623,7 +2699,7 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) {
if (dragged_anchor >= 0) {
// Draw the 4 lines when dragged
- bool snapped;
+ bool anchor_snapped;
Color color_snapped = Color(0.64, 0.93, 0.67, 0.5);
Vector2 corners_pos[4];
@@ -2637,14 +2713,8 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) {
float anchor_val = (i >= 2) ? ANCHOR_END - anchors_values[i] : anchors_values[i];
line_starts[i] = Vector2::linear_interpolate(corners_pos[i], corners_pos[(i + 1) % 4], anchor_val);
line_ends[i] = Vector2::linear_interpolate(corners_pos[(i + 3) % 4], corners_pos[(i + 2) % 4], anchor_val);
- snapped = anchors_values[i] == 0.0 || anchors_values[i] == 0.5 || anchors_values[i] == 1.0;
- int line_width;
- if (i == dragged_anchor || (i + 3) % 4 == dragged_anchor) {
- line_width = 2;
- } else {
- line_width = 1;
- }
- viewport->draw_line(line_starts[i], line_ends[i], snapped ? color_snapped : color_base, Math::round(line_width * EDSCALE));
+ anchor_snapped = anchors_values[i] == 0.0 || anchors_values[i] == 0.5 || anchors_values[i] == 1.0;
+ viewport->draw_line(line_starts[i], line_ends[i], anchor_snapped ? color_snapped : color_base, (i == dragged_anchor || (i + 3) % 4 == dragged_anchor) ? 2 : 1);
}
// Display the percentages next to the lines
@@ -2918,10 +2988,15 @@ void CanvasItemEditor::_draw_selection() {
Point2 bsfrom = transform.xform(drag_from);
Point2 bsto = transform.xform(box_selecting_to);
- VisualServer::get_singleton()->canvas_item_add_rect(
- ci,
+ viewport->draw_rect(
+ Rect2(bsfrom, bsto - bsfrom),
+ get_color("box_selection_fill_color", "Editor"));
+
+ viewport->draw_rect(
Rect2(bsfrom, bsto - bsfrom),
- get_color("accent_color", "Editor") * Color(1, 1, 1, 0.375));
+ get_color("box_selection_stroke_color", "Editor"),
+ false,
+ Math::round(EDSCALE));
}
if (drag_type == DRAG_ROTATE) {
@@ -3307,6 +3382,7 @@ void CanvasItemEditor::_draw_viewport() {
_draw_rulers();
if (show_guides)
_draw_guides();
+ _draw_smart_snapping();
_draw_focus();
_draw_hover();
}
@@ -3316,6 +3392,10 @@ void CanvasItemEditor::update_viewport() {
viewport->update();
}
+void CanvasItemEditor::set_current_tool(Tool p_tool) {
+ _button_tool_select(p_tool);
+}
+
void CanvasItemEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_PHYSICS_PROCESS) {
@@ -4349,6 +4429,27 @@ void CanvasItemEditor::_popup_callback(int p_op) {
}
} break;
+ case CLEAR_GUIDES: {
+
+ if (EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_horizontal_guides_") || EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_vertical_guides_")) {
+ undo_redo->create_action(TTR("Clear Guides"));
+ if (EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_horizontal_guides_")) {
+ Array hguides = EditorNode::get_singleton()->get_edited_scene()->get_meta("_edit_horizontal_guides_");
+
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_horizontal_guides_", Array());
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_horizontal_guides_", hguides);
+ }
+ if (EditorNode::get_singleton()->get_edited_scene()->has_meta("_edit_vertical_guides_")) {
+ Array vguides = EditorNode::get_singleton()->get_edited_scene()->get_meta("_edit_vertical_guides_");
+
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_vertical_guides_", Array());
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_vertical_guides_", vguides);
+ }
+ undo_redo->add_undo_method(viewport, "update");
+ undo_redo->commit_action();
+ }
+
+ } break;
case VIEW_CENTER_TO_SELECTION:
case VIEW_FRAME_TO_SELECTION: {
@@ -5079,6 +5180,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
p->add_separator();
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/center_selection", TTR("Center Selection"), KEY_F), VIEW_CENTER_TO_SELECTION);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/frame_selection", TTR("Frame Selection"), KEY_MASK_SHIFT | KEY_F), VIEW_FRAME_TO_SELECTION);
+ p->add_shortcut(ED_SHORTCUT("canvas_item_editor/clear_guides", TTR("Clear Guides")), CLEAR_GUIDES);
p->add_separator();
p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/preview_canvas_scale", TTR("Preview Canvas Scale"), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_P), PREVIEW_CANVAS_SCALE);
diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h
index e6eab57810..ac7d612292 100644
--- a/editor/plugins/canvas_item_editor_plugin.h
+++ b/editor/plugins/canvas_item_editor_plugin.h
@@ -86,6 +86,17 @@ public:
private:
EditorNode *editor;
+ enum SnapTarget {
+ SNAP_TARGET_NONE = 0,
+ SNAP_TARGET_PARENT,
+ SNAP_TARGET_SELF_ANCHORS,
+ SNAP_TARGET_SELF,
+ SNAP_TARGET_OTHER_NODE,
+ SNAP_TARGET_GUIDE,
+ SNAP_TARGET_GRID,
+ SNAP_TARGET_PIXEL
+ };
+
enum MenuOption {
SNAP_USE,
SNAP_USE_NODE_PARENT,
@@ -167,6 +178,7 @@ private:
ANIM_COPY_POSE,
ANIM_PASTE_POSE,
ANIM_CLEAR_POSE,
+ CLEAR_GUIDES,
VIEW_CENTER_TO_SELECTION,
VIEW_FRAME_TO_SELECTION,
PREVIEW_CANVAS_SCALE,
@@ -440,6 +452,7 @@ private:
void _draw_percentage_at_position(float p_value, Point2 p_position, Margin p_side);
void _draw_straight_line(Point2 p_from, Point2 p_to, Color p_color);
+ void _draw_smart_snapping();
void _draw_rulers();
void _draw_guides();
void _draw_focus();
@@ -475,9 +488,25 @@ private:
void _solve_IK(Node2D *leaf_node, Point2 target_position);
- void _snap_if_closer_float(float p_value, float p_target_snap, float &r_current_snap, bool &r_snapped, float p_radius = 10.0);
- void _snap_if_closer_point(Point2 p_value, Point2 p_target_snap, Point2 &r_current_snap, bool (&r_snapped)[2], real_t rotation = 0.0, float p_radius = 10.0);
- void _snap_other_nodes(Point2 p_value, Point2 &r_current_snap, bool (&r_snapped)[2], const Node *p_current, const CanvasItem *p_to_snap = NULL);
+ SnapTarget snap_target[2];
+ Transform2D snap_transform;
+ void _snap_if_closer_float(
+ float p_value,
+ float &r_current_snap, SnapTarget &r_current_snap_target,
+ float p_target_value, SnapTarget p_snap_target,
+ float p_radius = 10.0);
+ void _snap_if_closer_point(
+ Point2 p_value,
+ Point2 &r_current_snap, SnapTarget (&r_current_snap_target)[2],
+ Point2 p_target_value, SnapTarget p_snap_target,
+ real_t rotation = 0.0,
+ float p_radius = 10.0);
+ void _snap_other_nodes(
+ const Point2 p_value,
+ const Transform2D p_transform_to_snap,
+ Point2 &r_current_snap, SnapTarget (&r_current_snap_target)[2],
+ const SnapTarget p_snap_target, List<const CanvasItem *> p_exceptions,
+ const Node *p_current);
void _set_anchors_preset(Control::LayoutPreset p_preset);
void _set_margins_preset(Control::LayoutPreset p_preset);
@@ -558,7 +587,7 @@ public:
SNAP_DEFAULT = SNAP_GRID | SNAP_GUIDES | SNAP_PIXEL,
};
- Point2 snap_point(Point2 p_target, unsigned int p_modes = SNAP_DEFAULT, const CanvasItem *p_canvas_item = NULL, unsigned int p_forced_modes = 0);
+ Point2 snap_point(Point2 p_target, unsigned int p_modes = SNAP_DEFAULT, unsigned int p_forced_modes = 0, const CanvasItem *p_self_canvas_item = NULL, List<CanvasItem *> p_other_nodes_exceptions = List<CanvasItem *>());
float snap_angle(float p_target, float p_start = 0) const;
Transform2D get_canvas_transform() const { return transform; }
@@ -581,6 +610,7 @@ public:
void update_viewport();
Tool get_current_tool() { return tool; }
+ void set_current_tool(Tool p_tool);
void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
void edit(CanvasItem *p_canvas_item);
diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.cpp b/editor/plugins/cpu_particles_2d_editor_plugin.cpp
index 7c2116f06b..9d625af959 100644
--- a/editor/plugins/cpu_particles_2d_editor_plugin.cpp
+++ b/editor/plugins/cpu_particles_2d_editor_plugin.cpp
@@ -87,8 +87,7 @@ void CPUParticles2DEditorPlugin::_generate_emission_mask() {
Ref<Image> img;
img.instance();
Error err = ImageLoader::load_image(source_emission_file, img);
- ERR_EXPLAIN(TTR("Error loading image:") + " " + source_emission_file);
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Error loading image: " + source_emission_file + ".");
if (img->is_compressed()) {
img->decompress();
@@ -196,8 +195,7 @@ void CPUParticles2DEditorPlugin::_generate_emission_mask() {
valid_normals.resize(vpc);
}
- ERR_EXPLAIN(TTR("No pixels with transparency > 128 in image..."));
- ERR_FAIL_COND(valid_positions.size() == 0);
+ ERR_FAIL_COND_MSG(valid_positions.size() == 0, "No pixels with transparency > 128 in image...");
if (capture_colors) {
PoolColorArray pca;
diff --git a/editor/plugins/multimesh_editor_plugin.cpp b/editor/plugins/multimesh_editor_plugin.cpp
index d59efe49e7..3ea014a38d 100644
--- a/editor/plugins/multimesh_editor_plugin.cpp
+++ b/editor/plugins/multimesh_editor_plugin.cpp
@@ -147,9 +147,8 @@ void MultiMeshEditor::_populate() {
w.release();
PoolVector<Face3> faces = geometry;
- ERR_EXPLAIN(TTR("Parent has no solid faces to populate."));
int facecount = faces.size();
- ERR_FAIL_COND(!facecount);
+ ERR_FAIL_COND_MSG(!facecount, "Parent has no solid faces to populate.");
PoolVector<Face3>::Read r = faces.read();
@@ -164,10 +163,8 @@ void MultiMeshEditor::_populate() {
area_accum += area;
}
- ERR_EXPLAIN(TTR("Couldn't map area."));
- ERR_FAIL_COND(triangle_area_map.size() == 0);
- ERR_EXPLAIN(TTR("Couldn't map area."));
- ERR_FAIL_COND(area_accum == 0);
+ ERR_FAIL_COND_MSG(triangle_area_map.size() == 0, "Couldn't map area.");
+ ERR_FAIL_COND_MSG(area_accum == 0, "Couldn't map area.");
Ref<MultiMesh> multimesh = memnew(MultiMesh);
multimesh->set_mesh(mesh);
diff --git a/editor/plugins/particles_2d_editor_plugin.cpp b/editor/plugins/particles_2d_editor_plugin.cpp
index e68bca55cb..8025e12885 100644
--- a/editor/plugins/particles_2d_editor_plugin.cpp
+++ b/editor/plugins/particles_2d_editor_plugin.cpp
@@ -160,8 +160,7 @@ void Particles2DEditorPlugin::_generate_emission_mask() {
Ref<Image> img;
img.instance();
Error err = ImageLoader::load_image(source_emission_file, img);
- ERR_EXPLAIN(TTR("Error loading image:") + " " + source_emission_file);
- ERR_FAIL_COND(err != OK);
+ ERR_FAIL_COND_MSG(err != OK, "Error loading image: " + source_emission_file + ".");
if (img->is_compressed()) {
img->decompress();
@@ -269,8 +268,7 @@ void Particles2DEditorPlugin::_generate_emission_mask() {
valid_normals.resize(vpc);
}
- ERR_EXPLAIN(TTR("No pixels with transparency > 128 in image..."));
- ERR_FAIL_COND(valid_positions.size() == 0);
+ ERR_FAIL_COND_MSG(valid_positions.size() == 0, "No pixels with transparency > 128 in image...");
PoolVector<uint8_t> texdata;
diff --git a/editor/plugins/path_2d_editor_plugin.cpp b/editor/plugins/path_2d_editor_plugin.cpp
index b87bd29cbd..f02dc0bd6d 100644
--- a/editor/plugins/path_2d_editor_plugin.cpp
+++ b/editor/plugins/path_2d_editor_plugin.cpp
@@ -367,18 +367,18 @@ bool Path2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) {
void Path2DEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
- if (!node)
+ if (!node || !node->is_visible_in_tree() || !node->get_curve().is_valid())
return;
- if (!node->is_visible_in_tree())
- return;
+ Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- if (!node->get_curve().is_valid())
- return;
+ const Ref<Texture> path_sharp_handle = get_icon("EditorPathSharpHandle", "EditorIcons");
+ const Ref<Texture> path_smooth_handle = get_icon("EditorPathSmoothHandle", "EditorIcons");
+ // Both handle icons must be of the same size
+ const Size2 handle_size = path_sharp_handle->get_size();
- Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
- Size2 handle_size = handle->get_size();
+ const Ref<Texture> curve_handle = get_icon("EditorCurveHandle", "EditorIcons");
+ const Size2 curve_handle_size = curve_handle->get_size();
Ref<Curve2D> curve = node->get_curve();
@@ -387,19 +387,35 @@ void Path2DEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
for (int i = 0; i < len; i++) {
Vector2 point = xform.xform(curve->get_point_position(i));
- vpc->draw_texture_rect(handle, Rect2(point - handle_size * 0.5, handle_size), false, Color(1, 1, 1, 1));
+ // Determines the point icon to be used
+ bool smooth = false;
if (i < len - 1) {
Vector2 pointout = xform.xform(curve->get_point_position(i) + curve->get_point_out(i));
- vpc->draw_line(point, pointout, Color(0.5, 0.5, 1.0, 0.8), 1.0);
- vpc->draw_texture_rect(handle, Rect2(pointout - handle_size * 0.5, handle_size), false, Color(1, 0.5, 1, 0.3));
+ if (point != pointout) {
+ smooth = true;
+ // Draw the line with a dark and light color to be visible on all backgrounds
+ vpc->draw_line(point, pointout, Color(0, 0, 0, 0.5), Math::round(EDSCALE), true);
+ vpc->draw_line(point, pointout, Color(1, 1, 1, 0.5), Math::round(EDSCALE), true);
+ vpc->draw_texture_rect(curve_handle, Rect2(pointout - curve_handle_size * 0.5, curve_handle_size), false, Color(1, 1, 1, 0.75));
+ }
}
if (i > 0) {
Vector2 pointin = xform.xform(curve->get_point_position(i) + curve->get_point_in(i));
- vpc->draw_line(point, pointin, Color(0.5, 0.5, 1.0, 0.8), 1.0);
- vpc->draw_texture_rect(handle, Rect2(pointin - handle_size * 0.5, handle_size), false, Color(1, 0.5, 1, 0.3));
+ if (point != pointin) {
+ smooth = true;
+ // Draw the line with a dark and light color to be visible on all backgrounds
+ vpc->draw_line(point, pointin, Color(0, 0, 0, 0.5), Math::round(EDSCALE), true);
+ vpc->draw_line(point, pointin, Color(1, 1, 1, 0.5), Math::round(EDSCALE), true);
+ vpc->draw_texture_rect(curve_handle, Rect2(pointin - curve_handle_size * 0.5, curve_handle_size), false, Color(1, 1, 1, 0.75));
+ }
}
+
+ vpc->draw_texture_rect(
+ smooth ? path_smooth_handle : path_sharp_handle,
+ Rect2(point - handle_size * 0.5, handle_size),
+ false);
}
if (on_edge) {
diff --git a/editor/plugins/path_editor_plugin.cpp b/editor/plugins/path_editor_plugin.cpp
index 1ae5acc5ff..2493380585 100644
--- a/editor/plugins/path_editor_plugin.cpp
+++ b/editor/plugins/path_editor_plugin.cpp
@@ -652,7 +652,6 @@ PathSpatialGizmoPlugin::PathSpatialGizmoPlugin() {
Color path_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/path", Color(0.5, 0.5, 1.0, 0.8));
create_material("path_material", path_color);
- path_color.a = 0.4;
- create_material("path_thin_material", path_color);
+ create_material("path_thin_material", Color(0.5, 0.5, 0.5));
create_handle_material("handles");
}
diff --git a/editor/plugins/polygon_2d_editor_plugin.cpp b/editor/plugins/polygon_2d_editor_plugin.cpp
index 59004a08c0..bd532a6418 100644
--- a/editor/plugins/polygon_2d_editor_plugin.cpp
+++ b/editor/plugins/polygon_2d_editor_plugin.cpp
@@ -1045,8 +1045,8 @@ void Polygon2DEditor::_uv_draw() {
}
}
- Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
- Ref<Texture> internal_handle = get_icon("EditorInternalHandle", "EditorIcons");
+ // All UV points are sharp, so use the sharp handle icon
+ Ref<Texture> handle = get_icon("EditorPathSharpHandle", "EditorIcons");
Color poly_line_color = Color(0.9, 0.5, 0.5);
if (polygons.size() || polygon_create.size()) {
@@ -1120,7 +1120,8 @@ void Polygon2DEditor::_uv_draw() {
if (i < uv_draw_max) {
uv_edit_draw->draw_texture(handle, mtx.xform(uvs[i]) - handle->get_size() * 0.5);
} else {
- uv_edit_draw->draw_texture(internal_handle, mtx.xform(uvs[i]) - internal_handle->get_size() * 0.5);
+ // Internal vertex
+ uv_edit_draw->draw_texture(handle, mtx.xform(uvs[i]) - handle->get_size() * 0.5, Color(0.6, 0.8, 1));
}
}
}
diff --git a/editor/plugins/shader_editor_plugin.cpp b/editor/plugins/shader_editor_plugin.cpp
index 04820b8a8f..938dc8a1e7 100644
--- a/editor/plugins/shader_editor_plugin.cpp
+++ b/editor/plugins/shader_editor_plugin.cpp
@@ -55,6 +55,7 @@ void ShaderTextEditor::set_edited_shader(const Ref<Shader> &p_shader) {
_load_theme_settings();
get_text_edit()->set_text(p_shader->get_code());
+ get_text_edit()->clear_undo_history();
_validate_script();
_line_col_changed();
diff --git a/editor/plugins/spatial_editor_plugin.cpp b/editor/plugins/spatial_editor_plugin.cpp
index f2b1aad59d..2eb3ce1ec3 100644
--- a/editor/plugins/spatial_editor_plugin.cpp
+++ b/editor/plugins/spatial_editor_plugin.cpp
@@ -2373,16 +2373,22 @@ void SpatialEditorViewport::_draw() {
get_stylebox("Focus", "EditorStyles")->draw(surface->get_canvas_item(), r);
}
- RID ci = surface->get_canvas_item();
-
if (cursor.region_select) {
+ const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
- VisualServer::get_singleton()->canvas_item_add_rect(
- ci,
- Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin),
- get_color("accent_color", "Editor") * Color(1, 1, 1, 0.375));
+ surface->draw_rect(
+ selection_rect,
+ get_color("box_selection_fill_color", "Editor"));
+
+ surface->draw_rect(
+ selection_rect,
+ get_color("box_selection_stroke_color", "Editor"),
+ false,
+ Math::round(EDSCALE));
}
+ RID ci = surface->get_canvas_item();
+
if (message_time > 0) {
Ref<Font> font = get_font("font", "Label");
Point2 msgpos = Point2(5, get_size().y - 20);
@@ -5170,7 +5176,7 @@ void SpatialEditor::snap_selected_nodes_to_floor() {
// We add a bit of margin to the from position to avoid it from snapping
// when the spatial is already on a floor and there's another floor under
// it
- from = from + Vector3(0.0, 0.1, 0.0);
+ from = from + Vector3(0.0, 0.2, 0.0);
Dictionary d;
@@ -5185,31 +5191,56 @@ void SpatialEditor::snap_selected_nodes_to_floor() {
Array keys = snap_data.keys();
- if (keys.size()) {
- undo_redo->create_action(TTR("Snap Nodes To Floor"));
+ // The maximum height an object can travel to be snapped
+ const float max_snap_height = 20.0;
+
+ // Will be set to `true` if at least one node from the selection was sucessfully snapped
+ bool snapped_to_floor = false;
+ if (keys.size()) {
+ // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
+ // We need to check this before snapping to register the undo/redo action only if needed.
for (int i = 0; i < keys.size(); i++) {
Node *node = keys[i];
Spatial *sp = Object::cast_to<Spatial>(node);
-
Dictionary d = snap_data[node];
Vector3 from = d["from"];
- Vector3 position_offset = d["position_offset"];
-
- Vector3 to = from - Vector3(0.0, 10.0, 0.0);
+ Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
Set<RID> excluded = _get_physics_bodies_rid(sp);
if (ss->intersect_ray(from, to, result, excluded)) {
- Transform new_transform = sp->get_global_transform();
- new_transform.origin.y = result.position.y;
- new_transform.origin = new_transform.origin - position_offset;
-
- undo_redo->add_do_method(sp, "set_global_transform", new_transform);
- undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
+ snapped_to_floor = true;
}
}
- undo_redo->commit_action();
+ if (snapped_to_floor) {
+ undo_redo->create_action(TTR("Snap Nodes To Floor"));
+
+ // Perform snapping if at least one node can be snapped
+ for (int i = 0; i < keys.size(); i++) {
+ Node *node = keys[i];
+ Spatial *sp = Object::cast_to<Spatial>(node);
+ Dictionary d = snap_data[node];
+ Vector3 from = d["from"];
+ Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
+ Set<RID> excluded = _get_physics_bodies_rid(sp);
+
+ if (ss->intersect_ray(from, to, result, excluded)) {
+ Vector3 position_offset = d["position_offset"];
+ Transform new_transform = sp->get_global_transform();
+
+ new_transform.origin.y = result.position.y;
+ new_transform.origin = new_transform.origin - position_offset;
+
+ undo_redo->add_do_method(sp, "set_global_transform", new_transform);
+ undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
+ }
+ }
+
+ undo_redo->commit_action();
+ } else {
+ EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
+ }
}
}
@@ -5219,42 +5250,6 @@ void SpatialEditor::_unhandled_key_input(Ref<InputEvent> p_event) {
return;
snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
-
- Ref<InputEventKey> k = p_event;
-
- if (k.is_valid()) {
-
- // Note: need to check is_echo because first person movement keys might still be held
- if (!is_any_freelook_active() && !p_event->is_echo()) {
-
- if (!k->is_pressed())
- return;
-
- if (ED_IS_SHORTCUT("spatial_editor/tool_select", p_event)) {
- _menu_item_pressed(MENU_TOOL_SELECT);
- } else if (ED_IS_SHORTCUT("spatial_editor/tool_move", p_event)) {
- _menu_item_pressed(MENU_TOOL_MOVE);
- } else if (ED_IS_SHORTCUT("spatial_editor/tool_rotate", p_event)) {
- _menu_item_pressed(MENU_TOOL_ROTATE);
- } else if (ED_IS_SHORTCUT("spatial_editor/tool_scale", p_event)) {
- _menu_item_pressed(MENU_TOOL_SCALE);
- } else if (ED_IS_SHORTCUT("spatial_editor/snap_to_floor", p_event)) {
- snap_selected_nodes_to_floor();
- } else if (ED_IS_SHORTCUT("spatial_editor/local_coords", p_event)) {
- if (are_local_coords_enabled()) {
- _menu_item_toggled(false, MENU_TOOL_LOCAL_COORDS);
- } else {
- _menu_item_toggled(true, MENU_TOOL_LOCAL_COORDS);
- }
- } else if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
- if (is_snap_enabled()) {
- _menu_item_toggled(false, MENU_TOOL_USE_SNAP);
- } else {
- _menu_item_toggled(true, MENU_TOOL_USE_SNAP);
- }
- }
- }
- }
}
void SpatialEditor::_notification(int p_what) {
@@ -5528,7 +5523,8 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_button[TOOL_MODE_SELECT]->set_pressed(true);
button_binds.write[0] = MENU_TOOL_SELECT;
tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
- tool_button[TOOL_MODE_SELECT]->set_tooltip(TTR("Select Mode (Q)") + "\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection"));
+ tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q));
+ tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection"));
hbc_menu->add_child(memnew(VSeparator));
@@ -5538,7 +5534,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_button[TOOL_MODE_MOVE]->set_flat(true);
button_binds.write[0] = MENU_TOOL_MOVE;
tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
- tool_button[TOOL_MODE_MOVE]->set_tooltip(TTR("Move Mode (W)"));
+ tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W));
tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
@@ -5546,7 +5542,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_button[TOOL_MODE_ROTATE]->set_flat(true);
button_binds.write[0] = MENU_TOOL_ROTATE;
tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
- tool_button[TOOL_MODE_ROTATE]->set_tooltip(TTR("Rotate Mode (E)"));
+ tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E));
tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
@@ -5554,7 +5550,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_button[TOOL_MODE_SCALE]->set_flat(true);
button_binds.write[0] = MENU_TOOL_SCALE;
tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
- tool_button[TOOL_MODE_SCALE]->set_tooltip(TTR("Scale Mode (R)"));
+ tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R));
hbc_menu->add_child(memnew(VSeparator));
@@ -5598,9 +5594,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true);
button_binds.write[0] = MENU_TOOL_LOCAL_COORDS;
tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", this, "_menu_item_toggled", button_binds);
- ED_SHORTCUT("spatial_editor/local_coords", TTR("Local Coords"), KEY_T);
- sct = ED_GET_SHORTCUT("spatial_editor/local_coords").ptr()->get_as_text();
- tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_tooltip(vformat(TTR("Local Space Mode (%s)"), sct));
+ tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T));
tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton);
hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
@@ -5608,9 +5602,7 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true);
button_binds.write[0] = MENU_TOOL_USE_SNAP;
tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", this, "_menu_item_toggled", button_binds);
- ED_SHORTCUT("spatial_editor/snap", TTR("Snap"), KEY_Y);
- sct = ED_GET_SHORTCUT("spatial_editor/snap").ptr()->get_as_text();
- tool_option_button[TOOL_OPT_USE_SNAP]->set_tooltip(vformat(TTR("Snap Mode (%s)"), sct));
+ tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y));
hbc_menu->add_child(memnew(VSeparator));
@@ -5630,12 +5622,6 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_M);
ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
-
- ED_SHORTCUT("spatial_editor/tool_select", TTR("Tool Select"), KEY_Q);
- ED_SHORTCUT("spatial_editor/tool_move", TTR("Tool Move"), KEY_W);
- ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Tool Rotate"), KEY_E);
- ED_SHORTCUT("spatial_editor/tool_scale", TTR("Tool Scale"), KEY_R);
-
ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KEY_MASK_SHIFT + KEY_F);
PopupMenu *p;
diff --git a/editor/plugins/theme_editor_plugin.cpp b/editor/plugins/theme_editor_plugin.cpp
index 56357f298a..3055a9382c 100644
--- a/editor/plugins/theme_editor_plugin.cpp
+++ b/editor/plugins/theme_editor_plugin.cpp
@@ -191,11 +191,9 @@ void ThemeEditor::_save_template_cbk(String fname) {
}
FileAccess *file = FileAccess::open(filename, FileAccess::WRITE);
- if (!file) {
- ERR_EXPLAIN(TTR("Can't save theme to file:") + " " + filename);
- return;
- }
+ ERR_FAIL_COND_MSG(!file, "Can't save theme to file: " + filename + ".");
+
file->store_line("; ******************* ");
file->store_line("; Template Theme File ");
file->store_line("; ******************* ");
diff --git a/editor/plugins/tile_map_editor_plugin.cpp b/editor/plugins/tile_map_editor_plugin.cpp
index b2f06ca41f..26fae96025 100644
--- a/editor/plugins/tile_map_editor_plugin.cpp
+++ b/editor/plugins/tile_map_editor_plugin.cpp
@@ -972,7 +972,7 @@ static inline Vector<Point2i> line(int x0, int x1, int y0, int y1) {
bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) {
- if (!node || !node->get_tileset().is_valid() || !node->is_visible_in_tree())
+ if (!node || !node->get_tileset().is_valid() || !node->is_visible_in_tree() || CanvasItemEditor::get_singleton()->get_current_tool() != CanvasItemEditor::TOOL_SELECT)
return false;
Transform2D xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform();
@@ -1533,7 +1533,7 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) {
void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
- if (!node)
+ if (!node || CanvasItemEditor::get_singleton()->get_current_tool() != CanvasItemEditor::TOOL_SELECT)
return;
Transform2D cell_xf = node->get_cell_transform();
@@ -2006,7 +2006,7 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) {
// Tools
paint_button = memnew(ToolButton);
paint_button->set_shortcut(ED_SHORTCUT("tile_map_editor/paint_tile", TTR("Paint Tile"), KEY_P));
- paint_button->set_tooltip(TTR("Shift+RMB: Line Draw\nShift+Ctrl+RMB: Rectangle Paint"));
+ paint_button->set_tooltip(TTR("Shift+LMB: Line Draw\nShift+Ctrl+LMB: Rectangle Paint"));
paint_button->connect("pressed", this, "_button_tool_select", make_binds(TOOL_NONE));
paint_button->set_toggle_mode(true);
toolbar->add_child(paint_button);
@@ -2136,6 +2136,7 @@ void TileMapEditorPlugin::make_visible(bool p_visible) {
tile_map_editor->show();
tile_map_editor->get_toolbar()->show();
tile_map_editor->get_toolbar_right()->show();
+ CanvasItemEditor::get_singleton()->set_current_tool(CanvasItemEditor::TOOL_SELECT); //Change to TOOL_SELECT when TileMap node is selected, to prevent accidental movement.
} else {
tile_map_editor->hide();
diff --git a/editor/plugins/tile_set_editor_plugin.cpp b/editor/plugins/tile_set_editor_plugin.cpp
index 1a27e749e2..9096a0e0be 100644
--- a/editor/plugins/tile_set_editor_plugin.cpp
+++ b/editor/plugins/tile_set_editor_plugin.cpp
@@ -176,6 +176,86 @@ Error TileSetEditor::update_library_file(Node *p_base_scene, Ref<TileSet> ml, bo
return OK;
}
+Variant TileSetEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
+
+ return false;
+}
+
+bool TileSetEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
+
+ Dictionary d = p_data;
+
+ if (!d.has("type"))
+ return false;
+
+ if (d.has("from") && (Object *)(d["from"]) == texture_list)
+ return false;
+
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
+
+ Ref<Texture> texture = r;
+
+ if (texture.is_valid()) {
+
+ return true;
+ }
+ }
+
+ if (String(d["type"]) == "files") {
+
+ Vector<String> files = d["files"];
+
+ if (files.size() == 0)
+ return false;
+
+ for (int i = 0; i < files.size(); i++) {
+ String file = files[i];
+ String ftype = EditorFileSystem::get_singleton()->get_file_type(file);
+
+ if (!ClassDB::is_parent_class(ftype, "Texture")) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ return false;
+}
+
+void TileSetEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
+
+ if (!can_drop_data_fw(p_point, p_data, p_from))
+ return;
+
+ Dictionary d = p_data;
+
+ if (!d.has("type"))
+ return;
+
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
+
+ Ref<Texture> texture = r;
+
+ if (texture.is_valid())
+ add_texture(texture);
+
+ if (texture_list->get_item_count() > 0) {
+ update_texture_list_icon();
+ texture_list->select(texture_list->get_item_count() - 1);
+ _on_texture_list_selected(texture_list->get_item_count() - 1);
+ }
+ }
+
+ if (String(d["type"]) == "files") {
+
+ PoolVector<String> files = d["files"];
+
+ _on_textures_added(files);
+ }
+}
+
void TileSetEditor::_bind_methods() {
ClassDB::bind_method("_undo_redo_import_scene", &TileSetEditor::_undo_redo_import_scene);
@@ -203,6 +283,10 @@ void TileSetEditor::_bind_methods() {
ClassDB::bind_method("_select_edited_shape_coord", &TileSetEditor::_select_edited_shape_coord);
ClassDB::bind_method("_sort_tiles", &TileSetEditor::_sort_tiles);
+ ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &TileSetEditor::get_drag_data_fw);
+ ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &TileSetEditor::can_drop_data_fw);
+ ClassDB::bind_method(D_METHOD("drop_data_fw"), &TileSetEditor::drop_data_fw);
+
ClassDB::bind_method("edit", &TileSetEditor::edit);
ClassDB::bind_method("add_texture", &TileSetEditor::add_texture);
ClassDB::bind_method("remove_texture", &TileSetEditor::remove_texture);
@@ -274,6 +358,7 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) {
texture_list->set_v_size_flags(SIZE_EXPAND_FILL);
texture_list->set_custom_minimum_size(Size2(200, 0));
texture_list->connect("item_selected", this, "_on_texture_list_selected");
+ texture_list->set_drag_forwarding(this);
HBoxContainer *tileset_toolbar_container = memnew(HBoxContainer);
left_container->add_child(tileset_toolbar_container);
@@ -646,8 +731,7 @@ void TileSetEditor::_on_textures_added(const PoolStringArray &p_paths) {
for (int i = 0; i < p_paths.size(); i++) {
Ref<Texture> t = Ref<Texture>(ResourceLoader::load(p_paths[i]));
- ERR_EXPLAIN("'" + p_paths[i] + "' is not a valid texture.");
- ERR_CONTINUE(!t.is_valid());
+ ERR_CONTINUE_MSG(!t.is_valid(), "'" + p_paths[i] + "' is not a valid texture.");
if (texture_map.has(t->get_rid())) {
invalid_count++;
diff --git a/editor/plugins/tile_set_editor_plugin.h b/editor/plugins/tile_set_editor_plugin.h
index 69ad8205a4..fff9ef7731 100644
--- a/editor/plugins/tile_set_editor_plugin.h
+++ b/editor/plugins/tile_set_editor_plugin.h
@@ -173,6 +173,12 @@ class TileSetEditor : public HSplitContainer {
static void _import_scene(Node *p_scene, Ref<TileSet> p_library, bool p_merge);
void _undo_redo_import_scene(Node *p_scene, bool p_merge);
+ bool _is_drop_valid(const Dictionary &p_drag_data, const Dictionary &p_item_data) const;
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
+ void _file_load_request(const PoolVector<String> &p_path, int p_at_pos = -1);
+
protected:
static void _bind_methods();
void _notification(int p_what);
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index e193e237de..66fbc32b1c 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -41,6 +41,7 @@
#include "scene/gui/panel.h"
#include "scene/main/viewport.h"
#include "scene/resources/visual_shader_nodes.h"
+#include "servers/visual/shader_types.h"
Control *VisualShaderNodePlugin::create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node) {
@@ -69,8 +70,16 @@ void VisualShaderEditor::edit(VisualShader *p_visual_shader) {
}
}
visual_shader = Ref<VisualShader>(p_visual_shader);
+ if (!visual_shader->is_connected("changed", this, "_update_preview")) {
+ visual_shader->connect("changed", this, "_update_preview");
+ }
visual_shader->set_graph_offset(graph->get_scroll_ofs() / EDSCALE);
} else {
+ if (visual_shader.is_valid()) {
+ if (visual_shader->is_connected("changed", this, "")) {
+ visual_shader->disconnect("changed", this, "_update_preview");
+ }
+ }
visual_shader.unref();
}
@@ -81,6 +90,7 @@ void VisualShaderEditor::edit(VisualShader *p_visual_shader) {
_clear_buffer();
_update_custom_nodes();
_update_options_menu();
+ _update_preview();
}
_update_graph();
}
@@ -220,6 +230,14 @@ void VisualShaderEditor::_update_custom_nodes() {
}
}
+String VisualShaderEditor::_get_description(int p_idx) {
+ if (add_options[p_idx].highend) {
+ return TTR("(GLES3 only)") + " " + add_options[p_idx].description; // TODO: change it to (Vulkan Only) when its ready
+ } else {
+ return add_options[p_idx].description;
+ }
+}
+
void VisualShaderEditor::_update_options_menu() {
node_desc->set_text("");
@@ -323,11 +341,10 @@ void VisualShaderEditor::_update_options_menu() {
else if (add_options[i].highend)
item->set_custom_color(0, supported_color);
item->set_text(0, add_options[i].name);
- if (p_category == sub_category) {
- if (is_first_item) {
- item->select(0);
- is_first_item = false;
- }
+ if (is_first_item && use_filter) {
+ item->select(0);
+ node_desc->set_text(_get_description(i));
+ is_first_item = false;
}
switch (add_options[i].return_type) {
case VisualShaderNode::PORT_TYPE_SCALAR:
@@ -524,21 +541,23 @@ void VisualShaderEditor::_update_graph() {
offset->set_custom_minimum_size(Size2(0, 6 * EDSCALE));
node->add_child(offset);
- HBoxContainer *hb2 = memnew(HBoxContainer);
+ if (group_node->is_editable()) {
+ HBoxContainer *hb2 = memnew(HBoxContainer);
- Button *add_input_btn = memnew(Button);
- add_input_btn->set_text(TTR("Add input +"));
- add_input_btn->connect("pressed", this, "_add_input_port", varray(nodes[n_i], group_node->get_free_input_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "input" + itos(group_node->get_free_input_port_id())), CONNECT_DEFERRED);
- hb2->add_child(add_input_btn);
+ Button *add_input_btn = memnew(Button);
+ add_input_btn->set_text(TTR("Add input +"));
+ add_input_btn->connect("pressed", this, "_add_input_port", varray(nodes[n_i], group_node->get_free_input_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "input" + itos(group_node->get_free_input_port_id())), CONNECT_DEFERRED);
+ hb2->add_child(add_input_btn);
- hb2->add_spacer();
+ hb2->add_spacer();
- Button *add_output_btn = memnew(Button);
- add_output_btn->set_text(TTR("Add output +"));
- add_output_btn->connect("pressed", this, "_add_output_port", varray(nodes[n_i], group_node->get_free_output_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "output" + itos(group_node->get_free_output_port_id())), CONNECT_DEFERRED);
- hb2->add_child(add_output_btn);
+ Button *add_output_btn = memnew(Button);
+ add_output_btn->set_text(TTR("Add output +"));
+ add_output_btn->connect("pressed", this, "_add_output_port", varray(nodes[n_i], group_node->get_free_output_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "output" + itos(group_node->get_free_output_port_id())), CONNECT_DEFERRED);
+ hb2->add_child(add_output_btn);
- node->add_child(hb2);
+ node->add_child(hb2);
+ }
}
for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) {
@@ -1566,6 +1585,32 @@ void VisualShaderEditor::_notification(int p_what) {
node_filter->set_right_icon(Control::get_icon("Search", "EditorIcons"));
+ preview_shader->set_icon(Control::get_icon("Shader", "EditorIcons"));
+
+ {
+ Color background_color = EDITOR_GET("text_editor/highlighting/background_color");
+ Color text_color = EDITOR_GET("text_editor/highlighting/text_color");
+ Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color");
+ Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color");
+ Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color");
+
+ preview_text->add_color_override("background_color", background_color);
+
+ for (List<String>::Element *E = keyword_list.front(); E; E = E->next()) {
+
+ preview_text->add_keyword_color(E->get(), keyword_color);
+ }
+
+ preview_text->add_font_override("font", get_font("expression", "EditorFonts"));
+ preview_text->add_color_override("font_color", text_color);
+ preview_text->add_color_override("symbol_color", symbol_color);
+ preview_text->add_color_region("/*", "*/", comment_color, false);
+ preview_text->add_color_region("//", "", comment_color, false);
+
+ error_text->add_font_override("font", get_font("status_source", "EditorFonts"));
+ error_text->add_color_override("font_color", get_color("error_color", "Editor"));
+ }
+
tools->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Tools", "EditorIcons"));
if (p_what == NOTIFICATION_THEME_CHANGED && is_visible_in_tree())
@@ -1892,11 +1937,7 @@ void VisualShaderEditor::_member_selected() {
if (item != NULL && item->has_meta("id")) {
members_dialog->get_ok()->set_disabled(false);
- if (add_options[item->get_meta("id")].highend) {
- node_desc->set_text(TTR("(GLES3 only)") + " " + add_options[item->get_meta("id")].description); // TODO: change it to (Vulkan Only) when its ready
- } else {
- node_desc->set_text(add_options[item->get_meta("id")].description);
- }
+ node_desc->set_text(_get_description(item->get_meta("id")));
} else {
members_dialog->get_ok()->set_disabled(true);
node_desc->set_text("");
@@ -2016,6 +2057,48 @@ void VisualShaderEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
}
+void VisualShaderEditor::_show_preview_text() {
+ preview_showed = !preview_showed;
+ preview_vbox->set_visible(preview_showed);
+ if (preview_showed) {
+ if (pending_update_preview) {
+ _update_preview();
+ pending_update_preview = false;
+ }
+ }
+}
+
+void VisualShaderEditor::_update_preview() {
+
+ if (!preview_showed) {
+ pending_update_preview = true;
+ return;
+ }
+
+ String code = visual_shader->get_code();
+
+ preview_text->set_text(code);
+
+ ShaderLanguage sl;
+
+ Error err = sl.compile(code, ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(visual_shader->get_mode())), ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(visual_shader->get_mode())), ShaderTypes::get_singleton()->get_types());
+
+ for (int i = 0; i < preview_text->get_line_count(); i++) {
+ preview_text->set_line_as_marked(i, false);
+ }
+ if (err != OK) {
+ preview_text->set_line_as_marked(sl.get_error_line() - 1, true);
+ error_text->set_visible(true);
+
+ String text = "error(" + itos(sl.get_error_line()) + "): " + sl.get_error_text();
+ error_text->set_text(text);
+ shader_error = true;
+ } else {
+ error_text->set_visible(false);
+ shader_error = false;
+ }
+}
+
void VisualShaderEditor::_bind_methods() {
ClassDB::bind_method("_rebuild", &VisualShaderEditor::_rebuild);
ClassDB::bind_method("_update_graph", &VisualShaderEditor::_update_graph);
@@ -2055,6 +2138,8 @@ void VisualShaderEditor::_bind_methods() {
ClassDB::bind_method("_node_resized", &VisualShaderEditor::_node_resized);
ClassDB::bind_method("_set_node_size", &VisualShaderEditor::_set_node_size);
ClassDB::bind_method("_clear_buffer", &VisualShaderEditor::_clear_buffer);
+ ClassDB::bind_method("_show_preview_text", &VisualShaderEditor::_show_preview_text);
+ ClassDB::bind_method("_update_preview", &VisualShaderEditor::_update_preview);
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &VisualShaderEditor::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &VisualShaderEditor::can_drop_data_fw);
@@ -2081,13 +2166,25 @@ VisualShaderEditor::VisualShaderEditor() {
saved_node_pos = Point2(0, 0);
ShaderLanguage::get_keyword_list(&keyword_list);
+ preview_showed = false;
+ pending_update_preview = false;
+ shader_error = false;
+
to_node = -1;
to_slot = -1;
from_node = -1;
from_slot = -1;
+ main_box = memnew(HSplitContainer);
+ main_box->set_v_size_flags(SIZE_EXPAND_FILL);
+ main_box->set_h_size_flags(SIZE_EXPAND_FILL);
+ add_child(main_box);
+
graph = memnew(GraphEdit);
- add_child(graph);
+ graph->get_zoom_hbox()->set_h_size_flags(SIZE_EXPAND_FILL);
+ graph->set_v_size_flags(SIZE_EXPAND_FILL);
+ graph->set_h_size_flags(SIZE_EXPAND_FILL);
+ main_box->add_child(graph);
graph->set_drag_forwarding(this);
graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_SCALAR);
graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_BOOLEAN);
@@ -2136,6 +2233,32 @@ VisualShaderEditor::VisualShaderEditor() {
graph->get_zoom_hbox()->move_child(add_node, 0);
add_node->connect("pressed", this, "_show_members_dialog", varray(false));
+ preview_shader = memnew(ToolButton);
+ preview_shader->set_toggle_mode(true);
+ preview_shader->set_tooltip(TTR("Show resulted shader code."));
+ graph->get_zoom_hbox()->add_child(preview_shader);
+ preview_shader->connect("pressed", this, "_show_preview_text");
+
+ ///////////////////////////////////////
+ // PREVIEW PANEL
+ ///////////////////////////////////////
+
+ preview_vbox = memnew(VBoxContainer);
+ preview_vbox->set_visible(preview_showed);
+ main_box->add_child(preview_vbox);
+ preview_text = memnew(TextEdit);
+ preview_vbox->add_child(preview_text);
+ preview_text->set_h_size_flags(SIZE_EXPAND_FILL);
+ preview_text->set_v_size_flags(SIZE_EXPAND_FILL);
+ preview_text->set_custom_minimum_size(Size2(400 * EDSCALE, 0));
+ preview_text->set_syntax_coloring(true);
+ preview_text->set_show_line_numbers(true);
+ preview_text->set_readonly(true);
+
+ error_text = memnew(Label);
+ preview_vbox->add_child(error_text);
+ error_text->set_visible(false);
+
///////////////////////////////////////
// SHADER NODES TREE
///////////////////////////////////////
@@ -2413,8 +2536,8 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Sin", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("SinH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the hyperbolic sine of the parameter."), VisualShaderNodeScalarFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Sqrt", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeScalarFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("SmoothStep", "Scalar", "Functions", "VisualShaderNodeScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if x is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Step", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Step function( scalar(edge), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), VisualShaderNodeScalarOp::OP_STEP, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("SmoothStep", "Scalar", "Functions", "VisualShaderNodeScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if x is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("Step", "Scalar", "Functions", "VisualShaderNodeScalarOp", TTR("Step function( scalar(edge), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeScalarOp::OP_STEP, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Tan", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("TanH", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Returns the hyperbolic tangent of the parameter."), VisualShaderNodeScalarFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_SCALAR));
add_options.push_back(AddOption("Trunc", "Scalar", "Functions", "VisualShaderNodeScalarFunc", TTR("Finds the truncated value of the parameter."), VisualShaderNodeScalarFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_SCALAR));
@@ -2446,7 +2569,7 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("TransformDecompose", "Transform", "Composition", "VisualShaderNodeTransformDecompose", TTR("Decomposes transform to four vectors.")));
add_options.push_back(AddOption("Determinant", "Transform", "Functions", "VisualShaderNodeDeterminant", TTR("Calculates the determinant of a transform."), -1, VisualShaderNode::PORT_TYPE_SCALAR));
- add_options.push_back(AddOption("Inverse", "Transform", "Functions", "VisualShaderNodeTransformFunc", TTR("Calculates the inverse of a transform."), VisualShaderNodeTransformFunc::FUNC_INVERSE, VisualShaderNode::PORT_TYPE_TRANSFORM, -1, -1, -1, true));
+ add_options.push_back(AddOption("Inverse", "Transform", "Functions", "VisualShaderNodeTransformFunc", TTR("Calculates the inverse of a transform."), VisualShaderNodeTransformFunc::FUNC_INVERSE, VisualShaderNode::PORT_TYPE_TRANSFORM));
add_options.push_back(AddOption("Transpose", "Transform", "Functions", "VisualShaderNodeTransformFunc", TTR("Calculates the transpose of a transform."), VisualShaderNodeTransformFunc::FUNC_TRANSPOSE, VisualShaderNode::PORT_TYPE_TRANSFORM));
add_options.push_back(AddOption("TransformMult", "Transform", "Operators", "VisualShaderNodeTransformMult", TTR("Multiplies transform by transform."), -1, VisualShaderNode::PORT_TYPE_TRANSFORM));
@@ -2507,10 +2630,10 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Sin", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_VECTOR));
add_options.push_back(AddOption("SinH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the hyperbolic sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_VECTOR));
add_options.push_back(AddOption("Sqrt", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeVectorFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_VECTOR));
- add_options.push_back(AddOption("SmoothStep", "Vector", "Functions", "VisualShaderNodeVectorSmoothStep", TTR("SmoothStep function( vector(edge0), vector(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
- add_options.push_back(AddOption("SmoothStepS", "Vector", "Functions", "VisualShaderNodeVectorScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
- add_options.push_back(AddOption("Step", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Step function( vector(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), VisualShaderNodeVectorOp::OP_STEP, VisualShaderNode::PORT_TYPE_VECTOR));
- add_options.push_back(AddOption("StepS", "Vector", "Functions", "VisualShaderNodeVectorScalarStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller then 'edge' and otherwise 1.0."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("SmoothStep", "Vector", "Functions", "VisualShaderNodeVectorSmoothStep", TTR("SmoothStep function( vector(edge0), vector(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("SmoothStepS", "Vector", "Functions", "VisualShaderNodeVectorScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("Step", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Step function( vector(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeVectorOp::OP_STEP, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("StepS", "Vector", "Functions", "VisualShaderNodeVectorScalarStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
add_options.push_back(AddOption("Tan", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_VECTOR));
add_options.push_back(AddOption("TanH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the hyperbolic tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_VECTOR));
add_options.push_back(AddOption("Trunc", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Finds the truncated value of the parameter."), VisualShaderNodeVectorFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_VECTOR));
@@ -2528,6 +2651,7 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Expression", "Special", "", "VisualShaderNodeExpression", TTR("Custom Godot Shader Language expression, with custom amount of input and output ports. This is a direct injection of code into the vertex/fragment/light function, do not use it to write the function declarations inside.")));
add_options.push_back(AddOption("Fresnel", "Special", "", "VisualShaderNodeFresnel", TTR("Returns falloff based on the dot product of surface normal and view direction of camera (pass associated inputs to it)."), -1, VisualShaderNode::PORT_TYPE_SCALAR));
+ add_options.push_back(AddOption("GlobalExpression", "Special", "", "VisualShaderNodeGlobalExpression", TTR("Custom Godot Shader Language expression, which placed on top of the resulted shader. You can place various function definitions inside and call it later in the Expressions. You can also declare varyings, uniforms and constants.")));
add_options.push_back(AddOption("ScalarDerivativeFunc", "Special", "Common", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) Scalar derivative function."), -1, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true));
add_options.push_back(AddOption("VectorDerivativeFunc", "Special", "Common", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) Vector derivative function."), -1, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true));
diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h
index b5b00f2b5e..cd5efc366b 100644
--- a/editor/plugins/visual_shader_editor_plugin.h
+++ b/editor/plugins/visual_shader_editor_plugin.h
@@ -60,14 +60,22 @@ class VisualShaderEditor : public VBoxContainer {
int editing_port;
Ref<VisualShader> visual_shader;
+ HSplitContainer *main_box;
GraphEdit *graph;
ToolButton *add_node;
+ ToolButton *preview_shader;
OptionButton *edit_type;
PanelContainer *error_panel;
Label *error_label;
+ bool pending_update_preview;
+ bool shader_error;
+ VBoxContainer *preview_vbox;
+ TextEdit *preview_text;
+ Label *error_text;
+
UndoRedo *undo_redo;
Point2 saved_node_pos;
bool saved_node_pos_dirty;
@@ -75,6 +83,8 @@ class VisualShaderEditor : public VBoxContainer {
ConfirmationDialog *members_dialog;
MenuButton *tools;
+ bool preview_showed;
+
enum ToolsMenuOptions {
EXPAND_ALL,
COLLAPSE_ALL
@@ -146,6 +156,10 @@ class VisualShaderEditor : public VBoxContainer {
void _update_custom_nodes();
void _update_options_menu();
+ void _show_preview_text();
+ void _update_preview();
+ String _get_description(int p_idx);
+
static VisualShaderEditor *singleton;
void _node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node);
diff --git a/editor/project_export.cpp b/editor/project_export.cpp
index c78a81dbe0..956da92c35 100644
--- a/editor/project_export.cpp
+++ b/editor/project_export.cpp
@@ -931,17 +931,8 @@ void ProjectExportDialog::_export_project() {
export_project->add_filter("*." + extension_list[i] + " ; " + platform->get_name() + " Export");
}
- String current_preset_export_path = current->get_export_path();
-
- if (current_preset_export_path != "") {
-
- if (!DirAccess::exists(current_preset_export_path.get_base_dir())) {
-
- DirAccessRef da(DirAccess::create(DirAccess::ACCESS_FILESYSTEM));
- da->make_dir_recursive(current_preset_export_path.get_base_dir());
- }
-
- export_project->set_current_path(current_preset_export_path);
+ if (current->get_export_path() != "") {
+ export_project->set_current_path(current->get_export_path());
} else {
if (extension_list.size() >= 1) {
export_project->set_current_file(default_filename + "." + extension_list[0]);
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 0f3c4c924a..23aba06956 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -195,7 +195,7 @@ private:
unzFile pkg = unzOpen2(valid_path.utf8().get_data(), &io);
if (!pkg) {
- set_message(TTR("Error opening package file, not in zip format."), MESSAGE_ERROR);
+ set_message(TTR("Error opening package file, not in ZIP format."), MESSAGE_ERROR);
memdelete(d);
get_ok()->set_disabled(true);
unzClose(pkg);
@@ -519,7 +519,7 @@ private:
unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io);
if (!pkg) {
- dialog_error->set_text(TTR("Error opening package file, not in zip format."));
+ dialog_error->set_text(TTR("Error opening package file, not in ZIP format."));
dialog_error->popup_centered_minsize();
return;
}
@@ -946,6 +946,11 @@ public:
static const char *SIGNAL_SELECTION_CHANGED;
static const char *SIGNAL_PROJECT_ASK_OPEN;
+ enum MenuOptions {
+ GLOBAL_NEW_WINDOW,
+ GLOBAL_OPEN_PROJECT
+ };
+
// Can often be passed by copy
struct Item {
String project_key;
@@ -997,7 +1002,6 @@ public:
void load_projects();
void set_search_term(String p_search_term);
- void set_filter_option(ProjectListFilter::FilterOption p_option);
void set_order_option(ProjectListFilter::FilterOption p_option);
void sort_projects();
int get_project_count() const;
@@ -1030,7 +1034,6 @@ private:
static void load_project_data(const String &p_property_key, Item &p_item, bool p_favorite);
String _search_term;
- ProjectListFilter::FilterOption _filter_option;
ProjectListFilter::FilterOption _order_option;
Set<String> _selected_project_keys;
String _last_clicked; // Project key
@@ -1063,7 +1066,6 @@ struct ProjectListComparator {
};
ProjectList::ProjectList() {
- _filter_option = ProjectListFilter::FILTER_NAME;
_order_option = ProjectListFilter::FILTER_MODIFIED;
_scroll_children = memnew(VBoxContainer);
@@ -1184,6 +1186,7 @@ void ProjectList::load_projects() {
_projects.clear();
_last_clicked = "";
_selected_project_keys.clear();
+ OS::get_singleton()->global_menu_clear("_dock");
// Load data
// TODO Would be nice to change how projects and favourites are stored... it complicates things a bit.
@@ -1221,6 +1224,9 @@ void ProjectList::load_projects() {
create_project_item_control(i);
}
+ OS::get_singleton()->global_menu_add_separator("_dock");
+ OS::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), GLOBAL_NEW_WINDOW, Variant());
+
sort_projects();
set_v_scroll(0);
@@ -1258,19 +1264,22 @@ void ProjectList::create_project_item_control(int p_index) {
TextureRect *tf = memnew(TextureRect);
tf->set_texture(get_icon("DefaultProjectIcon", "EditorIcons"));
+ if (item.missing) {
+ tf->set_modulate(Color(1, 1, 1, 0.5));
+ }
hb->add_child(tf);
hb->icon = tf;
VBoxContainer *vb = memnew(VBoxContainer);
if (item.grayed)
- vb->set_modulate(Color(0.5, 0.5, 0.5));
+ vb->set_modulate(Color(1, 1, 1, 0.5));
vb->set_h_size_flags(SIZE_EXPAND_FILL);
hb->add_child(vb);
Control *ec = memnew(Control);
ec->set_custom_minimum_size(Size2(0, 1));
ec->set_mouse_filter(MOUSE_FILTER_PASS);
vb->add_child(ec);
- Label *title = memnew(Label(item.project_name));
+ Label *title = memnew(Label(!item.missing ? item.project_name : TTR("Missing Project")));
title->add_font_override("font", get_font("title", "EditorFonts"));
title->add_color_override("font_color", font_color);
title->set_clip_text(true);
@@ -1281,12 +1290,21 @@ void ProjectList::create_project_item_control(int p_index) {
vb->add_child(path_hb);
Button *show = memnew(Button);
- show->set_icon(get_icon("Load", "EditorIcons")); // Folder icon
+ // Display a folder icon if the project directory can be opened, or a "broken file" icon if it can't
+ show->set_icon(get_icon(!item.missing ? "Load" : "FileBroken", "EditorIcons"));
show->set_flat(true);
- show->set_modulate(Color(1, 1, 1, 0.5));
+ if (!item.grayed) {
+ // Don't make the icon less prominent if the parent is already grayed out
+ show->set_modulate(Color(1, 1, 1, 0.5));
+ }
path_hb->add_child(show);
- show->connect("pressed", this, "_show_project", varray(item.path));
- show->set_tooltip(TTR("Show in File Manager"));
+
+ if (!item.missing) {
+ show->connect("pressed", this, "_show_project", varray(item.path));
+ show->set_tooltip(TTR("Show in File Manager"));
+ } else {
+ show->set_tooltip(TTR("Error: Project is missing on the filesystem."));
+ }
Label *fpath = memnew(Label(item.path));
path_hb->add_child(fpath);
@@ -1296,6 +1314,7 @@ void ProjectList::create_project_item_control(int p_index) {
fpath->set_clip_text(true);
_scroll_children->add_child(hb);
+ OS::get_singleton()->global_menu_add_item("_dock", item.project_name + " ( " + item.path + " )", GLOBAL_OPEN_PROJECT, Variant(item.path.plus_file("project.godot")));
item.control = hb;
}
@@ -1303,12 +1322,6 @@ void ProjectList::set_search_term(String p_search_term) {
_search_term = p_search_term;
}
-void ProjectList::set_filter_option(ProjectListFilter::FilterOption p_option) {
- if (_filter_option != p_option) {
- _filter_option = p_option;
- }
-}
-
void ProjectList::set_order_option(ProjectListFilter::FilterOption p_option) {
if (_order_option != p_option) {
_order_option = p_option;
@@ -1328,11 +1341,18 @@ void ProjectList::sort_projects() {
bool visible = true;
if (_search_term != "") {
- if (_filter_option == ProjectListFilter::FILTER_PATH) {
- visible = item.path.findn(_search_term) != -1;
- } else if (_filter_option == ProjectListFilter::FILTER_NAME) {
- visible = item.project_name.findn(_search_term) != -1;
+
+ String search_path;
+ if (_search_term.find("/") != -1) {
+ // Search path will match the whole path
+ search_path = item.path;
+ } else {
+ // Search path will only match the last path component to make searching more strict
+ search_path = item.path.get_file();
}
+
+ // When searching, display projects whose name or path contain the search term
+ visible = item.project_name.findn(_search_term) != -1 || search_path.findn(_search_term) != -1;
}
item.control->set_visible(visible);
@@ -1694,7 +1714,6 @@ void ProjectList::_bind_methods() {
ClassDB::bind_method("_panel_input", &ProjectList::_panel_input);
ClassDB::bind_method("_favorite_pressed", &ProjectList::_favorite_pressed);
ClassDB::bind_method("_show_project", &ProjectList::_show_project);
- //ClassDB::bind_method("_unhandled_input", &ProjectList::_unhandled_input);
ADD_SIGNAL(MethodInfo(SIGNAL_SELECTION_CHANGED));
ADD_SIGNAL(MethodInfo(SIGNAL_PROJECT_ASK_OPEN));
@@ -1740,10 +1759,18 @@ void ProjectManager::_update_project_buttons() {
Vector<ProjectList::Item> selected_projects = _project_list->get_selected_projects();
bool empty_selection = selected_projects.empty();
+ bool is_missing_project_selected = false;
+ for (int i = 0; i < selected_projects.size(); ++i) {
+ if (selected_projects[i].missing) {
+ is_missing_project_selected = true;
+ break;
+ }
+ }
+
erase_btn->set_disabled(empty_selection);
- open_btn->set_disabled(empty_selection);
- rename_btn->set_disabled(empty_selection);
- run_btn->set_disabled(empty_selection);
+ open_btn->set_disabled(empty_selection || is_missing_project_selected);
+ rename_btn->set_disabled(empty_selection || is_missing_project_selected);
+ run_btn->set_disabled(empty_selection || is_missing_project_selected);
erase_missing_btn->set_visible(_project_list->is_any_project_missing());
}
@@ -1754,8 +1781,19 @@ void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) {
if (k.is_valid()) {
- if (!k->is_pressed())
+ if (!k->is_pressed()) {
return;
+ }
+
+ // Pressing Command + Q quits the Project Manager
+ // This is handled by the platform implementation on macOS,
+ // so only define the shortcut on other platforms
+#ifndef OSX_ENABLED
+ if (k->get_scancode_with_modifiers() == (KEY_MASK_CMD | KEY_Q)) {
+ _dim_window();
+ get_tree()->quit();
+ }
+#endif
if (tabs->get_current_tab() != 0)
return;
@@ -1794,7 +1832,7 @@ void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) {
break;
int index = _project_list->get_single_selected_index();
- if (index - 1 > 0) {
+ if (index > 0) {
_project_list->select_project(index - 1);
_project_list->ensure_project_visible(index - 1);
_update_project_buttons();
@@ -1834,7 +1872,6 @@ void ProjectManager::_unhandled_input(const Ref<InputEvent> &p_ev) {
void ProjectManager::_load_recent_projects() {
- _project_list->set_filter_option(project_filter->get_filter_option());
_project_list->set_order_option(project_order_filter->get_filter_option());
_project_list->set_search_term(project_filter->get_search_term());
_project_list->load_projects();
@@ -1867,6 +1904,29 @@ void ProjectManager::_confirm_update_settings() {
_open_selected_projects();
}
+void ProjectManager::_global_menu_action(const Variant &p_id, const Variant &p_meta) {
+
+ int id = (int)p_id;
+ if (id == ProjectList::GLOBAL_NEW_WINDOW) {
+ List<String> args;
+ String exec = OS::get_singleton()->get_executable_path();
+
+ OS::ProcessID pid = 0;
+ OS::get_singleton()->execute(exec, args, false, &pid);
+ } else if (id == ProjectList::GLOBAL_OPEN_PROJECT) {
+ String conf = (String)p_meta;
+
+ if (conf != String()) {
+ List<String> args;
+ args.push_back(conf);
+ String exec = OS::get_singleton()->get_executable_path();
+
+ OS::ProcessID pid = 0;
+ OS::get_singleton()->execute(exec, args, false, &pid);
+ }
+ }
+}
+
void ProjectManager::_open_selected_projects() {
const Set<String> &selected_list = _project_list->get_selected_project_keys();
@@ -1921,6 +1981,9 @@ void ProjectManager::_open_selected_projects_ask() {
}
ProjectList::Item project = _project_list->get_selected_projects()[0];
+ if (project.missing) {
+ return;
+ }
// Update the project settings or don't open
String conf = project.path.plus_file("project.godot");
@@ -2103,7 +2166,7 @@ void ProjectManager::_erase_project() {
void ProjectManager::_erase_missing_projects() {
- erase_missing_ask->set_text(TTR("Remove all missing projects from the list? (Folders contents will not be modified)"));
+ erase_missing_ask->set_text(TTR("Remove all missing projects from the list?\nThe project folders' contents won't be modified."));
erase_missing_ask->popup_centered_minsize();
}
@@ -2198,7 +2261,6 @@ void ProjectManager::_on_order_option_changed() {
}
void ProjectManager::_on_filter_option_changed() {
- _project_list->set_filter_option(project_filter->get_filter_option());
_project_list->set_search_term(project_filter->get_search_term());
_project_list->sort_projects();
}
@@ -2207,6 +2269,7 @@ void ProjectManager::_bind_methods() {
ClassDB::bind_method("_open_selected_projects_ask", &ProjectManager::_open_selected_projects_ask);
ClassDB::bind_method("_open_selected_projects", &ProjectManager::_open_selected_projects);
+ ClassDB::bind_method(D_METHOD("_global_menu_action"), &ProjectManager::_global_menu_action, DEFVAL(Variant()));
ClassDB::bind_method("_run_project", &ProjectManager::_run_project);
ClassDB::bind_method("_run_project_confirm", &ProjectManager::_run_project_confirm);
ClassDB::bind_method("_scan_projects", &ProjectManager::_scan_projects);
@@ -2270,6 +2333,9 @@ ProjectManager::ProjectManager() {
} break;
}
+ // Define a minimum window size to prevent UI elements from overlapping or being cut off
+ OS::get_singleton()->set_min_window_size(Size2(750, 420) * EDSCALE);
+
#ifndef OSX_ENABLED
// The macOS platform implementation uses its own hiDPI window resizing code
// TODO: Resize windows on hiDPI displays on Windows and Linux and remove the line below
@@ -2295,26 +2361,11 @@ ProjectManager::ProjectManager() {
VBoxContainer *vb = memnew(VBoxContainer);
panel->add_child(vb);
vb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 8 * EDSCALE);
- vb->add_constant_override("separation", 8 * EDSCALE);
String cp;
cp += 0xA9;
OS::get_singleton()->set_window_title(VERSION_NAME + String(" - ") + TTR("Project Manager") + " - " + cp + " 2007-2019 Juan Linietsky, Ariel Manzur & Godot Contributors");
- HBoxContainer *top_hb = memnew(HBoxContainer);
- vb->add_child(top_hb);
- Label *l = memnew(Label);
- l->set_text(VERSION_NAME + String(" - ") + TTR("Project Manager"));
- top_hb->add_child(l);
- top_hb->add_spacer();
- l = memnew(Label);
- String hash = String(VERSION_HASH);
- if (hash.length() != 0)
- hash = "." + hash.left(9);
- l->set_text("v" VERSION_FULL_BUILD "" + hash);
- l->set_align(Label::ALIGN_CENTER);
- top_hb->add_child(l);
-
Control *center_box = memnew(Control);
center_box->set_v_size_flags(SIZE_EXPAND_FILL);
vb->add_child(center_box);
@@ -2322,11 +2373,12 @@ ProjectManager::ProjectManager() {
tabs = memnew(TabContainer);
center_box->add_child(tabs);
tabs->set_anchors_and_margins_preset(Control::PRESET_WIDE);
+ tabs->set_tab_align(TabContainer::ALIGN_LEFT);
HBoxContainer *tree_hb = memnew(HBoxContainer);
projects_hb = tree_hb;
- projects_hb->set_name(TTR("Project List"));
+ projects_hb->set_name(TTR("Projects"));
tabs->add_child(tree_hb);
@@ -2343,6 +2395,7 @@ ProjectManager::ProjectManager() {
sort_filter_titles.push_back("Path");
sort_filter_titles.push_back("Last Modified");
project_order_filter = memnew(ProjectListFilter);
+ project_order_filter->add_filter_option();
project_order_filter->_setup_filters(sort_filter_titles);
project_order_filter->set_filter_size(150);
sort_filters->add_child(project_order_filter);
@@ -2353,21 +2406,12 @@ ProjectManager::ProjectManager() {
project_order_filter->set_filter_option((ProjectListFilter::FilterOption)projects_sorting_order);
sort_filters->add_spacer(true);
- Label *search_label = memnew(Label);
- search_label->set_text(TTR("Search:"));
- sort_filters->add_child(search_label);
-
- HBoxContainer *search_filters = memnew(HBoxContainer);
- Vector<String> vec2;
- vec2.push_back("Name");
- vec2.push_back("Path");
+
project_filter = memnew(ProjectListFilter);
- project_filter->_setup_filters(vec2);
project_filter->add_search_box();
- search_filters->add_child(project_filter);
project_filter->connect("filter_changed", this, "_on_filter_option_changed");
project_filter->set_custom_minimum_size(Size2(280, 10) * EDSCALE);
- sort_filters->add_child(search_filters);
+ sort_filters->add_child(project_filter);
search_tree_vb->add_child(sort_filters);
@@ -2457,6 +2501,17 @@ ProjectManager::ProjectManager() {
settings_hb->set_alignment(BoxContainer::ALIGN_END);
settings_hb->set_h_grow_direction(Control::GROW_DIRECTION_BEGIN);
+ Label *version_label = memnew(Label);
+ String hash = String(VERSION_HASH);
+ if (hash.length() != 0) {
+ hash = "." + hash.left(9);
+ }
+ version_label->set_text("v" VERSION_FULL_BUILD "" + hash);
+ // Fade out the version label to be less prominent, but still readable
+ version_label->set_self_modulate(Color(1, 1, 1, 0.6));
+ version_label->set_align(Label::ALIGN_CENTER);
+ settings_hb->add_child(version_label);
+
language_btn = memnew(OptionButton);
language_btn->set_flat(true);
language_btn->set_focus_mode(Control::FOCUS_NONE);
@@ -2489,27 +2544,6 @@ ProjectManager::ProjectManager() {
center_box->add_child(settings_hb);
settings_hb->set_anchors_and_margins_preset(Control::PRESET_TOP_RIGHT);
- CenterContainer *cc = memnew(CenterContainer);
- Button *cancel = memnew(Button);
- cancel->set_text(TTR("Exit"));
- cancel->set_custom_minimum_size(Size2(100, 1) * EDSCALE);
-
-#ifndef OSX_ENABLED
- // Pressing Command + Q quits the Project Manager
- // This is handled by the platform implementation on macOS,
- // so only define the shortcut on other platforms
- InputEventKey *quit_key = memnew(InputEventKey);
- quit_key->set_command(true);
- quit_key->set_scancode(KEY_Q);
- ShortCut *quit_shortcut = memnew(ShortCut);
- quit_shortcut->set_shortcut(quit_key);
- cancel->set_shortcut(quit_shortcut);
-#endif
-
- cc->add_child(cancel);
- cancel->connect("pressed", this, "_exit_dialog");
- vb->add_child(cc);
-
//////////////////////////////////////////////////////////////
language_restart_ask = memnew(ConfirmationDialog);
@@ -2561,6 +2595,7 @@ ProjectManager::ProjectManager() {
}
SceneTree::get_singleton()->connect("files_dropped", this, "_files_dropped");
+ SceneTree::get_singleton()->connect("global_menu_action", this, "_global_menu_action");
run_error_diag = memnew(AcceptDialog);
gui_base->add_child(run_error_diag);
@@ -2630,11 +2665,20 @@ void ProjectListFilter::_bind_methods() {
ADD_SIGNAL(MethodInfo("filter_changed"));
}
+void ProjectListFilter::add_filter_option() {
+ filter_option = memnew(OptionButton);
+ filter_option->set_clip_text(true);
+ filter_option->connect("item_selected", this, "_filter_option_selected");
+ add_child(filter_option);
+}
+
void ProjectListFilter::add_search_box() {
search_box = memnew(LineEdit);
+ search_box->set_placeholder(TTR("Search"));
search_box->connect("text_changed", this, "_search_text_changed");
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(search_box);
+
has_search_box = true;
}
@@ -2645,13 +2689,6 @@ void ProjectListFilter::set_filter_size(int h_size) {
ProjectListFilter::ProjectListFilter() {
_current_filter = FILTER_NAME;
-
- filter_option = memnew(OptionButton);
- set_filter_size(80);
- filter_option->set_clip_text(true);
- filter_option->connect("item_selected", this, "_filter_option_selected");
- add_child(filter_option);
-
has_search_box = false;
}
diff --git a/editor/project_manager.h b/editor/project_manager.h
index 4ccb99d6bd..cf0b8b8801 100644
--- a/editor/project_manager.h
+++ b/editor/project_manager.h
@@ -43,6 +43,7 @@ class ProjectList;
class ProjectListFilter;
class ProjectManager : public Control {
+
GDCLASS(ProjectManager, Control);
Button *erase_btn;
@@ -96,6 +97,7 @@ class ProjectManager : public Control {
void _restart_confirm();
void _exit_dialog();
void _scan_begin(const String &p_base);
+ void _global_menu_action(const Variant &p_id, const Variant &p_meta);
void _confirm_update_settings();
@@ -152,6 +154,7 @@ protected:
public:
void _setup_filters(Vector<String> options);
+ void add_filter_option();
void add_search_box();
void set_filter_size(int h_size);
String get_search_term();
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 032b3a19a6..f0114b393d 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -986,9 +986,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} else {
new_node = Object::cast_to<Node>(ClassDB::instance(selected_favorite_root));
}
+
if (!new_node) {
- ERR_EXPLAIN("Creating root from favorite '" + selected_favorite_root + "' failed. Creating 'Node' instead.");
new_node = memnew(Node);
+ ERR_PRINTS("Creating root from favorite '" + selected_favorite_root + "' failed. Creating 'Node' instead.");
}
} else {
switch (p_tool) {
@@ -1537,10 +1538,7 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V
Node *validate = new_parent;
while (validate) {
- if (p_nodes.find(validate) != -1) {
- ERR_EXPLAIN("Selection changed at some point.. can't reparent");
- ERR_FAIL();
- }
+ ERR_FAIL_COND_MSG(p_nodes.find(validate) != -1, "Selection changed at some point.. can't reparent.");
validate = validate->get_parent();
}
//ok all valid
@@ -2253,8 +2251,7 @@ void SceneTreeDock::_normalize_drop(Node *&to_node, int &to_pos, int p_type) {
//drop at above selected node
if (to_node == EditorNode::get_singleton()->get_edited_scene()) {
to_node = NULL;
- ERR_EXPLAIN("Cannot perform drop above the root node!");
- ERR_FAIL();
+ ERR_FAIL_MSG("Cannot perform drop above the root node!");
}
to_pos = to_node->get_index();
@@ -2712,6 +2709,7 @@ void SceneTreeDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_feature_profile_changed"), &SceneTreeDock::_feature_profile_changed);
ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance);
+ ClassDB::bind_method(D_METHOD("get_tree_editor"), &SceneTreeDock::get_tree_editor);
ClassDB::bind_method(D_METHOD("replace_node"), &SceneTreeDock::replace_node);
ADD_SIGNAL(MethodInfo("remote_tree_selected"));
diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp
index 2d9accc3d8..43f540e688 100644
--- a/editor/scene_tree_editor.cpp
+++ b/editor/scene_tree_editor.cpp
@@ -270,15 +270,30 @@ bool SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
item->add_button(0, get_icon("NodeWarning", "EditorIcons"), BUTTON_WARNING, false, TTR("Node configuration warning:") + "\n" + p_node->get_configuration_warning());
}
- bool has_connections = p_node->has_persistent_signal_connections();
- bool has_groups = p_node->has_persistent_groups();
-
- if (has_connections && has_groups) {
- item->add_button(0, get_icon("SignalsAndGroups", "EditorIcons"), BUTTON_SIGNALS, false, TTR("Node has connection(s) and group(s).\nClick to show signals dock."));
- } else if (has_connections) {
- item->add_button(0, get_icon("Signals", "EditorIcons"), BUTTON_SIGNALS, false, TTR("Node has connections.\nClick to show signals dock."));
- } else if (has_groups) {
- item->add_button(0, get_icon("Groups", "EditorIcons"), BUTTON_GROUPS, false, TTR("Node is in group(s).\nClick to show groups dock."));
+ int num_connections = p_node->get_persistent_signal_connection_count();
+ int num_groups = p_node->get_persistent_group_count();
+
+ if (num_connections >= 1 && num_groups >= 1) {
+ item->add_button(
+ 0,
+ get_icon("SignalsAndGroups", "EditorIcons"),
+ BUTTON_SIGNALS,
+ false,
+ vformat(TTR("Node has %s connection(s) and %s group(s).\nClick to show signals dock."), num_connections, num_groups));
+ } else if (num_connections >= 1) {
+ item->add_button(
+ 0,
+ get_icon("Signals", "EditorIcons"),
+ BUTTON_SIGNALS,
+ false,
+ vformat(TTR("Node has %s connection(s).\nClick to show signals dock."), num_connections));
+ } else if (num_groups >= 1) {
+ item->add_button(
+ 0,
+ get_icon("Groups", "EditorIcons"),
+ BUTTON_GROUPS,
+ false,
+ vformat(TTR("Node is in %s group(s).\nClick to show groups dock."), num_groups));
}
}
@@ -995,6 +1010,17 @@ bool SceneTreeEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_d
return true;
}
+ if (String(d["type"]) == "script_list_element") {
+ ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(d["script_list_element"]);
+ if (se) {
+ String sp = se->get_edited_resource()->get_path();
+ if (_is_script_type(EditorFileSystem::get_singleton()->get_file_type(sp))) {
+ tree->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM);
+ return true;
+ }
+ }
+ }
+
return String(d["type"]) == "nodes";
}
void SceneTreeEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
@@ -1032,6 +1058,16 @@ void SceneTreeEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data,
emit_signal("files_dropped", files, np, section);
}
}
+
+ if (String(d["type"]) == "script_list_element") {
+ ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(d["script_list_element"]);
+ if (se) {
+ String sp = se->get_edited_resource()->get_path();
+ if (_is_script_type(EditorFileSystem::get_singleton()->get_file_type(sp))) {
+ emit_signal("script_dropped", sp, np);
+ }
+ }
+ }
}
void SceneTreeEditor::_rmb_select(const Vector2 &p_pos) {
diff --git a/editor/script_create_dialog.cpp b/editor/script_create_dialog.cpp
index 7d0f40fe91..ffb3f5feab 100644
--- a/editor/script_create_dialog.cpp
+++ b/editor/script_create_dialog.cpp
@@ -34,6 +34,7 @@
#include "core/os/file_access.h"
#include "core/project_settings.h"
#include "core/script_language.h"
+#include "core/string_builder.h"
#include "editor/create_dialog.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
@@ -238,16 +239,22 @@ void ScriptCreateDialog::_parent_name_changed(const String &p_parent) {
void ScriptCreateDialog::_template_changed(int p_template) {
- String selected_template = p_template == 0 ? "" : template_menu->get_item_text(template_menu->get_selected());
+ String selected_template = p_template == 0 ? "" : template_menu->get_item_text(p_template);
EditorSettings::get_singleton()->set_project_metadata("script_setup", "last_selected_template", selected_template);
if (p_template == 0) {
//default
script_template = "";
return;
}
- String ext = ScriptServer::get_language(language_menu->get_selected())->get_extension();
- String name = template_list[p_template - 1] + "." + ext;
- script_template = EditorSettings::get_singleton()->get_script_templates_dir().plus_file(name);
+ int selected_id = template_menu->get_selected_id();
+
+ for (int i = 0; i < template_list.size(); i++) {
+ const ScriptTemplateInfo &sinfo = template_list[i];
+ if (sinfo.id == selected_id) {
+ script_template = sinfo.dir.plus_file(sinfo.name + "." + sinfo.extension);
+ break;
+ }
+ }
}
void ScriptCreateDialog::ok_pressed() {
@@ -368,23 +375,77 @@ void ScriptCreateDialog::_lang_changed(int l) {
bool use_templates = language->is_using_templates();
template_menu->set_disabled(!use_templates);
template_menu->clear();
- if (use_templates) {
- template_list = EditorSettings::get_singleton()->get_script_templates(language->get_extension());
+ if (use_templates) {
+ _update_script_templates(language->get_extension());
String last_lang = EditorSettings::get_singleton()->get_project_metadata("script_setup", "last_selected_language", "");
String last_template = EditorSettings::get_singleton()->get_project_metadata("script_setup", "last_selected_template", "");
template_menu->add_item(TTR("Default"));
+
+ ScriptTemplateInfo *templates = template_list.ptrw();
+
+ Vector<String> origin_names;
+ origin_names.push_back(TTR("Project"));
+ origin_names.push_back(TTR("Editor"));
+ int cur_origin = -1;
+
+ // Populate script template items previously sorted and now grouped by origin
for (int i = 0; i < template_list.size(); i++) {
- String s = template_list[i].capitalize();
- template_menu->add_item(s);
- if (language_menu->get_item_text(language_menu->get_selected()) == last_lang && last_template == s) {
- template_menu->select(i + 1);
+
+ if (int(templates[i].origin) != cur_origin) {
+ template_menu->add_separator();
+
+ String origin_name = origin_names[templates[i].origin];
+
+ int last_index = template_menu->get_item_count() - 1;
+ template_menu->set_item_text(last_index, origin_name);
+
+ cur_origin = templates[i].origin;
}
+ String item_name = templates[i].name.capitalize();
+ template_menu->add_item(item_name);
+
+ int new_id = template_menu->get_item_count() - 1;
+ templates[i].id = new_id;
}
- } else {
+ // Disable overridden
+ for (Map<String, Vector<int> >::Element *E = template_overrides.front(); E; E = E->next()) {
+ const Vector<int> &overrides = E->get();
+
+ if (overrides.size() == 1) {
+ continue; // doesn't override anything
+ }
+ const ScriptTemplateInfo &extended = template_list[overrides[0]];
+
+ StringBuilder override_info;
+ override_info += TTR("Overrides");
+ override_info += ": ";
+
+ for (int i = 1; i < overrides.size(); i++) {
+ const ScriptTemplateInfo &overridden = template_list[overrides[i]];
+
+ int disable_index = template_menu->get_item_index(overridden.id);
+ template_menu->set_item_disabled(disable_index, true);
+ override_info += origin_names[overridden.origin];
+ if (i < overrides.size() - 1) {
+ override_info += ", ";
+ }
+ }
+ template_menu->set_item_icon(extended.id, get_icon("Override", "EditorIcons"));
+ template_menu->get_popup()->set_item_tooltip(extended.id, override_info.as_string());
+ }
+ // Reselect last selected template
+ for (int i = 0; i < template_menu->get_item_count(); i++) {
+ const String &ti = template_menu->get_item_text(i);
+ if (language_menu->get_item_text(language_menu->get_selected()) == last_lang && last_template == ti) {
+ template_menu->select(i);
+ break;
+ }
+ }
+ } else {
template_menu->add_item(TTR("N/A"));
script_template = "";
}
@@ -396,6 +457,41 @@ void ScriptCreateDialog::_lang_changed(int l) {
_update_dialog();
}
+void ScriptCreateDialog::_update_script_templates(const String &p_extension) {
+
+ template_list.clear();
+ template_overrides.clear();
+
+ Vector<String> dirs;
+
+ // Ordered from local to global for correct override mechanism
+ dirs.push_back(EditorSettings::get_singleton()->get_project_script_templates_dir());
+ dirs.push_back(EditorSettings::get_singleton()->get_script_templates_dir());
+
+ for (int i = 0; i < dirs.size(); i++) {
+
+ Vector<String> list = EditorSettings::get_singleton()->get_script_templates(p_extension, dirs[i]);
+
+ for (int j = 0; j < list.size(); j++) {
+ ScriptTemplateInfo sinfo;
+ sinfo.origin = ScriptOrigin(i);
+ sinfo.dir = dirs[i];
+ sinfo.name = list[j];
+ sinfo.extension = p_extension;
+ template_list.push_back(sinfo);
+
+ if (!template_overrides.has(sinfo.name)) {
+ Vector<int> overrides;
+ overrides.push_back(template_list.size() - 1); // first one
+ template_overrides.insert(sinfo.name, overrides);
+ } else {
+ Vector<int> &overrides = template_overrides[sinfo.name];
+ overrides.push_back(template_list.size() - 1);
+ }
+ }
+ }
+}
+
void ScriptCreateDialog::_built_in_pressed() {
if (internal->is_pressed()) {
diff --git a/editor/script_create_dialog.h b/editor/script_create_dialog.h
index 202846fd3c..31cf2478cf 100644
--- a/editor/script_create_dialog.h
+++ b/editor/script_create_dialog.h
@@ -78,8 +78,25 @@ class ScriptCreateDialog : public ConfirmationDialog {
int current_language;
int default_language;
bool re_check_path;
+
+ enum ScriptOrigin {
+ SCRIPT_ORIGIN_PROJECT,
+ SCRIPT_ORIGIN_EDITOR,
+ };
+ struct ScriptTemplateInfo {
+ int id;
+ ScriptOrigin origin;
+ String dir;
+ String name;
+ String extension;
+ };
+
String script_template;
- Vector<String> template_list;
+ Vector<ScriptTemplateInfo> template_list;
+ Map<String, Vector<int> > template_overrides; // name : indices
+
+ void _update_script_templates(const String &p_extension);
+
String base_type;
void _path_hbox_sorted();
diff --git a/editor/script_editor_debugger.cpp b/editor/script_editor_debugger.cpp
index f7ff754a0b..fc5aecdbe9 100644
--- a/editor/script_editor_debugger.cpp
+++ b/editor/script_editor_debugger.cpp
@@ -1376,7 +1376,7 @@ void ScriptEditorDebugger::stop() {
profiler->set_enabled(true);
inspect_scene_tree->clear();
- inspector->edit(NULL);
+ EditorNode::get_singleton()->edit_current();
EditorNode::get_singleton()->get_pause_button()->set_pressed(false);
EditorNode::get_singleton()->get_pause_button()->set_disabled(true);
EditorNode::get_singleton()->get_scene_tree_dock()->hide_remote_tree();
diff --git a/editor/spatial_editor_gizmos.cpp b/editor/spatial_editor_gizmos.cpp
index f7ba5e5e3c..4c5371769f 100644
--- a/editor/spatial_editor_gizmos.cpp
+++ b/editor/spatial_editor_gizmos.cpp
@@ -2037,8 +2037,11 @@ PortalSpatialGizmo::PortalSpatialGizmo(Portal *p_portal) {
RayCastSpatialGizmoPlugin::RayCastSpatialGizmoPlugin() {
- Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
+ const Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
create_material("shape_material", gizmo_color);
+ const float gizmo_value = gizmo_color.get_v();
+ const Color gizmo_color_disabled = Color(gizmo_value, gizmo_value, gizmo_value, 0.65);
+ create_material("shape_material_disabled", gizmo_color_disabled);
}
bool RayCastSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
@@ -2064,7 +2067,8 @@ void RayCastSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
lines.push_back(Vector3());
lines.push_back(raycast->get_cast_to());
- Ref<SpatialMaterial> material = get_material("shape_material", p_gizmo);
+ const Ref<SpatialMaterial> material =
+ get_material(raycast->is_enabled() ? "shape_material" : "shape_material_disabled", p_gizmo);
p_gizmo->add_lines(lines, material);
p_gizmo->add_collision_segments(lines);
@@ -3108,8 +3112,11 @@ void BakedIndirectLightGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
////
CollisionShapeSpatialGizmoPlugin::CollisionShapeSpatialGizmoPlugin() {
- Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
+ const Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
create_material("shape_material", gizmo_color);
+ const float gizmo_value = gizmo_color.get_v();
+ const Color gizmo_color_disabled = Color(gizmo_value, gizmo_value, gizmo_value, 0.65);
+ create_material("shape_material_disabled", gizmo_color_disabled);
create_handle_material("handles");
}
@@ -3432,7 +3439,8 @@ void CollisionShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
if (s.is_null())
return;
- Ref<Material> material = get_material("shape_material", p_gizmo);
+ const Ref<Material> material =
+ get_material(!cs->is_disabled() ? "shape_material" : "shape_material_disabled", p_gizmo);
Ref<Material> handles_material = get_material("handles");
if (Object::cast_to<SphereShape>(*s)) {
@@ -3733,8 +3741,11 @@ void CollisionShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
/////
CollisionPolygonSpatialGizmoPlugin::CollisionPolygonSpatialGizmoPlugin() {
- Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
+ const Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/shape", Color(0.5, 0.7, 1));
create_material("shape_material", gizmo_color);
+ const float gizmo_value = gizmo_color.get_v();
+ const Color gizmo_color_disabled = Color(gizmo_value, gizmo_value, gizmo_value, 0.65);
+ create_material("shape_material_disabled", gizmo_color_disabled);
}
bool CollisionPolygonSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
@@ -3770,7 +3781,8 @@ void CollisionPolygonSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
lines.push_back(Vector3(points[i].x, points[i].y, -depth));
}
- Ref<Material> material = get_material("shape_material", p_gizmo);
+ const Ref<Material> material =
+ get_material(!polygon->is_disabled() ? "shape_material" : "shape_material_disabled", p_gizmo);
p_gizmo->add_lines(lines, material);
p_gizmo->add_collision_segments(lines);
diff --git a/main/gamecontrollerdb.txt b/main/gamecontrollerdb.txt
index 440c0a8621..0e30cfe8d0 100644
--- a/main/gamecontrollerdb.txt
+++ b/main/gamecontrollerdb.txt
@@ -9,6 +9,7 @@
03000000c82d00000060000000000000,8Bitdo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,
03000000c82d00000061000000000000,8Bitdo SF30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,platform:Windows,
03000000102800000900000000000000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Windows,
+03000000c82d00003028000000000000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Windows,
03000000a00500003232000000000000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Windows,
030000008f0e00001200000000000000,Acme GA-02,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Windows,
03000000fa190000f0ff000000000000,Acteck AGJ-3200,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
@@ -26,6 +27,7 @@
03000000bc2000006012000000000000,Betop 2126F,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000bc2000000055000000000000,Betop BFM Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,
03000000bc2000006312000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
+03000000bc2000006321000000000000,BETOP CONTROLLER,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000bc2000006412000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000c01100000555000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000c01100000655000000000000,Betop Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
@@ -38,6 +40,8 @@
03000000e82000006058000000000000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
030000005e0400008e02000000000000,Controller (XBOX 360 For Windows),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
030000005e040000a102000000000000,Controller (Xbox 360 Wireless Receiver for Windows),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
+030000005e040000ff02000000000000,Controller (Xbox One For Windows) - Wired,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
+030000005e040000ea02000000000000,Controller (Xbox One For Windows) - Wireless,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
03000000260900008888000000000000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a4,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,platform:Windows,
03000000a306000022f6000000000000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,
03000000451300000830000000000000,Defender Game Racer X7,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
@@ -64,6 +68,7 @@
03000000ac0500003d03000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,
03000000ac0500004d04000000000000,GameSir,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,
03000000ffff00000000000000000000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
+030000006f0e00000102000000007801,GameStop Xbox 360 Wired Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
030000008305000009a0000000000000,Genius,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
030000008305000031b0000000000000,Genius Maxfire Blaze 3,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
03000000451300000010000000000000,Genius Maxfire Grandias 12,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
@@ -73,6 +78,7 @@
03000000f025000021c1000000000000,Gioteck PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000f0250000c383000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000f0250000c483000000000000,Gioteck VX2 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
+030000007d0400000540000000000000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,
03000000341a00000302000000000000,Hama Scorpad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f00004900000000000000,Hatsune Miku Sho Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
03000000d81400000862000000000000,HitBox Edition Cthulhu+,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b5,lefttrigger:b4,rightshoulder:b7,righttrigger:b6,start:b9,x:b0,y:b3,platform:Windows,
@@ -83,6 +89,7 @@
030000000d0f00005400000000000000,Hori Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f00000900000000000000,Hori Pad 3 Turbo,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f00004d00000000000000,Hori Pad A,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
+030000000d0f00009200000000000000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f0000c100000000000000,Horipad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f00006e00000000000000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
030000000d0f00006600000000000000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Windows,
@@ -96,11 +103,14 @@
030000006f0e00002401000000000000,INJUSTICE FightStick PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,
03000000ac0500002c02000000000000,IPEGA,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b13,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b14,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,
03000000491900000204000000000000,Ipega PG-9023,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b3,y:b4,platform:Windows,
+03000000491900000304000000000000,Ipega PG-9087 - Bluetooth Gamepad,+righty:+a5,-righty:-a4,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,start:b11,x:b3,y:b4,platform:Windows,
030000006e0500000a20000000000000,JC-DUX60 ELECOM MMO Gamepad,a:b2,b:b3,back:b17,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b8,leftstick:b14,lefttrigger:b12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b15,righttrigger:b13,rightx:a3,righty:a4,start:b20,x:b0,y:b1,platform:Windows,
030000006e0500000520000000000000,JC-P301U,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Windows,
030000006e0500000320000000000000,JC-U3613M (DInput),a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Windows,
030000006e0500000720000000000000,JC-W01U,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b1,platform:Windows,
+030000007e0500000620000000000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Windows,
030000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Windows,
+030000007e0500000720000000000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Windows,
030000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Windows,
03000000bd12000003c0000000000000,JY-P70UR,a:b1,b:b0,back:b5,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b7,leftx:a0,lefty:a1,rightshoulder:b8,rightstick:b11,righttrigger:b9,rightx:a3,righty:a2,start:b4,x:b3,y:b2,platform:Windows,
03000000790000000200000000000000,King PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b3,y:b0,platform:Windows,
@@ -139,7 +149,7 @@
03000000bd12000015d0000000000000,Nintendo Retrolink USB Super SNES Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a0,lefty:a1,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Windows,
030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
030000000d0500000308000000000000,Nostromo N45,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,platform:Windows,
-03000000550900001472000000000000,NVIDIA Controller v01.04,a:b11,b:b10,x:b9,y:b8,back:b13,guide:b12,start:b3,leftstick:b5,rightstick:b4,leftshoulder:b7,rightshoulder:b6,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a3,righty:a6,lefttrigger:a4,righttrigger:a5,platform:Windows,
+03000000550900001472000000000000,NVIDIA Controller v01.04,a:b11,b:b10,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b7,leftstick:b5,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b4,righttrigger:a5,rightx:a3,righty:a6,start:b3,x:b9,y:b8,platform:Windows,
030000004b120000014d000000000000,NYKO AIRFLO,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:a3,leftstick:a0,lefttrigger:b6,rightshoulder:b5,rightstick:a2,righttrigger:b7,start:b9,x:b2,y:b3,platform:Windows,
03000000782300000a10000000000000,Onlive Wireless Controller,a:b15,b:b14,back:b7,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b5,leftshoulder:b11,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b13,y:b12,platform:Windows,
03000000d62000006d57000000000000,OPP PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
@@ -147,6 +157,7 @@
03000000362800000100000000000000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a3,righty:a4,x:b1,y:b2,platform:Windows,
03000000120c0000f60e000000000000,P4 Wired Gamepad,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b7,rightshoulder:b4,righttrigger:b6,start:b9,x:b0,y:b3,platform:Windows,
030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Windows,
+030000004c050000da0c000000000000,PlayStation Classic Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,lefttrigger:b4,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Windows,
03000000d62000006dca000000000000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
03000000d62000009557000000000000,Pro Elite PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
03000000d62000009f31000000000000,Pro Ex mini PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
@@ -201,6 +212,7 @@
03000000a30600001af5000000000000,Saitek Cyborg,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b0,y:b3,platform:Windows,
03000000a306000023f6000000000000,Saitek Cyborg V.1 Game pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Windows,
03000000300f00001201000000000000,Saitek Dual Analog Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,
+03000000a30600000701000000000000,Saitek P220,a:b2,b:b3,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b5,x:b0,y:b1,platform:Windows,
03000000a30600000cff000000000000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,x:b0,y:b1,platform:Windows,
03000000a30600000c04000000000000,Saitek P2900,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b3,platform:Windows,
03000000300f00001001000000000000,Saitek P480 Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,
@@ -211,6 +223,7 @@
03000000300f00001101000000000000,Saitek Rumble Pad,a:b2,b:b3,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Windows,
0300000000050000289b000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,platform:Windows,
030000009b2800000500000000000000,Saturn_Adapter_2.0,a:b1,b:b2,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b0,y:b3,platform:Windows,
+030000005e0400008e02000000007801,ShanWan PS3/PC Wired GamePad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
03000000341a00000208000000000000,SL-6555-SBK,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:-a4,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a3,righty:a2,start:b7,x:b2,y:b3,platform:Windows,
03000000341a00000908000000000000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
030000008f0e00000800000000000000,SpeedLink Strike FX,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
@@ -244,6 +257,7 @@
03000000ff1100004133000000000000,USB gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a4,righty:a2,start:b9,x:b3,y:b0,platform:Windows,
03000000632500002305000000000000,USB Vibration Joystick (BM),a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Windows,
03000000790000001b18000000000000,Venom Arcade Joystick,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Windows,
+030000005e0400000a0b000000000000,Xbox Adaptive Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:+a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:-a2,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Windows,
03000000341a00000608000000000000,Xeox,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
03000000450c00002043000000000000,XEOX Gamepad SL-6556-BK,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Windows,
03000000172700004431000000000000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a7,rightx:a2,righty:a5,start:b11,x:b3,y:b4,platform:Windows,
@@ -259,18 +273,21 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
03000000102800000900000000000000,8Bitdo SFC30 GamePad Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Mac OS X,
03000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Mac OS X,
03000000a00500003232000009010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Mac OS X,
-03000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,x:b2,y:b3,back:b10,start:b9,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Mac OS X,
+03000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,
030000008305000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
03000000260900008888000088020000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,platform:Mac OS X,
03000000a306000022f6000001030000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,platform:Mac OS X,
03000000790000000600000000000000,G-Shark GP-702,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,platform:Mac OS X,
03000000ad1b000001f9000000000000,Gamestop BB-070 X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,
+030000006f0e00000102000000000000,GameStop Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
+030000007d0400000540000001010000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00005f00000000010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00005e00000000010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00005f00000000000000,HORI Fighting Commander 4 PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00005e00000000000000,HORI Fighting Commander 4 PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00004d00000000000000,HORI Gem Pad 3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
+030000000d0f00009200000000010000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00006e00000000010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00006600000000010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
030000000d0f00006600000000000000,HORIPAD FPS PLUS 4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
@@ -296,9 +313,10 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
0300000025090000e803000000000000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:b13,dpleft:b12,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Mac OS X,
03000000790000000018000000000000,Mayflash WiiU Pro Game Controller Adapter (DInput),a:b4,b:b8,back:b32,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b16,leftstick:b40,lefttrigger:b24,leftx:a0,lefty:a4,rightshoulder:b20,rightstick:b44,righttrigger:b28,rightx:a8,righty:a12,start:b36,x:b0,y:b12,platform:Mac OS X,
03000000d8140000cecf000000000000,MC Cthulhu,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Mac OS X,
-03000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,x:b2,y:b3,back:b9,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Mac OS X,
+03000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Mac OS X,
030000001008000001e5000006010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,platform:Mac OS X,
030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,
+030000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Mac OS X,
030000008f0e00000300000000000000,Piranha xtreme,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Mac OS X,
03000000d62000006dca000000010000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
030000004c0500006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,platform:Mac OS X,
@@ -311,8 +329,8 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
03000000321500000204000000010000,Razer Panthera (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Mac OS X,
03000000321500000104000000010000,Razer Panthera (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
03000000321500000010000000010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
-03000000321500000009000000020000,Razer Serval,a:b0,b:b1,x:b2,y:b3,back:b6,guide:b8,start:b7,leftstick:b9,rightstick:b10,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Mac OS X,
-030000003215000000090000163a0000,Razer Serval,a:b0,b:b1,x:b2,y:b3,back:b6,guide:b8,start:b7,leftstick:b9,rightstick:b10,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Mac OS X,
+03000000321500000009000000020000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Mac OS X,
+030000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Mac OS X,
0300000032150000030a000000000000,Razer Wildcat,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
03000000790000001100000000000000,Retrolink Classic Controller,a:b2,b:b1,back:b8,leftshoulder:b4,leftx:a3,lefty:a4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,
03000000790000001100000006010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,platform:Mac OS X,
@@ -321,6 +339,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
03000000811700007e05000000000000,Sega Saturn,a:b2,b:b4,dpdown:b16,dpleft:b15,dpright:b14,dpup:b17,leftshoulder:b8,lefttrigger:a5,leftx:a0,lefty:a2,rightshoulder:b9,righttrigger:a4,start:b13,x:b0,y:b6,platform:Mac OS X,
03000000b40400000a01000000000000,Sega Saturn USB Gamepad,a:b0,b:b1,back:b5,guide:b2,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b8,x:b3,y:b4,platform:Mac OS X,
030000003512000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,platform:Mac OS X,
+0300000000f00000f100000000000000,SNES RetroPort,a:b2,b:b3,back:b4,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b5,rightshoulder:b7,start:b6,x:b0,y:b1,platform:Mac OS X,
030000004c050000cc09000000000000,Sony DualShock 4 V2,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
030000004c050000a00b000000000000,Sony DualShock 4 Wireless Adaptor,a:b1,b:b2,back:b13,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
030000005e0400008e02000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
@@ -338,6 +357,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
050000005769696d6f74652028313800,Wii U Pro Controller,a:b16,b:b15,back:b7,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b8,leftshoulder:b19,leftstick:b23,lefttrigger:b21,leftx:a0,lefty:a1,rightshoulder:b20,rightstick:b24,righttrigger:b22,rightx:a2,righty:a3,start:b6,x:b18,y:b17,platform:Mac OS X,
030000005e0400008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
03000000c6240000045d000000000000,Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
+030000005e0400000a0b000000000000,Xbox Adaptive Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
030000005e040000d102000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
030000005e040000dd02000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
030000005e040000e302000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,platform:Mac OS X,
@@ -349,6 +369,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
03000000120c0000100e000000010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Mac OS X,
# Linux
+05000000c82d00001038000000010000,8Bitdo FC30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,
03000000022000000090000011010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,
05000000203800000900000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,
05000000c82d00002038000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,
@@ -360,9 +381,10 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
05000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,platform:Linux,
030000006f0e00001302000000010000,Afterglow,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
030000006f0e00003901000020060000,Afterglow Controller for Xbox One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
+030000006f0e00003901000013020000,Afterglow Prismatic Wired Controller 048-007-NA,a:b0,b:b1,x:b2,y:b3,back:b6,guide:b8,start:b7,leftstick:b9,rightstick:b10,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a3,righty:a4,lefttrigger:a2,righttrigger:a5,platform:Linux,
030000006f0e00003901000000430000,Afterglow Prismatic Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
03000000100000008200000011010000,Akishop Customs PS360+ v1.66,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,
-05000000491900000204000021000000,Amazon Fire Game Controller,a:b0,b:b1,x:b3,y:b4,back:b10,guide:b12,start:b11,leftstick:b13,rightstick:b14,leftshoulder:b6,rightshoulder:b7,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Linux,
+05000000491900000204000021000000,Amazon Fire Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,
05000000050b00000045000031000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,platform:Linux,
05000000050b00000045000040000000,ASUS Gamepad,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b6,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b10,x:b2,y:b3,platform:Linux,
03000000120c00000500000010010000,AxisPad,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,start:b11,x:b0,y:b1,platform:Linux,
@@ -381,6 +403,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
030000006f0e00001304000000010000,Generic X-Box pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:a0,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:a3,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
03000000f0250000c183000010010000,Goodbetterbest Ltd USB Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
0300000079000000d418000000010000,GPD Win 2 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
+030000007d0400000540000000010000,Gravis Eliminator GamePad Pro,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,
03000000280400000140000000010000,Gravis GamePad Pro USB ,a:b1,b:b2,back:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,
030000008f0e00000610000000010000,GreenAsia Electronics 4Axes 12Keys GamePad ,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b9,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b10,righttrigger:b5,rightx:a3,righty:a2,start:b11,x:b3,y:b0,platform:Linux,
030000008f0e00001200000010010000,GreenAsia Inc. USB Joystick,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Linux,
@@ -396,6 +419,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
030000000d0f00005f00000011010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
030000000d0f00005e00000011010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,
03000000ad1b000001f5000033050000,Hori Pad EX Turbo 2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
+030000000d0f00009200000011010000,Hori Pokken Tournament DX Pro Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,platform:Linux,
030000000d0f00006e00000011010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
030000000d0f00006600000011010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,
030000000d0f0000ee00000011010000,HORIPAD mini4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,
@@ -408,9 +432,12 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
0500000049190000020400001b010000,Ipega PG-9069 - Bluetooth Gamepad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b161,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,
030000006e0500000320000010010000,JC-U3613M - DirectInput Mode,a:b2,b:b3,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,start:b11,x:b0,y:b1,platform:Linux,
03000000300f00001001000010010000,Jess Tech Dual Analog Rumble Pad,a:b2,b:b3,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b0,y:b1,platform:Linux,
+03000000300f00000b01000010010000,Jess Tech GGE909 PC Recoil Pad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,
03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,platform:Linux,
030000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Linux,
+050000007e0500000620000001000000,Joy-Con (L),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b13,leftshoulder:b4,leftstick:b10,rightshoulder:b5,start:b8,x:b2,y:b3,platform:Linux,
030000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Linux,
+050000007e0500000720000001000000,Joy-Con (R),+leftx:h0.2,+lefty:h0.4,-leftx:h0.8,-lefty:h0.1,a:b0,b:b1,back:b12,leftshoulder:b4,leftstick:b11,rightshoulder:b5,start:b9,x:b2,y:b3,platform:Linux,
030000006f0e00000103000000020000,Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
030000006d04000016c2000010010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
@@ -439,6 +466,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
0300000079000000d218000011010000,MAGIC-NS,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
03000000120c00000500000000010000,Manta Dualshock 2,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b2,y:b3,platform:Linux,
03000000790000004418000010010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,platform:Linux,
+03000000790000004318000010010000,Mayflash GameCube Controller Adapter,a:b1,b:b0,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b2,y:b3,platform:Linux,
0300000025090000e803000001010000,Mayflash Wii Classic Controller,a:b1,b:b0,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:a4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:a5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,platform:Linux,
03000000780000000600000010010000,Microntek USB Joystick,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Linux,
030000005e0400000e00000000010000,Microsoft SideWinder,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,rightshoulder:b7,start:b8,x:b3,y:b4,platform:Linux,
@@ -450,9 +478,9 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
030000005e040000d102000003020000,Microsoft X-Box One pad v2,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
030000005e0400008502000000010000,Microsoft X-Box pad (Japan),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,
030000005e0400008902000021010000,Microsoft X-Box pad v2 (US),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,
-05000000d6200000e589000001000000,Moga 2 HID,a:b0,b:b1,x:b2,y:b3,back:b9,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Linux,
+05000000d6200000e589000001000000,Moga 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,
05000000d6200000ad0d000001000000,Moga Pro,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,
-05000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,x:b2,y:b3,back:b9,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,platform:Linux,
+05000000d62000007162000001000000,Moga Pro 2 HID,a:b0,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b7,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a3,start:b6,x:b2,y:b3,platform:Linux,
03000000250900006688000000010000,MP-8866 Super Dual Box,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Linux,
030000000d0f00000900000010010000,Natec Genesis P44,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
030000001008000001e5000010010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,platform:Linux,
@@ -461,15 +489,17 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
05000000010000000100000003000000,Nintendo Wiimote,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,
030000000d0500000308000010010000,Nostromo n45 Dual Analog Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,platform:Linux,
03000000550900001072000011010000,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b13,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,platform:Linux,
-05000000550900001472000001000000,NVIDIA Controller v01.04,a:b0,b:b1,x:b2,y:b3,back:b14,guide:b16,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a5,lefttrigger:a3,righttrigger:a4,platform:Linux,
-03000000550900001472000011010000,NVIDIA Controller v01.04,a:b0,b:b1,x:b2,y:b3,back:b14,guide:b16,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a5,lefttrigger:a3,righttrigger:a4,platform:Linux,
+03000000550900001472000011010000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,platform:Linux,
+05000000550900001472000001000000,NVIDIA Controller v01.04,a:b0,b:b1,back:b14,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b4,leftstick:b7,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b8,righttrigger:a4,rightx:a2,righty:a5,start:b6,x:b2,y:b3,platform:Linux,
03000000451300000830000010010000,NYKO CORE,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a5,start:b9,x:b0,y:b3,platform:Linux,
030000005e0400000202000000010000,Old Xbox pad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b5,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b2,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b3,y:b4,platform:Linux,
05000000362800000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,platform:Linux,
05000000362800000100000003010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,platform:Linux,
03000000ff1100003133000010010000,PC Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,
030000006f0e00006401000001010000,PDP Battlefield One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
+030000006f0e0000a802000023020000,PDP Wired Controller for Xbox One,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,
03000000c62400000053000000010000,PowerA,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
+03000000c62400003a54000001010000,PowerA 1428124-01,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,platform:Linux,
03000000d62000006dca000011010000,PowerA Pro Ex,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
03000000ff1100004133000010010000,PS2 Controller,a:b2,b:b1,back:b8,leftshoulder:b6,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b5,start:b9,x:b3,y:b0,platform:Linux,
03000000341a00003608000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Linux,
@@ -524,6 +554,7 @@ xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,
03000000c01600008704000011010000,Serial/Keyboard/Mouse/Joystick,a:b12,b:b10,back:b4,dpdown:b2,dpleft:b3,dpright:b1,dpup:b0,leftshoulder:b9,leftstick:b14,lefttrigger:b6,leftx:a1,lefty:a0,rightshoulder:b8,rightstick:b15,righttrigger:b7,rightx:a2,righty:a3,start:b5,x:b13,y:b11,platform:Linux,
03000000f025000021c1000010010000,ShanWan Gioteck PS3 Wired Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,
03000000632500007505000010010000,SHANWAN PS3/PC Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,
+03000000bc2000000055000010010000,ShanWan PS3/PC Wired GamePad,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,platform:Linux,
03000000632500002305000010010000,ShanWan USB Gamepad,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,platform:Linux,
03000000341a00000908000010010000,SL-6566,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,platform:Linux,
03000000250900000500000000010000,Sony PS2 pad with SmartJoy adapter,a:b2,b:b1,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b3,y:b0,platform:Linux,
diff --git a/main/input_default.cpp b/main/input_default.cpp
index 5ba98c20e2..60675f1115 100644
--- a/main/input_default.cpp
+++ b/main/input_default.cpp
@@ -472,6 +472,10 @@ void InputDefault::stop_joy_vibration(int p_device) {
joy_vibration[p_device] = vibration;
}
+void InputDefault::vibrate_handheld(int p_duration_ms) {
+ OS::get_singleton()->vibrate_handheld(p_duration_ms);
+}
+
void InputDefault::set_gravity(const Vector3 &p_gravity) {
_THREAD_SAFE_METHOD_
diff --git a/main/input_default.h b/main/input_default.h
index 80ee17656c..4fc4ad6506 100644
--- a/main/input_default.h
+++ b/main/input_default.h
@@ -226,6 +226,7 @@ public:
virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration = 0);
virtual void stop_joy_vibration(int p_device);
+ virtual void vibrate_handheld(int p_duration_ms = 500);
void set_main_loop(MainLoop *p_main_loop);
void set_mouse_position(const Point2 &p_posf);
diff --git a/main/main.cpp b/main/main.cpp
index 027273c4f4..f4665c4ad4 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -30,6 +30,7 @@
#include "main.h"
+#include "core/crypto/crypto.h"
#include "core/input_map.h"
#include "core/io/file_access_network.h"
#include "core/io/file_access_pack.h"
@@ -37,8 +38,6 @@
#include "core/io/image_loader.h"
#include "core/io/ip.h"
#include "core/io/resource_loader.h"
-#include "core/io/stream_peer_ssl.h"
-#include "core/io/stream_peer_tcp.h"
#include "core/message_queue.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
@@ -599,6 +598,14 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
auto_build_solutions = true;
editor = true;
+#ifdef DEBUG_METHODS_ENABLED
+ } else if (I->get() == "--gdnative-generate-json-api") {
+ // Register as an editor instance to use the GLES2 fallback automatically on hardware that doesn't support the GLES3 backend
+ editor = true;
+
+ // We still pass it to the main arguments since the argument handling itself is not done in this function
+ main_args.push_back(I->get());
+#endif
} else if (I->get() == "--export" || I->get() == "--export-debug") { // Export project
editor = true;
@@ -937,7 +944,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", false);
}
- video_mode.use_vsync = GLOBAL_DEF("display/window/vsync/use_vsync", true);
+ video_mode.use_vsync = GLOBAL_DEF_RST("display/window/vsync/use_vsync", true);
OS::get_singleton()->_use_vsync = video_mode.use_vsync;
OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
@@ -1741,7 +1748,7 @@ bool Main::start() {
if (!project_manager && !editor) { // game
// Load SSL Certificates from Project Settings (or builtin).
- StreamPeerSSL::load_certs_from_memory(StreamPeerSSL::get_project_cert_array());
+ Crypto::load_default_certificates(GLOBAL_DEF("network/ssl/certificates", ""));
if (game_path != "") {
Node *scene = NULL;
@@ -1793,17 +1800,15 @@ bool Main::start() {
}
if (project_manager || editor) {
- // Load SSL Certificates from Editor Settings (or builtin).
- String certs = EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String();
- if (certs != "")
- StreamPeerSSL::load_certs_from_file(certs);
- else
- StreamPeerSSL::load_certs_from_memory(StreamPeerSSL::get_project_cert_array());
-
// Hide console window if requested (Windows-only).
bool hide_console = EditorSettings::get_singleton()->get_setting("interface/editor/hide_console_window");
OS::get_singleton()->set_console_visible(!hide_console);
}
+
+ if (project_manager || editor) {
+ // Load SSL Certificates from Editor Settings (or builtin)
+ Crypto::load_default_certificates(EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String());
+ }
#endif
}
diff --git a/main/tests/test_oa_hash_map.cpp b/main/tests/test_oa_hash_map.cpp
index 070420e432..bf5b4588ea 100644
--- a/main/tests/test_oa_hash_map.cpp
+++ b/main/tests/test_oa_hash_map.cpp
@@ -121,6 +121,25 @@ MainLoop *test() {
delete[] keys;
}
+ // regression test / test for issue related to #31402
+ {
+
+ OS::get_singleton()->print("test for issue #31402 started...\n");
+
+ const int num_test_values = 12;
+ int test_values[num_test_values] = { 0, 24, 48, 72, 96, 120, 144, 168, 192, 216, 240, 264 };
+
+ int dummy = 0;
+ OAHashMap<int, int> map;
+ map.clear();
+
+ for (int i = 0; i < num_test_values; ++i) {
+ map.set(test_values[i], dummy);
+ }
+
+ OS::get_singleton()->print("test for issue #31402 passed.\n");
+ }
+
return NULL;
}
} // namespace TestOAHashMap
diff --git a/misc/hooks/pre-commit-clang-format b/misc/hooks/pre-commit-clang-format
index db241ad172..3a0ac9f389 100755
--- a/misc/hooks/pre-commit-clang-format
+++ b/misc/hooks/pre-commit-clang-format
@@ -86,6 +86,9 @@ do
if grep -q "thirdparty" <<< $file; then
continue;
fi
+ if grep -q "platform/android/java/src/com" <<< $file; then
+ continue;
+ fi
# ignore file if we do check for file extensions and the file
# does not match any of the extensions specified in $FILE_EXTS
diff --git a/misc/ide/jetbrains/build.gradle b/misc/ide/jetbrains/build.gradle
index eb2fbc0e69..dea81b4ea3 100644
--- a/misc/ide/jetbrains/build.gradle
+++ b/misc/ide/jetbrains/build.gradle
@@ -4,7 +4,7 @@ buildscript {
jcenter()
}
dependencies {
- classpath 'com.android.tools.build:gradle:3.3.2'
+ classpath 'com.android.tools.build:gradle:3.4.2'
}
}
diff --git a/misc/ide/jetbrains/gradle/wrapper/gradle-wrapper.properties b/misc/ide/jetbrains/gradle/wrapper/gradle-wrapper.properties
index b477add150..22e7a5c60b 100644
--- a/misc/ide/jetbrains/gradle/wrapper/gradle-wrapper.properties
+++ b/misc/ide/jetbrains/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Sun Mar 31 16:34:43 PDT 2019
+#Wed Aug 21 13:47:30 PDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
diff --git a/misc/travis/clang-format.sh b/misc/travis/clang-format.sh
index 5463a6cedf..48378281d4 100755
--- a/misc/travis/clang-format.sh
+++ b/misc/travis/clang-format.sh
@@ -11,7 +11,7 @@ else
RANGE=HEAD
fi
-FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java|glsl)$")
+FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -v platform/android/java/src/com/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java|glsl)$")
echo "Checking files:\n$FILES"
# create a random filename to store our generated patch
diff --git a/modules/arkit/arkit_interface.h b/modules/arkit/arkit_interface.h
index 8129611287..e1dbca1488 100644
--- a/modules/arkit/arkit_interface.h
+++ b/modules/arkit/arkit_interface.h
@@ -3,10 +3,10 @@
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
-/* http://www.godotengine.org */
+/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/arkit/arkit_interface.mm b/modules/arkit/arkit_interface.mm
index 68844c54c2..9614f775a5 100644
--- a/modules/arkit/arkit_interface.mm
+++ b/modules/arkit/arkit_interface.mm
@@ -3,10 +3,10 @@
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
-/* http://www.godotengine.org */
+/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/arkit/arkit_session_delegate.h b/modules/arkit/arkit_session_delegate.h
index afe093656b..9303552ca6 100644
--- a/modules/arkit/arkit_session_delegate.h
+++ b/modules/arkit/arkit_session_delegate.h
@@ -3,10 +3,10 @@
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
-/* http://www.godotengine.org */
+/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/arkit/arkit_session_delegate.mm b/modules/arkit/arkit_session_delegate.mm
index 56485c987c..d4072fc391 100644
--- a/modules/arkit/arkit_session_delegate.mm
+++ b/modules/arkit/arkit_session_delegate.mm
@@ -3,10 +3,10 @@
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
-/* http://www.godotengine.org */
+/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp
index fd0d36eddf..f1b3fa2ac6 100644
--- a/modules/csg/csg.cpp
+++ b/modules/csg/csg.cpp
@@ -242,7 +242,7 @@ void CSGBrushOperation::BuildPoly::_clip_segment(const CSGBrush *p_brush, int p_
//check if edge and poly share a vertex, of so, assign it to segment_idx
for (int i = 0; i < points.size(); i++) {
for (int j = 0; j < 2; j++) {
- if (Math::is_zero_approx(segment[j].distance_to(points[i].point))) {
+ if (segment[j] == points[i].point) {
segment_idx[j] = i;
inserted_points.push_back(i);
break;
@@ -310,7 +310,7 @@ void CSGBrushOperation::BuildPoly::_clip_segment(const CSGBrush *p_brush, int p_
Vector2 edgeseg[2] = { points[edges[i].points[0]].point, points[edges[i].points[1]].point };
Vector2 closest = Geometry::get_closest_point_to_segment_2d(segment[j], edgeseg);
- if (Math::is_zero_approx(closest.distance_to(segment[j]))) {
+ if (closest == segment[j]) {
//point rest of this edge
res = closest;
found = true;
@@ -439,7 +439,7 @@ void CSGBrushOperation::BuildPoly::clip(const CSGBrush *p_brush, int p_face, Mes
//transform A points to 2D
- if (Math::is_zero_approx(segment[0].distance_to(segment[1])))
+ if (segment[0] == segment[1])
return; //too small
_clip_segment(p_brush, p_face, segment, mesh_merge, p_for_B);
@@ -461,10 +461,10 @@ void CSGBrushOperation::_collision_callback(const CSGBrush *A, int p_face_a, Map
{
//check if either is a degenerate
- if (Math::is_zero_approx(va[0].distance_to(va[1])) || Math::is_zero_approx(va[0].distance_to(va[2])) || Math::is_zero_approx(va[1].distance_to(va[2])))
+ if (va[0] == va[1] || va[0] == va[2] || va[1] == va[2])
return;
- if (Math::is_zero_approx(vb[0].distance_to(vb[1])) || Math::is_zero_approx(vb[0].distance_to(vb[2])) || Math::is_zero_approx(vb[1].distance_to(vb[2])))
+ if (vb[0] == vb[1] || vb[0] == vb[2] || vb[1] == vb[2])
return;
}
diff --git a/modules/etc/texture_loader_pkm.cpp b/modules/etc/texture_loader_pkm.cpp
index 3337460dfc..dd61d816d4 100644
--- a/modules/etc/texture_loader_pkm.cpp
+++ b/modules/etc/texture_loader_pkm.cpp
@@ -62,10 +62,8 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path,
f->set_endian_swap(true);
ETC1Header h;
- ERR_EXPLAIN("Invalid or Unsupported PKM texture file: " + p_path);
f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag));
- if (strncmp(h.tag, "PKM 10", sizeof(h.tag)))
- ERR_FAIL_V(RES());
+ ERR_FAIL_COND_V_MSG(strncmp(h.tag, "PKM 10", sizeof(h.tag)), RES(), "Invalid or unsupported PKM texture file: " + p_path + ".");
h.format = f->get_16();
h.texWidth = f->get_16();
diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp
index 9f7c3880ec..7c313c983f 100644
--- a/modules/gdnative/nativescript/nativescript.cpp
+++ b/modules/gdnative/nativescript/nativescript.cpp
@@ -79,7 +79,7 @@ void NativeScript::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "script_class_name"), "set_script_class_name", "get_script_class_name");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "script_class_icon_path", PROPERTY_HINT_FILE), "set_script_class_icon_path", "get_script_class_icon_path");
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &NativeScript::_new, MethodInfo(Variant::OBJECT, "new"));
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &NativeScript::_new, MethodInfo("new"));
}
#define NSL NativeScriptLanguage::get_singleton()
diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp
index b82823ab64..94d38e1be1 100644
--- a/modules/gdnative/pluginscript/pluginscript_script.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_script.cpp
@@ -50,7 +50,7 @@
#endif
void PluginScript::_bind_methods() {
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &PluginScript::_new, MethodInfo(Variant::OBJECT, "new"));
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &PluginScript::_new, MethodInfo("new"));
}
PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Variant::CallError &r_error) {
diff --git a/modules/gdscript/SCsub b/modules/gdscript/SCsub
index 6904154953..6285e6bb54 100644
--- a/modules/gdscript/SCsub
+++ b/modules/gdscript/SCsub
@@ -9,3 +9,4 @@ env_gdscript.add_source_files(env.modules_sources, "*.cpp")
if env['tools']:
env_gdscript.add_source_files(env.modules_sources, "./editor/*.cpp")
+ env_gdscript.add_source_files(env.modules_sources, "./language_server/*.cpp")
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index d929bdb3e5..5dab063061 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -710,7 +710,7 @@ void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
void GDScript::_bind_methods() {
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new"));
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new"));
ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
}
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index 9f65a9fff1..7c01e85ff7 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -634,7 +634,7 @@ static GDScriptCompletionIdentifier _type_from_gdtype(const GDScriptDataType &p_
switch (p_gdtype.kind) {
case GDScriptDataType::UNINITIALIZED: {
- ERR_EXPLAIN("Uninitialized completion. Please report a bug.");
+ ERR_PRINT("Uninitialized completion. Please report a bug.");
} break;
case GDScriptDataType::BUILTIN: {
ci.type.kind = GDScriptParser::DataType::BUILTIN;
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 9a25e788c7..a9f22225a0 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -504,7 +504,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
Ref<GDScript> gds = res;
if (gds.is_valid() && !gds->is_valid()) {
- _set_error("Could not fully preload the script, possible cyclic reference or compilation error. Use 'load()' instead if a cyclic reference is intended.");
+ _set_error("Couldn't fully preload the script, possible cyclic reference or compilation error. Use \"load()\" instead if a cyclic reference is intended.");
return NULL;
}
@@ -518,7 +518,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
} else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_YIELD) {
if (!current_function) {
- _set_error("yield() can only be used inside function blocks.");
+ _set_error("\"yield()\" can only be used inside function blocks.");
return NULL;
}
@@ -526,7 +526,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected '(' after 'yield'");
+ _set_error("Expected \"(\" after \"yield\".");
return NULL;
}
@@ -552,7 +552,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
yield->arguments.push_back(object);
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected ',' after first argument of 'yield'");
+ _set_error("Expected \",\" after the first argument of \"yield\".");
return NULL;
}
@@ -578,7 +578,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
yield->arguments.push_back(signal);
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' after second argument of 'yield'");
+ _set_error("Expected \")\" after the second argument of \"yield\".");
return NULL;
}
@@ -592,7 +592,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
} else if (tokenizer->get_token() == GDScriptTokenizer::TK_SELF) {
if (p_static) {
- _set_error("'self'' not allowed in static function or constant expression");
+ _set_error("\"self\" isn't allowed in a static function or constant expression.");
return NULL;
}
//constant defined by tokenizer
@@ -613,7 +613,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
if (identifier == StringName()) {
- _set_error("Built-in type constant or static function expected after '.'");
+ _set_error("Built-in type constant or static function expected after \".\".");
return NULL;
}
if (!Variant::has_constant(bi_type, identifier)) {
@@ -2309,7 +2309,7 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m
// static type check if possible
if (pattern_type.has_type && to_match_type.has_type) {
if (!_is_type_compatible(to_match_type, pattern_type) && !_is_type_compatible(pattern_type, to_match_type)) {
- _set_error("Pattern type (" + pattern_type.to_string() + ") is not compatible with the type of the value to match (" + to_match_type.to_string() + ").",
+ _set_error("The pattern type (" + pattern_type.to_string() + ") isn't compatible with the type of the value to match (" + to_match_type.to_string() + ").",
p_pattern->line);
return;
}
@@ -2761,24 +2761,24 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
case GDScriptTokenizer::TK_CF_PASS: {
if (tokenizer->get_token(1) != GDScriptTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF) {
- _set_error("Expected ';' or <NewLine>.");
+ _set_error("Expected \";\" or a line break.");
return;
}
_mark_line_as_safe(tokenizer->get_token_line());
tokenizer->advance();
if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) {
- // Ignore semicolon after 'pass'
+ // Ignore semicolon after 'pass'.
tokenizer->advance();
}
} break;
case GDScriptTokenizer::TK_PR_VAR: {
- //variale declaration and (eventual) initialization
+ // Variable declaration and (eventual) initialization.
tokenizer->advance();
int var_line = tokenizer->get_token_line();
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected identifier for local variable name.");
+ _set_error("Expected an identifier for the local variable name.");
return;
}
StringName n = tokenizer->get_token_literal();
@@ -2786,7 +2786,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
if (current_function) {
for (int i = 0; i < current_function->arguments.size(); i++) {
if (n == current_function->arguments[i]) {
- _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(current_function->line) + ").");
+ _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(current_function->line) + ").");
return;
}
}
@@ -2794,7 +2794,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
BlockNode *check_block = p_block;
while (check_block) {
if (check_block->variables.has(n)) {
- _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variables[n]->line) + ").");
+ _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(check_block->variables[n]->line) + ").");
return;
}
check_block = check_block->parent_block;
@@ -2816,7 +2816,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
#endif
tokenizer->advance();
} else if (!_parse_type(lv->datatype)) {
- _set_error("Expected type for variable.");
+ _set_error("Expected a type for the variable.");
return;
}
}
@@ -2865,7 +2865,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
lv->assign = assigned;
if (!_end_statement()) {
- _set_error("Expected end of statement (var)");
+ _set_error("Expected end of statement (\"var\").");
return;
}
@@ -2894,7 +2894,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->sub_blocks.push_back(cf_if->body);
if (!_enter_indent_block(cf_if->body)) {
- _set_error("Expected indented block after 'if'");
+ _set_error("Expected an indented block after \"if\".");
p_block->end_line = tokenizer->get_token_line();
return;
}
@@ -2924,7 +2924,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
if (tab_level.back()->get() > indent_level) {
- _set_error("Invalid indent");
+ _set_error("Invalid indentation.");
return;
}
@@ -2955,7 +2955,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->sub_blocks.push_back(cf_if->body);
if (!_enter_indent_block(cf_if->body)) {
- _set_error("Expected indented block after 'elif'");
+ _set_error("Expected an indented block after \"elif\".");
p_block->end_line = tokenizer->get_token_line();
return;
}
@@ -2971,7 +2971,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
} else if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELSE) {
if (tab_level.back()->get() > indent_level) {
- _set_error("Invalid indent");
+ _set_error("Invalid indentation.");
return;
}
@@ -2981,7 +2981,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->sub_blocks.push_back(cf_if->body_else);
if (!_enter_indent_block(cf_if->body_else)) {
- _set_error("Expected indented block after 'else'");
+ _set_error("Expected an indented block after \"else\".");
p_block->end_line = tokenizer->get_token_line();
return;
}
@@ -3026,7 +3026,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->sub_blocks.push_back(cf_while->body);
if (!_enter_indent_block(cf_while->body)) {
- _set_error("Expected indented block after 'while'");
+ _set_error("Expected an indented block after \"while\".");
p_block->end_line = tokenizer->get_token_line();
return;
}
@@ -3045,7 +3045,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("identifier expected after 'for'");
+ _set_error("Identifier expected after \"for\".");
}
IdentifierNode *id = alloc_node<IdentifierNode>();
@@ -3054,7 +3054,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_IN) {
- _set_error("'in' expected after identifier");
+ _set_error("\"in\" expected after identifier.");
return;
}
@@ -3144,7 +3144,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->sub_blocks.push_back(cf_for->body);
if (!_enter_indent_block(cf_for->body)) {
- _set_error("Expected indented block after 'for'");
+ _set_error("Expected indented block after \"for\".");
p_block->end_line = tokenizer->get_token_line();
return;
}
@@ -3171,23 +3171,25 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
} break;
case GDScriptTokenizer::TK_CF_CONTINUE: {
+ _mark_line_as_safe(tokenizer->get_token_line());
tokenizer->advance();
ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>();
cf_continue->cf_type = ControlFlowNode::CF_CONTINUE;
p_block->statements.push_back(cf_continue);
if (!_end_statement()) {
- _set_error("Expected end of statement (continue)");
+ _set_error("Expected end of statement (\"continue\").");
return;
}
} break;
case GDScriptTokenizer::TK_CF_BREAK: {
+ _mark_line_as_safe(tokenizer->get_token_line());
tokenizer->advance();
ControlFlowNode *cf_break = alloc_node<ControlFlowNode>();
cf_break->cf_type = ControlFlowNode::CF_BREAK;
p_block->statements.push_back(cf_break);
if (!_end_statement()) {
- _set_error("Expected end of statement (break)");
+ _set_error("Expected end of statement (\"break\").");
return;
}
} break;
@@ -3241,7 +3243,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
match_node->val_to_match = val_to_match;
if (!_enter_indent_block()) {
- _set_error("Expected indented pattern matching block after 'match'");
+ _set_error("Expected indented pattern matching block after \"match\".");
return;
}
@@ -3280,7 +3282,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->statements.push_back(an);
if (!_end_statement()) {
- _set_error("Expected end of statement after assert.");
+ _set_error("Expected end of statement after \"assert\".");
return;
}
} break;
@@ -3291,7 +3293,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
p_block->statements.push_back(bn);
if (!_end_statement()) {
- _set_error("Expected end of statement after breakpoint.");
+ _set_error("Expected end of statement after \"breakpoint\".");
return;
}
} break;
@@ -3323,7 +3325,7 @@ bool GDScriptParser::_parse_newline() {
int current_indent = tab_level.back()->get();
if (indent > current_indent) {
- _set_error("Unexpected indent.");
+ _set_error("Unexpected indentation.");
return false;
}
@@ -3333,7 +3335,7 @@ bool GDScriptParser::_parse_newline() {
//exit block
if (tab_level.size() == 1) {
- _set_error("Invalid indent. BUG?");
+ _set_error("Invalid indentation. Bug?");
return false;
}
@@ -3360,13 +3362,13 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) {
if (p_class->extends_used) {
- _set_error("'extends' already used for this class.");
+ _set_error("\"extends\" can only be present once per script.");
return;
}
if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty() || p_class->classname_used) {
- _set_error("'extends' must be used before anything else.");
+ _set_error("\"extends\" must be used before anything else.");
return;
}
@@ -3386,7 +3388,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) {
Variant constant = tokenizer->get_token_constant();
if (constant.get_type() != Variant::STRING) {
- _set_error("'extends' constant must be a string.");
+ _set_error("\"extends\" constant must be a string.");
return;
}
@@ -3421,7 +3423,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) {
default: {
- _set_error("Invalid 'extends' syntax, expected string constant (path) and/or identifier (parent class).");
+ _set_error("Invalid \"extends\" syntax, expected string constant (path) and/or identifier (parent class).");
return;
}
}
@@ -3481,7 +3483,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (error_set)
return;
if (!_end_statement()) {
- _set_error("Expected end of statement after extends");
+ _set_error("Expected end of statement after \"extends\".");
return;
}
@@ -3490,20 +3492,20 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
_mark_line_as_safe(tokenizer->get_token_line());
if (p_class->owner) {
- _set_error("'class_name' is only valid for the main class namespace.");
+ _set_error("\"class_name\" is only valid for the main class namespace.");
return;
}
if (self_path.begins_with("res://") && self_path.find("::") != -1) {
- _set_error("'class_name' not allowed in built-in scripts.");
+ _set_error("\"class_name\" isn't allowed in built-in scripts.");
return;
}
if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) {
- _set_error("'class_name' syntax: 'class_name <UniqueName>'");
+ _set_error("\"class_name\" syntax: \"class_name <UniqueName>\"");
return;
}
if (p_class->classname_used) {
- _set_error("'class_name' already used for this class.");
+ _set_error("\"class_name\" can only be present once per script.");
return;
}
@@ -3512,12 +3514,12 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
p_class->name = tokenizer->get_token_identifier(1);
if (self_path != String() && ScriptServer::is_global_class(p_class->name) && ScriptServer::get_global_class_path(p_class->name) != self_path) {
- _set_error("Unique global class '" + p_class->name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name));
+ _set_error("Unique global class \"" + p_class->name + "\" already exists at path: " + ScriptServer::get_global_class_path(p_class->name));
return;
}
if (ClassDB::class_exists(p_class->name)) {
- _set_error("Class '" + p_class->name + "' shadows a native class.");
+ _set_error("The class \"" + p_class->name + "\" shadows a native class.");
return;
}
@@ -3544,12 +3546,12 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
} else {
- _set_error("Optional parameter after 'class_name' must be a string constant file path to an icon.");
+ _set_error("The optional parameter after \"class_name\" must be a string constant file path to an icon.");
return;
}
} else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) {
- _set_error("Class icon must be separated by a comma.");
+ _set_error("The class icon must be separated by a comma.");
return;
}
@@ -3558,7 +3560,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (p_class->tool) {
- _set_error("tool used more than once");
+ _set_error("The \"tool\" keyword can only be present once per script.");
return;
}
@@ -3573,7 +3575,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) {
- _set_error("'class' syntax: 'class <Name>:' or 'class <Name> extends <BaseClass>:'");
+ _set_error("\"class\" syntax: \"class <Name>:\" or \"class <Name> extends <BaseClass>:\"");
return;
}
name = tokenizer->get_token_identifier(1);
@@ -3581,23 +3583,23 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
// Check if name is shadowing something else
if (ClassDB::class_exists(name) || ClassDB::class_exists("_" + name.operator String())) {
- _set_error("Class '" + String(name) + "' shadows a native class.");
+ _set_error("The class \"" + String(name) + "\" shadows a native class.");
return;
}
if (ScriptServer::is_global_class(name)) {
- _set_error("Can't override name of unique global class '" + name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name));
+ _set_error("Can't override name of the unique global class \"" + name + "\". It already exists at: " + ScriptServer::get_global_class_path(p_class->name));
return;
}
ClassNode *outer_class = p_class;
while (outer_class) {
for (int i = 0; i < outer_class->subclasses.size(); i++) {
if (outer_class->subclasses[i]->name == name) {
- _set_error("Another class named '" + String(name) + "' already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ").");
+ _set_error("Another class named \"" + String(name) + "\" already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ").");
return;
}
}
if (outer_class->constant_expressions.has(name)) {
- _set_error("A constant named '" + String(name) + "' already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ").");
+ _set_error("A constant named \"" + String(name) + "\" already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ").");
return;
}
@@ -3641,7 +3643,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected 'func'.");
+ _set_error("Expected \"func\".");
return;
}
@@ -3665,18 +3667,18 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (name == StringName()) {
- _set_error("Expected identifier after 'func' (syntax: 'func <identifier>([arguments]):' ).");
+ _set_error("Expected an identifier after \"func\" (syntax: \"func <identifier>([arguments]):\").");
return;
}
for (int i = 0; i < p_class->functions.size(); i++) {
if (p_class->functions[i]->name == name) {
- _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->functions[i]->line) + ").");
+ _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->functions[i]->line) + ").");
}
}
for (int i = 0; i < p_class->static_functions.size(); i++) {
if (p_class->static_functions[i]->name == name) {
- _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->static_functions[i]->line) + ").");
+ _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->static_functions[i]->line) + ").");
}
}
@@ -3698,7 +3700,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected '(' after identifier (syntax: 'func <identifier>([arguments]):' ).");
+ _set_error("Expected \"(\" after the identifier (syntax: \"func <identifier>([arguments]):\" ).");
return;
}
@@ -3730,7 +3732,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected identifier for argument.");
+ _set_error("Expected an identifier for an argument.");
return;
}
@@ -3748,7 +3750,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
argtype.infer_type = true;
tokenizer->advance();
} else if (!_parse_type(argtype)) {
- _set_error("Expected type for argument.");
+ _set_error("Expected a type for an argument.");
return;
}
}
@@ -3797,7 +3799,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
continue;
} else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ',' or ')'.");
+ _set_error("Expected \",\" or \")\".");
return;
}
@@ -3826,7 +3828,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (name == "_init") {
if (_static) {
- _set_error("Constructor cannot be static.");
+ _set_error("The constructor cannot be static.");
return;
}
@@ -3843,7 +3845,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("expected '(' for parent constructor arguments.");
+ _set_error("Expected \"(\" for parent constructor arguments.");
return;
}
tokenizer->advance();
@@ -3863,7 +3865,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
continue;
} else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ',' or ')'.");
+ _set_error("Expected \",\" or \")\".");
return;
}
@@ -3888,7 +3890,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_FORWARD_ARROW) {
if (!_parse_type(return_type, true)) {
- _set_error("Expected return type for function.");
+ _set_error("Expected a return type for the function.");
return;
}
}
@@ -3918,7 +3920,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (!tokenizer->is_token_literal()) {
- _set_error("Expected identifier after 'signal'.");
+ _set_error("Expected an identifier after \"signal\".");
return;
}
@@ -3942,7 +3944,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected identifier in signal argument.");
+ _set_error("Expected an identifier in a \"signal\" argument.");
return;
}
@@ -3956,7 +3958,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
tokenizer->advance();
} else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ',' or ')' after signal parameter identifier.");
+ _set_error("Expected \",\" or \")\" after a \"signal\" parameter identifier.");
return;
}
}
@@ -3965,7 +3967,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
p_class->_signals.push_back(sig);
if (!_end_statement()) {
- _set_error("Expected end of statement (signal)");
+ _set_error("Expected end of statement (\"signal\").");
return;
}
} break;
@@ -4024,7 +4026,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
break;
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected ',' in bit flags hint.");
+ _set_error("Expected \",\" in the bit flags hint.");
return;
}
@@ -4036,7 +4038,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
current_export = PropertyInfo();
- _set_error("Expected a string constant in named bit flags hint.");
+ _set_error("Expected a string constant in the named bit flags hint.");
return;
}
@@ -4054,7 +4056,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
current_export = PropertyInfo();
- _set_error("Expected ')' or ',' in named bit flags hint.");
+ _set_error("Expected \")\" or \",\" in the named bit flags hint.");
return;
}
tokenizer->advance();
@@ -4067,7 +4069,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in layers 2D render hint.");
+ _set_error("Expected \")\" in the layers 2D render hint.");
return;
}
current_export.hint = PROPERTY_HINT_LAYERS_2D_RENDER;
@@ -4078,7 +4080,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in layers 2D physics hint.");
+ _set_error("Expected \")\" in the layers 2D physics hint.");
return;
}
current_export.hint = PROPERTY_HINT_LAYERS_2D_PHYSICS;
@@ -4089,7 +4091,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in layers 3D render hint.");
+ _set_error("Expected \")\" in the layers 3D render hint.");
return;
}
current_export.hint = PROPERTY_HINT_LAYERS_3D_RENDER;
@@ -4100,7 +4102,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in layers 3D physics hint.");
+ _set_error("Expected \")\" in the layers 3D physics hint.");
return;
}
current_export.hint = PROPERTY_HINT_LAYERS_3D_PHYSICS;
@@ -4116,7 +4118,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
current_export = PropertyInfo();
- _set_error("Expected a string constant in enumeration hint.");
+ _set_error("Expected a string constant in the enumeration hint.");
return;
}
@@ -4134,7 +4136,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
current_export = PropertyInfo();
- _set_error("Expected ')' or ',' in enumeration hint.");
+ _set_error("Expected \")\" or \",\" in the enumeration hint.");
return;
}
@@ -4152,7 +4154,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
current_export.hint = PROPERTY_HINT_EXP_EASING;
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in hint.");
+ _set_error("Expected \")\" in the hint.");
return;
}
break;
@@ -4167,7 +4169,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
break;
else if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected ')' or ',' in exponential range hint.");
+ _set_error("Expected \")\" or \",\" in the exponential range hint.");
return;
}
tokenizer->advance();
@@ -4183,7 +4185,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
current_export = PropertyInfo();
- _set_error("Expected a range in numeric hint.");
+ _set_error("Expected a range in the numeric hint.");
return;
}
@@ -4198,7 +4200,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
current_export = PropertyInfo();
- _set_error("Expected ',' or ')' in numeric range hint.");
+ _set_error("Expected \",\" or \")\" in the numeric range hint.");
return;
}
@@ -4213,7 +4215,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
current_export = PropertyInfo();
- _set_error("Expected a number as upper bound in numeric range hint.");
+ _set_error("Expected a number as upper bound in the numeric range hint.");
return;
}
@@ -4226,7 +4228,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
current_export = PropertyInfo();
- _set_error("Expected ',' or ')' in numeric range hint.");
+ _set_error("Expected \",\" or \")\" in the numeric range hint.");
return;
}
@@ -4240,7 +4242,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
current_export = PropertyInfo();
- _set_error("Expected a number as step in numeric range hint.");
+ _set_error("Expected a number as step in the numeric range hint.");
return;
}
@@ -4259,7 +4261,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
current_export = PropertyInfo();
- _set_error("Expected a string constant in enumeration hint.");
+ _set_error("Expected a string constant in the enumeration hint.");
return;
}
@@ -4276,7 +4278,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
current_export = PropertyInfo();
- _set_error("Expected ')' or ',' in enumeration hint.");
+ _set_error("Expected \")\" or \",\" in the enumeration hint.");
return;
}
tokenizer->advance();
@@ -4296,7 +4298,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) {
- _set_error("Expected 'GLOBAL' after comma in directory hint.");
+ _set_error("Expected \"GLOBAL\" after comma in the directory hint.");
return;
}
if (!p_class->tool) {
@@ -4307,11 +4309,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in hint.");
+ _set_error("Expected \")\" in the hint.");
return;
}
} else {
- _set_error("Expected ')' or ',' in hint.");
+ _set_error("Expected \")\" or \",\" in the hint.");
return;
}
break;
@@ -4340,7 +4342,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA)
tokenizer->advance();
else {
- _set_error("Expected ')' or ',' in hint.");
+ _set_error("Expected \")\" or \",\" in the hint.");
return;
}
}
@@ -4348,9 +4350,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE)
- _set_error("Expected string constant with filter");
+ _set_error("Expected string constant with filter.");
else
- _set_error("Expected 'GLOBAL' or string constant with filter");
+ _set_error("Expected \"GLOBAL\" or string constant with filter.");
return;
}
current_export.hint_string = tokenizer->get_token_constant();
@@ -4358,7 +4360,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in hint.");
+ _set_error("Expected \")\" in the hint.");
return;
}
break;
@@ -4369,7 +4371,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
current_export.hint = PROPERTY_HINT_MULTILINE_TEXT;
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' in hint.");
+ _set_error("Expected \")\" in the hint.");
return;
}
break;
@@ -4380,7 +4382,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER) {
current_export = PropertyInfo();
- _set_error("Color type hint expects RGB or RGBA as hints");
+ _set_error("Color type hint expects RGB or RGBA as hints.");
return;
}
@@ -4391,7 +4393,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
//none
} else {
current_export = PropertyInfo();
- _set_error("Color type hint expects RGB or RGBA as hints");
+ _set_error("Color type hint expects RGB or RGBA as hints.");
return;
}
tokenizer->advance();
@@ -4400,7 +4402,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
default: {
current_export = PropertyInfo();
- _set_error("Type '" + Variant::get_type_name(type) + "' can't take hints.");
+ _set_error("Type \"" + Variant::get_type_name(type) + "\" can't take hints.");
return;
} break;
}
@@ -4438,7 +4440,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
} else {
current_export = PropertyInfo();
- _set_error("Export hint not a resource type.");
+ _set_error("The export hint isn't a resource type.");
}
} else if (constant.get_type() == Variant::DICTIONARY) {
// Enumeration
@@ -4452,7 +4454,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
} else {
current_export = PropertyInfo();
- _set_error("Expected 'FLAGS' after comma.");
+ _set_error("Expected \"FLAGS\" after comma.");
}
}
@@ -4489,7 +4491,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
current_export = PropertyInfo();
- _set_error("Expected ')' or ',' after export hint.");
+ _set_error("Expected \")\" or \",\" after the export hint.");
return;
}
@@ -4509,7 +4511,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPET && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTESYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTERSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPETSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SLAVE) {
current_export = PropertyInfo();
- _set_error("Expected 'var', 'onready', 'remote', 'master', 'puppet', 'sync', 'remotesync', 'mastersync', 'puppetsync'.");
+ _set_error("Expected \"var\", \"onready\", \"remote\", \"master\", \"puppet\", \"sync\", \"remotesync\", \"mastersync\", \"puppetsync\".");
return;
}
@@ -4520,7 +4522,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
//may be fallthrough from export, ignore if so
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
return;
}
@@ -4532,13 +4534,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (current_export.type) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
return;
}
} else {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
}
@@ -4552,13 +4554,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (current_export.type) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
return;
}
} else {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
}
@@ -4577,13 +4579,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (current_export.type) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
return;
}
} else {
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
}
@@ -4598,9 +4600,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
if (current_export.type)
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
else
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
@@ -4613,9 +4615,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
if (current_export.type)
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
else
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
@@ -4628,9 +4630,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
if (current_export.type)
- _set_error("Expected 'var'.");
+ _set_error("Expected \"var\".");
else
- _set_error("Expected 'var' or 'func'.");
+ _set_error("Expected \"var\" or \"func\".");
return;
}
@@ -4653,7 +4655,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected identifier for member variable name.");
+ _set_error("Expected an identifier for the member variable name.");
return;
}
@@ -4669,14 +4671,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
#endif
if (current_class->constant_expressions.has(member.identifier)) {
- _set_error("A constant named '" + String(member.identifier) + "' already exists in this class (at line: " +
+ _set_error("A constant named \"" + String(member.identifier) + "\" already exists in this class (at line: " +
itos(current_class->constant_expressions[member.identifier].expression->line) + ").");
return;
}
for (int i = 0; i < current_class->variables.size(); i++) {
if (current_class->variables[i].identifier == member.identifier) {
- _set_error("Variable '" + String(member.identifier) + "' already exists in this class (at line: " +
+ _set_error("Variable \"" + String(member.identifier) + "\" already exists in this class (at line: " +
itos(current_class->variables[i].line) + ").");
return;
}
@@ -4684,7 +4686,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
for (int i = 0; i < current_class->subclasses.size(); i++) {
if (current_class->subclasses[i]->name == member.identifier) {
- _set_error("A class named '" + String(member.identifier) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ _set_error("A class named \"" + String(member.identifier) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
return;
}
}
@@ -4714,7 +4716,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
#endif
tokenizer->advance();
} else if (!_parse_type(member.data_type)) {
- _set_error("Expected type for class variable.");
+ _set_error("Expected a type for the class variable.");
return;
}
}
@@ -4742,7 +4744,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]);
if (id->name == "get_node") {
- _set_error("Use 'onready var " + String(member.identifier) + " = get_node(..)' instead");
+ _set_error("Use \"onready var " + String(member.identifier) + " = get_node(...)\" instead.");
return;
}
}
@@ -4770,7 +4772,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
Object *obj = cn->value;
Resource *res = Object::cast_to<Resource>(obj);
if (res == NULL) {
- _set_error("Exported constant not a type or resource.");
+ _set_error("The exported constant isn't a type or resource.");
return;
}
member._export.hint = PROPERTY_HINT_RESOURCE_TYPE;
@@ -4788,7 +4790,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
const Variant *args = &cn->value;
cn->value = Variant::construct(member._export.type, &args, 1, err);
} else {
- _set_error("Cannot convert the provided value to the export type.");
+ _set_error("Can't convert the provided value to the export type.");
return;
}
}
@@ -4886,7 +4888,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
//just comma means using only getter
if (!tokenizer->is_token_literal()) {
- _set_error("Expected identifier for setter function after 'setget'.");
+ _set_error("Expected an identifier for the setter function after \"setget\".");
}
member.setter = tokenizer->get_token_literal();
@@ -4899,7 +4901,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (!tokenizer->is_token_literal()) {
- _set_error("Expected identifier for getter function after ','.");
+ _set_error("Expected an identifier for the getter function after \",\".");
}
member.getter = tokenizer->get_token_literal();
@@ -4910,7 +4912,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
p_class->variables.push_back(member);
if (!_end_statement()) {
- _set_error("Expected end of statement (continue)");
+ _set_error("Expected end of statement (\"continue\").");
return;
}
} break;
@@ -4922,7 +4924,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected name (identifier) for constant.");
+ _set_error("Expected an identifier for the constant.");
return;
}
@@ -4930,14 +4932,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
int line = tokenizer->get_token_line();
if (current_class->constant_expressions.has(const_id)) {
- _set_error("Constant '" + String(const_id) + "' already exists in this class (at line: " +
+ _set_error("Constant \"" + String(const_id) + "\" already exists in this class (at line " +
itos(current_class->constant_expressions[const_id].expression->line) + ").");
return;
}
for (int i = 0; i < current_class->variables.size(); i++) {
if (current_class->variables[i].identifier == const_id) {
- _set_error("A variable named '" + String(const_id) + "' already exists in this class (at line: " +
+ _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " +
itos(current_class->variables[i].line) + ").");
return;
}
@@ -4945,7 +4947,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
for (int i = 0; i < current_class->subclasses.size(); i++) {
if (current_class->subclasses[i]->name == const_id) {
- _set_error("A class named '" + String(const_id) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
return;
}
}
@@ -4960,13 +4962,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
#endif
tokenizer->advance();
} else if (!_parse_type(constant.type)) {
- _set_error("Expected type for class constant.");
+ _set_error("Expected a type for the class constant.");
return;
}
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) {
- _set_error("Constant expects assignment.");
+ _set_error("Constants must be assigned immediately.");
return;
}
@@ -4981,7 +4983,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
if (subexpr->type != Node::TYPE_CONSTANT) {
- _set_error("Expected constant expression", line);
+ _set_error("Expected a constant expression.", line);
return;
}
subexpr->line = line;
@@ -4990,7 +4992,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
p_class->constant_expressions.insert(const_id, constant);
if (!_end_statement()) {
- _set_error("Expected end of statement (constant)", line);
+ _set_error("Expected end of statement (constant).", line);
return;
}
@@ -5007,14 +5009,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
enum_name = tokenizer->get_token_literal();
if (current_class->constant_expressions.has(enum_name)) {
- _set_error("A constant named '" + String(enum_name) + "' already exists in this class (at line: " +
+ _set_error("A constant named \"" + String(enum_name) + "\" already exists in this class (at line " +
itos(current_class->constant_expressions[enum_name].expression->line) + ").");
return;
}
for (int i = 0; i < current_class->variables.size(); i++) {
if (current_class->variables[i].identifier == enum_name) {
- _set_error("A variable named '" + String(enum_name) + "' already exists in this class (at line: " +
+ _set_error("A variable named \"" + String(enum_name) + "\" already exists in this class (at line " +
itos(current_class->variables[i].line) + ").");
return;
}
@@ -5022,7 +5024,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
for (int i = 0; i < current_class->subclasses.size(); i++) {
if (current_class->subclasses[i]->name == enum_name) {
- _set_error("A class named '" + String(enum_name) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ _set_error("A class named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
return;
}
}
@@ -5030,7 +5032,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) {
- _set_error("Expected '{' in enum declaration");
+ _set_error("Expected \"{\" in the enum declaration.");
return;
}
tokenizer->advance();
@@ -5048,7 +5050,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
_set_error("Unexpected end of file.");
} else {
- _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected identifier");
+ _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected an identifier.");
}
return;
@@ -5071,14 +5073,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
if (subexpr->type != Node::TYPE_CONSTANT) {
- _set_error("Expected constant expression");
+ _set_error("Expected a constant expression.");
return;
}
enum_value_expr = static_cast<ConstantNode *>(subexpr);
if (enum_value_expr->value.get_type() != Variant::INT) {
- _set_error("Expected an int value for enum");
+ _set_error("Expected an integer value for \"enum\".");
return;
}
@@ -5094,7 +5096,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
tokenizer->advance();
} else if (tokenizer->is_token_literal(0, true)) {
- _set_error("Unexpected identifier");
+ _set_error("Unexpected identifier.");
return;
}
@@ -5102,14 +5104,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
enum_dict[const_id] = enum_value_expr->value;
} else {
if (current_class->constant_expressions.has(const_id)) {
- _set_error("A constant named '" + String(const_id) + "' already exists in this class (at line: " +
+ _set_error("A constant named \"" + String(const_id) + "\" already exists in this class (at line " +
itos(current_class->constant_expressions[const_id].expression->line) + ").");
return;
}
for (int i = 0; i < current_class->variables.size(); i++) {
if (current_class->variables[i].identifier == const_id) {
- _set_error("A variable named '" + String(const_id) + "' already exists in this class (at line: " +
+ _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " +
itos(current_class->variables[i].line) + ").");
return;
}
@@ -5117,7 +5119,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
for (int i = 0; i < current_class->subclasses.size(); i++) {
if (current_class->subclasses[i]->name == const_id) {
- _set_error("A class named '" + String(const_id) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
return;
}
}
@@ -5144,7 +5146,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
if (!_end_statement()) {
- _set_error("Expected end of statement (enum)");
+ _set_error("Expected end of statement (\"enum\").");
return;
}
@@ -5190,19 +5192,19 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
String base = base_path;
if (base == "" || base.is_rel_path()) {
- _set_error("Could not resolve relative path for parent class: " + path, p_class->line);
+ _set_error("Couldn't resolve relative path for the parent class: " + path, p_class->line);
return;
}
path = base.plus_file(path).simplify_path();
}
script = ResourceLoader::load(path);
if (script.is_null()) {
- _set_error("Could not load base class: " + path, p_class->line);
+ _set_error("Couldn't load the base class: " + path, p_class->line);
return;
}
if (!script->is_valid()) {
- _set_error("Script not fully loaded (cyclic preload?): " + path, p_class->line);
+ _set_error("Script isn't fully loaded (cyclic preload?): " + path, p_class->line);
return;
}
@@ -5217,7 +5219,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
script = subclass;
} else {
- _set_error("Could not find subclass: " + sub, p_class->line);
+ _set_error("Couldn't find the subclass: " + sub, p_class->line);
return;
}
}
@@ -5239,7 +5241,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
if (ScriptServer::is_global_class(base)) {
base_script = ResourceLoader::load(ScriptServer::get_global_class_path(base));
if (!base_script.is_valid()) {
- _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic dependency).", p_class->line);
+ _set_error("The class \"" + base + "\" couldn't be fully loaded (script error or cyclic dependency).", p_class->line);
return;
}
p = NULL;
@@ -5280,13 +5282,13 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
if (p->constant_expressions.has(base)) {
if (p->constant_expressions[base].expression->type != Node::TYPE_CONSTANT) {
- _set_error("Could not resolve constant '" + base + "'.", p_class->line);
+ _set_error("Couldn't resolve the constant \"" + base + "\".", p_class->line);
return;
}
const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[base].expression);
base_script = cn->value;
if (base_script.is_null()) {
- _set_error("Constant is not a class: " + base, p_class->line);
+ _set_error("Constant isn't a class: " + base, p_class->line);
return;
}
break;
@@ -5313,13 +5315,13 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
Ref<GDScript> new_base_class = base_script->get_constants()[subclass];
if (new_base_class.is_null()) {
- _set_error("Constant is not a class: " + ident, p_class->line);
+ _set_error("Constant isn't a class: " + ident, p_class->line);
return;
}
find_subclass = new_base_class;
} else {
- _set_error("Could not find subclass: " + ident, p_class->line);
+ _set_error("Couldn't find the subclass: " + ident, p_class->line);
return;
}
}
@@ -5330,13 +5332,13 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
if (p_class->extends_class.size() > 1) {
- _set_error("Invalid inheritance (unknown class + subclasses)", p_class->line);
+ _set_error("Invalid inheritance (unknown class + subclasses).", p_class->line);
return;
}
//if not found, try engine classes
if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {
- _set_error("Unknown class: '" + base + "'", p_class->line);
+ _set_error("Unknown class: \"" + base + "\"", p_class->line);
return;
}
@@ -5358,7 +5360,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive
p_class->base_type.kind = DataType::NATIVE;
p_class->base_type.native_type = native;
} else {
- _set_error("Could not determine inheritance", p_class->line);
+ _set_error("Couldn't determine inheritance.", p_class->line);
return;
}
@@ -5503,7 +5505,7 @@ bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) {
switch (tokenizer->get_token()) {
case GDScriptTokenizer::TK_PERIOD: {
if (!can_index) {
- _set_error("Unexpected '.'.");
+ _set_error("Unexpected \".\".");
return false;
}
can_index = false;
@@ -5534,7 +5536,7 @@ bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) {
}
if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PERIOD) {
- _set_error("Expected subclass identifier.");
+ _set_error("Expected a subclass identifier.");
return false;
}
@@ -5572,7 +5574,7 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source,
Ref<GDScript> gds = script;
if (gds.is_valid()) {
if (!gds->is_valid()) {
- _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic dependency).", p_line);
+ _set_error("The class \"" + id + "\" couldn't be fully loaded (script error or cyclic dependency).", p_line);
return DataType();
}
result.kind = DataType::GDSCRIPT;
@@ -5581,7 +5583,7 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source,
result.kind = DataType::SCRIPT;
result.script_type = script;
} else {
- _set_error("Class '" + id + "' was found in global scope but its script could not be loaded.", p_line);
+ _set_error("The class \"" + id + "\" was found in global scope, but its script couldn't be loaded.", p_line);
return DataType();
}
}
@@ -5682,8 +5684,8 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source,
} else {
base = result.to_string();
}
- _set_error("Identifier '" + String(id) + "' is not a valid type (not a script or class), or could not be found on base '" +
- base + "'.",
+ _set_error("The identifier \"" + String(id) + "\" isn't a valid type (not a script or class), or couldn't be found on base \"" +
+ base + "\".",
p_line);
return DataType();
}
@@ -5761,7 +5763,7 @@ GDScriptParser::DataType GDScriptParser::_type_from_gdtype(const GDScriptDataTyp
switch (p_gdtype.kind) {
case GDScriptDataType::UNINITIALIZED: {
- ERR_EXPLAIN("Uninitialized datatype. Please report a bug.");
+ ERR_PRINT("Uninitialized datatype. Please report a bug.");
} break;
case GDScriptDataType::BUILTIN: {
result.kind = DataType::BUILTIN;
@@ -6147,8 +6149,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
}
if (!valid) {
- _set_error("Invalid cast. Cannot convert from '" + source_type.to_string() +
- "' to '" + cn->cast_type.to_string() + "'.",
+ _set_error("Invalid cast. Cannot convert from \"" + source_type.to_string() +
+ "\" to \"" + cn->cast_type.to_string() + "\".",
cn->line);
return DataType();
}
@@ -6177,11 +6179,11 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
DataType signal_type = _reduce_node_type(op->arguments[1]);
// TODO: Check if signal exists when it's a constant
if (base_type.has_type && base_type.kind == DataType::BUILTIN && base_type.builtin_type != Variant::NIL && base_type.builtin_type != Variant::OBJECT) {
- _set_error("First argument of 'yield()' must be an object.", op->line);
+ _set_error("The first argument of \"yield()\" must be an object.", op->line);
return DataType();
}
if (signal_type.has_type && (signal_type.kind != DataType::BUILTIN || signal_type.builtin_type != Variant::STRING)) {
- _set_error("Second argument of 'yield()' must be a string.", op->line);
+ _set_error("The second argument of \"yield()\" must be a string.", op->line);
return DataType();
}
}
@@ -6201,15 +6203,15 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
if (check_types && type_type.has_type) {
if (!type_type.is_meta_type && (type_type.kind != DataType::NATIVE || !ClassDB::is_parent_class(type_type.native_type, "Script"))) {
- _set_error("Invalid 'is' test: right operand is not a type (not a native type nor a script).", op->line);
+ _set_error("Invalid \"is\" test: the right operand isn't a type (neither a native type nor a script).", op->line);
return DataType();
}
type_type.is_meta_type = false; // Test the actual type
if (!_is_type_compatible(type_type, value_type) && !_is_type_compatible(value_type, type_type)) {
if (op->op == OperatorNode::OP_IS) {
- _set_error("A value of type '" + value_type.to_string() + "' will never be an instance of '" + type_type.to_string() + "'.", op->line);
+ _set_error("A value of type \"" + value_type.to_string() + "\" will never be an instance of \"" + type_type.to_string() + "\".", op->line);
} else {
- _set_error("A value of type '" + value_type.to_string() + "' will never be of type '" + type_type.to_string() + "'.", op->line);
+ _set_error("A value of type \"" + value_type.to_string() + "\" will never be of type \"" + type_type.to_string() + "\".", op->line);
}
return DataType();
}
@@ -6237,8 +6239,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
node_type = _get_operation_type(var_op, argument_type, argument_type, valid);
if (check_types && !valid) {
- _set_error("Invalid operand type ('" + argument_type.to_string() +
- "') to unary operator '" + Variant::get_operator_name(var_op) + "'.",
+ _set_error("Invalid operand type (\"" + argument_type.to_string() +
+ "\") to unary operator \"" + Variant::get_operator_name(var_op) + "\".",
op->line, op->column);
return DataType();
}
@@ -6282,8 +6284,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
node_type = _get_operation_type(var_op, argument_a_type, argument_b_type, valid);
if (check_types && !valid) {
- _set_error("Invalid operand types ('" + argument_a_type.to_string() + "' and '" +
- argument_b_type.to_string() + "') to operator '" + Variant::get_operator_name(var_op) + "'.",
+ _set_error("Invalid operand types (\"" + argument_a_type.to_string() + "\" and \"" +
+ argument_b_type.to_string() + "\") to operator \"" + Variant::get_operator_name(var_op) + "\".",
op->line, op->column);
return DataType();
}
@@ -6298,7 +6300,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
// Ternary operators
case OperatorNode::OP_TERNARY_IF: {
if (op->arguments.size() != 3) {
- _set_error("Parser bug: ternary operation without 3 arguments");
+ _set_error("Parser bug: ternary operation without 3 arguments.");
ERR_FAIL_V(DataType());
}
@@ -6331,7 +6333,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
case OperatorNode::OP_ASSIGN_BIT_XOR:
case OperatorNode::OP_INIT_ASSIGN: {
- _set_error("Assignment inside expression is not allowed (parser bug?).", op->line);
+ _set_error("Assignment inside an expression isn't allowed (parser bug?).", op->line);
return DataType();
} break;
@@ -6367,8 +6369,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
if (valid) {
result = _type_from_variant(res);
} else if (check_types) {
- _set_error("Can't get index '" + String(member_id->name.operator String()) + "' on base '" +
- base_type.to_string() + "'.",
+ _set_error("Can't get index \"" + String(member_id->name.operator String()) + "\" on base \"" +
+ base_type.to_string() + "\".",
op->line);
return DataType();
}
@@ -6460,7 +6462,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
}
}
if (error) {
- _set_error("Invalid index type (" + index_type.to_string() + ") for base '" + base_type.to_string() + "'.",
+ _set_error("Invalid index type (" + index_type.to_string() + ") for base \"" + base_type.to_string() + "\".",
op->line);
return DataType();
}
@@ -6493,8 +6495,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
node_type = _type_from_variant(res);
node_type.is_constant = false;
} else if (check_types) {
- _set_error("Can't get index '" + String(cn->value) + "' on base '" +
- base_type.to_string() + "'.",
+ _set_error("Can't get index \"" + String(cn->value) + "\" on base \"" +
+ base_type.to_string() + "\".",
op->line);
return DataType();
}
@@ -6504,7 +6506,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
_mark_line_as_unsafe(op->line);
}
} else if (!for_completion && (index_type.kind != DataType::BUILTIN || index_type.builtin_type != Variant::STRING)) {
- _set_error("Only strings can be used as index in the base type '" + base_type.to_string() + "'.", op->line);
+ _set_error("Only strings can be used as an index in the base type \"" + base_type.to_string() + "\".", op->line);
return DataType();
}
}
@@ -6521,7 +6523,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
case Variant::REAL:
case Variant::NODE_PATH:
case Variant::_RID: {
- _set_error("Can't index on a value of type '" + base_type.to_string() + "'.", op->line);
+ _set_error("Can't index on a value of type \"" + base_type.to_string() + "\".", op->line);
return DataType();
} break;
// Return int
@@ -6919,7 +6921,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat
if (check_types) {
if (!tmp.has_method(callee_name)) {
- _set_error("Method '" + callee_name + "' is not declared on base '" + base_type.to_string() + "'.", p_call->line);
+ _set_error("The method \"" + callee_name + "\" isn't declared on base \"" + base_type.to_string() + "\".", p_call->line);
return DataType();
}
@@ -6979,7 +6981,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat
if (!valid) {
#ifdef DEBUG_ENABLED
if (p_call->arguments[0]->type == Node::TYPE_SELF) {
- _set_error("Method '" + callee_name + "' is not declared in the current class.", p_call->line);
+ _set_error("The method \"" + callee_name + "\" isn't declared in the current class.", p_call->line);
return DataType();
}
DataType tmp_type;
@@ -7004,7 +7006,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat
}
if (check_types && !is_static && !is_initializer && base_type.is_meta_type) {
- _set_error("Non-static function '" + String(callee_name) + "' can only be called from an instance.", p_call->line);
+ _set_error("Non-static function \"" + String(callee_name) + "\" can only be called from an instance.", p_call->line);
return DataType();
}
@@ -7029,11 +7031,11 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat
}
if (arg_count < arg_types.size() - default_args_count) {
- _set_error("Too few arguments for '" + callee_name + "()' call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line);
+ _set_error("Too few arguments for \"" + callee_name + "()\" call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line);
return return_type;
}
if (!is_vararg && arg_count > arg_types.size()) {
- _set_error("Too many arguments for '" + callee_name + "()' call. Expected at most " + itos(arg_types.size()) + ".", p_call->line);
+ _set_error("Too many arguments for \"" + callee_name + "()\" call. Expected at most " + itos(arg_types.size()) + ".", p_call->line);
return return_type;
}
@@ -7055,7 +7057,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat
} else if (!_is_type_compatible(arg_types[i - arg_diff], par_type, true)) {
// Supertypes are acceptable for dynamic compliance
if (!_is_type_compatible(par_type, arg_types[i - arg_diff])) {
- _set_error("At '" + callee_name + "()' call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" +
+ _set_error("At \"" + callee_name + "()\" call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" +
par_type.to_string() + ") doesn't match the function argument's type (" +
arg_types[i - arg_diff].to_string() + ").",
p_call->line);
@@ -7203,7 +7205,7 @@ bool GDScriptParser::_get_member_type(const DataType &p_base_type, const StringN
}
if (!ClassDB::class_exists(native)) {
if (!check_types) return false;
- ERR_FAIL_V_MSG(false, "Parser bug: Class '" + String(native) + "' not found.");
+ ERR_FAIL_V_MSG(false, "Parser bug: Class \"" + String(native) + "\" not found.");
}
bool valid = false;
@@ -7373,7 +7375,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType
Ref<GDScript> gds = scr;
if (gds.is_valid()) {
if (!gds->is_valid()) {
- _set_error("Class '" + p_identifier + "' could not be fully loaded (script error or cyclic dependency).");
+ _set_error("The class \"" + p_identifier + "\" couldn't be fully loaded (script error or cyclic dependency).");
return DataType();
}
result.kind = DataType::GDSCRIPT;
@@ -7382,7 +7384,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType
}
return result;
}
- _set_error("Class '" + p_identifier + "' was found in global scope but its script could not be loaded.");
+ _set_error("The class \"" + p_identifier + "\" was found in global scope, but its script couldn't be loaded.");
return DataType();
}
@@ -7425,7 +7427,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType
Ref<GDScript> gds = singleton;
if (gds.is_valid()) {
if (!gds->is_valid()) {
- _set_error("Couldn't fully load singleton script '" + p_identifier + "' (possible cyclic reference or parse error).", p_line);
+ _set_error("Couldn't fully load the singleton script \"" + p_identifier + "\" (possible cyclic reference or parse error).", p_line);
return DataType();
}
result.kind = DataType::GDSCRIPT;
@@ -7437,7 +7439,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType
}
// This means looking in the current class, which type is always known
- _set_error("Identifier '" + p_identifier.operator String() + "' is not declared in the current scope.", p_line);
+ _set_error("The identifier \"" + p_identifier.operator String() + "\" isn't declared in the current scope.", p_line);
}
#ifdef DEBUG_ENABLED
@@ -7469,7 +7471,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
DataType expr = _resolve_type(c.expression->get_datatype(), c.expression->line);
if (check_types && !_is_type_compatible(cont, expr)) {
- _set_error("Constant value type (" + expr.to_string() + ") is not compatible with declared type (" + cont.to_string() + ").",
+ _set_error("The constant value type (" + expr.to_string() + ") isn't compatible with declared type (" + cont.to_string() + ").",
c.expression->line);
return;
}
@@ -7480,7 +7482,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
DataType tmp;
if (_get_member_type(p_class->base_type, E->key(), tmp)) {
- _set_error("Member '" + String(E->key()) + "' already exists in parent class.", c.expression->line);
+ _set_error("The member \"" + String(E->key()) + "\" already exists in a parent class.", c.expression->line);
return;
}
}
@@ -7502,7 +7504,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
DataType tmp;
if (_get_member_type(p_class->base_type, v.identifier, tmp)) {
- _set_error("Member '" + String(v.identifier) + "' already exists in parent class.", v.line);
+ _set_error("The member \"" + String(v.identifier) + "\" already exists in a parent class.", v.line);
return;
}
@@ -7519,7 +7521,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
} else {
// Try with implicit conversion
if (v.data_type.kind != DataType::BUILTIN || !_is_type_compatible(v.data_type, expr_type, true)) {
- _set_error("Assigned expression type (" + expr_type.to_string() + ") doesn't match the variable's type (" +
+ _set_error("The assigned expression's type (" + expr_type.to_string() + ") doesn't match the variable's type (" +
v.data_type.to_string() + ").",
v.line);
return;
@@ -7548,7 +7550,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
if (v.data_type.infer_type) {
if (!expr_type.has_type) {
- _set_error("Assigned value does not have a set type, variable type cannot be inferred.", v.line);
+ _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", v.line);
return;
}
v.data_type = expr_type;
@@ -7560,7 +7562,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
if (v.data_type.has_type && v._export.type != Variant::NIL) {
DataType export_type = _type_from_property(v._export);
if (!_is_type_compatible(v.data_type, export_type, true)) {
- _set_error("Export hint type (" + export_type.to_string() + ") doesn't match the variable's type (" +
+ _set_error("The export hint's type (" + export_type.to_string() + ") doesn't match the variable's type (" +
v.data_type.to_string() + ").",
v.line);
return;
@@ -7579,15 +7581,15 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
if (setter->get_required_argument_count() != 1 &&
!(setter->get_required_argument_count() == 0 && setter->default_values.size() > 0)) {
- _set_error("Setter function needs to receive exactly 1 argument. See '" + setter->name +
- "()' definition at line " + itos(setter->line) + ".",
+ _set_error("The setter function needs to receive exactly 1 argument. See \"" + setter->name +
+ "()\" definition at line " + itos(setter->line) + ".",
v.line);
return;
}
if (!_is_type_compatible(v.data_type, setter->argument_types[0])) {
- _set_error("Setter argument type (" + setter->argument_types[0].to_string() +
- ") doesn't match the variable's type (" + v.data_type.to_string() + "). See '" +
- setter->name + "()' definition at line " + itos(setter->line) + ".",
+ _set_error("The setter argument's type (" + setter->argument_types[0].to_string() +
+ ") doesn't match the variable's type (" + v.data_type.to_string() + "). See \"" +
+ setter->name + "()\" definition at line " + itos(setter->line) + ".",
v.line);
return;
}
@@ -7598,15 +7600,15 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
FunctionNode *getter = p_class->functions[j];
if (getter->get_required_argument_count() != 0) {
- _set_error("Getter function can't receive arguments. See '" + getter->name +
- "()' definition at line " + itos(getter->line) + ".",
+ _set_error("The getter function can't receive arguments. See \"" + getter->name +
+ "()\" definition at line " + itos(getter->line) + ".",
v.line);
return;
}
if (!_is_type_compatible(v.data_type, getter->get_datatype())) {
- _set_error("Getter return type (" + getter->get_datatype().to_string() +
+ _set_error("The getter return type (" + getter->get_datatype().to_string() +
") doesn't match the variable's type (" + v.data_type.to_string() +
- "). See '" + getter->name + "()' definition at line " + itos(getter->line) + ".",
+ "). See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".",
v.line);
return;
}
@@ -7620,23 +7622,23 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
for (int j = 0; j < p_class->static_functions.size(); j++) {
if (v.setter == p_class->static_functions[j]->name) {
FunctionNode *setter = p_class->static_functions[j];
- _set_error("Setter can't be a static function. See '" + setter->name + "()' definition at line " + itos(setter->line) + ".", v.line);
+ _set_error("The setter can't be a static function. See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line);
return;
}
if (v.getter == p_class->static_functions[j]->name) {
FunctionNode *getter = p_class->static_functions[j];
- _set_error("Getter can't be a static function. See '" + getter->name + "()' definition at line " + itos(getter->line) + ".", v.line);
+ _set_error("The getter can't be a static function. See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line);
return;
}
}
if (!found_setter && v.setter != StringName()) {
- _set_error("Setter function is not defined.", v.line);
+ _set_error("The setter function isn't defined.", v.line);
return;
}
if (!found_getter && v.getter != StringName()) {
- _set_error("Getter function is not defined.", v.line);
+ _set_error("The getter function isn't defined.", v.line);
return;
}
}
@@ -7683,7 +7685,7 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) {
if (!_is_type_compatible(p_function->argument_types[i], def_type, true)) {
String arg_name = p_function->arguments[i];
_set_error("Value type (" + def_type.to_string() + ") doesn't match the type of argument '" +
- arg_name + "' (" + p_function->arguments[i] + ")",
+ arg_name + "' (" + p_function->arguments[i] + ").",
p_function->line);
}
}
@@ -7746,21 +7748,21 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) {
}
}
parent_signature += ")";
- _set_error("Function signature doesn't match the parent. Parent signature is: '" + parent_signature + "'.", p_function->line);
+ _set_error("The function signature doesn't match the parent. Parent signature is: \"" + parent_signature + "\".", p_function->line);
return;
}
}
#endif // DEBUG_ENABLED
} else {
if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) {
- _set_error("Constructor cannot return a value.", p_function->line);
+ _set_error("The constructor can't return a value.", p_function->line);
return;
}
}
if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) {
if (!p_function->body->has_return) {
- _set_error("Non-void function must return a value in all possible paths.", p_function->line);
+ _set_error("A non-void function must return a value in all possible paths.", p_function->line);
return;
}
}
@@ -7891,7 +7893,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
} else {
// Try implicit conversion
if (lv->datatype.kind != DataType::BUILTIN || !_is_type_compatible(lv->datatype, assign_type, true)) {
- _set_error("Assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" +
+ _set_error("The assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" +
lv->datatype.to_string() + ").",
lv->line);
return;
@@ -7923,7 +7925,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
}
if (lv->datatype.infer_type) {
if (!assign_type.has_type) {
- _set_error("Assigned value does not have a set type, variable type cannot be inferred.", lv->line);
+ _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", lv->line);
return;
}
lv->datatype = assign_type;
@@ -7974,7 +7976,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
}
}
if (lh_type.is_constant) {
- _set_error("Cannot assign a new value to a constant.", op->line);
+ _set_error("Can't assign a new value to a constant.", op->line);
return;
}
}
@@ -7993,8 +7995,8 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
rh_type = _get_operation_type(oper, lh_type, arg_type, valid);
if (check_types && !valid) {
- _set_error("Invalid operand types ('" + lh_type.to_string() + "' and '" + arg_type.to_string() +
- "') to assignment operator '" + Variant::get_operator_name(oper) + "'.",
+ _set_error("Invalid operand types (\"" + lh_type.to_string() + "\" and \"" + arg_type.to_string() +
+ "\") to assignment operator \"" + Variant::get_operator_name(oper) + "\".",
op->line);
return;
}
@@ -8022,7 +8024,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
} else {
// Try implicit conversion
if (lh_type.kind != DataType::BUILTIN || !_is_type_compatible(lh_type, rh_type, true)) {
- _set_error("Assigned value type (" + rh_type.to_string() + ") doesn't match the variable's type (" +
+ _set_error("The assigned value's type (" + rh_type.to_string() + ") doesn't match the variable's type (" +
lh_type.to_string() + ").",
op->line);
return;
@@ -8107,18 +8109,18 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) {
if (function_type.kind == DataType::BUILTIN && function_type.builtin_type == Variant::NIL) {
// Return void, should not have arguments
if (cf->arguments.size() > 0) {
- _set_error("Void function cannot return a value.", cf->line, cf->column);
+ _set_error("A void function cannot return a value.", cf->line, cf->column);
return;
}
} else {
// Return something, cannot be empty
if (cf->arguments.size() == 0) {
- _set_error("Non-void function must return a value.", cf->line, cf->column);
+ _set_error("A non-void function must return a value.", cf->line, cf->column);
return;
}
if (!_is_type_compatible(function_type, ret_type)) {
- _set_error("Returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" +
+ _set_error("The returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" +
function_type.to_string() + ").",
cf->line, cf->column);
return;
@@ -8255,6 +8257,10 @@ int GDScriptParser::get_error_column() const {
return error_column;
}
+bool GDScriptParser::has_error() const {
+ return error_set;
+}
+
Error GDScriptParser::_parse(const String &p_base_path) {
base_path = p_base_path;
@@ -8271,7 +8277,7 @@ Error GDScriptParser::_parse(const String &p_base_path) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) {
error_set = false;
- _set_error("Parse Error: " + tokenizer->get_token_error());
+ _set_error("Parse error: " + tokenizer->get_token_error());
}
if (error_set && !for_completion) {
diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h
index 62d7bdb393..72aa819a8c 100644
--- a/modules/gdscript/gdscript_parser.h
+++ b/modules/gdscript/gdscript_parser.h
@@ -632,6 +632,7 @@ private:
Error _parse(const String &p_base_path);
public:
+ bool has_error() const;
String get_error() const;
int get_error_line() const;
int get_error_column() const;
diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp
new file mode 100644
index 0000000000..45f9ec9c6a
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp
@@ -0,0 +1,759 @@
+/*************************************************************************/
+/* gdscript_extend_parser.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "gdscript_extend_parser.h"
+#include "../gdscript.h"
+#include "core/io/json.h"
+#include "gdscript_language_protocol.h"
+#include "gdscript_workspace.h"
+
+void ExtendGDScriptParser::update_diagnostics() {
+
+ diagnostics.clear();
+
+ if (has_error()) {
+ lsp::Diagnostic diagnostic;
+ diagnostic.severity = lsp::DiagnosticSeverity::Error;
+ diagnostic.message = get_error();
+ diagnostic.source = "gdscript";
+ diagnostic.code = -1;
+ lsp::Range range;
+ lsp::Position pos;
+ int line = LINE_NUMBER_TO_INDEX(get_error_line());
+ const String &line_text = get_lines()[line];
+ pos.line = line;
+ pos.character = line_text.length() - line_text.strip_edges(true, false).length();
+ range.start = pos;
+ range.end = range.start;
+ range.end.character = line_text.strip_edges(false).length();
+ diagnostic.range = range;
+ diagnostics.push_back(diagnostic);
+ }
+
+ const List<GDScriptWarning> &warnings = get_warnings();
+ for (const List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
+ const GDScriptWarning &warning = E->get();
+ lsp::Diagnostic diagnostic;
+ diagnostic.severity = lsp::DiagnosticSeverity::Warning;
+ diagnostic.message = warning.get_message();
+ diagnostic.source = "gdscript";
+ diagnostic.code = warning.code;
+ lsp::Range range;
+ lsp::Position pos;
+ int line = LINE_NUMBER_TO_INDEX(warning.line);
+ const String &line_text = get_lines()[line];
+ pos.line = line;
+ pos.character = line_text.length() - line_text.strip_edges(true, false).length();
+ range.start = pos;
+ range.end = pos;
+ range.end.character = line_text.strip_edges(false).length();
+ diagnostic.range = range;
+ diagnostics.push_back(diagnostic);
+ }
+}
+
+void ExtendGDScriptParser::update_symbols() {
+
+ members.clear();
+
+ const GDScriptParser::Node *head = get_parse_tree();
+ if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) {
+
+ parse_class_symbol(gdclass, class_symbol);
+
+ for (int i = 0; i < class_symbol.children.size(); i++) {
+ const lsp::DocumentSymbol &symbol = class_symbol.children[i];
+ members.set(symbol.name, &symbol);
+
+ // cache level one inner classes
+ if (symbol.kind == lsp::SymbolKind::Class) {
+ ClassMembers inner_class;
+ for (int j = 0; j < symbol.children.size(); j++) {
+ const lsp::DocumentSymbol &s = symbol.children[j];
+ inner_class.set(s.name, &s);
+ }
+ inner_classes.set(symbol.name, inner_class);
+ }
+ }
+ }
+}
+
+void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol) {
+
+ const String uri = get_uri();
+
+ r_symbol.uri = uri;
+ r_symbol.script_path = path;
+ r_symbol.children.clear();
+ r_symbol.name = p_class->name;
+ if (r_symbol.name.empty())
+ r_symbol.name = path.get_file();
+ r_symbol.kind = lsp::SymbolKind::Class;
+ r_symbol.deprecated = false;
+ r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_class->line);
+ r_symbol.range.start.character = p_class->column;
+ r_symbol.range.end.line = LINE_NUMBER_TO_INDEX(p_class->end_line);
+ r_symbol.selectionRange.start.line = r_symbol.range.start.line;
+ r_symbol.detail = "class " + r_symbol.name;
+ bool is_root_class = &r_symbol == &class_symbol;
+ r_symbol.documentation = parse_documentation_as_markdown(is_root_class ? 0 : LINE_NUMBER_TO_INDEX(p_class->line), is_root_class);
+
+ for (int i = 0; i < p_class->variables.size(); ++i) {
+
+ const GDScriptParser::ClassNode::Member &m = p_class->variables[i];
+
+ lsp::DocumentSymbol symbol;
+ symbol.name = m.identifier;
+ symbol.kind = lsp::SymbolKind::Variable;
+ symbol.deprecated = false;
+ const int line = LINE_NUMBER_TO_INDEX(m.line);
+ symbol.range.start.line = line;
+ symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length();
+ symbol.range.end.line = line;
+ symbol.range.end.character = lines[line].length();
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ if (m._export.type != Variant::NIL) {
+ symbol.detail += "export ";
+ }
+ symbol.detail += "var " + m.identifier;
+ if (m.data_type.kind != GDScriptParser::DataType::UNRESOLVED) {
+ symbol.detail += ": " + m.data_type.to_string();
+ }
+ if (m.default_value.get_type() != Variant::NIL) {
+ symbol.detail += " = " + JSON::print(m.default_value);
+ }
+
+ symbol.documentation = parse_documentation_as_markdown(line);
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ r_symbol.children.push_back(symbol);
+ }
+
+ for (int i = 0; i < p_class->_signals.size(); ++i) {
+ const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i];
+
+ lsp::DocumentSymbol symbol;
+ symbol.name = signal.name;
+ symbol.kind = lsp::SymbolKind::Event;
+ symbol.deprecated = false;
+ const int line = LINE_NUMBER_TO_INDEX(signal.line);
+ symbol.range.start.line = line;
+ symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length();
+ symbol.range.end.line = symbol.range.start.line;
+ symbol.range.end.character = lines[line].length();
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ symbol.documentation = parse_documentation_as_markdown(line);
+ symbol.uri = uri;
+ symbol.script_path = path;
+ symbol.detail = "signal " + signal.name + "(";
+ for (int j = 0; j < signal.arguments.size(); j++) {
+ if (j > 0) {
+ symbol.detail += ", ";
+ }
+ symbol.detail += signal.arguments[j];
+ }
+ symbol.detail += ")";
+
+ r_symbol.children.push_back(symbol);
+ }
+
+ for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
+ lsp::DocumentSymbol symbol;
+ const GDScriptParser::ClassNode::Constant &c = E->value();
+ const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression);
+ symbol.name = E->key();
+ symbol.kind = lsp::SymbolKind::Constant;
+ symbol.deprecated = false;
+ const int line = LINE_NUMBER_TO_INDEX(E->get().expression->line);
+ symbol.range.start.line = line;
+ symbol.range.start.character = E->get().expression->column;
+ symbol.range.end.line = symbol.range.start.line;
+ symbol.range.end.character = lines[line].length();
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ symbol.documentation = parse_documentation_as_markdown(line);
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ symbol.detail = "const " + symbol.name;
+ if (c.type.kind != GDScriptParser::DataType::UNRESOLVED) {
+ symbol.detail += ": " + c.type.to_string();
+ }
+
+ String value_text;
+ if (node->value.get_type() == Variant::OBJECT) {
+ RES res = node->value;
+ if (res.is_valid() && !res->get_path().empty()) {
+ value_text = "preload(\"" + res->get_path() + "\")";
+ if (symbol.documentation.empty()) {
+ if (Map<String, ExtendGDScriptParser *>::Element *S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
+ symbol.documentation = S->get()->class_symbol.documentation;
+ }
+ }
+ } else {
+ value_text = JSON::print(node->value);
+ }
+ } else {
+ value_text = JSON::print(node->value);
+ }
+ if (!value_text.empty()) {
+ symbol.detail += " = " + value_text;
+ }
+
+ r_symbol.children.push_back(symbol);
+ }
+
+ for (int i = 0; i < p_class->functions.size(); ++i) {
+ const GDScriptParser::FunctionNode *func = p_class->functions[i];
+ lsp::DocumentSymbol symbol;
+ parse_function_symbol(func, symbol);
+ r_symbol.children.push_back(symbol);
+ }
+
+ for (int i = 0; i < p_class->static_functions.size(); ++i) {
+ const GDScriptParser::FunctionNode *func = p_class->static_functions[i];
+ lsp::DocumentSymbol symbol;
+ parse_function_symbol(func, symbol);
+ r_symbol.children.push_back(symbol);
+ }
+
+ for (int i = 0; i < p_class->subclasses.size(); ++i) {
+ const GDScriptParser::ClassNode *subclass = p_class->subclasses[i];
+ lsp::DocumentSymbol symbol;
+ parse_class_symbol(subclass, symbol);
+ r_symbol.children.push_back(symbol);
+ }
+}
+
+void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol) {
+
+ const String uri = get_uri();
+
+ r_symbol.name = p_func->name;
+ r_symbol.kind = lsp::SymbolKind::Function;
+ r_symbol.detail = "func " + p_func->name + "(";
+ r_symbol.deprecated = false;
+ const int line = LINE_NUMBER_TO_INDEX(p_func->line);
+ r_symbol.range.start.line = line;
+ r_symbol.range.start.character = p_func->column;
+ r_symbol.range.end.line = MAX(p_func->body->end_line - 2, p_func->body->line);
+ r_symbol.range.end.character = lines[r_symbol.range.end.line].length();
+ r_symbol.selectionRange.start.line = r_symbol.range.start.line;
+ r_symbol.documentation = parse_documentation_as_markdown(line);
+ r_symbol.uri = uri;
+ r_symbol.script_path = path;
+
+ String arguments;
+ for (int i = 0; i < p_func->arguments.size(); i++) {
+ lsp::DocumentSymbol symbol;
+ symbol.kind = lsp::SymbolKind::Variable;
+ symbol.name = p_func->arguments[i];
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_func->body->line);
+ symbol.range.start.character = p_func->body->column;
+ symbol.range.end = symbol.range.start;
+ symbol.uri = uri;
+ symbol.script_path = path;
+ r_symbol.children.push_back(symbol);
+ if (i > 0) {
+ arguments += ", ";
+ }
+ arguments += String(p_func->arguments[i]);
+ if (p_func->argument_types[i].kind != GDScriptParser::DataType::UNRESOLVED) {
+ arguments += ": " + p_func->argument_types[i].to_string();
+ }
+ int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size());
+ if (default_value_idx >= 0) {
+ const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]);
+ if (const_node == NULL) {
+ const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]);
+ if (operator_node) {
+ const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next);
+ }
+ }
+
+ if (const_node) {
+ String value = JSON::print(const_node->value);
+ arguments += " = " + value;
+ }
+ }
+ }
+ r_symbol.detail += arguments + ")";
+ if (p_func->return_type.kind != GDScriptParser::DataType::UNRESOLVED) {
+ r_symbol.detail += " -> " + p_func->return_type.to_string();
+ }
+
+ for (const Map<StringName, LocalVarNode *>::Element *E = p_func->body->variables.front(); E; E = E->next()) {
+ lsp::DocumentSymbol symbol;
+ const GDScriptParser::LocalVarNode *var = E->value();
+ symbol.name = E->key();
+ symbol.kind = lsp::SymbolKind::Variable;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(E->get()->line);
+ symbol.range.start.character = E->get()->column;
+ symbol.range.end.line = symbol.range.start.line;
+ symbol.range.end.character = lines[symbol.range.end.line].length();
+ symbol.uri = uri;
+ symbol.script_path = path;
+ symbol.detail = "var " + symbol.name;
+ if (var->datatype.kind != GDScriptParser::DataType::UNRESOLVED) {
+ symbol.detail += ": " + var->datatype.to_string();
+ }
+ symbol.documentation = parse_documentation_as_markdown(line);
+ r_symbol.children.push_back(symbol);
+ }
+}
+
+String ExtendGDScriptParser::marked_documentation(const String &p_bbcode) {
+
+ String markdown = p_bbcode.strip_edges();
+
+ Vector<String> lines = markdown.split("\n");
+ bool in_code_block = false;
+ int code_block_indent = -1;
+
+ markdown = "";
+ for (int i = 0; i < lines.size(); i++) {
+ String line = lines[i];
+ int block_start = line.find("[codeblock]");
+ if (block_start != -1) {
+ code_block_indent = block_start;
+ in_code_block = true;
+ line = "'''gdscript";
+ line = "\n";
+ } else if (in_code_block) {
+ line = "\t" + line.substr(code_block_indent, line.length());
+ }
+
+ if (in_code_block && line.find("[/codeblock]") != -1) {
+ line = "'''\n";
+ line = "\n";
+ in_code_block = false;
+ }
+
+ if (!in_code_block) {
+ line = line.strip_edges();
+ line = line.replace("[code]", "`");
+ line = line.replace("[/code]", "`");
+ line = line.replace("[i]", "*");
+ line = line.replace("[/i]", "*");
+ line = line.replace("[b]", "**");
+ line = line.replace("[/b]", "**");
+ line = line.replace("[u]", "__");
+ line = line.replace("[/u]", "__");
+ line = line.replace("[method ", "`");
+ line = line.replace("[member ", "`");
+ line = line.replace("[signal ", "`");
+ line = line.replace("[enum ", "`");
+ line = line.replace("[constant ", "`");
+ line = line.replace("[", "`");
+ line = line.replace("]", "`");
+ }
+
+ if (!in_code_block && i < lines.size() - 1) {
+ line += "\n\n";
+ } else if (i < lines.size() - 1) {
+ line += "\n";
+ }
+ markdown += line;
+ }
+ return markdown;
+}
+
+String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) {
+ ERR_FAIL_INDEX_V(p_line, lines.size(), String());
+
+ List<String> doc_lines;
+
+ if (!p_docs_down) { // inline comment
+ String inline_comment = lines[p_line];
+ int comment_start = inline_comment.find("#");
+ if (comment_start != -1) {
+ inline_comment = inline_comment.substr(comment_start, inline_comment.length()).strip_edges();
+ if (inline_comment.length() > 1) {
+ doc_lines.push_back(inline_comment.substr(1, inline_comment.length()));
+ }
+ }
+ }
+
+ int step = p_docs_down ? 1 : -1;
+ int start_line = p_docs_down ? p_line : p_line - 1;
+ for (int i = start_line; true; i += step) {
+
+ if (i < 0 || i >= lines.size()) break;
+
+ String line_comment = lines[i].strip_edges(true, false);
+ if (line_comment.begins_with("#")) {
+ line_comment = line_comment.substr(1, line_comment.length());
+ if (p_docs_down) {
+ doc_lines.push_back(line_comment);
+ } else {
+ doc_lines.push_front(line_comment);
+ }
+ } else {
+ break;
+ }
+ }
+
+ String doc;
+ for (List<String>::Element *E = doc_lines.front(); E; E = E->next()) {
+ doc += E->get() + "\n";
+ }
+ return doc;
+}
+
+String ExtendGDScriptParser::get_text_for_completion(const lsp::Position &p_cursor) const {
+
+ String longthing;
+ int len = lines.size();
+ for (int i = 0; i < len; i++) {
+
+ if (i == p_cursor.line) {
+ longthing += lines[i].substr(0, p_cursor.character);
+ longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ longthing += lines[i].substr(p_cursor.character, lines[i].size());
+ } else {
+
+ longthing += lines[i];
+ }
+
+ if (i != len - 1)
+ longthing += "\n";
+ }
+
+ return longthing;
+}
+
+String ExtendGDScriptParser::get_text_for_lookup_symbol(const lsp::Position &p_cursor, const String &p_symbol, bool p_func_requred) const {
+ String longthing;
+ int len = lines.size();
+ for (int i = 0; i < len; i++) {
+
+ if (i == p_cursor.line) {
+ String line = lines[i];
+ String first_part = line.substr(0, p_cursor.character);
+ String last_part = line.substr(p_cursor.character + 1, lines[i].length());
+ if (!p_symbol.empty()) {
+ String left_cursor_text;
+ for (int c = p_cursor.character - 1; c >= 0; c--) {
+ left_cursor_text = line.substr(c, p_cursor.character - c);
+ if (p_symbol.begins_with(left_cursor_text)) {
+ first_part = line.substr(0, c);
+ first_part += p_symbol;
+ break;
+ }
+ }
+ }
+
+ longthing += first_part;
+ longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ if (p_func_requred) {
+ longthing += "("; // tell the parser this is a function call
+ }
+ longthing += last_part;
+ } else {
+
+ longthing += lines[i];
+ }
+
+ if (i != len - 1)
+ longthing += "\n";
+ }
+
+ return longthing;
+}
+
+String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &p_position, Vector2i &p_offset) const {
+
+ ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
+ String line = lines[p_position.line];
+ ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
+
+ int start_pos = p_position.character;
+ for (int c = p_position.character; c >= 0; c--) {
+ start_pos = c;
+ CharType ch = line[c];
+ bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_';
+ if (!valid_char) {
+ break;
+ }
+ }
+
+ int end_pos = p_position.character;
+ for (int c = p_position.character; c < line.length(); c++) {
+ CharType ch = line[c];
+ bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_';
+ if (!valid_char) {
+ break;
+ }
+ end_pos = c;
+ }
+ if (start_pos < end_pos) {
+ p_offset.x = start_pos - p_position.character;
+ p_offset.y = end_pos - p_position.character;
+ return line.substr(start_pos + 1, end_pos - start_pos);
+ }
+
+ return "";
+}
+
+String ExtendGDScriptParser::get_uri() const {
+ return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
+}
+
+const lsp::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const lsp::DocumentSymbol &p_parent) const {
+ const lsp::DocumentSymbol *ret = NULL;
+ if (p_line < p_parent.range.start.line) {
+ return ret;
+ } else if (p_parent.range.start.line == p_line) {
+ return &p_parent;
+ } else {
+ for (int i = 0; i < p_parent.children.size(); i++) {
+ ret = search_symbol_defined_at_line(p_line, p_parent.children[i]);
+ if (ret) {
+ break;
+ }
+ }
+ }
+ return ret;
+}
+
+String ExtendGDScriptParser::parse_documentation_as_markdown(int p_line, bool p_docs_down) {
+ return marked_documentation(parse_documentation(p_line, p_docs_down));
+}
+
+const lsp::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line) const {
+ if (p_line <= 0) {
+ return &class_symbol;
+ }
+ return search_symbol_defined_at_line(p_line, class_symbol);
+}
+
+const lsp::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
+
+ if (p_subclass.empty()) {
+ const lsp::DocumentSymbol *const *ptr = members.getptr(p_name);
+ if (ptr) {
+ return *ptr;
+ }
+ } else {
+ if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
+ const lsp::DocumentSymbol *const *ptr = _class->getptr(p_name);
+ if (ptr) {
+ return *ptr;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+const Array &ExtendGDScriptParser::get_member_completions() {
+
+ if (member_completions.empty()) {
+
+ const String *name = members.next(NULL);
+ while (name) {
+
+ const lsp::DocumentSymbol *symbol = members.get(*name);
+ lsp::CompletionItem item = symbol->make_completion_item();
+ item.data = JOIN_SYMBOLS(path, *name);
+ member_completions.push_back(item.to_json());
+
+ name = members.next(name);
+ }
+
+ const String *_class = inner_classes.next(NULL);
+ while (_class) {
+
+ const ClassMembers *inner_class = inner_classes.getptr(*_class);
+ const String *member_name = inner_class->next(NULL);
+ while (member_name) {
+ const lsp::DocumentSymbol *symbol = inner_class->get(*member_name);
+ lsp::CompletionItem item = symbol->make_completion_item();
+ item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(*_class, *member_name));
+ member_completions.push_back(item.to_json());
+
+ member_name = inner_class->next(member_name);
+ }
+
+ _class = inner_classes.next(_class);
+ }
+ }
+
+ return member_completions;
+}
+
+Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
+ Dictionary func;
+ ERR_FAIL_NULL_V(p_func, func);
+ func["name"] = p_func->name;
+ func["return_type"] = p_func->return_type.to_string();
+ func["rpc_mode"] = p_func->rpc_mode;
+ Array arguments;
+ for (int i = 0; i < p_func->arguments.size(); i++) {
+ Dictionary arg;
+ arg["name"] = p_func->arguments[i];
+ arg["type"] = p_func->argument_types[i].to_string();
+ int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size());
+ if (default_value_idx >= 0) {
+ const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]);
+ if (const_node == NULL) {
+ const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]);
+ if (operator_node) {
+ const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next);
+ }
+ }
+ if (const_node) {
+ arg["default_value"] = const_node->value;
+ }
+ }
+ arguments.push_back(arg);
+ }
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->line))) {
+ func["signature"] = symbol->detail;
+ func["description"] = symbol->documentation;
+ }
+ func["arguments"] = arguments;
+ return func;
+}
+
+Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
+ Dictionary class_api;
+
+ ERR_FAIL_NULL_V(p_class, class_api);
+
+ class_api["name"] = String(p_class->name);
+ class_api["path"] = path;
+ Array extends_class;
+ for (int i = 0; i < p_class->extends_class.size(); i++) {
+ extends_class.append(String(p_class->extends_class[i]));
+ }
+ class_api["extends_class"] = extends_class;
+ class_api["extends_file"] = String(p_class->extends_file);
+ class_api["icon"] = String(p_class->icon_path);
+
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->line))) {
+ class_api["signature"] = symbol->detail;
+ class_api["description"] = symbol->documentation;
+ }
+
+ Array subclasses;
+ for (int i = 0; i < p_class->subclasses.size(); i++) {
+ subclasses.push_back(dump_class_api(p_class->subclasses[i]));
+ }
+ class_api["sub_classes"] = subclasses;
+
+ Array constants;
+ for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
+
+ const GDScriptParser::ClassNode::Constant &c = E->value();
+ const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression);
+
+ Dictionary api;
+ api["name"] = E->key();
+ api["value"] = node->value;
+ api["data_type"] = node->datatype.to_string();
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(node->line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ constants.push_back(api);
+ }
+ class_api["constants"] = constants;
+
+ Array members;
+ for (int i = 0; i < p_class->variables.size(); ++i) {
+ const GDScriptParser::ClassNode::Member &m = p_class->variables[i];
+ Dictionary api;
+ api["name"] = m.identifier;
+ api["data_type"] = m.data_type.to_string();
+ api["default_value"] = m.default_value;
+ api["setter"] = String(m.setter);
+ api["getter"] = String(m.getter);
+ api["export"] = m._export.type != Variant::NIL;
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ members.push_back(api);
+ }
+ class_api["members"] = members;
+
+ Array signals;
+ for (int i = 0; i < p_class->_signals.size(); ++i) {
+ const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i];
+ Dictionary api;
+ api["name"] = signal.name;
+ Array args;
+ for (int j = 0; j < signal.arguments.size(); j++) {
+ args.append(signal.arguments[j]);
+ }
+ api["arguments"] = args;
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(signal.line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ signals.push_back(api);
+ }
+ class_api["signals"] = signals;
+
+ Array methods;
+ for (int i = 0; i < p_class->functions.size(); ++i) {
+ methods.append(dump_function_api(p_class->functions[i]));
+ }
+ class_api["methods"] = methods;
+
+ Array static_functions;
+ for (int i = 0; i < p_class->static_functions.size(); ++i) {
+ static_functions.append(dump_function_api(p_class->functions[i]));
+ }
+ class_api["static_functions"] = static_functions;
+
+ return class_api;
+}
+
+Dictionary ExtendGDScriptParser::generate_api() const {
+
+ Dictionary api;
+ const GDScriptParser::Node *head = get_parse_tree();
+ if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) {
+ api = dump_class_api(gdclass);
+ }
+ return api;
+}
+
+Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
+ path = p_path;
+ lines = p_code.split("\n");
+
+ Error err = GDScriptParser::parse(p_code, p_path.get_base_dir(), false, p_path, false, NULL, false);
+ update_diagnostics();
+ update_symbols();
+ return err;
+}
diff --git a/modules/gdscript/language_server/gdscript_extend_parser.h b/modules/gdscript/language_server/gdscript_extend_parser.h
new file mode 100644
index 0000000000..dd0453d3ff
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_extend_parser.h
@@ -0,0 +1,103 @@
+/*************************************************************************/
+/* gdscript_extend_parser.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GDSCRIPT_EXTEND_PARSER_H
+#define GDSCRIPT_EXTEND_PARSER_H
+
+#include "../gdscript_parser.h"
+#include "core/variant.h"
+#include "lsp.hpp"
+
+#ifndef LINE_NUMBER_TO_INDEX
+#define LINE_NUMBER_TO_INDEX(p_line) ((p_line)-1)
+#endif
+
+#ifndef SYMBOL_SEPERATOR
+#define SYMBOL_SEPERATOR "::"
+#endif
+
+#ifndef JOIN_SYMBOLS
+#define JOIN_SYMBOLS(p_path, name) ((p_path) + SYMBOL_SEPERATOR + (name))
+#endif
+
+typedef HashMap<String, const lsp::DocumentSymbol *> ClassMembers;
+
+class ExtendGDScriptParser : public GDScriptParser {
+
+ String path;
+ Vector<String> lines;
+
+ lsp::DocumentSymbol class_symbol;
+ Vector<lsp::Diagnostic> diagnostics;
+ ClassMembers members;
+ HashMap<String, ClassMembers> inner_classes;
+
+ void update_diagnostics();
+
+ void update_symbols();
+ void parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol);
+ void parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol);
+
+ Dictionary dump_function_api(const GDScriptParser::FunctionNode *p_func) const;
+ Dictionary dump_class_api(const GDScriptParser::ClassNode *p_class) const;
+
+ String parse_documentation(int p_line, bool p_docs_down = false);
+ const lsp::DocumentSymbol *search_symbol_defined_at_line(int p_line, const lsp::DocumentSymbol &p_parent) const;
+
+ Array member_completions;
+
+ String parse_documentation_as_markdown(int p_line, bool p_docs_down = false);
+
+public:
+ static String marked_documentation(const String &p_bbcode);
+
+public:
+ _FORCE_INLINE_ const String &get_path() const { return path; }
+ _FORCE_INLINE_ const Vector<String> &get_lines() const { return lines; }
+ _FORCE_INLINE_ const lsp::DocumentSymbol &get_symbols() const { return class_symbol; }
+ _FORCE_INLINE_ const Vector<lsp::Diagnostic> &get_diagnostics() const { return diagnostics; }
+ _FORCE_INLINE_ const ClassMembers &get_members() const { return members; }
+ _FORCE_INLINE_ const HashMap<String, ClassMembers> &get_inner_classes() const { return inner_classes; }
+
+ String get_text_for_completion(const lsp::Position &p_cursor) const;
+ String get_text_for_lookup_symbol(const lsp::Position &p_cursor, const String &p_symbol = "", bool p_func_requred = false) const;
+ String get_identifier_under_position(const lsp::Position &p_position, Vector2i &p_offset) const;
+ String get_uri() const;
+
+ const lsp::DocumentSymbol *get_symbol_defined_at_line(int p_line) const;
+ const lsp::DocumentSymbol *get_member_symbol(const String &p_name, const String &p_subclass = "") const;
+
+ const Array &get_member_completions();
+ Dictionary generate_api() const;
+
+ Error parse(const String &p_code, const String &p_path);
+};
+
+#endif
diff --git a/modules/gdscript/language_server/gdscript_language_protocol.cpp b/modules/gdscript/language_server/gdscript_language_protocol.cpp
new file mode 100644
index 0000000000..afe461b68e
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_language_protocol.cpp
@@ -0,0 +1,211 @@
+/*************************************************************************/
+/* gdscript_language_protocol.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "gdscript_language_protocol.h"
+#include "core/io/json.h"
+#include "core/os/copymem.h"
+#include "core/project_settings.h"
+#include "editor/editor_node.h"
+
+GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = NULL;
+
+void GDScriptLanguageProtocol::on_data_received(int p_id) {
+ lastest_client_id = p_id;
+ Ref<WebSocketPeer> peer = server->get_peer(p_id);
+ PoolByteArray data;
+ if (OK == peer->get_packet_buffer(data)) {
+ String message;
+ message.parse_utf8((const char *)data.read().ptr(), data.size());
+ if (message.begins_with("Content-Length:")) return;
+ String output = process_message(message);
+ if (!output.empty()) {
+ CharString charstr = output.utf8();
+ peer->put_packet((const uint8_t *)charstr.ptr(), charstr.length());
+ }
+ }
+}
+
+void GDScriptLanguageProtocol::on_client_connected(int p_id, const String &p_protocal) {
+ clients.set(p_id, server->get_peer(p_id));
+}
+
+void GDScriptLanguageProtocol::on_client_disconnected(int p_id, bool p_was_clean_close) {
+ clients.erase(p_id);
+}
+
+String GDScriptLanguageProtocol::process_message(const String &p_text) {
+ String ret = process_string(p_text);
+ if (ret.empty()) {
+ return ret;
+ } else {
+ return format_output(ret);
+ }
+}
+
+String GDScriptLanguageProtocol::format_output(const String &p_text) {
+
+ String header = "Content-Length: ";
+ CharString charstr = p_text.utf8();
+ size_t len = charstr.length();
+ header += itos(len);
+ header += "\r\n\r\n";
+
+ return header + p_text;
+}
+
+void GDScriptLanguageProtocol::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
+ ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
+ ClassDB::bind_method(D_METHOD("on_data_received"), &GDScriptLanguageProtocol::on_data_received);
+ ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
+ ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
+ ClassDB::bind_method(D_METHOD("notify_all_clients", "p_method", "p_params"), &GDScriptLanguageProtocol::notify_all_clients, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("notify_client", "p_method", "p_params", "p_client"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
+ ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
+ ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
+ ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
+}
+
+Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
+
+ lsp::InitializeResult ret;
+
+ String root_uri = p_params["rootUri"];
+ String root = p_params["rootPath"];
+ bool is_same_workspace = root == workspace->root;
+ is_same_workspace = root.to_lower() == workspace->root.to_lower();
+#ifdef WINDOWS_ENABLED
+ is_same_workspace = root.replace("\\", "/").to_lower() == workspace->root.to_lower();
+#endif
+
+ if (root_uri.length() && is_same_workspace) {
+ workspace->root_uri = root_uri;
+ } else {
+
+ workspace->root_uri = "file://" + workspace->root;
+
+ Dictionary params;
+ params["path"] = workspace->root;
+ Dictionary request = make_notification("gdscrip_client/changeWorkspace", params);
+ if (Ref<WebSocketPeer> *peer = clients.getptr(lastest_client_id)) {
+ String msg = JSON::print(request);
+ msg = format_output(msg);
+ CharString charstr = msg.utf8();
+ (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length());
+ }
+ }
+
+ if (!_initialized) {
+ workspace->initialize();
+ text_document->initialize();
+ _initialized = true;
+ }
+
+ return ret.to_json();
+}
+
+void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
+}
+
+void GDScriptLanguageProtocol::poll() {
+ server->poll();
+}
+
+Error GDScriptLanguageProtocol::start(int p_port) {
+ if (server == NULL) {
+ server = dynamic_cast<WebSocketServer *>(ClassDB::instance("WebSocketServer"));
+ server->set_buffers(8192, 1024, 8192, 1024); // 8mb should be way more than enough
+ server->connect("data_received", this, "on_data_received");
+ server->connect("client_connected", this, "on_client_connected");
+ server->connect("client_disconnected", this, "on_client_disconnected");
+ }
+ return server->listen(p_port);
+}
+
+void GDScriptLanguageProtocol::stop() {
+ server->stop();
+}
+
+void GDScriptLanguageProtocol::notify_all_clients(const String &p_method, const Variant &p_params) {
+
+ Dictionary message = make_notification(p_method, p_params);
+ String msg = JSON::print(message);
+ msg = format_output(msg);
+ CharString charstr = msg.utf8();
+ const int *p_id = clients.next(NULL);
+ while (p_id != NULL) {
+ Ref<WebSocketPeer> peer = clients.get(*p_id);
+ (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length());
+ p_id = clients.next(p_id);
+ }
+}
+
+void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client) {
+
+ if (p_client == -1) {
+ p_client = lastest_client_id;
+ }
+
+ Ref<WebSocketPeer> *peer = clients.getptr(p_client);
+ ERR_FAIL_COND(peer == NULL);
+
+ Dictionary message = make_notification(p_method, p_params);
+ String msg = JSON::print(message);
+ msg = format_output(msg);
+ CharString charstr = msg.utf8();
+
+ (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length());
+}
+
+bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
+ return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
+}
+
+bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
+ return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
+}
+
+GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
+ server = NULL;
+ singleton = this;
+ _initialized = false;
+ workspace.instance();
+ text_document.instance();
+ set_scope("textDocument", text_document.ptr());
+ set_scope("completionItem", text_document.ptr());
+ set_scope("workspace", workspace.ptr());
+ workspace->root = ProjectSettings::get_singleton()->get_resource_path();
+}
+
+GDScriptLanguageProtocol::~GDScriptLanguageProtocol() {
+ memdelete(server);
+ server = NULL;
+}
diff --git a/modules/gdscript/language_server/gdscript_language_protocol.h b/modules/gdscript/language_server/gdscript_language_protocol.h
new file mode 100644
index 0000000000..136b45fd78
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_language_protocol.h
@@ -0,0 +1,93 @@
+/*************************************************************************/
+/* gdscript_language_protocol.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GDSCRIPT_PROTOCAL_SERVER_H
+#define GDSCRIPT_PROTOCAL_SERVER_H
+
+#include "gdscript_text_document.h"
+#include "gdscript_workspace.h"
+#include "lsp.hpp"
+#include "modules/jsonrpc/jsonrpc.h"
+#include "modules/websocket/websocket_peer.h"
+#include "modules/websocket/websocket_server.h"
+
+class GDScriptLanguageProtocol : public JSONRPC {
+ GDCLASS(GDScriptLanguageProtocol, JSONRPC)
+
+ enum LSPErrorCode {
+ RequestCancelled = -32800,
+ ContentModified = -32801,
+ };
+
+ static GDScriptLanguageProtocol *singleton;
+
+ HashMap<int, Ref<WebSocketPeer> > clients;
+ WebSocketServer *server;
+ int lastest_client_id;
+
+ Ref<GDScriptTextDocument> text_document;
+ Ref<GDScriptWorkspace> workspace;
+
+ void on_data_received(int p_id);
+ void on_client_connected(int p_id, const String &p_protocal);
+ void on_client_disconnected(int p_id, bool p_was_clean_close);
+
+ String process_message(const String &p_text);
+ String format_output(const String &p_text);
+
+ bool _initialized;
+
+protected:
+ static void _bind_methods();
+
+ Dictionary initialize(const Dictionary &p_params);
+ void initialized(const Variant &p_params);
+
+public:
+ _FORCE_INLINE_ static GDScriptLanguageProtocol *get_singleton() { return singleton; }
+ _FORCE_INLINE_ Ref<GDScriptWorkspace> get_workspace() { return workspace; }
+ _FORCE_INLINE_ Ref<GDScriptTextDocument> get_text_document() { return text_document; }
+ _FORCE_INLINE_ bool is_initialized() const { return _initialized; }
+
+ void poll();
+ Error start(int p_port);
+ void stop();
+
+ void notify_all_clients(const String &p_method, const Variant &p_params = Variant());
+ void notify_client(const String &p_method, const Variant &p_params = Variant(), int p_client = -1);
+
+ bool is_smart_resolve_enabled() const;
+ bool is_goto_native_symbols_enabled() const;
+
+ GDScriptLanguageProtocol();
+ ~GDScriptLanguageProtocol();
+};
+
+#endif
diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp
new file mode 100644
index 0000000000..9bea4557ac
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_language_server.cpp
@@ -0,0 +1,88 @@
+/*************************************************************************/
+/* gdscript_language_server.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "gdscript_language_server.h"
+#include "core/os/file_access.h"
+#include "core/os/os.h"
+#include "editor/editor_node.h"
+
+GDScriptLanguageServer::GDScriptLanguageServer() {
+ thread = NULL;
+ thread_exit = false;
+ _EDITOR_DEF("network/language_server/remote_port", 6008);
+ _EDITOR_DEF("network/language_server/enable_smart_resolve", false);
+ _EDITOR_DEF("network/language_server/show_native_symbols_in_editor", false);
+}
+
+void GDScriptLanguageServer::_notification(int p_what) {
+
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE:
+ start();
+ break;
+ case NOTIFICATION_EXIT_TREE:
+ stop();
+ break;
+ }
+}
+
+void GDScriptLanguageServer::thread_main(void *p_userdata) {
+ GDScriptLanguageServer *self = static_cast<GDScriptLanguageServer *>(p_userdata);
+ while (!self->thread_exit) {
+ self->protocol.poll();
+ OS::get_singleton()->delay_usec(10);
+ }
+}
+
+void GDScriptLanguageServer::start() {
+ int port = (int)_EDITOR_GET("network/language_server/remote_port");
+ if (protocol.start(port) == OK) {
+ EditorNode::get_log()->add_message("** GDScript Language Server Started **");
+ ERR_FAIL_COND(thread != NULL || thread_exit);
+ thread_exit = false;
+ thread = Thread::create(GDScriptLanguageServer::thread_main, this);
+ }
+}
+
+void GDScriptLanguageServer::stop() {
+ ERR_FAIL_COND(NULL == thread || thread_exit);
+ thread_exit = true;
+ Thread::wait_to_finish(thread);
+ memdelete(thread);
+ thread = NULL;
+ protocol.stop();
+ EditorNode::get_log()->add_message("** GDScript Language Server Stopped **");
+}
+
+void register_lsp_types() {
+ ClassDB::register_class<GDScriptLanguageProtocol>();
+ ClassDB::register_class<GDScriptTextDocument>();
+ ClassDB::register_class<GDScriptWorkspace>();
+}
diff --git a/modules/gdscript/language_server/gdscript_language_server.h b/modules/gdscript/language_server/gdscript_language_server.h
new file mode 100644
index 0000000000..83c2320d98
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_language_server.h
@@ -0,0 +1,60 @@
+/*************************************************************************/
+/* gdscript_language_server.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GDSCRIPT_LANGUAGE_SERVER_H
+#define GDSCRIPT_LANGUAGE_SERVER_H
+
+#include "../gdscript_parser.h"
+#include "editor/editor_plugin.h"
+#include "gdscript_language_protocol.h"
+
+class GDScriptLanguageServer : public EditorPlugin {
+ GDCLASS(GDScriptLanguageServer, EditorPlugin);
+
+ GDScriptLanguageProtocol protocol;
+
+ Thread *thread;
+ bool thread_exit;
+ static void thread_main(void *p_userdata);
+
+private:
+ void _notification(int p_what);
+ void _iteration();
+
+public:
+ Error parse_script_file(const String &p_path);
+ GDScriptLanguageServer();
+ void start();
+ void stop();
+};
+
+void register_lsp_types();
+
+#endif // GDSCRIPT_LANGUAGE_SERVER_H
diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp
new file mode 100644
index 0000000000..f211fae526
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_text_document.cpp
@@ -0,0 +1,391 @@
+/*************************************************************************/
+/* gdscript_text_document.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "gdscript_text_document.h"
+#include "../gdscript.h"
+#include "core/os/os.h"
+#include "editor/editor_settings.h"
+#include "editor/plugins/script_text_editor.h"
+#include "gdscript_extend_parser.h"
+#include "gdscript_language_protocol.h"
+
+void GDScriptTextDocument::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("didOpen"), &GDScriptTextDocument::didOpen);
+ ClassDB::bind_method(D_METHOD("didChange"), &GDScriptTextDocument::didChange);
+ ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol);
+ ClassDB::bind_method(D_METHOD("completion"), &GDScriptTextDocument::completion);
+ ClassDB::bind_method(D_METHOD("resolve"), &GDScriptTextDocument::resolve);
+ ClassDB::bind_method(D_METHOD("foldingRange"), &GDScriptTextDocument::foldingRange);
+ ClassDB::bind_method(D_METHOD("codeLens"), &GDScriptTextDocument::codeLens);
+ ClassDB::bind_method(D_METHOD("documentLink"), &GDScriptTextDocument::documentLink);
+ ClassDB::bind_method(D_METHOD("colorPresentation"), &GDScriptTextDocument::colorPresentation);
+ ClassDB::bind_method(D_METHOD("hover"), &GDScriptTextDocument::hover);
+ ClassDB::bind_method(D_METHOD("definition"), &GDScriptTextDocument::definition);
+ ClassDB::bind_method(D_METHOD("show_native_symbol_in_editor"), &GDScriptTextDocument::show_native_symbol_in_editor);
+}
+
+void GDScriptTextDocument::didOpen(const Variant &p_param) {
+ lsp::TextDocumentItem doc = load_document_item(p_param);
+ sync_script_content(doc.uri, doc.text);
+}
+
+void GDScriptTextDocument::didChange(const Variant &p_param) {
+ lsp::TextDocumentItem doc = load_document_item(p_param);
+ Dictionary dict = p_param;
+ Array contentChanges = dict["contentChanges"];
+ for (int i = 0; i < contentChanges.size(); ++i) {
+ lsp::TextDocumentContentChangeEvent evt;
+ evt.load(contentChanges[i]);
+ doc.text = evt.text;
+ }
+ sync_script_content(doc.uri, doc.text);
+}
+
+lsp::TextDocumentItem GDScriptTextDocument::load_document_item(const Variant &p_param) {
+ lsp::TextDocumentItem doc;
+ Dictionary params = p_param;
+ doc.load(params["textDocument"]);
+ return doc;
+}
+
+void GDScriptTextDocument::initialize() {
+
+ if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
+
+ const HashMap<StringName, ClassMembers> &native_members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members;
+
+ const StringName *class_ptr = native_members.next(NULL);
+ while (class_ptr) {
+
+ const ClassMembers &members = native_members.get(*class_ptr);
+
+ const String *name = members.next(NULL);
+ while (name) {
+
+ const lsp::DocumentSymbol *symbol = members.get(*name);
+ lsp::CompletionItem item = symbol->make_completion_item();
+ item.data = JOIN_SYMBOLS(String(*class_ptr), *name);
+ native_member_completions.push_back(item.to_json());
+
+ name = members.next(name);
+ }
+
+ class_ptr = native_members.next(class_ptr);
+ }
+ }
+}
+
+Array GDScriptTextDocument::documentSymbol(const Dictionary &p_params) {
+ Dictionary params = p_params["textDocument"];
+ String uri = params["uri"];
+ String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(uri);
+ Array arr;
+ if (const Map<String, ExtendGDScriptParser *>::Element *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(path)) {
+ Vector<lsp::DocumentedSymbolInformation> list;
+ parser->get()->get_symbols().symbol_tree_as_list(uri, list);
+ for (int i = 0; i < list.size(); i++) {
+ arr.push_back(list[i].to_json());
+ }
+ }
+ return arr;
+}
+
+Array GDScriptTextDocument::completion(const Dictionary &p_params) {
+
+ Array arr;
+
+ lsp::CompletionParams params;
+ params.load(p_params);
+ Dictionary request_data = params.to_json();
+
+ List<ScriptCodeCompletionOption> options;
+ GDScriptLanguageProtocol::get_singleton()->get_workspace()->completion(params, &options);
+
+ if (!options.empty()) {
+
+ int i = 0;
+ arr.resize(options.size());
+
+ for (const List<ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) {
+
+ const ScriptCodeCompletionOption &option = E->get();
+ lsp::CompletionItem item;
+ item.label = option.display;
+ item.data = request_data;
+
+ switch (option.kind) {
+ case ScriptCodeCompletionOption::KIND_ENUM:
+ item.kind = lsp::CompletionItemKind::Enum;
+ break;
+ case ScriptCodeCompletionOption::KIND_CLASS:
+ item.kind = lsp::CompletionItemKind::Class;
+ break;
+ case ScriptCodeCompletionOption::KIND_MEMBER:
+ item.kind = lsp::CompletionItemKind::Property;
+ break;
+ case ScriptCodeCompletionOption::KIND_FUNCTION:
+ item.kind = lsp::CompletionItemKind::Method;
+ break;
+ case ScriptCodeCompletionOption::KIND_SIGNAL:
+ item.kind = lsp::CompletionItemKind::Event;
+ break;
+ case ScriptCodeCompletionOption::KIND_CONSTANT:
+ item.kind = lsp::CompletionItemKind::Constant;
+ break;
+ case ScriptCodeCompletionOption::KIND_VARIABLE:
+ item.kind = lsp::CompletionItemKind::Variable;
+ break;
+ case ScriptCodeCompletionOption::KIND_FILE_PATH:
+ item.kind = lsp::CompletionItemKind::File;
+ break;
+ case ScriptCodeCompletionOption::KIND_NODE_PATH:
+ item.kind = lsp::CompletionItemKind::Snippet;
+ break;
+ case ScriptCodeCompletionOption::KIND_PLAIN_TEXT:
+ item.kind = lsp::CompletionItemKind::Text;
+ break;
+ }
+
+ arr[i] = item.to_json();
+ i++;
+ }
+ } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
+
+ arr = native_member_completions.duplicate();
+
+ for (Map<String, ExtendGDScriptParser *>::Element *E = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.front(); E; E = E->next()) {
+
+ ExtendGDScriptParser *script = E->get();
+ const Array &items = script->get_member_completions();
+
+ const int start_size = arr.size();
+ arr.resize(start_size + items.size());
+ for (int i = start_size; i < arr.size(); i++) {
+ arr[i] = items[i - start_size];
+ }
+ }
+ }
+ return arr;
+}
+
+Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
+
+ lsp::CompletionItem item;
+ item.load(p_params);
+
+ lsp::CompletionParams params;
+ Variant data = p_params["data"];
+
+ const lsp::DocumentSymbol *symbol = NULL;
+
+ if (data.get_type() == Variant::DICTIONARY) {
+
+ params.load(p_params["data"]);
+ symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params, item.label, item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function);
+
+ } else if (data.get_type() == Variant::STRING) {
+
+ String query = data;
+
+ Vector<String> param_symbols = query.split(SYMBOL_SEPERATOR, false);
+
+ if (param_symbols.size() >= 2) {
+
+ String class_ = param_symbols[0];
+ StringName class_name = class_;
+ String member_name = param_symbols[param_symbols.size() - 1];
+ String inner_class_name;
+ if (param_symbols.size() >= 3) {
+ inner_class_name = param_symbols[1];
+ }
+
+ if (const ClassMembers *members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members.getptr(class_name)) {
+ if (const lsp::DocumentSymbol *const *member = members->getptr(member_name)) {
+ symbol = *member;
+ }
+ }
+
+ if (!symbol) {
+ if (const Map<String, ExtendGDScriptParser *>::Element *E = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(class_name)) {
+ symbol = E->get()->get_member_symbol(member_name, inner_class_name);
+ }
+ }
+ }
+ }
+
+ if (symbol) {
+ item.documentation = symbol->render();
+ }
+
+ if ((item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function) && !item.label.ends_with("):")) {
+ item.insertText = item.label + "(";
+ if (symbol && symbol->detail.find(",") == -1) {
+ item.insertText += ")";
+ }
+ } else if (item.kind == lsp::CompletionItemKind::Event) {
+ if (params.context.triggerKind == lsp::CompletionTriggerKind::TriggerCharacter && (params.context.triggerCharacter == "(")) {
+ const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\"";
+ item.insertText = quote_style + item.label + quote_style;
+ }
+ }
+
+ return item.to_json(true);
+}
+
+Array GDScriptTextDocument::foldingRange(const Dictionary &p_params) {
+ Dictionary params = p_params["textDocument"];
+ String path = params["uri"];
+ Array arr;
+ return arr;
+}
+
+Array GDScriptTextDocument::codeLens(const Dictionary &p_params) {
+ Array arr;
+ return arr;
+}
+
+Variant GDScriptTextDocument::documentLink(const Dictionary &p_params) {
+ Variant ret;
+ return ret;
+}
+
+Array GDScriptTextDocument::colorPresentation(const Dictionary &p_params) {
+ Array arr;
+ return arr;
+}
+
+Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
+
+ lsp::TextDocumentPositionParams params;
+ params.load(p_params);
+
+ const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
+ if (symbol) {
+
+ lsp::Hover hover;
+ hover.contents = symbol->render();
+ return hover.to_json();
+
+ } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
+
+ Dictionary ret;
+ Array contents;
+ List<const lsp::DocumentSymbol *> list;
+ GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(params, list);
+ for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) {
+ if (const lsp::DocumentSymbol *s = E->get()) {
+ contents.push_back(s->render().value);
+ }
+ }
+ ret["contents"] = contents;
+ return ret;
+ }
+
+ return Variant();
+}
+
+Array GDScriptTextDocument::definition(const Dictionary &p_params) {
+ Array arr;
+
+ lsp::TextDocumentPositionParams params;
+ params.load(p_params);
+
+ const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
+ if (symbol) {
+ lsp::Location location;
+ location.uri = symbol->uri;
+ location.range = symbol->range;
+
+ const String &path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(symbol->uri);
+ if (file_checker->file_exists(path)) {
+ arr.push_back(location.to_json());
+ } else if (!symbol->native_class.empty() && GDScriptLanguageProtocol::get_singleton()->is_goto_native_symbols_enabled()) {
+ String id;
+ switch (symbol->kind) {
+ case lsp::SymbolKind::Class:
+ id = "class_name:" + symbol->name;
+ break;
+ case lsp::SymbolKind::Constant:
+ id = "class_constant:" + symbol->native_class + ":" + symbol->name;
+ break;
+ case lsp::SymbolKind::Property:
+ case lsp::SymbolKind::Variable:
+ id = "class_property:" + symbol->native_class + ":" + symbol->name;
+ break;
+ case lsp::SymbolKind::Enum:
+ id = "class_enum:" + symbol->native_class + ":" + symbol->name;
+ break;
+ case lsp::SymbolKind::Method:
+ case lsp::SymbolKind::Function:
+ id = "class_method:" + symbol->native_class + ":" + symbol->name;
+ break;
+ default:
+ id = "class_global:" + symbol->native_class + ":" + symbol->name;
+ break;
+ }
+ call_deferred("show_native_symbol_in_editor", id);
+ }
+ } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
+
+ List<const lsp::DocumentSymbol *> list;
+ GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(params, list);
+ for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) {
+
+ if (const lsp::DocumentSymbol *s = E->get()) {
+ if (!s->uri.empty()) {
+ lsp::Location location;
+ location.uri = s->uri;
+ location.range = s->range;
+ arr.push_back(location.to_json());
+ }
+ }
+ }
+ }
+
+ return arr;
+}
+
+GDScriptTextDocument::GDScriptTextDocument() {
+ file_checker = FileAccess::create(FileAccess::ACCESS_RESOURCES);
+}
+
+GDScriptTextDocument::~GDScriptTextDocument() {
+ memdelete(file_checker);
+}
+
+void GDScriptTextDocument::sync_script_content(const String &p_uri, const String &p_content) {
+ String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(p_uri);
+ GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_script(path, p_content);
+}
+
+void GDScriptTextDocument::show_native_symbol_in_editor(const String &p_symbol_id) {
+ ScriptEditor::get_singleton()->call_deferred("_help_class_goto", p_symbol_id);
+ OS::get_singleton()->move_window_to_foreground();
+}
diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h
new file mode 100644
index 0000000000..d15022d2c4
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_text_document.h
@@ -0,0 +1,73 @@
+/*************************************************************************/
+/* gdscript_text_document.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GDSCRIPT_TEXT_DOCUMENT_H
+#define GDSCRIPT_TEXT_DOCUMENT_H
+
+#include "core/os/file_access.h"
+#include "core/reference.h"
+#include "lsp.hpp"
+
+class GDScriptTextDocument : public Reference {
+ GDCLASS(GDScriptTextDocument, Reference)
+protected:
+ static void _bind_methods();
+
+ FileAccess *file_checker;
+
+ void didOpen(const Variant &p_param);
+ void didChange(const Variant &p_param);
+
+ void sync_script_content(const String &p_path, const String &p_content);
+ void show_native_symbol_in_editor(const String &p_symbol_id);
+
+ Array native_member_completions;
+
+private:
+ lsp::TextDocumentItem load_document_item(const Variant &p_param);
+
+public:
+ Array documentSymbol(const Dictionary &p_params);
+ Array completion(const Dictionary &p_params);
+ Dictionary resolve(const Dictionary &p_params);
+ Array foldingRange(const Dictionary &p_params);
+ Array codeLens(const Dictionary &p_params);
+ Variant documentLink(const Dictionary &p_params);
+ Array colorPresentation(const Dictionary &p_params);
+ Variant hover(const Dictionary &p_params);
+ Array definition(const Dictionary &p_params);
+
+ void initialize();
+
+ GDScriptTextDocument();
+ virtual ~GDScriptTextDocument();
+};
+
+#endif
diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp
new file mode 100644
index 0000000000..1901daacff
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_workspace.cpp
@@ -0,0 +1,504 @@
+/*************************************************************************/
+/* gdscript_workspace.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "gdscript_workspace.h"
+#include "../gdscript.h"
+#include "../gdscript_parser.h"
+#include "core/project_settings.h"
+#include "core/script_language.h"
+#include "editor/editor_help.h"
+#include "gdscript_language_protocol.h"
+
+void GDScriptWorkspace::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("symbol"), &GDScriptWorkspace::symbol);
+ ClassDB::bind_method(D_METHOD("parse_script", "p_path", "p_content"), &GDScriptWorkspace::parse_script);
+ ClassDB::bind_method(D_METHOD("parse_local_script", "p_path"), &GDScriptWorkspace::parse_local_script);
+ ClassDB::bind_method(D_METHOD("get_file_path", "p_uri"), &GDScriptWorkspace::get_file_path);
+ ClassDB::bind_method(D_METHOD("get_file_uri", "p_path"), &GDScriptWorkspace::get_file_uri);
+ ClassDB::bind_method(D_METHOD("publish_diagnostics", "p_path"), &GDScriptWorkspace::publish_diagnostics);
+ ClassDB::bind_method(D_METHOD("generate_script_api", "p_path"), &GDScriptWorkspace::generate_script_api);
+}
+
+void GDScriptWorkspace::remove_cache_parser(const String &p_path) {
+ Map<String, ExtendGDScriptParser *>::Element *parser = parse_results.find(p_path);
+ Map<String, ExtendGDScriptParser *>::Element *script = scripts.find(p_path);
+ if (parser && script) {
+ if (script->get() && script->get() == script->get()) {
+ memdelete(script->get());
+ } else {
+ memdelete(script->get());
+ memdelete(parser->get());
+ }
+ parse_results.erase(p_path);
+ scripts.erase(p_path);
+ } else if (parser) {
+ memdelete(parser->get());
+ parse_results.erase(p_path);
+ } else if (script) {
+ memdelete(script->get());
+ scripts.erase(p_path);
+ }
+}
+
+const lsp::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
+
+ StringName class_name = p_class;
+ StringName empty;
+
+ while (class_name != empty) {
+ if (const Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(class_name)) {
+ const lsp::DocumentSymbol &class_symbol = E->value();
+
+ if (p_member.empty()) {
+ return &class_symbol;
+ } else {
+ for (int i = 0; i < class_symbol.children.size(); i++) {
+ const lsp::DocumentSymbol &symbol = class_symbol.children[i];
+ if (symbol.name == p_member) {
+ return &symbol;
+ }
+ }
+ }
+ }
+ class_name = ClassDB::get_parent_class(class_name);
+ }
+
+ return NULL;
+}
+
+const lsp::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
+ const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path);
+ if (S) {
+ return &(S->get()->get_symbols());
+ }
+ return NULL;
+}
+
+void GDScriptWorkspace::reload_all_workspace_scripts() {
+ List<String> pathes;
+ list_script_files("res://", pathes);
+ for (List<String>::Element *E = pathes.front(); E; E = E->next()) {
+ const String &path = E->get();
+ Error err;
+ String content = FileAccess::get_file_as_string(path, &err);
+ ERR_CONTINUE(err != OK);
+ err = parse_script(path, content);
+
+ if (err != OK) {
+ Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(path);
+ String err_msg = "Failed parse script " + path;
+ if (S) {
+ err_msg += "\n" + S->get()->get_error();
+ }
+ ERR_EXPLAIN(err_msg);
+ ERR_CONTINUE(err != OK);
+ }
+ }
+}
+
+void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
+ Error err;
+ DirAccessRef dir = DirAccess::open(p_root_dir, &err);
+ if (OK == err) {
+ dir->list_dir_begin();
+ String file_name = dir->get_next();
+ while (file_name.length()) {
+ if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
+ list_script_files(p_root_dir.plus_file(file_name), r_files);
+ } else if (file_name.ends_with(".gd")) {
+ String script_file = p_root_dir.plus_file(file_name);
+ r_files.push_back(script_file);
+ }
+ file_name = dir->get_next();
+ }
+ }
+}
+
+ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) {
+ const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path);
+ if (!S) {
+ parse_local_script(p_path);
+ S = scripts.find(p_path);
+ }
+ if (S) {
+ return S->get();
+ }
+ return NULL;
+}
+
+ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) {
+ const Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(p_path);
+ if (!S) {
+ parse_local_script(p_path);
+ S = parse_results.find(p_path);
+ }
+ if (S) {
+ return S->get();
+ }
+ return NULL;
+}
+
+Array GDScriptWorkspace::symbol(const Dictionary &p_params) {
+ String query = p_params["query"];
+ Array arr;
+ if (!query.empty()) {
+ for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
+ Vector<lsp::DocumentedSymbolInformation> script_symbols;
+ E->get()->get_symbols().symbol_tree_as_list(E->key(), script_symbols);
+ for (int i = 0; i < script_symbols.size(); ++i) {
+ if (query.is_subsequence_ofi(script_symbols[i].name)) {
+ arr.push_back(script_symbols[i].to_json());
+ }
+ }
+ }
+ }
+ return arr;
+}
+
+Error GDScriptWorkspace::initialize() {
+ if (initialized) return OK;
+
+ DocData *doc = EditorHelp::get_doc_data();
+ for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
+
+ const DocData::ClassDoc &class_data = E->value();
+ lsp::DocumentSymbol class_symbol;
+ String class_name = E->key();
+ class_symbol.name = class_name;
+ class_symbol.native_class = class_name;
+ class_symbol.kind = lsp::SymbolKind::Class;
+ class_symbol.detail = String("<Native> class ") + class_name;
+ if (!class_data.inherits.empty()) {
+ class_symbol.detail += " extends " + class_data.inherits;
+ }
+ class_symbol.documentation = ExtendGDScriptParser::marked_documentation(class_data.brief_description) + "\n" + ExtendGDScriptParser::marked_documentation(class_data.description);
+
+ for (int i = 0; i < class_data.constants.size(); i++) {
+ const DocData::ConstantDoc &const_data = class_data.constants[i];
+ lsp::DocumentSymbol symbol;
+ symbol.name = const_data.name;
+ symbol.native_class = class_name;
+ symbol.kind = lsp::SymbolKind::Constant;
+ symbol.detail = "const " + class_name + "." + const_data.name;
+ if (const_data.enumeration.length()) {
+ symbol.detail += ": " + const_data.enumeration;
+ }
+ symbol.detail += " = " + const_data.value;
+ symbol.documentation = ExtendGDScriptParser::marked_documentation(const_data.description);
+ class_symbol.children.push_back(symbol);
+ }
+
+ Vector<DocData::PropertyDoc> properties;
+ properties.append_array(class_data.properties);
+ const int theme_prop_start_idx = properties.size();
+ properties.append_array(class_data.theme_properties);
+
+ for (int i = 0; i < class_data.properties.size(); i++) {
+ const DocData::PropertyDoc &data = class_data.properties[i];
+ lsp::DocumentSymbol symbol;
+ symbol.name = data.name;
+ symbol.native_class = class_name;
+ symbol.kind = lsp::SymbolKind::Property;
+ symbol.detail = String(i >= theme_prop_start_idx ? "<Theme> var" : "var") + " " + class_name + "." + data.name;
+ if (data.enumeration.length()) {
+ symbol.detail += ": " + data.enumeration;
+ } else {
+ symbol.detail += ": " + data.type;
+ }
+ symbol.documentation = ExtendGDScriptParser::marked_documentation(data.description);
+ class_symbol.children.push_back(symbol);
+ }
+
+ Vector<DocData::MethodDoc> methods_signals;
+ methods_signals.append_array(class_data.methods);
+ const int signal_start_idx = methods_signals.size();
+ methods_signals.append_array(class_data.signals);
+
+ for (int i = 0; i < methods_signals.size(); i++) {
+ const DocData::MethodDoc &data = methods_signals[i];
+
+ lsp::DocumentSymbol symbol;
+ symbol.name = data.name;
+ symbol.native_class = class_name;
+ symbol.kind = i >= signal_start_idx ? lsp::SymbolKind::Event : lsp::SymbolKind::Method;
+
+ String params = "";
+ bool arg_default_value_started = false;
+ for (int j = 0; j < data.arguments.size(); j++) {
+ const DocData::ArgumentDoc &arg = data.arguments[j];
+ if (!arg_default_value_started && !arg.default_value.empty()) {
+ arg_default_value_started = true;
+ }
+ String arg_str = arg.name + ": " + arg.type;
+ if (arg_default_value_started) {
+ arg_str += " = " + arg.default_value;
+ }
+ if (j < data.arguments.size() - 1) {
+ arg_str += ", ";
+ }
+ params += arg_str;
+ }
+ if (data.qualifiers.find("vararg") != -1) {
+ params += params.empty() ? "..." : ", ...";
+ }
+
+ symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + data.return_type;
+ symbol.documentation = ExtendGDScriptParser::marked_documentation(data.description);
+ class_symbol.children.push_back(symbol);
+ }
+
+ native_symbols.insert(class_name, class_symbol);
+ }
+
+ reload_all_workspace_scripts();
+
+ if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
+ for (Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.front(); E; E = E->next()) {
+ ClassMembers members;
+ const lsp::DocumentSymbol &class_symbol = E->get();
+ for (int i = 0; i < class_symbol.children.size(); i++) {
+ const lsp::DocumentSymbol &symbol = class_symbol.children[i];
+ members.set(symbol.name, &symbol);
+ }
+ native_members.set(E->key(), members);
+ }
+
+ // cache member completions
+ for (Map<String, ExtendGDScriptParser *>::Element *S = scripts.front(); S; S = S->next()) {
+ S->get()->get_member_completions();
+ }
+ }
+
+ return OK;
+}
+
+Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
+
+ ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
+ Error err = parser->parse(p_content, p_path);
+ Map<String, ExtendGDScriptParser *>::Element *last_parser = parse_results.find(p_path);
+ Map<String, ExtendGDScriptParser *>::Element *last_script = scripts.find(p_path);
+
+ if (err == OK) {
+
+ remove_cache_parser(p_path);
+ parse_results[p_path] = parser;
+ scripts[p_path] = parser;
+
+ } else {
+ if (last_parser && last_script && last_parser->get() != last_script->get()) {
+ memdelete(last_parser->get());
+ }
+ parse_results[p_path] = parser;
+ }
+
+ publish_diagnostics(p_path);
+
+ return err;
+}
+
+Error GDScriptWorkspace::parse_local_script(const String &p_path) {
+ Error err;
+ String content = FileAccess::get_file_as_string(p_path, &err);
+ if (err == OK) {
+ err = parse_script(p_path, content);
+ }
+ return err;
+}
+
+String GDScriptWorkspace::get_file_path(const String &p_uri) const {
+ String path = p_uri;
+ path = path.replace(root_uri + "/", "res://");
+ path = path.http_unescape();
+ return path;
+}
+
+String GDScriptWorkspace::get_file_uri(const String &p_path) const {
+ String uri = p_path;
+ uri = uri.replace("res://", root_uri + "/");
+ return uri;
+}
+
+void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
+ Dictionary params;
+ Array errors;
+ const Map<String, ExtendGDScriptParser *>::Element *ele = parse_results.find(p_path);
+ if (ele) {
+ const Vector<lsp::Diagnostic> &list = ele->get()->get_diagnostics();
+ errors.resize(list.size());
+ for (int i = 0; i < list.size(); ++i) {
+ errors[i] = list[i].to_json();
+ }
+ }
+ params["diagnostics"] = errors;
+ params["uri"] = get_file_uri(p_path);
+ GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
+}
+
+void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options) {
+
+ String path = get_file_path(p_params.textDocument.uri);
+ String call_hint;
+ bool forced = false;
+
+ if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
+ String code = parser->get_text_for_completion(p_params.position);
+ GDScriptLanguage::get_singleton()->complete_code(code, path, NULL, r_options, forced, call_hint);
+ }
+}
+
+const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_requred) {
+
+ const lsp::DocumentSymbol *symbol = NULL;
+
+ String path = get_file_path(p_doc_pos.textDocument.uri);
+ if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
+
+ String symbol_identifier = p_symbol_name;
+ Vector<String> identifier_parts = symbol_identifier.split("(");
+ if (identifier_parts.size()) {
+ symbol_identifier = identifier_parts[0];
+ }
+
+ lsp::Position pos = p_doc_pos.position;
+ if (symbol_identifier.empty()) {
+ Vector2i offset;
+ symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
+ pos.character += offset.y;
+ }
+
+ if (!symbol_identifier.empty()) {
+
+ if (ScriptServer::is_global_class(symbol_identifier)) {
+
+ String class_path = ScriptServer::get_global_class_path(symbol_identifier);
+ symbol = get_script_symbol(class_path);
+
+ } else {
+
+ ScriptLanguage::LookupResult ret;
+ if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_requred), symbol_identifier, path, NULL, ret)) {
+
+ if (ret.type == ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION) {
+
+ String target_script_path = path;
+ if (!ret.script.is_null()) {
+ target_script_path = ret.script->get_path();
+ }
+
+ if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
+ symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location));
+ }
+
+ } else {
+
+ String member = ret.class_member;
+ if (member.empty() && symbol_identifier != ret.class_name) {
+ member = symbol_identifier;
+ }
+ symbol = get_native_symbol(ret.class_name, member);
+ }
+ } else {
+ symbol = parser->get_member_symbol(symbol_identifier);
+ }
+ }
+ }
+ }
+
+ return symbol;
+}
+
+void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list) {
+
+ String path = get_file_path(p_doc_pos.textDocument.uri);
+ if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
+
+ String symbol_identifier;
+ Vector2i offset;
+ symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
+
+ const StringName *class_ptr = native_members.next(NULL);
+ while (class_ptr) {
+ const ClassMembers &members = native_members.get(*class_ptr);
+ if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
+ r_list.push_back(*symbol);
+ }
+ class_ptr = native_members.next(class_ptr);
+ }
+
+ for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
+ const ExtendGDScriptParser *script = E->get();
+ const ClassMembers &members = script->get_members();
+ if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
+ r_list.push_back(*symbol);
+ }
+
+ const HashMap<String, ClassMembers> &inner_classes = script->get_inner_classes();
+ const String *_class = inner_classes.next(NULL);
+ while (_class) {
+
+ const ClassMembers *inner_class = inner_classes.getptr(*_class);
+ if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
+ r_list.push_back(*symbol);
+ }
+
+ _class = inner_classes.next(_class);
+ }
+ }
+ }
+}
+
+Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
+ Dictionary api;
+ if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) {
+ api = parser->generate_api();
+ }
+ return api;
+}
+
+GDScriptWorkspace::GDScriptWorkspace() {
+ ProjectSettings::get_singleton()->get_resource_path();
+}
+
+GDScriptWorkspace::~GDScriptWorkspace() {
+ Set<String> cached_parsers;
+
+ for (Map<String, ExtendGDScriptParser *>::Element *E = parse_results.front(); E; E = E->next()) {
+ cached_parsers.insert(E->key());
+ }
+
+ for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
+ cached_parsers.insert(E->key());
+ }
+
+ for (Set<String>::Element *E = cached_parsers.front(); E; E = E->next()) {
+ remove_cache_parser(E->get());
+ }
+}
diff --git a/modules/gdscript/language_server/gdscript_workspace.h b/modules/gdscript/language_server/gdscript_workspace.h
new file mode 100644
index 0000000000..adce169d4b
--- /dev/null
+++ b/modules/gdscript/language_server/gdscript_workspace.h
@@ -0,0 +1,91 @@
+/*************************************************************************/
+/* gdscript_workspace.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GDSCRIPT_WORKSPACE_H
+#define GDSCRIPT_WORKSPACE_H
+
+#include "../gdscript_parser.h"
+#include "core/variant.h"
+#include "gdscript_extend_parser.h"
+#include "lsp.hpp"
+
+class GDScriptWorkspace : public Reference {
+ GDCLASS(GDScriptWorkspace, Reference);
+
+protected:
+ static void _bind_methods();
+ void remove_cache_parser(const String &p_path);
+ bool initialized = false;
+ Map<StringName, lsp::DocumentSymbol> native_symbols;
+
+ const lsp::DocumentSymbol *get_native_symbol(const String &p_class, const String &p_member = "") const;
+ const lsp::DocumentSymbol *get_script_symbol(const String &p_path) const;
+
+ void reload_all_workspace_scripts();
+
+ ExtendGDScriptParser *get_parse_successed_script(const String &p_path);
+ ExtendGDScriptParser *get_parse_result(const String &p_path);
+
+ void strip_flat_symbols(const String &p_branch);
+ void list_script_files(const String &p_root_dir, List<String> &r_files);
+
+public:
+ String root;
+ String root_uri;
+
+ Map<String, ExtendGDScriptParser *> scripts;
+ Map<String, ExtendGDScriptParser *> parse_results;
+ HashMap<StringName, ClassMembers> native_members;
+
+public:
+ Array symbol(const Dictionary &p_params);
+
+public:
+ Error initialize();
+
+ Error parse_script(const String &p_path, const String &p_content);
+ Error parse_local_script(const String &p_path);
+
+ String get_file_path(const String &p_uri) const;
+ String get_file_uri(const String &p_path) const;
+
+ void publish_diagnostics(const String &p_path);
+ void completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options);
+
+ const lsp::DocumentSymbol *resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name = "", bool p_func_requred = false);
+ void resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list);
+
+ Dictionary generate_script_api(const String &p_path);
+
+ GDScriptWorkspace();
+ ~GDScriptWorkspace();
+};
+
+#endif
diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/lsp.hpp
new file mode 100644
index 0000000000..3e57b6ee7e
--- /dev/null
+++ b/modules/gdscript/language_server/lsp.hpp
@@ -0,0 +1,1506 @@
+/*************************************************************************/
+/* lsp.hpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GODOT_LSP_H
+#define GODOT_LSP_H
+
+#include "core/variant.h"
+
+namespace lsp {
+
+typedef String DocumentUri;
+
+/**
+ * Text documents are identified using a URI. On the protocol level, URIs are passed as strings.
+ */
+struct TextDocumentIdentifier {
+ /**
+ * The text document's URI.
+ */
+ DocumentUri uri;
+
+ _FORCE_INLINE_ void load(const Dictionary &p_params) {
+ uri = p_params["uri"];
+ }
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["uri"] = uri;
+ return dict;
+ }
+};
+
+/**
+ * Position in a text document expressed as zero-based line and zero-based character offset.
+ * A position is between two characters like an ‘insert’ cursor in a editor.
+ * Special values like for example -1 to denote the end of a line are not supported.
+ */
+struct Position {
+ /**
+ * Line position in a document (zero-based).
+ */
+ int line = 0;
+
+ /**
+ * Character offset on a line in a document (zero-based). Assuming that the line is
+ * represented as a string, the `character` value represents the gap between the
+ * `character` and `character + 1`.
+ *
+ * If the character value is greater than the line length it defaults back to the
+ * line length.
+ */
+ int character = 0;
+
+ _FORCE_INLINE_ void load(const Dictionary &p_params) {
+ line = p_params["line"];
+ character = p_params["character"];
+ }
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["line"] = line;
+ dict["character"] = character;
+ return dict;
+ }
+};
+
+/**
+ * A range in a text document expressed as (zero-based) start and end positions.
+ * A range is comparable to a selection in an editor. Therefore the end position is exclusive.
+ * If you want to specify a range that contains a line including the line ending character(s) then use an end position denoting the start of the next line.
+ */
+struct Range {
+ /**
+ * The range's start position.
+ */
+ Position start;
+
+ /**
+ * The range's end position.
+ */
+ Position end;
+
+ _FORCE_INLINE_ void load(const Dictionary &p_params) {
+ start.load(p_params["start"]);
+ end.load(p_params["end"]);
+ }
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["start"] = start.to_json();
+ dict["end"] = end.to_json();
+ return dict;
+ }
+};
+
+/**
+ * Represents a location inside a resource, such as a line inside a text file.
+ */
+struct Location {
+ DocumentUri uri;
+ Range range;
+
+ _FORCE_INLINE_ void load(const Dictionary &p_params) {
+ uri = p_params["uri"];
+ range.load(p_params["range"]);
+ }
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["uri"] = uri;
+ dict["range"] = range.to_json();
+ return dict;
+ }
+};
+
+/**
+ * Represents a link between a source and a target location.
+ */
+struct LocationLink {
+
+ /**
+ * Span of the origin of this link.
+ *
+ * Used as the underlined span for mouse interaction. Defaults to the word range at
+ * the mouse position.
+ */
+ Range *originSelectionRange = NULL;
+
+ /**
+ * The target resource identifier of this link.
+ */
+ String targetUri;
+
+ /**
+ * The full target range of this link. If the target for example is a symbol then target range is the
+ * range enclosing this symbol not including leading/trailing whitespace but everything else
+ * like comments. This information is typically used to highlight the range in the editor.
+ */
+ Range targetRange;
+
+ /**
+ * The range that should be selected and revealed when this link is being followed, e.g the name of a function.
+ * Must be contained by the the `targetRange`. See also `DocumentSymbol#range`
+ */
+ Range targetSelectionRange;
+};
+
+/**
+ * A parameter literal used in requests to pass a text document and a position inside that document.
+ */
+struct TextDocumentPositionParams {
+ /**
+ * The text document.
+ */
+ TextDocumentIdentifier textDocument;
+
+ /**
+ * The position inside the text document.
+ */
+ Position position;
+
+ _FORCE_INLINE_ void load(const Dictionary &p_params) {
+ textDocument.load(p_params["textDocument"]);
+ position.load(p_params["position"]);
+ }
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["textDocument"] = textDocument.to_json();
+ dict["position"] = position.to_json();
+ return dict;
+ }
+};
+
+/**
+ * A textual edit applicable to a text document.
+ */
+struct TextEdit {
+ /**
+ * The range of the text document to be manipulated. To insert
+ * text into a document create a range where start === end.
+ */
+ Range range;
+
+ /**
+ * The string to be inserted. For delete operations use an
+ * empty string.
+ */
+ String newText;
+};
+
+/**
+ * Represents a reference to a command.
+ * Provides a title which will be used to represent a command in the UI.
+ * Commands are identified by a string identifier.
+ * The recommended way to handle commands is to implement their execution on the server side if the client and server provides the corresponding capabilities.
+ * Alternatively the tool extension code could handle the command. The protocol currently doesn’t specify a set of well-known commands.
+ */
+struct Command {
+ /**
+ * Title of the command, like `save`.
+ */
+ String title;
+ /**
+ * The identifier of the actual command handler.
+ */
+ String command;
+ /**
+ * Arguments that the command handler should be
+ * invoked with.
+ */
+ Array arguments;
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["title"] = title;
+ dict["command"] = command;
+ if (arguments.size()) dict["arguments"] = arguments;
+ return dict;
+ }
+};
+
+namespace TextDocumentSyncKind {
+/**
+ * Documents should not be synced at all.
+ */
+static const int None = 0;
+
+/**
+ * Documents are synced by always sending the full content
+ * of the document.
+ */
+static const int Full = 1;
+
+/**
+ * Documents are synced by sending the full content on open.
+ * After that only incremental updates to the document are
+ * send.
+ */
+static const int Incremental = 2;
+}; // namespace TextDocumentSyncKind
+
+/**
+ * Completion options.
+ */
+struct CompletionOptions {
+ /**
+ * The server provides support to resolve additional
+ * information for a completion item.
+ */
+ bool resolveProvider = true;
+
+ /**
+ * The characters that trigger completion automatically.
+ */
+ Vector<String> triggerCharacters;
+
+ CompletionOptions() {
+ triggerCharacters.push_back(".");
+ triggerCharacters.push_back("$");
+ triggerCharacters.push_back("'");
+ triggerCharacters.push_back("\"");
+ triggerCharacters.push_back("(");
+ triggerCharacters.push_back(",");
+ }
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["resolveProvider"] = resolveProvider;
+ dict["triggerCharacters"] = triggerCharacters;
+ return dict;
+ }
+};
+
+/**
+ * Signature help options.
+ */
+struct SignatureHelpOptions {
+ /**
+ * The characters that trigger signature help
+ * automatically.
+ */
+ Vector<String> triggerCharacters;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["triggerCharacters"] = triggerCharacters;
+ return dict;
+ }
+};
+
+/**
+ * Code Lens options.
+ */
+struct CodeLensOptions {
+ /**
+ * Code lens has a resolve provider as well.
+ */
+ bool resolveProvider = false;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["resolveProvider"] = resolveProvider;
+ return dict;
+ }
+};
+
+/**
+ * Rename options
+ */
+struct RenameOptions {
+ /**
+ * Renames should be checked and tested before being executed.
+ */
+ bool prepareProvider = false;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["prepareProvider"] = prepareProvider;
+ return dict;
+ }
+};
+
+/**
+ * Document link options.
+ */
+struct DocumentLinkOptions {
+ /**
+ * Document links have a resolve provider as well.
+ */
+ bool resolveProvider = false;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["resolveProvider"] = resolveProvider;
+ return dict;
+ }
+};
+
+/**
+ * Execute command options.
+ */
+struct ExecuteCommandOptions {
+ /**
+ * The commands to be executed on the server
+ */
+ Vector<String> commands;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["commands"] = commands;
+ return dict;
+ }
+};
+
+/**
+ * Save options.
+ */
+struct SaveOptions {
+ /**
+ * The client is supposed to include the content on save.
+ */
+ bool includeText = true;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["includeText"] = includeText;
+ return dict;
+ }
+};
+
+/**
+ * Color provider options.
+ */
+struct ColorProviderOptions {
+ Dictionary to_json() {
+ Dictionary dict;
+ return dict;
+ }
+};
+
+/**
+ * Folding range provider options.
+ */
+struct FoldingRangeProviderOptions {
+ Dictionary to_json() {
+ Dictionary dict;
+ return dict;
+ }
+};
+
+struct TextDocumentSyncOptions {
+ /**
+ * Open and close notifications are sent to the server. If omitted open close notification should not
+ * be sent.
+ */
+ bool openClose = true;
+
+ /**
+ * Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
+ * and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.
+ */
+ int change = TextDocumentSyncKind::Full;
+
+ /**
+ * If present will save notifications are sent to the server. If omitted the notification should not be
+ * sent.
+ */
+ bool willSave = false;
+
+ /**
+ * If present will save wait until requests are sent to the server. If omitted the request should not be
+ * sent.
+ */
+ bool willSaveWaitUntil = false;
+
+ /**
+ * If present save notifications are sent to the server. If omitted the notification should not be
+ * sent.
+ */
+ SaveOptions save;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["willSaveWaitUntil"] = willSaveWaitUntil;
+ dict["willSave"] = willSave;
+ dict["openClose"] = openClose;
+ dict["change"] = change;
+ dict["change"] = save.to_json();
+ return dict;
+ }
+};
+
+/**
+ * Static registration options to be returned in the initialize request.
+ */
+struct StaticRegistrationOptions {
+ /**
+ * The id used to register the request. The id can be used to deregister
+ * the request again. See also Registration#id.
+ */
+ String id;
+};
+
+/**
+ * Format document on type options.
+ */
+struct DocumentOnTypeFormattingOptions {
+ /**
+ * A character on which formatting should be triggered, like `}`.
+ */
+ String firstTriggerCharacter;
+
+ /**
+ * More trigger characters.
+ */
+ Vector<String> moreTriggerCharacter;
+
+ Dictionary to_json() {
+ Dictionary dict;
+ dict["firstTriggerCharacter"] = firstTriggerCharacter;
+ dict["moreTriggerCharacter"] = moreTriggerCharacter;
+ return dict;
+ }
+};
+
+struct TextDocumentItem {
+ /**
+ * The text document's URI.
+ */
+ DocumentUri uri;
+
+ /**
+ * The text document's language identifier.
+ */
+ String languageId;
+
+ /**
+ * The version number of this document (it will increase after each
+ * change, including undo/redo).
+ */
+ int version;
+
+ /**
+ * The content of the opened text document.
+ */
+ String text;
+
+ void load(const Dictionary &p_dict) {
+ uri = p_dict["uri"];
+ languageId = p_dict["languageId"];
+ version = p_dict["version"];
+ text = p_dict["text"];
+ }
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["uri"] = uri;
+ dict["languageId"] = languageId;
+ dict["version"] = version;
+ dict["text"] = text;
+ return dict;
+ }
+};
+
+/**
+ * An event describing a change to a text document. If range and rangeLength are omitted
+ * the new text is considered to be the full content of the document.
+ */
+struct TextDocumentContentChangeEvent {
+ /**
+ * The range of the document that changed.
+ */
+ Range range;
+
+ /**
+ * The length of the range that got replaced.
+ */
+ int rangeLength;
+
+ /**
+ * The new text of the range/document.
+ */
+ String text;
+
+ void load(const Dictionary &p_params) {
+ text = p_params["text"];
+ rangeLength = p_params["rangeLength"];
+ range.load(p_params["range"]);
+ }
+};
+
+namespace DiagnosticSeverity {
+/**
+ * Reports an error.
+ */
+static const int Error = 1;
+/**
+ * Reports a warning.
+ */
+static const int Warning = 2;
+/**
+ * Reports an information.
+ */
+static const int Information = 3;
+/**
+ * Reports a hint.
+ */
+static const int Hint = 4;
+}; // namespace DiagnosticSeverity
+
+/**
+ * Represents a related message and source code location for a diagnostic. This should be
+ * used to point to code locations that cause or related to a diagnostics, e.g when duplicating
+ * a symbol in a scope.
+ */
+struct DiagnosticRelatedInformation {
+ /**
+ * The location of this related diagnostic information.
+ */
+ Location location;
+
+ /**
+ * The message of this related diagnostic information.
+ */
+ String message;
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["location"] = location.to_json(),
+ dict["message"] = message;
+ return dict;
+ }
+};
+
+/**
+ * Represents a diagnostic, such as a compiler error or warning.
+ * Diagnostic objects are only valid in the scope of a resource.
+ */
+struct Diagnostic {
+ /**
+ * The range at which the message applies.
+ */
+ Range range;
+
+ /**
+ * The diagnostic's severity. Can be omitted. If omitted it is up to the
+ * client to interpret diagnostics as error, warning, info or hint.
+ */
+ int severity;
+
+ /**
+ * The diagnostic's code, which might appear in the user interface.
+ */
+ int code;
+
+ /**
+ * A human-readable string describing the source of this
+ * diagnostic, e.g. 'typescript' or 'super lint'.
+ */
+ String source;
+
+ /**
+ * The diagnostic's message.
+ */
+ String message;
+
+ /**
+ * An array of related diagnostic information, e.g. when symbol-names within
+ * a scope collide all definitions can be marked via this property.
+ */
+ Vector<DiagnosticRelatedInformation> relatedInformation;
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["range"] = range.to_json();
+ dict["code"] = code;
+ dict["severity"] = severity;
+ dict["message"] = message;
+ dict["source"] = source;
+ if (!relatedInformation.empty()) {
+ Array arr;
+ arr.resize(relatedInformation.size());
+ for (int i = 0; i < relatedInformation.size(); i++) {
+ arr[i] = relatedInformation[i].to_json();
+ }
+ dict["relatedInformation"] = arr;
+ }
+ return dict;
+ }
+};
+
+/**
+ * Describes the content type that a client supports in various
+ * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
+ *
+ * Please note that `MarkupKinds` must not start with a `$`. This kinds
+ * are reserved for internal usage.
+ */
+namespace MarkupKind {
+static const String PlainText = "plaintext";
+static const String Markdown = "markdown";
+}; // namespace MarkupKind
+
+/**
+ * A `MarkupContent` literal represents a string value which content is interpreted base on its
+ * kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.
+ *
+ * If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.
+ * See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting
+ *
+ * Here is an example how such a string can be constructed using JavaScript / TypeScript:
+ * ```typescript
+ * let markdown: MarkdownContent = {
+ * kind: MarkupKind.Markdown,
+ * value: [
+ * '# Header',
+ * 'Some text',
+ * '```typescript',
+ * 'someCode();',
+ * '```'
+ * ].join('\n')
+ * };
+ * ```
+ *
+ * *Please Note* that clients might sanitize the return markdown. A client could decide to
+ * remove HTML from the markdown to avoid script execution.
+ */
+struct MarkupContent {
+ /**
+ * The type of the Markup
+ */
+ String kind;
+
+ /**
+ * The content itself
+ */
+ String value;
+
+ MarkupContent() {
+ kind = MarkupKind::Markdown;
+ }
+
+ MarkupContent(const String &p_value) {
+ value = p_value;
+ kind = MarkupKind::Markdown;
+ }
+
+ Dictionary to_json() const {
+ Dictionary dict;
+ dict["kind"] = kind;
+ dict["value"] = value;
+ return dict;
+ }
+};
+
+/**
+ * The kind of a completion entry.
+ */
+namespace CompletionItemKind {
+static const int Text = 1;
+static const int Method = 2;
+static const int Function = 3;
+static const int Constructor = 4;
+static const int Field = 5;
+static const int Variable = 6;
+static const int Class = 7;
+static const int Interface = 8;
+static const int Module = 9;
+static const int Property = 10;
+static const int Unit = 11;
+static const int Value = 12;
+static const int Enum = 13;
+static const int Keyword = 14;
+static const int Snippet = 15;
+static const int Color = 16;
+static const int File = 17;
+static const int Reference = 18;
+static const int Folder = 19;
+static const int EnumMember = 20;
+static const int Constant = 21;
+static const int Struct = 22;
+static const int Event = 23;
+static const int Operator = 24;
+static const int TypeParameter = 25;
+}; // namespace CompletionItemKind
+
+/**
+ * Defines whether the insert text in a completion item should be interpreted as
+ * plain text or a snippet.
+ */
+namespace InsertTextFormat {
+/**
+ * The primary text to be inserted is treated as a plain string.
+ */
+static const int PlainText = 1;
+
+/**
+ * The primary text to be inserted is treated as a snippet.
+ *
+ * A snippet can define tab stops and placeholders with `$1`, `$2`
+ * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
+ * the end of the snippet. Placeholders with equal identifiers are linked,
+ * that is typing in one will update others too.
+ */
+static const int Snippet = 2;
+}; // namespace InsertTextFormat
+
+struct CompletionItem {
+ /**
+ * The label of this completion item. By default
+ * also the text that is inserted when selecting
+ * this completion.
+ */
+ String label;
+
+ /**
+ * The kind of this completion item. Based of the kind
+ * an icon is chosen by the editor. The standardized set
+ * of available values is defined in `CompletionItemKind`.
+ */
+ int kind;
+
+ /**
+ * A human-readable string with additional information
+ * about this item, like type or symbol information.
+ */
+ String detail;
+
+ /**
+ * A human-readable string that represents a doc-comment.
+ */
+ MarkupContent documentation;
+
+ /**
+ * Indicates if this item is deprecated.
+ */
+ bool deprecated = false;
+
+ /**
+ * Select this item when showing.
+ *
+ * *Note* that only one completion item can be selected and that the
+ * tool / client decides which item that is. The rule is that the *first*
+ * item of those that match best is selected.
+ */
+ bool preselect = false;
+
+ /**
+ * A string that should be used when comparing this item
+ * with other items. When `falsy` the label is used.
+ */
+ String sortText;
+
+ /**
+ * A string that should be used when filtering a set of
+ * completion items. When `falsy` the label is used.
+ */
+ String filterText;
+
+ /**
+ * A string that should be inserted into a document when selecting
+ * this completion. When `falsy` the label is used.
+ *
+ * The `insertText` is subject to interpretation by the client side.
+ * Some tools might not take the string literally. For example
+ * VS Code when code complete is requested in this example `con<cursor position>`
+ * and a completion item with an `insertText` of `console` is provided it
+ * will only insert `sole`. Therefore it is recommended to use `textEdit` instead
+ * since it avoids additional client side interpretation.
+ *
+ * @deprecated Use textEdit instead.
+ */
+ String insertText;
+
+ /**
+ * The format of the insert text. The format applies to both the `insertText` property
+ * and the `newText` property of a provided `textEdit`.
+ */
+ int insertTextFormat;
+
+ /**
+ * An edit which is applied to a document when selecting this completion. When an edit is provided the value of
+ * `insertText` is ignored.
+ *
+ * *Note:* The range of the edit must be a single line range and it must contain the position at which completion
+ * has been requested.
+ */
+ TextEdit textEdit;
+
+ /**
+ * An optional array of additional text edits that are applied when
+ * selecting this completion. Edits must not overlap (including the same insert position)
+ * with the main edit nor with themselves.
+ *
+ * Additional text edits should be used to change text unrelated to the current cursor position
+ * (for example adding an import statement at the top of the file if the completion item will
+ * insert an unqualified type).
+ */
+ Vector<TextEdit> additionalTextEdits;
+
+ /**
+ * An optional set of characters that when pressed while this completion is active will accept it first and
+ * then type that character. *Note* that all commit characters should have `length=1` and that superfluous
+ * characters will be ignored.
+ */
+ Vector<String> commitCharacters;
+
+ /**
+ * An optional command that is executed *after* inserting this completion. *Note* that
+ * additional modifications to the current document should be described with the
+ * additionalTextEdits-property.
+ */
+ Command command;
+
+ /**
+ * A data entry field that is preserved on a completion item between
+ * a completion and a completion resolve request.
+ */
+ Variant data;
+
+ _FORCE_INLINE_ Dictionary to_json(bool resolved = false) const {
+ Dictionary dict;
+ dict["label"] = label;
+ dict["kind"] = kind;
+ dict["data"] = data;
+ if (resolved) {
+ dict["insertText"] = insertText;
+ dict["detail"] = detail;
+ dict["documentation"] = documentation.to_json();
+ dict["deprecated"] = deprecated;
+ dict["preselect"] = preselect;
+ dict["sortText"] = sortText;
+ dict["filterText"] = filterText;
+ if (commitCharacters.size()) dict["commitCharacters"] = commitCharacters;
+ dict["command"] = command.to_json();
+ }
+ return dict;
+ }
+
+ void load(const Dictionary &p_dict) {
+ if (p_dict.has("label")) label = p_dict["label"];
+ if (p_dict.has("kind")) kind = p_dict["kind"];
+ if (p_dict.has("detail")) detail = p_dict["detail"];
+ if (p_dict.has("documentation")) {
+ Variant doc = p_dict["documentation"];
+ if (doc.get_type() == Variant::STRING) {
+ documentation.value = doc;
+ } else if (doc.get_type() == Variant::DICTIONARY) {
+ Dictionary v = doc;
+ documentation.value = v["value"];
+ }
+ }
+ if (p_dict.has("deprecated")) deprecated = p_dict["deprecated"];
+ if (p_dict.has("preselect")) preselect = p_dict["preselect"];
+ if (p_dict.has("sortText")) sortText = p_dict["sortText"];
+ if (p_dict.has("filterText")) filterText = p_dict["filterText"];
+ if (p_dict.has("insertText")) insertText = p_dict["insertText"];
+ if (p_dict.has("data")) data = p_dict["data"];
+ }
+};
+
+/**
+ * Represents a collection of [completion items](#CompletionItem) to be presented
+ * in the editor.
+ */
+struct CompletionList {
+ /**
+ * This list it not complete. Further typing should result in recomputing
+ * this list.
+ */
+ bool isIncomplete;
+
+ /**
+ * The completion items.
+ */
+ Vector<CompletionItem> items;
+};
+
+/**
+ * A symbol kind.
+ */
+namespace SymbolKind {
+static const int File = 1;
+static const int Module = 2;
+static const int Namespace = 3;
+static const int Package = 4;
+static const int Class = 5;
+static const int Method = 6;
+static const int Property = 7;
+static const int Field = 8;
+static const int Constructor = 9;
+static const int Enum = 10;
+static const int Interface = 11;
+static const int Function = 12;
+static const int Variable = 13;
+static const int Constant = 14;
+static const int String = 15;
+static const int Number = 16;
+static const int Boolean = 17;
+static const int Array = 18;
+static const int Object = 19;
+static const int Key = 20;
+static const int Null = 21;
+static const int EnumMember = 22;
+static const int Struct = 23;
+static const int Event = 24;
+static const int Operator = 25;
+static const int TypeParameter = 26;
+}; // namespace SymbolKind
+
+/**
+ * Represents information about programming constructs like variables, classes,
+ * interfaces etc.
+ */
+struct SymbolInformation {
+ /**
+ * The name of this symbol.
+ */
+ String name;
+
+ /**
+ * The kind of this symbol.
+ */
+ int kind = SymbolKind::File;
+
+ /**
+ * Indicates if this symbol is deprecated.
+ */
+ bool deprecated = false;
+
+ /**
+ * The location of this symbol. The location's range is used by a tool
+ * to reveal the location in the editor. If the symbol is selected in the
+ * tool the range's start information is used to position the cursor. So
+ * the range usually spans more then the actual symbol's name and does
+ * normally include things like visibility modifiers.
+ *
+ * The range doesn't have to denote a node range in the sense of a abstract
+ * syntax tree. It can therefore not be used to re-construct a hierarchy of
+ * the symbols.
+ */
+ Location location;
+
+ /**
+ * The name of the symbol containing this symbol. This information is for
+ * user interface purposes (e.g. to render a qualifier in the user interface
+ * if necessary). It can't be used to re-infer a hierarchy for the document
+ * symbols.
+ */
+ String containerName;
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["name"] = name;
+ dict["kind"] = kind;
+ dict["deprecated"] = deprecated;
+ dict["location"] = location.to_json();
+ dict["containerName"] = containerName;
+ return dict;
+ }
+};
+
+struct DocumentedSymbolInformation : public SymbolInformation {
+ /**
+ * A human-readable string with additional information
+ */
+ String detail;
+
+ /**
+ * A human-readable string that represents a doc-comment.
+ */
+ String documentation;
+};
+
+/**
+ * Represents programming constructs like variables, classes, interfaces etc. that appear in a document. Document symbols can be
+ * hierarchical and they have two ranges: one that encloses its definition and one that points to its most interesting range,
+ * e.g. the range of an identifier.
+ */
+struct DocumentSymbol {
+
+ /**
+ * The name of this symbol. Will be displayed in the user interface and therefore must not be
+ * an empty string or a string only consisting of white spaces.
+ */
+ String name;
+
+ /**
+ * More detail for this symbol, e.g the signature of a function.
+ */
+ String detail;
+
+ /**
+ * Documentation for this symbol
+ */
+ String documentation;
+
+ /**
+ * Class name for the native symbols
+ */
+ String native_class;
+
+ /**
+ * The kind of this symbol.
+ */
+ int kind = SymbolKind::File;
+
+ /**
+ * Indicates if this symbol is deprecated.
+ */
+ bool deprecated = false;
+
+ /**
+ * The range enclosing this symbol not including leading/trailing whitespace but everything else
+ * like comments. This information is typically used to determine if the clients cursor is
+ * inside the symbol to reveal in the symbol in the UI.
+ */
+ Range range;
+
+ /**
+ * The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.
+ * Must be contained by the `range`.
+ */
+ Range selectionRange;
+
+ DocumentUri uri;
+ String script_path;
+
+ /**
+ * Children of this symbol, e.g. properties of a class.
+ */
+ Vector<DocumentSymbol> children;
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["name"] = name;
+ dict["detail"] = detail;
+ dict["kind"] = kind;
+ dict["deprecated"] = deprecated;
+ dict["range"] = range.to_json();
+ dict["selectionRange"] = selectionRange.to_json();
+ Array arr;
+ arr.resize(children.size());
+ for (int i = 0; i < children.size(); i++) {
+ arr[i] = children[i].to_json();
+ }
+ dict["children"] = arr;
+ return dict;
+ }
+
+ void symbol_tree_as_list(const String &p_uri, Vector<DocumentedSymbolInformation> &r_list, const String &p_container = "", bool p_join_name = false) const {
+ DocumentedSymbolInformation si;
+ if (p_join_name && !p_container.empty()) {
+ si.name = p_container + ">" + name;
+ } else {
+ si.name = name;
+ }
+ si.kind = kind;
+ si.containerName = p_container;
+ si.deprecated = deprecated;
+ si.location.uri = p_uri;
+ si.location.range = range;
+ si.detail = detail;
+ si.documentation = documentation;
+ r_list.push_back(si);
+ for (int i = 0; i < children.size(); i++) {
+ children[i].symbol_tree_as_list(p_uri, r_list, si.name, p_join_name);
+ }
+ }
+
+ _FORCE_INLINE_ MarkupContent render() const {
+ MarkupContent markdown;
+ if (detail.length()) {
+ markdown.value = "\t" + detail + "\n\n";
+ }
+ if (documentation.length()) {
+ markdown.value += documentation + "\n\n";
+ }
+ if (script_path.length()) {
+ markdown.value += "Defined in [" + script_path + "](" + uri + ")";
+ }
+ return markdown;
+ }
+
+ _FORCE_INLINE_ CompletionItem make_completion_item(bool resolved = false) const {
+
+ lsp::CompletionItem item;
+ item.label = name;
+
+ if (resolved) {
+ item.documentation = render();
+ }
+
+ switch (kind) {
+ case lsp::SymbolKind::Enum:
+ item.kind = lsp::CompletionItemKind::Enum;
+ break;
+ case lsp::SymbolKind::Class:
+ item.kind = lsp::CompletionItemKind::Class;
+ break;
+ case lsp::SymbolKind::Property:
+ item.kind = lsp::CompletionItemKind::Property;
+ break;
+ case lsp::SymbolKind::Method:
+ case lsp::SymbolKind::Function:
+ item.kind = lsp::CompletionItemKind::Method;
+ break;
+ case lsp::SymbolKind::Event:
+ item.kind = lsp::CompletionItemKind::Event;
+ break;
+ case lsp::SymbolKind::Constant:
+ item.kind = lsp::CompletionItemKind::Constant;
+ break;
+ case lsp::SymbolKind::Variable:
+ item.kind = lsp::CompletionItemKind::Variable;
+ break;
+ case lsp::SymbolKind::File:
+ item.kind = lsp::CompletionItemKind::File;
+ break;
+ default:
+ item.kind = lsp::CompletionItemKind::Text;
+ break;
+ }
+
+ return item;
+ }
+};
+
+/**
+ * Enum of known range kinds
+ */
+namespace FoldingRangeKind {
+/**
+ * Folding range for a comment
+ */
+static const String Comment = "comment";
+/**
+ * Folding range for a imports or includes
+ */
+static const String Imports = "imports";
+/**
+ * Folding range for a region (e.g. `#region`)
+ */
+static const String Region = "region";
+} // namespace FoldingRangeKind
+
+/**
+ * Represents a folding range.
+ */
+struct FoldingRange {
+
+ /**
+ * The zero-based line number from where the folded range starts.
+ */
+ int startLine = 0;
+
+ /**
+ * The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.
+ */
+ int startCharacter = 0;
+
+ /**
+ * The zero-based line number where the folded range ends.
+ */
+ int endLine = 0;
+
+ /**
+ * The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.
+ */
+ int endCharacter = 0;
+
+ /**
+ * Describes the kind of the folding range such as `comment' or 'region'. The kind
+ * is used to categorize folding ranges and used by commands like 'Fold all comments'. See
+ * [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds.
+ */
+ String kind = FoldingRangeKind::Region;
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["startLine"] = startLine;
+ dict["startCharacter"] = startCharacter;
+ dict["endLine"] = endLine;
+ dict["endCharacter"] = endCharacter;
+ return dict;
+ }
+};
+
+/**
+ * How a completion was triggered
+ */
+namespace CompletionTriggerKind {
+/**
+ * Completion was triggered by typing an identifier (24x7 code
+ * complete), manual invocation (e.g Ctrl+Space) or via API.
+ */
+static const int Invoked = 1;
+
+/**
+ * Completion was triggered by a trigger character specified by
+ * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
+ */
+static const int TriggerCharacter = 2;
+
+/**
+ * Completion was re-triggered as the current completion list is incomplete.
+ */
+static const int TriggerForIncompleteCompletions = 3;
+} // namespace CompletionTriggerKind
+
+/**
+ * Contains additional information about the context in which a completion request is triggered.
+ */
+struct CompletionContext {
+ /**
+ * How the completion was triggered.
+ */
+ int triggerKind = CompletionTriggerKind::TriggerCharacter;
+
+ /**
+ * The trigger character (a single character) that has trigger code complete.
+ * Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
+ */
+ String triggerCharacter;
+
+ void load(const Dictionary &p_params) {
+ triggerKind = int(p_params["triggerKind"]);
+ triggerCharacter = p_params["triggerCharacter"];
+ }
+};
+
+struct CompletionParams : public TextDocumentPositionParams {
+
+ /**
+ * The completion context. This is only available if the client specifies
+ * to send this using `ClientCapabilities.textDocument.completion.contextSupport === true`
+ */
+ CompletionContext context;
+
+ void load(const Dictionary &p_params) {
+ TextDocumentPositionParams::load(p_params);
+ context.load(p_params["context"]);
+ }
+};
+
+/**
+ * The result of a hover request.
+ */
+struct Hover {
+ /**
+ * The hover's content
+ */
+ MarkupContent contents;
+
+ /**
+ * An optional range is a range inside a text document
+ * that is used to visualize a hover, e.g. by changing the background color.
+ */
+ Range range;
+
+ _FORCE_INLINE_ Dictionary to_json() const {
+ Dictionary dict;
+ dict["range"] = range.to_json();
+ dict["contents"] = contents.to_json();
+ return dict;
+ }
+};
+
+struct ServerCapabilities {
+ /**
+ * Defines how text documents are synced. Is either a detailed structure defining each notification or
+ * for backwards compatibility the TextDocumentSyncKind number. If omitted it defaults to `TextDocumentSyncKind.None`.
+ */
+ TextDocumentSyncOptions textDocumentSync;
+
+ /**
+ * The server provides hover support.
+ */
+ bool hoverProvider = true;
+
+ /**
+ * The server provides completion support.
+ */
+ CompletionOptions completionProvider;
+
+ /**
+ * The server provides signature help support.
+ */
+ SignatureHelpOptions signatureHelpProvider;
+
+ /**
+ * The server provides goto definition support.
+ */
+ bool definitionProvider = true;
+
+ /**
+ * The server provides Goto Type Definition support.
+ *
+ * Since 3.6.0
+ */
+ bool typeDefinitionProvider = false;
+
+ /**
+ * The server provides Goto Implementation support.
+ *
+ * Since 3.6.0
+ */
+ bool implementationProvider = false;
+
+ /**
+ * The server provides find references support.
+ */
+ bool referencesProvider = false;
+
+ /**
+ * The server provides document highlight support.
+ */
+ bool documentHighlightProvider = false;
+
+ /**
+ * The server provides document symbol support.
+ */
+ bool documentSymbolProvider = true;
+
+ /**
+ * The server provides workspace symbol support.
+ */
+ bool workspaceSymbolProvider = true;
+
+ /**
+ * The server provides code actions. The `CodeActionOptions` return type is only
+ * valid if the client signals code action literal support via the property
+ * `textDocument.codeAction.codeActionLiteralSupport`.
+ */
+ bool codeActionProvider = false;
+
+ /**
+ * The server provides code lens.
+ */
+ CodeLensOptions codeLensProvider;
+
+ /**
+ * The server provides document formatting.
+ */
+ bool documentFormattingProvider = false;
+
+ /**
+ * The server provides document range formatting.
+ */
+ bool documentRangeFormattingProvider = false;
+
+ /**
+ * The server provides document formatting on typing.
+ */
+ DocumentOnTypeFormattingOptions documentOnTypeFormattingProvider;
+
+ /**
+ * The server provides rename support. RenameOptions may only be
+ * specified if the client states that it supports
+ * `prepareSupport` in its initial `initialize` request.
+ */
+ RenameOptions renameProvider;
+
+ /**
+ * The server provides document link support.
+ */
+ DocumentLinkOptions documentLinkProvider;
+
+ /**
+ * The server provides color provider support.
+ *
+ * Since 3.6.0
+ */
+ ColorProviderOptions colorProvider;
+
+ /**
+ * The server provides folding provider support.
+ *
+ * Since 3.10.0
+ */
+ FoldingRangeProviderOptions foldingRangeProvider;
+
+ /**
+ * The server provides go to declaration support.
+ *
+ * Since 3.14.0
+ */
+ bool declarationProvider = true;
+
+ /**
+ * The server provides execute command support.
+ */
+ ExecuteCommandOptions executeCommandProvider;
+
+ _FORCE_INLINE_ Dictionary to_json() {
+ Dictionary dict;
+ dict["textDocumentSync"] = (int)textDocumentSync.change;
+ dict["completionProvider"] = completionProvider.to_json();
+ dict["signatureHelpProvider"] = signatureHelpProvider.to_json();
+ dict["codeLensProvider"] = false; // codeLensProvider.to_json();
+ dict["documentOnTypeFormattingProvider"] = documentOnTypeFormattingProvider.to_json();
+ dict["renameProvider"] = renameProvider.to_json();
+ dict["documentLinkProvider"] = documentLinkProvider.to_json();
+ dict["colorProvider"] = false; // colorProvider.to_json();
+ dict["foldingRangeProvider"] = false; //foldingRangeProvider.to_json();
+ dict["executeCommandProvider"] = executeCommandProvider.to_json();
+ dict["hoverProvider"] = hoverProvider;
+ dict["definitionProvider"] = definitionProvider;
+ dict["typeDefinitionProvider"] = typeDefinitionProvider;
+ dict["implementationProvider"] = implementationProvider;
+ dict["referencesProvider"] = referencesProvider;
+ dict["documentHighlightProvider"] = documentHighlightProvider;
+ dict["documentSymbolProvider"] = documentSymbolProvider;
+ dict["workspaceSymbolProvider"] = workspaceSymbolProvider;
+ dict["codeActionProvider"] = codeActionProvider;
+ dict["documentFormattingProvider"] = documentFormattingProvider;
+ dict["documentRangeFormattingProvider"] = documentRangeFormattingProvider;
+ dict["declarationProvider"] = declarationProvider;
+ return dict;
+ }
+};
+
+struct InitializeResult {
+ /**
+ * The capabilities the language server provides.
+ */
+ ServerCapabilities capabilities;
+
+ _FORCE_INLINE_ Dictionary to_json() {
+ Dictionary dict;
+ dict["capabilities"] = capabilities.to_json();
+ return dict;
+ }
+};
+
+} // namespace lsp
+
+#endif
diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp
index 62117dcaf3..d07949b34b 100644
--- a/modules/gdscript/register_types.cpp
+++ b/modules/gdscript/register_types.cpp
@@ -37,6 +37,7 @@
#include "editor/gdscript_highlighter.h"
#include "gdscript.h"
#include "gdscript_tokenizer.h"
+#include "language_server/gdscript_language_server.h"
GDScriptLanguage *script_language_gd = NULL;
Ref<ResourceFormatLoaderGDScript> resource_loader_gd;
@@ -44,6 +45,7 @@ Ref<ResourceFormatSaverGDScript> resource_saver_gd;
#ifdef TOOLS_ENABLED
+#include "core/engine.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
@@ -134,6 +136,11 @@ static void _editor_init() {
Ref<EditorExportGDScript> gd_export;
gd_export.instance();
EditorExport::get_singleton()->add_export_plugin(gd_export);
+
+ register_lsp_types();
+ GDScriptLanguageServer *lsp_plugin = memnew(GDScriptLanguageServer);
+ EditorNode::get_singleton()->add_editor_plugin(lsp_plugin);
+ Engine::get_singleton()->add_singleton(Engine::Singleton("GDScriptLanguageProtocol", GDScriptLanguageProtocol::get_singleton()));
}
#endif
diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp
index e610619b54..1abf26bfee 100644
--- a/modules/hdr/image_loader_hdr.cpp
+++ b/modules/hdr/image_loader_hdr.cpp
@@ -37,7 +37,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
String header = f->get_token();
- ERR_FAIL_COND_V(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + ".");
while (true) {
String line = f->get_line();
@@ -45,12 +45,9 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
if (line == "") // empty line indicates end of header
break;
if (line.begins_with("FORMAT=")) { // leave option to implement other commands
- if (line != "FORMAT=32-bit_rle_rgbe") {
- ERR_EXPLAIN("Only 32-bit_rle_rgbe is supported for HDR files.");
- return ERR_FILE_UNRECOGNIZED;
- }
+ ERR_FAIL_COND_V_MSG(line != "FORMAT=32-bit_rle_rgbe", ERR_FILE_UNRECOGNIZED, "Only 32-bit_rle_rgbe is supported for HDR files.");
} else if (!line.begins_with("#")) { // not comment
- WARN_PRINTS("Ignoring unsupported header information in HDR : " + line);
+ WARN_PRINTS("Ignoring unsupported header information in HDR: " + line + ".");
}
}
diff --git a/modules/jsonrpc/SCsub b/modules/jsonrpc/SCsub
new file mode 100644
index 0000000000..13c9ffb253
--- /dev/null
+++ b/modules/jsonrpc/SCsub
@@ -0,0 +1,7 @@
+#!/usr/bin/env python
+
+Import('env')
+Import('env_modules')
+
+env_jsonrpc = env_modules.Clone()
+env_jsonrpc.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/jsonrpc/config.py b/modules/jsonrpc/config.py
new file mode 100644
index 0000000000..53bc827027
--- /dev/null
+++ b/modules/jsonrpc/config.py
@@ -0,0 +1,5 @@
+def can_build(env, platform):
+ return True
+
+def configure(env):
+ pass
diff --git a/modules/jsonrpc/jsonrpc.cpp b/modules/jsonrpc/jsonrpc.cpp
new file mode 100644
index 0000000000..b18b48d1b0
--- /dev/null
+++ b/modules/jsonrpc/jsonrpc.cpp
@@ -0,0 +1,171 @@
+/*************************************************************************/
+/* jsonrpc.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "jsonrpc.h"
+#include "core/io/json.h"
+
+JSONRPC::JSONRPC() {
+}
+
+JSONRPC::~JSONRPC() {
+}
+
+void JSONRPC::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_scope", "scope", "target"), &JSONRPC::set_scope);
+ ClassDB::bind_method(D_METHOD("process_action", "action", "recurse"), &JSONRPC::process_action, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("process_string", "action"), &JSONRPC::process_string);
+
+ ClassDB::bind_method(D_METHOD("make_request", "method", "params", "id"), &JSONRPC::make_request);
+ ClassDB::bind_method(D_METHOD("make_response", "result", "id"), &JSONRPC::make_response);
+ ClassDB::bind_method(D_METHOD("make_notification", "method", "params"), &JSONRPC::make_notification);
+ ClassDB::bind_method(D_METHOD("make_response_error", "code", "message", "id"), &JSONRPC::make_response_error, DEFVAL(Variant()));
+
+ BIND_ENUM_CONSTANT(ParseError)
+ BIND_ENUM_CONSTANT(InvalidRequest)
+ BIND_ENUM_CONSTANT(MethodNotFound)
+ BIND_ENUM_CONSTANT(InvalidParams)
+ BIND_ENUM_CONSTANT(InternalError)
+}
+
+Dictionary JSONRPC::make_response_error(int p_code, const String &p_message, const Variant &p_id) const {
+ Dictionary dict;
+ dict["jsonrpc"] = "2.0";
+
+ Dictionary err;
+ err["code"] = p_code;
+ err["message"] = p_message;
+
+ dict["error"] = err;
+ dict["id"] = p_id;
+
+ return dict;
+}
+
+Dictionary JSONRPC::make_response(const Variant &p_value, const Variant &p_id) {
+ Dictionary dict;
+ dict["jsonrpc"] = "2.0";
+ dict["id"] = p_id;
+ dict["result"] = p_value;
+ return dict;
+}
+
+Dictionary JSONRPC::make_notification(const String &p_method, const Variant &p_params) {
+ Dictionary dict;
+ dict["jsonrpc"] = "2.0";
+ dict["method"] = p_method;
+ dict["params"] = p_params;
+ return dict;
+}
+
+Dictionary JSONRPC::make_request(const String &p_method, const Variant &p_params, const Variant &p_id) {
+ Dictionary dict;
+ dict["jsonrpc"] = "2.0";
+ dict["method"] = p_method;
+ dict["params"] = p_params;
+ dict["id"] = p_id;
+ return dict;
+}
+
+Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elements) {
+ Variant ret;
+ if (p_action.get_type() == Variant::DICTIONARY) {
+ Dictionary dict = p_action;
+ String method = dict.get("method", "");
+ Array args;
+ if (dict.has("params")) {
+ Variant params = dict.get("params", Variant());
+ if (params.get_type() == Variant::ARRAY) {
+ args = params;
+ } else {
+ args.push_back(params);
+ }
+ }
+
+ Object *object = this;
+ if (method_scopes.has(method.get_base_dir())) {
+ object = method_scopes[method.get_base_dir()];
+ method = method.get_file();
+ }
+
+ Variant id;
+ if (dict.has("id")) {
+ id = dict["id"];
+ }
+
+ if (object == NULL || !object->has_method(method)) {
+ ret = make_response_error(JSONRPC::MethodNotFound, "Method not found", id);
+ } else {
+ Variant call_ret = object->callv(method, args);
+ if (id.get_type() != Variant::NIL) {
+ ret = make_response(call_ret, id);
+ }
+ }
+ } else if (p_action.get_type() == Variant::ARRAY && p_process_arr_elements) {
+ Array arr = p_action;
+ int size = arr.size();
+ if (size) {
+ Array arr_ret;
+ for (int i = 0; i < size; i++) {
+ const Variant &var = arr.get(i);
+ arr_ret.push_back(process_action(var));
+ }
+ ret = arr_ret;
+ } else {
+ ret = make_response_error(JSONRPC::InvalidRequest, "Invalid Request");
+ }
+ } else {
+ ret = make_response_error(JSONRPC::InvalidRequest, "Invalid Request");
+ }
+ return ret;
+}
+
+String JSONRPC::process_string(const String &p_input) {
+
+ if (p_input.empty()) return String();
+
+ Variant ret;
+ Variant input;
+ String err_message;
+ int err_line;
+ if (OK != JSON::parse(p_input, input, err_message, err_line)) {
+ ret = make_response_error(JSONRPC::ParseError, "Parse error");
+ } else {
+ ret = process_action(input, true);
+ }
+
+ if (ret.get_type() == Variant::NIL) {
+ return "";
+ }
+ return JSON::print(ret);
+}
+
+void JSONRPC::set_scope(const String &p_scope, Object *p_obj) {
+ method_scopes[p_scope] = p_obj;
+}
diff --git a/modules/jsonrpc/jsonrpc.h b/modules/jsonrpc/jsonrpc.h
new file mode 100644
index 0000000000..bcb34ecc65
--- /dev/null
+++ b/modules/jsonrpc/jsonrpc.h
@@ -0,0 +1,70 @@
+/*************************************************************************/
+/* jsonrpc.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef GODOT_JSON_RPC_H
+#define GODOT_JSON_RPC_H
+
+#include "core/object.h"
+#include "core/variant.h"
+
+class JSONRPC : public Object {
+ GDCLASS(JSONRPC, Object)
+
+ Map<String, Object *> method_scopes;
+
+protected:
+ static void _bind_methods();
+
+public:
+ JSONRPC();
+ ~JSONRPC();
+
+ enum ErrorCode {
+ ParseError = -32700,
+ InvalidRequest = -32600,
+ MethodNotFound = -32601,
+ InvalidParams = -32602,
+ InternalError = -32603,
+ };
+
+ Dictionary make_response_error(int p_code, const String &p_message, const Variant &p_id = Variant()) const;
+ Dictionary make_response(const Variant &p_value, const Variant &p_id);
+ Dictionary make_notification(const String &p_method, const Variant &p_params);
+ Dictionary make_request(const String &p_method, const Variant &p_params, const Variant &p_id);
+
+ Variant process_action(const Variant &p_action, bool p_process_arr_elements = false);
+ String process_string(const String &p_input);
+
+ void set_scope(const String &p_scope, Object *p_obj);
+};
+
+VARIANT_ENUM_CAST(JSONRPC::ErrorCode);
+
+#endif
diff --git a/modules/jsonrpc/register_types.cpp b/modules/jsonrpc/register_types.cpp
new file mode 100644
index 0000000000..242b0e9df4
--- /dev/null
+++ b/modules/jsonrpc/register_types.cpp
@@ -0,0 +1,40 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "register_types.h"
+#include "core/class_db.h"
+#include "jsonrpc.h"
+
+void register_jsonrpc_types() {
+ ClassDB::register_class<JSONRPC>();
+}
+
+void unregister_jsonrpc_types() {
+}
diff --git a/modules/jsonrpc/register_types.h b/modules/jsonrpc/register_types.h
new file mode 100644
index 0000000000..e4648b901f
--- /dev/null
+++ b/modules/jsonrpc/register_types.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+void register_jsonrpc_types();
+void unregister_jsonrpc_types();
diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp
new file mode 100644
index 0000000000..1e02084ae2
--- /dev/null
+++ b/modules/mbedtls/crypto_mbedtls.cpp
@@ -0,0 +1,285 @@
+/*************************************************************************/
+/* crypto_mbedtls.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "crypto_mbedtls.h"
+
+#include "core/os/file_access.h"
+
+#include "core/engine.h"
+#include "core/io/certs_compressed.gen.h"
+#include "core/io/compression.h"
+#include "core/project_settings.h"
+
+#ifdef TOOLS_ENABLED
+#include "editor/editor_settings.h"
+#endif
+#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
+#define PEM_END_CRT "-----END CERTIFICATE-----\n"
+
+#include "mbedtls/pem.h"
+#include <mbedtls/debug.h>
+
+CryptoKey *CryptoKeyMbedTLS::create() {
+ return memnew(CryptoKeyMbedTLS);
+}
+
+Error CryptoKeyMbedTLS::load(String p_path) {
+ ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
+
+ PoolByteArray out;
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
+
+ int flen = f->get_len();
+ out.resize(flen + 1);
+ {
+ PoolByteArray::Write w = out.write();
+ f->get_buffer(w.ptr(), flen);
+ w[flen] = 0; //end f string
+ }
+ memdelete(f);
+
+ int ret = mbedtls_pk_parse_key(&pkey, out.read().ptr(), out.size(), NULL, 0);
+ // We MUST zeroize the memory for safety!
+ mbedtls_platform_zeroize(out.write().ptr(), out.size());
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing private key: " + itos(ret));
+
+ return OK;
+}
+
+Error CryptoKeyMbedTLS::save(String p_path) {
+ FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
+
+ unsigned char w[16000];
+ memset(w, 0, sizeof(w));
+
+ int ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
+ if (ret != 0) {
+ memdelete(f);
+ memset(w, 0, sizeof(w)); // Zeroize anything we might have written.
+ ERR_FAIL_V_MSG(FAILED, "Error writing key: " + itos(ret));
+ }
+
+ size_t len = strlen((char *)w);
+ f->store_buffer(w, len);
+ memdelete(f);
+ memset(w, 0, sizeof(w)); // Zeroize temporary buffer.
+ return OK;
+}
+
+X509Certificate *X509CertificateMbedTLS::create() {
+ return memnew(X509CertificateMbedTLS);
+}
+
+Error X509CertificateMbedTLS::load(String p_path) {
+ ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use");
+
+ PoolByteArray out;
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
+
+ int flen = f->get_len();
+ out.resize(flen + 1);
+ {
+ PoolByteArray::Write w = out.write();
+ f->get_buffer(w.ptr(), flen);
+ w[flen] = 0; //end f string
+ }
+ memdelete(f);
+
+ int ret = mbedtls_x509_crt_parse(&cert, out.read().ptr(), out.size());
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret));
+
+ return OK;
+}
+
+Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) {
+ ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use");
+
+ int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len);
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing certificates: " + itos(ret));
+ return OK;
+}
+
+Error X509CertificateMbedTLS::save(String p_path) {
+ FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
+
+ mbedtls_x509_crt *crt = &cert;
+ while (crt) {
+ unsigned char w[4096];
+ size_t wrote = 0;
+ int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote);
+ if (ret != 0 || wrote == 0) {
+ memdelete(f);
+ ERR_FAIL_V_MSG(FAILED, "Error writing certificate: " + itos(ret));
+ }
+
+ f->store_buffer(w, wrote - 1); // don't write the string terminator
+ crt = crt->next;
+ }
+ memdelete(f);
+ return OK;
+}
+
+Crypto *CryptoMbedTLS::create() {
+ return memnew(CryptoMbedTLS);
+}
+
+void CryptoMbedTLS::initialize_crypto() {
+
+#ifdef DEBUG_ENABLED
+ mbedtls_debug_set_threshold(1);
+#endif
+
+ Crypto::_create = create;
+ Crypto::_load_default_certificates = load_default_certificates;
+ X509CertificateMbedTLS::make_default();
+ CryptoKeyMbedTLS::make_default();
+}
+
+void CryptoMbedTLS::finalize_crypto() {
+ Crypto::_create = NULL;
+ Crypto::_load_default_certificates = NULL;
+ if (default_certs) {
+ memdelete(default_certs);
+ default_certs = NULL;
+ }
+ X509CertificateMbedTLS::finalize();
+ CryptoKeyMbedTLS::finalize();
+}
+
+CryptoMbedTLS::CryptoMbedTLS() {
+ mbedtls_ctr_drbg_init(&ctr_drbg);
+ mbedtls_entropy_init(&entropy);
+ int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
+ if (ret != 0) {
+ ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
+ }
+}
+
+CryptoMbedTLS::~CryptoMbedTLS() {
+ mbedtls_ctr_drbg_free(&ctr_drbg);
+ mbedtls_entropy_free(&entropy);
+}
+
+X509CertificateMbedTLS *CryptoMbedTLS::default_certs = NULL;
+
+X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() {
+ return default_certs;
+}
+
+void CryptoMbedTLS::load_default_certificates(String p_path) {
+ ERR_FAIL_COND(default_certs != NULL);
+
+ default_certs = memnew(X509CertificateMbedTLS);
+ ERR_FAIL_COND(default_certs == NULL);
+
+ String certs_path = GLOBAL_DEF("network/ssl/certificates", "");
+
+ if (p_path != "") {
+ // Use certs defined in project settings.
+ default_certs->load(p_path);
+ }
+#ifdef BUILTIN_CERTS_ENABLED
+ else {
+ // Use builtin certs only if user did not override it in project settings.
+ PoolByteArray out;
+ out.resize(_certs_uncompressed_size + 1);
+ PoolByteArray::Write w = out.write();
+ Compression::decompress(w.ptr(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
+ w[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
+#ifdef DEBUG_ENABLED
+ print_verbose("Loaded builtin certs");
+#endif
+ default_certs->load_from_memory(out.read().ptr(), out.size());
+ }
+#endif
+}
+
+Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
+ Ref<CryptoKeyMbedTLS> out;
+ out.instance();
+ int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
+ ERR_FAIL_COND_V(ret != 0, NULL);
+ ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
+ ERR_FAIL_COND_V(ret != 0, NULL);
+ return out;
+}
+
+Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) {
+ Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS> >(p_key);
+ mbedtls_x509write_cert crt;
+ mbedtls_x509write_crt_init(&crt);
+
+ mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey));
+ mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey));
+ mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data());
+ mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data());
+ mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
+ mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
+
+ mbedtls_mpi serial;
+ mbedtls_mpi_init(&serial);
+ uint8_t rand_serial[20];
+ mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, 20);
+ ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), NULL);
+ mbedtls_x509write_crt_set_serial(&crt, &serial);
+
+ mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data());
+ mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1);
+ mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0);
+
+ unsigned char buf[4096];
+ memset(buf, 0, 4096);
+ Ref<X509CertificateMbedTLS> out;
+ out.instance();
+ mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
+
+ int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096);
+ if (err != 0) {
+ mbedtls_mpi_free(&serial);
+ mbedtls_x509write_crt_free(&crt);
+ ERR_PRINTS("Generated invalid certificate: " + itos(err));
+ return NULL;
+ }
+
+ mbedtls_mpi_free(&serial);
+ mbedtls_x509write_crt_free(&crt);
+ return out;
+}
+
+PoolByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
+ PoolByteArray out;
+ out.resize(p_bytes);
+ mbedtls_ctr_drbg_random(&ctr_drbg, out.write().ptr(), p_bytes);
+ return out;
+}
diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h
new file mode 100644
index 0000000000..06b3ecd234
--- /dev/null
+++ b/modules/mbedtls/crypto_mbedtls.h
@@ -0,0 +1,124 @@
+/*************************************************************************/
+/* crypto_mbedtls.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef CRYPTO_MBEDTLS_H
+#define CRYPTO_MBEDTLS_H
+
+#include "core/crypto/crypto.h"
+#include "core/resource.h"
+
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/ssl.h>
+
+class CryptoMbedTLS;
+class SSLContextMbedTLS;
+class CryptoKeyMbedTLS : public CryptoKey {
+
+private:
+ mbedtls_pk_context pkey;
+ int locks;
+
+public:
+ static CryptoKey *create();
+ static void make_default() { CryptoKey::_create = create; }
+ static void finalize() { CryptoKey::_create = NULL; }
+
+ virtual Error load(String p_path);
+ virtual Error save(String p_path);
+
+ CryptoKeyMbedTLS() {
+ mbedtls_pk_init(&pkey);
+ locks = 0;
+ }
+ ~CryptoKeyMbedTLS() {
+ mbedtls_pk_free(&pkey);
+ }
+
+ _FORCE_INLINE_ void lock() { locks++; }
+ _FORCE_INLINE_ void unlock() { locks--; }
+
+ friend class CryptoMbedTLS;
+ friend class SSLContextMbedTLS;
+};
+
+class X509CertificateMbedTLS : public X509Certificate {
+
+private:
+ mbedtls_x509_crt cert;
+ int locks;
+
+public:
+ static X509Certificate *create();
+ static void make_default() { X509Certificate::_create = create; }
+ static void finalize() { X509Certificate::_create = NULL; }
+
+ virtual Error load(String p_path);
+ virtual Error load_from_memory(const uint8_t *p_buffer, int p_len);
+ virtual Error save(String p_path);
+
+ X509CertificateMbedTLS() {
+ mbedtls_x509_crt_init(&cert);
+ locks = 0;
+ }
+ ~X509CertificateMbedTLS() {
+ mbedtls_x509_crt_free(&cert);
+ }
+
+ _FORCE_INLINE_ void lock() { locks++; }
+ _FORCE_INLINE_ void unlock() { locks--; }
+
+ friend class CryptoMbedTLS;
+ friend class SSLContextMbedTLS;
+};
+
+class CryptoMbedTLS : public Crypto {
+
+private:
+ mbedtls_entropy_context entropy;
+ mbedtls_ctr_drbg_context ctr_drbg;
+ static X509CertificateMbedTLS *default_certs;
+
+public:
+ static Crypto *create();
+ static void initialize_crypto();
+ static void finalize_crypto();
+ static X509CertificateMbedTLS *get_default_certificates();
+ static void load_default_certificates(String p_path);
+
+ virtual PoolByteArray generate_random_bytes(int p_bytes);
+ virtual Ref<CryptoKey> generate_rsa(int p_bytes);
+ virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
+
+ CryptoMbedTLS();
+ ~CryptoMbedTLS();
+};
+
+#endif // CRYPTO_MBEDTLS_H
diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp
index 121ed5eb02..f7dc6c785f 100755
--- a/modules/mbedtls/register_types.cpp
+++ b/modules/mbedtls/register_types.cpp
@@ -30,15 +30,17 @@
#include "register_types.h"
-#include "stream_peer_mbed_tls.h"
+#include "crypto_mbedtls.h"
+#include "stream_peer_mbedtls.h"
void register_mbedtls_types() {
- ClassDB::register_class<StreamPeerMbedTLS>();
+ CryptoMbedTLS::initialize_crypto();
StreamPeerMbedTLS::initialize_ssl();
}
void unregister_mbedtls_types() {
StreamPeerMbedTLS::finalize_ssl();
+ CryptoMbedTLS::finalize_crypto();
}
diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp
new file mode 100644
index 0000000000..eeaf831b4a
--- /dev/null
+++ b/modules/mbedtls/ssl_context_mbedtls.cpp
@@ -0,0 +1,151 @@
+/*************************************************************************/
+/* ssl_context_mbedtls.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "ssl_context_mbedtls.h"
+
+static void my_debug(void *ctx, int level,
+ const char *file, int line,
+ const char *str) {
+
+ printf("%s:%04d: %s", file, line, str);
+ fflush(stdout);
+}
+
+Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) {
+ ERR_FAIL_COND_V_MSG(inited, ERR_ALREADY_IN_USE, "This SSL context is already active");
+
+ mbedtls_ssl_init(&ssl);
+ mbedtls_ssl_config_init(&conf);
+ mbedtls_ctr_drbg_init(&ctr_drbg);
+ mbedtls_entropy_init(&entropy);
+ inited = true;
+
+ int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
+ if (ret != 0) {
+ clear(); // Never leave unusable resources around.
+ ERR_FAIL_V_MSG(FAILED, "mbedtls_ctr_drbg_seed returned an error" + itos(ret));
+ }
+
+ ret = mbedtls_ssl_config_defaults(&conf, p_endpoint, p_transport, MBEDTLS_SSL_PRESET_DEFAULT);
+ if (ret != 0) {
+ clear();
+ ERR_FAIL_V_MSG(FAILED, "mbedtls_ssl_config_defaults returned an error" + itos(ret));
+ }
+ mbedtls_ssl_conf_authmode(&conf, p_authmode);
+ mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
+ mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
+ return OK;
+}
+
+Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert) {
+ ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER);
+
+ Error err = _setup(MBEDTLS_SSL_IS_SERVER, p_transport, p_authmode);
+ ERR_FAIL_COND_V(err != OK, err);
+
+ // Locking key and certificate(s)
+ pkey = p_pkey;
+ certs = p_cert;
+ if (pkey.is_valid())
+ pkey->lock();
+ if (certs.is_valid())
+ certs->lock();
+
+ // Adding key and certificate
+ int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey));
+ if (ret != 0) {
+ clear();
+ ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid cert/key combination " + itos(ret));
+ }
+ // Adding CA chain if available.
+ if (certs->cert.next) {
+ mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, NULL);
+ }
+ mbedtls_ssl_setup(&ssl, &conf);
+ return OK;
+}
+
+Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) {
+ Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode);
+ ERR_FAIL_COND_V(err != OK, err);
+
+ X509CertificateMbedTLS *cas = NULL;
+
+ if (p_valid_cas.is_valid()) {
+ // Locking CA certificates
+ certs = p_valid_cas;
+ certs->lock();
+ cas = certs.ptr();
+ } else {
+ // Fall back to default certificates (no need to lock those).
+ cas = CryptoMbedTLS::get_default_certificates();
+ if (cas == NULL) {
+ clear();
+ ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "SSL module failed to initialize!");
+ }
+ }
+
+ // Set valid CAs
+ mbedtls_ssl_conf_ca_chain(&conf, &(cas->cert), NULL);
+ mbedtls_ssl_setup(&ssl, &conf);
+ return OK;
+}
+
+void SSLContextMbedTLS::clear() {
+ if (!inited)
+ return;
+ mbedtls_ssl_free(&ssl);
+ mbedtls_ssl_config_free(&conf);
+ mbedtls_ctr_drbg_free(&ctr_drbg);
+ mbedtls_entropy_free(&entropy);
+
+ // Unlock and key and certificates
+ if (certs.is_valid())
+ certs->unlock();
+ certs = Ref<X509Certificate>();
+ if (pkey.is_valid())
+ pkey->unlock();
+ pkey = Ref<CryptoKeyMbedTLS>();
+ inited = false;
+}
+
+mbedtls_ssl_context *SSLContextMbedTLS::get_context() {
+ ERR_FAIL_COND_V(!inited, NULL);
+ return &ssl;
+}
+
+SSLContextMbedTLS::SSLContextMbedTLS() {
+ inited = false;
+}
+
+SSLContextMbedTLS::~SSLContextMbedTLS() {
+ clear();
+}
diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h
new file mode 100644
index 0000000000..e49d532912
--- /dev/null
+++ b/modules/mbedtls/ssl_context_mbedtls.h
@@ -0,0 +1,73 @@
+/*************************************************************************/
+/* ssl_context_mbedtls.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef SSL_CONTEXT_MBED_TLS_H
+#define SSL_CONTEXT_MBED_TLS_H
+
+#include "crypto_mbedtls.h"
+
+#include "core/os/file_access.h"
+#include "core/pool_vector.h"
+#include "core/reference.h"
+
+#include <mbedtls/config.h>
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/debug.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/ssl.h>
+
+class SSLContextMbedTLS : public Reference {
+
+protected:
+ bool inited;
+
+ static PoolByteArray _read_file(String p_path);
+
+public:
+ Ref<X509CertificateMbedTLS> certs;
+ mbedtls_entropy_context entropy;
+ mbedtls_ctr_drbg_context ctr_drbg;
+ mbedtls_ssl_context ssl;
+ mbedtls_ssl_config conf;
+
+ Ref<CryptoKeyMbedTLS> pkey;
+
+ Error _setup(int p_endpoint, int p_transport, int p_authmode);
+ Error init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert);
+ Error init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas);
+ void clear();
+
+ mbedtls_ssl_context *get_context();
+
+ SSLContextMbedTLS();
+ ~SSLContextMbedTLS();
+};
+
+#endif // SSL_CONTEXT_MBED_TLS_H
diff --git a/modules/mbedtls/stream_peer_mbed_tls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp
index 4bb7557150..a2e342e219 100755
--- a/modules/mbedtls/stream_peer_mbed_tls.cpp
+++ b/modules/mbedtls/stream_peer_mbedtls.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* stream_peer_mbed_tls.cpp */
+/* stream_peer_mbedtls.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,19 +28,11 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "stream_peer_mbed_tls.h"
+#include "stream_peer_mbedtls.h"
#include "core/io/stream_peer_tcp.h"
#include "core/os/file_access.h"
-static void my_debug(void *ctx, int level,
- const char *file, int line,
- const char *str) {
-
- printf("%s:%04d: %s", file, line, str);
- fflush(stdout);
-}
-
void _print_error(int ret) {
printf("mbedtls error: returned -0x%x\n\n", -ret);
fflush(stdout);
@@ -86,18 +78,14 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
void StreamPeerMbedTLS::_cleanup() {
- mbedtls_ssl_free(&ssl);
- mbedtls_ssl_config_free(&conf);
- mbedtls_ctr_drbg_free(&ctr_drbg);
- mbedtls_entropy_free(&entropy);
-
+ ssl_ctx->clear();
base = Ref<StreamPeer>();
status = STATUS_DISCONNECTED;
}
Error StreamPeerMbedTLS::_do_handshake() {
int ret = 0;
- while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
+ while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
// An error occurred.
ERR_PRINTS("TLS handshake error: " + itos(ret));
@@ -118,7 +106,7 @@ Error StreamPeerMbedTLS::_do_handshake() {
return OK;
}
-Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
+Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) {
ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
@@ -126,31 +114,11 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
int ret = 0;
int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE;
- mbedtls_ssl_init(&ssl);
- mbedtls_ssl_config_init(&conf);
- mbedtls_ctr_drbg_init(&ctr_drbg);
- mbedtls_entropy_init(&entropy);
-
- ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
- if (ret != 0) {
- ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
- _cleanup();
- return FAILED;
- }
+ Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs);
+ ERR_FAIL_COND_V(err != OK, err);
- mbedtls_ssl_config_defaults(&conf,
- MBEDTLS_SSL_IS_CLIENT,
- MBEDTLS_SSL_TRANSPORT_STREAM,
- MBEDTLS_SSL_PRESET_DEFAULT);
-
- mbedtls_ssl_conf_authmode(&conf, authmode);
- mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
- mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
- mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
- mbedtls_ssl_setup(&ssl, &conf);
- mbedtls_ssl_set_hostname(&ssl, p_for_hostname.utf8().get_data());
-
- mbedtls_ssl_set_bio(&ssl, this, bio_send, bio_recv, NULL);
+ mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data());
+ mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL);
status = STATUS_HANDSHAKING;
@@ -162,11 +130,26 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
return OK;
}
-Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base) {
+Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) {
+
+ ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
+
+ Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert);
+ ERR_FAIL_COND_V(err != OK, err);
+
+ base = p_base;
+
+ mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL);
+
+ status = STATUS_HANDSHAKING;
+
+ if ((err = _do_handshake()) != OK) {
+ return FAILED;
+ }
+ status = STATUS_CONNECTED;
return OK;
}
-
Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
@@ -197,7 +180,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in
if (p_bytes == 0)
return OK;
- int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes);
+ int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
// Non blocking IO
ret = 0;
@@ -243,7 +226,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r
r_received = 0;
- int ret = mbedtls_ssl_read(&ssl, p_buffer, p_bytes);
+ int ret = mbedtls_ssl_read(ssl_ctx->get_context(), p_buffer, p_bytes);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
ret = 0; // non blocking io
} else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
@@ -273,7 +256,7 @@ void StreamPeerMbedTLS::poll() {
// We could pass NULL as second parameter, but some behaviour sanitizers doesn't seem to like that.
// Passing a 1 byte buffer to workaround it.
uint8_t byte;
- int ret = mbedtls_ssl_read(&ssl, &byte, 0);
+ int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
// Nothing to read/write (non blocking IO)
@@ -298,10 +281,11 @@ int StreamPeerMbedTLS::get_available_bytes() const {
ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0);
- return mbedtls_ssl_get_bytes_avail(&ssl);
+ return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl));
}
StreamPeerMbedTLS::StreamPeerMbedTLS() {
+ ssl_ctx.instance();
status = STATUS_DISCONNECTED;
}
@@ -317,7 +301,7 @@ void StreamPeerMbedTLS::disconnect_from_stream() {
Ref<StreamPeerTCP> tcp = base;
if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
// We are still connected on the socket, try to send close notify.
- mbedtls_ssl_close_notify(&ssl);
+ mbedtls_ssl_close_notify(ssl_ctx->get_context());
}
_cleanup();
@@ -333,28 +317,9 @@ StreamPeerSSL *StreamPeerMbedTLS::_create_func() {
return memnew(StreamPeerMbedTLS);
}
-mbedtls_x509_crt StreamPeerMbedTLS::cacert;
-
-void StreamPeerMbedTLS::_load_certs(const PoolByteArray &p_array) {
- int arr_len = p_array.size();
- PoolByteArray::Read r = p_array.read();
- int err = mbedtls_x509_crt_parse(&cacert, &r[0], arr_len);
- if (err != 0) {
- WARN_PRINTS("Error parsing some certificates: " + itos(err));
- }
-}
-
void StreamPeerMbedTLS::initialize_ssl() {
_create = _create_func;
- load_certs_func = _load_certs;
-
- mbedtls_x509_crt_init(&cacert);
-
-#ifdef DEBUG_ENABLED
- mbedtls_debug_set_threshold(1);
-#endif
-
available = true;
}
@@ -362,6 +327,4 @@ void StreamPeerMbedTLS::finalize_ssl() {
available = false;
_create = NULL;
- load_certs_func = NULL;
- mbedtls_x509_crt_free(&cacert);
}
diff --git a/modules/mbedtls/stream_peer_mbed_tls.h b/modules/mbedtls/stream_peer_mbedtls.h
index ab87b779c1..eec7eab631 100755
--- a/modules/mbedtls/stream_peer_mbed_tls.h
+++ b/modules/mbedtls/stream_peer_mbedtls.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* stream_peer_mbed_tls.h */
+/* stream_peer_mbedtls.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -32,15 +32,7 @@
#define STREAM_PEER_OPEN_SSL_H
#include "core/io/stream_peer_ssl.h"
-
-#include <mbedtls/config.h>
-#include <mbedtls/ctr_drbg.h>
-#include <mbedtls/debug.h>
-#include <mbedtls/entropy.h>
-#include <mbedtls/ssl.h>
-
-#include <stdio.h>
-#include <stdlib.h>
+#include "ssl_context_mbedtls.h"
class StreamPeerMbedTLS : public StreamPeerSSL {
private:
@@ -50,19 +42,13 @@ private:
Ref<StreamPeer> base;
static StreamPeerSSL *_create_func();
- static void _load_certs(const PoolByteArray &p_array);
static int bio_recv(void *ctx, unsigned char *buf, size_t len);
static int bio_send(void *ctx, const unsigned char *buf, size_t len);
void _cleanup();
protected:
- static mbedtls_x509_crt cacert;
-
- mbedtls_entropy_context entropy;
- mbedtls_ctr_drbg_context ctr_drbg;
- mbedtls_ssl_context ssl;
- mbedtls_ssl_config conf;
+ Ref<SSLContextMbedTLS> ssl_ctx;
static void _bind_methods();
@@ -70,8 +56,8 @@ protected:
public:
virtual void poll();
- virtual Error accept_stream(Ref<StreamPeer> p_base);
- virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String());
+ virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>());
+ virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>());
virtual Status get_status() const;
virtual void disconnect_from_stream();
diff --git a/modules/mono/SCsub b/modules/mono/SCsub
index cc60e64a11..a9afa7ccf6 100644
--- a/modules/mono/SCsub
+++ b/modules/mono/SCsub
@@ -8,13 +8,7 @@ Import('env_modules')
env_mono = env_modules.Clone()
-env_mono.add_source_files(env.modules_sources, '*.cpp')
-env_mono.add_source_files(env.modules_sources, 'glue/*.cpp')
-env_mono.add_source_files(env.modules_sources, 'mono_gd/*.cpp')
-env_mono.add_source_files(env.modules_sources, 'utils/*.cpp')
-
if env['tools']:
- env_mono.add_source_files(env.modules_sources, 'editor/*.cpp')
# NOTE: It is safe to generate this file here, since this is still executed serially
import build_scripts.make_cs_compressed_header as make_cs_compressed_header
make_cs_compressed_header.generate_header(
@@ -62,3 +56,13 @@ if env_mono['tools']:
# GodotTools.ProjectEditor which doesn't depend on the Godot API solution and
# is required by the bindings generator in order to be able to generated it.
godot_tools_build.build_project_editor_only(env_mono)
+
+# Add sources
+
+env_mono.add_source_files(env.modules_sources, '*.cpp')
+env_mono.add_source_files(env.modules_sources, 'glue/*.cpp')
+env_mono.add_source_files(env.modules_sources, 'mono_gd/*.cpp')
+env_mono.add_source_files(env.modules_sources, 'utils/*.cpp')
+
+if env['tools']:
+ env_mono.add_source_files(env.modules_sources, 'editor/*.cpp')
diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py
index cd9210897d..8cad204d7b 100644
--- a/modules/mono/build_scripts/make_android_mono_config.py
+++ b/modules/mono/build_scripts/make_android_mono_config.py
@@ -3,23 +3,6 @@ def generate_compressed_config(config_src, output_dir):
import os.path
from compat import byte_to_str
- # Header file
- with open(os.path.join(output_dir, 'android_mono_config.gen.h'), 'w') as header:
- header.write('''/* THIS FILE IS GENERATED DO NOT EDIT */
-#ifndef ANDROID_MONO_CONFIG_GEN_H
-#define ANDROID_MONO_CONFIG_GEN_H
-
-#ifdef ANDROID_ENABLED
-
-#include "core/ustring.h"
-
-String get_godot_android_mono_config();
-
-#endif // ANDROID_ENABLED
-
-#endif // ANDROID_MONO_CONFIG_GEN_H
-''')
-
# Source file
with open(os.path.join(output_dir, 'android_mono_config.gen.cpp'), 'w') as cpp:
with open(config_src, 'rb') as f:
@@ -36,7 +19,7 @@ String get_godot_android_mono_config();
bytes_seq_str += byte_to_str(buf[buf_idx])
cpp.write('''/* THIS FILE IS GENERATED DO NOT EDIT */
-#include "android_mono_config.gen.h"
+#include "android_mono_config.h"
#ifdef ANDROID_ENABLED
diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp
index 4a6637434a..7580911a0a 100644
--- a/modules/mono/class_db_api_json.cpp
+++ b/modules/mono/class_db_api_json.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/mono/class_db_api_json.h b/modules/mono/class_db_api_json.h
index ddfe2debea..9888ecfb55 100644
--- a/modules/mono/class_db_api_json.h
+++ b/modules/mono/class_db_api_json.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index 8c17bac3c9..4c9dd9c1a9 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -2661,7 +2661,7 @@ void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
void CSharpScript::_bind_methods() {
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
}
Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
index f3ac353c0f..dcfdd83831 100644
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
@@ -11,6 +11,7 @@
<AssemblyName>GodotTools.BuildLogger</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
index f36b40f87c..24c7cb1573 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
@@ -8,6 +8,7 @@
<RootNamespace>GodotTools.Core</RootNamespace>
<AssemblyName>GodotTools.Core</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj
index 84c08251ab..94e525715b 100644
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj
@@ -11,6 +11,7 @@
<AssemblyName>GodotTools.IdeConnection</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
index 08b8ba3946..c745fe321b 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
@@ -9,6 +9,7 @@
<AssemblyName>GodotTools.ProjectEditor</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
index 099c7fcb56..7da7cff933 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -359,7 +359,7 @@ namespace GodotTools
aboutLabel.Text =
"C# support in Godot Engine is in late alpha stage and, while already usable, " +
"it is not meant for use in production.\n\n" +
- "Projects can be exported to Linux, macOS and Windows, but not yet to mobile or web platforms. " +
+ "Projects can be exported to Linux, macOS, Windows and Android, but not yet to iOS, HTML5 or UWP. " +
"Bugs and usability issues will be addressed gradually over future releases, " +
"potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" +
"If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" +
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
index e2d576caef..3c57900873 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
@@ -10,6 +10,7 @@
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
<GodotApiConfiguration>Debug</GodotApiConfiguration>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs
index d515254e65..309b917c71 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs
@@ -9,6 +9,7 @@ using System.Threading.Tasks;
using GodotTools.IdeConnection;
using GodotTools.Internals;
using GodotTools.Utils;
+using Directory = System.IO.Directory;
using File = System.IO.File;
using Thread = System.Threading.Thread;
@@ -33,6 +34,9 @@ namespace GodotTools.Ides
this.launchIdeAction = launchIdeAction;
+ // Make sure the directory exists
+ Directory.CreateDirectory(projectMetadataDir);
+
// The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing...
const FileShare metaFileShare = FileShare.ReadWrite;
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs
index a3490fa89f..700b786752 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs
@@ -51,7 +51,7 @@ namespace GodotTools.Utils
{
continuation = null;
exception = null;
- result = default;
+ result = default(T);
IsCompleted = false;
return this;
}
diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp
index 7db1090e2a..cd1ca2a2c7 100644
--- a/modules/mono/editor/editor_internal_calls.cpp
+++ b/modules/mono/editor/editor_internal_calls.cpp
@@ -271,7 +271,7 @@ MonoString *godot_icall_Internal_SimplifyGodotPath(MonoString *p_path) {
MonoBoolean godot_icall_Internal_IsOsxAppBundleInstalled(MonoString *p_bundle_id) {
#ifdef OSX_ENABLED
String bundle_id = GDMonoMarshal::mono_string_to_godot(p_bundle_id);
- return (MonoBoolean)osx_is_app_bundle_installed;
+ return (MonoBoolean)osx_is_app_bundle_installed(bundle_id);
#else
(void)p_bundle_id; // UNUSED
return (MonoBoolean) false;
diff --git a/modules/mono/glue/Managed/Files/Vector2.cs b/modules/mono/glue/Managed/Files/Vector2.cs
index b1c1dae3c2..0daa94057e 100644
--- a/modules/mono/glue/Managed/Files/Vector2.cs
+++ b/modules/mono/glue/Managed/Files/Vector2.cs
@@ -14,10 +14,19 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 2-element structure that can be used to represent positions in 2D space or any other pair of numeric values.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
+ public enum Axis
+ {
+ X = 0,
+ Y
+ }
+
public real_t x;
public real_t y;
@@ -202,6 +211,22 @@ namespace Godot
return v;
}
+ public Vector2 PosMod(real_t mod)
+ {
+ Vector2 v;
+ v.x = Mathf.PosMod(x, mod);
+ v.y = Mathf.PosMod(y, mod);
+ return v;
+ }
+
+ public Vector2 PosMod(Vector2 modv)
+ {
+ Vector2 v;
+ v.x = Mathf.PosMod(x, modv.x);
+ v.y = Mathf.PosMod(y, modv.y);
+ return v;
+ }
+
public Vector2 Project(Vector2 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
@@ -236,6 +261,14 @@ namespace Godot
y = v.y;
}
+ public Vector2 Sign()
+ {
+ Vector2 v;
+ v.x = Mathf.Sign(x);
+ v.y = Mathf.Sign(y);
+ return v;
+ }
+
public Vector2 Slerp(Vector2 b, real_t t)
{
real_t theta = AngleTo(b);
@@ -265,7 +298,7 @@ namespace Godot
private static readonly Vector2 _up = new Vector2(0, -1);
private static readonly Vector2 _down = new Vector2(0, 1);
- private static readonly Vector2 _right = new Vector2(1, 0);
+ private static readonly Vector2 _right = new Vector2(1, 0);
private static readonly Vector2 _left = new Vector2(-1, 0);
public static Vector2 Zero { get { return _zero; } }
@@ -346,6 +379,20 @@ namespace Godot
return left;
}
+ public static Vector2 operator %(Vector2 vec, real_t divisor)
+ {
+ vec.x %= divisor;
+ vec.y %= divisor;
+ return vec;
+ }
+
+ public static Vector2 operator %(Vector2 vec, Vector2 divisorv)
+ {
+ vec.x %= divisorv.x;
+ vec.y %= divisorv.y;
+ return vec;
+ }
+
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
diff --git a/modules/mono/glue/Managed/Files/Vector3.cs b/modules/mono/glue/Managed/Files/Vector3.cs
index c2da7b8bb1..9076dbd3b0 100644
--- a/modules/mono/glue/Managed/Files/Vector3.cs
+++ b/modules/mono/glue/Managed/Files/Vector3.cs
@@ -14,6 +14,9 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 3-element structure that can be used to represent positions in 3D space or any other pair of numeric values.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3 : IEquatable<Vector3>
@@ -225,6 +228,24 @@ namespace Godot
);
}
+ public Vector3 PosMod(real_t mod)
+ {
+ Vector3 v;
+ v.x = Mathf.PosMod(x, mod);
+ v.y = Mathf.PosMod(y, mod);
+ v.z = Mathf.PosMod(z, mod);
+ return v;
+ }
+
+ public Vector3 PosMod(Vector3 modv)
+ {
+ Vector3 v;
+ v.x = Mathf.PosMod(x, modv.x);
+ v.y = Mathf.PosMod(y, modv.y);
+ v.z = Mathf.PosMod(z, modv.z);
+ return v;
+ }
+
public Vector3 Project(Vector3 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
@@ -264,6 +285,15 @@ namespace Godot
z = v.z;
}
+ public Vector3 Sign()
+ {
+ Vector3 v;
+ v.x = Mathf.Sign(x);
+ v.y = Mathf.Sign(y);
+ v.z = Mathf.Sign(z);
+ return v;
+ }
+
public Vector3 Slerp(Vector3 b, real_t t)
{
real_t theta = AngleTo(b);
@@ -397,6 +427,22 @@ namespace Godot
return left;
}
+ public static Vector3 operator %(Vector3 vec, real_t divisor)
+ {
+ vec.x %= divisor;
+ vec.y %= divisor;
+ vec.z %= divisor;
+ return vec;
+ }
+
+ public static Vector3 operator %(Vector3 vec, Vector3 divisorv)
+ {
+ vec.x %= divisorv.x;
+ vec.y %= divisorv.y;
+ vec.z %= divisorv.z;
+ return vec;
+ }
+
public static bool operator ==(Vector3 left, Vector3 right)
{
return left.Equals(right);
diff --git a/modules/mono/glue/Managed/Managed.csproj b/modules/mono/glue/Managed/Managed.csproj
index ad55fe9539..c8eca71199 100644
--- a/modules/mono/glue/Managed/Managed.csproj
+++ b/modules/mono/glue/Managed/Managed.csproj
@@ -8,6 +8,7 @@
<RootNamespace>Managed</RootNamespace>
<AssemblyName>Managed</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <LangVersion>7</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/modules/mono/mono_gd/android_mono_config.h b/modules/mono/mono_gd/android_mono_config.h
new file mode 100644
index 0000000000..c5cc244aec
--- /dev/null
+++ b/modules/mono/mono_gd/android_mono_config.h
@@ -0,0 +1,43 @@
+/*************************************************************************/
+/* android_mono_config.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef ANDROID_MONO_CONFIG_H
+#define ANDROID_MONO_CONFIG_H
+
+#ifdef ANDROID_ENABLED
+
+#include "core/ustring.h"
+
+// This function is defined in an auto-generated source file
+String get_godot_android_mono_config();
+
+#endif // ANDROID_ENABLED
+
+#endif // ANDROID_MONO_CONFIG_H
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp
index eed8812305..aa69803a58 100644
--- a/modules/mono/mono_gd/gd_mono.cpp
+++ b/modules/mono/mono_gd/gd_mono.cpp
@@ -56,7 +56,7 @@
#endif
#ifdef ANDROID_ENABLED
-#include "android_mono_config.gen.h"
+#include "android_mono_config.h"
#endif
GDMono *GDMono::singleton = NULL;
diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp
index 8986e49cf0..d1bfa20842 100644
--- a/modules/webp/image_loader_webp.cpp
+++ b/modules/webp/image_loader_webp.cpp
@@ -106,8 +106,7 @@ static Ref<Image> _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) {
errdec = WebPDecodeRGBInto(&r[4], size, dst_w.ptr(), datasize, 3 * features.width) == NULL;
}
- //ERR_EXPLAIN("Error decoding webp! - "+p_file);
- ERR_FAIL_COND_V(errdec, Ref<Image>());
+ ERR_FAIL_COND_V_MSG(errdec, Ref<Image>(), "Failed decoding WebP image.");
dst_w.release();
@@ -121,7 +120,6 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
WebPBitstreamFeatures features;
if (WebPGetFeatures(p_buffer, p_buffer_len, &features) != VP8_STATUS_OK) {
- // ERR_EXPLAIN("Error decoding WEBP image");
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
@@ -138,8 +136,7 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
}
dst_w.release();
- //ERR_EXPLAIN("Error decoding webp!");
- ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V_MSG(errdec, ERR_FILE_CORRUPT, "Failed decoding WebP image.");
p_image->create(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp
index 58b68d926b..6f97842064 100644
--- a/modules/webrtc/register_types.cpp
+++ b/modules/webrtc/register_types.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "register_types.h"
+#include "core/project_settings.h"
#include "webrtc_data_channel.h"
#include "webrtc_peer_connection.h"
@@ -43,6 +44,12 @@
#include "webrtc_multiplayer.h"
void register_webrtc_types() {
+#define _SET_HINT(NAME, _VAL_, _MAX_) \
+ GLOBAL_DEF(NAME, _VAL_); \
+ ProjectSettings::get_singleton()->set_custom_property_info(NAME, PropertyInfo(Variant::INT, NAME, PROPERTY_HINT_RANGE, "2," #_MAX_ ",1,or_greater"));
+
+ _SET_HINT(WRTC_IN_BUF, 64, 4096);
+
#ifdef JAVASCRIPT_ENABLED
WebRTCPeerConnectionJS::make_default();
#elif defined(WEBRTC_GDNATIVE_ENABLED)
diff --git a/modules/webrtc/webrtc_data_channel.cpp b/modules/webrtc/webrtc_data_channel.cpp
index 2bd30e68f5..7b3843410a 100644
--- a/modules/webrtc/webrtc_data_channel.cpp
+++ b/modules/webrtc/webrtc_data_channel.cpp
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "webrtc_data_channel.h"
+#include "core/project_settings.h"
void WebRTCDataChannel::_bind_methods() {
ClassDB::bind_method(D_METHOD("poll"), &WebRTCDataChannel::poll);
@@ -58,6 +59,7 @@ void WebRTCDataChannel::_bind_methods() {
}
WebRTCDataChannel::WebRTCDataChannel() {
+ _in_buffer_shift = nearest_shift((int)GLOBAL_GET(WRTC_IN_BUF) - 1) + 10;
}
WebRTCDataChannel::~WebRTCDataChannel() {
diff --git a/modules/webrtc/webrtc_data_channel.h b/modules/webrtc/webrtc_data_channel.h
index 0b161da784..7e2c08d9d7 100644
--- a/modules/webrtc/webrtc_data_channel.h
+++ b/modules/webrtc/webrtc_data_channel.h
@@ -33,6 +33,8 @@
#include "core/io/packet_peer.h"
+#define WRTC_IN_BUF "network/limits/webrtc/max_channel_in_buffer_kb"
+
class WebRTCDataChannel : public PacketPeer {
GDCLASS(WebRTCDataChannel, PacketPeer);
@@ -50,6 +52,8 @@ public:
};
protected:
+ unsigned int _in_buffer_shift;
+
static void _bind_methods();
public:
diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp
index 996db35cba..2edd212a50 100644
--- a/modules/webrtc/webrtc_data_channel_js.cpp
+++ b/modules/webrtc/webrtc_data_channel_js.cpp
@@ -56,7 +56,7 @@ EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_message(void *obj, uint8_t *p_data, uint3
}
void WebRTCDataChannelJS::_on_open() {
- in_buffer.resize(16);
+ in_buffer.resize(_in_buffer_shift);
}
void WebRTCDataChannelJS::_on_close() {
diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp
index 62f09bfbf9..dd86c758bf 100644
--- a/modules/websocket/websocket_multiplayer_peer.cpp
+++ b/modules/websocket/websocket_multiplayer_peer.cpp
@@ -265,7 +265,10 @@ Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, cons
ERR_FAIL_COND_V(p_to == p_from, FAILED);
- return get_peer(p_to)->put_packet(p_buffer, p_buffer_size); // Sending to specific peer
+ Ref<WebSocketPeer> peer_to = get_peer(p_to);
+ ERR_FAIL_COND_V(peer_to.is_null(), FAILED);
+
+ return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer
}
}
@@ -296,8 +299,6 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u
ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages
ERR_FAIL_COND(from != p_peer_id); // Someone is cheating
- _server_relay(from, to, in_buffer, size); // Relay if needed
-
if (to == 1) { // This is for the server
_store_pkt(from, to, in_buffer, data_size);
@@ -312,13 +313,9 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u
// All but one, for us if not excluded
if (_peer_id != -(int32_t)p_peer_id)
_store_pkt(from, to, in_buffer, data_size);
-
- } else {
-
- // Send to specific peer
- ERR_FAIL_COND(!_peer_map.has(to));
- get_peer(to)->put_packet(in_buffer, size);
}
+ // Relay if needed (i.e. "to" includes a peer that is not the server)
+ _server_relay(from, to, in_buffer, size);
} else {
diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp
index cf2ad55b4a..0006a057e0 100644
--- a/modules/websocket/wsl_client.cpp
+++ b/modules/websocket/wsl_client.cpp
@@ -121,17 +121,17 @@ bool WSLClient::_verify_headers(String &r_protocol) {
headers[name] = value;
}
-#define _WLS_EXPLAIN(NAME, VALUE) \
- ERR_EXPLAIN("Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'");
-#define _WLS_CHECK(NAME, VALUE) \
- _WLS_EXPLAIN(NAME, VALUE); \
- ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false);
-#define _WLS_CHECK_NC(NAME, VALUE) \
- _WLS_EXPLAIN(NAME, VALUE); \
- ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME] != VALUE, false);
- _WLS_CHECK("connection", "upgrade");
- _WLS_CHECK("upgrade", "websocket");
- _WLS_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
+#define _WSL_CHECK(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+#define _WSL_CHECK_NC(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+ _WSL_CHECK("connection", "upgrade");
+ _WSL_CHECK("upgrade", "websocket");
+ _WSL_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
+#undef _WSL_CHECK_NC
+#undef _WSL_CHECK
if (_protocols.size() == 0) {
// We didn't request a custom protocol
ERR_FAIL_COND_V(headers.has("sec-websocket-protocol"), false);
@@ -148,10 +148,6 @@ bool WSLClient::_verify_headers(String &r_protocol) {
if (!valid)
return false;
}
-#undef _WLS_CHECK_NC
-#undef _WLS_CHECK
-#undef _WLS_EXPLAIN
-
return true;
}
diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp
index b11bd2b70f..74fb901232 100644
--- a/modules/websocket/wsl_peer.cpp
+++ b/modules/websocket/wsl_peer.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* lws_peer.cpp */
+/* wsl_peer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -35,7 +35,7 @@
#include "wsl_client.h"
#include "wsl_server.h"
-#include "core/math/crypto_core.h"
+#include "core/crypto/crypto_core.h"
#include "core/math/random_number_generator.h"
#include "core/os/os.h"
diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp
index 1feae420b9..efb526eed1 100644
--- a/modules/websocket/wsl_server.cpp
+++ b/modules/websocket/wsl_server.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* lws_server.cpp */
+/* wsl_server.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -64,18 +64,17 @@ bool WSLServer::PendingPeer::_parse_request(const PoolStringArray p_protocols) {
else
headers[name] = value;
}
-#define _WLS_CHECK(NAME, VALUE) \
- ERR_EXPLAIN("Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'"); \
- ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false);
-#define _WLS_CHECK_EX(NAME) \
- ERR_EXPLAIN("Missing header '" + String(NAME) + "'."); \
- ERR_FAIL_COND_V(!headers.has(NAME), false);
- _WLS_CHECK("upgrade", "websocket");
- _WLS_CHECK("sec-websocket-version", "13");
- _WLS_CHECK_EX("sec-websocket-key");
- _WLS_CHECK_EX("connection");
-#undef _WLS_CHECK_EX
-#undef _WLS_CHECK
+#define _WSL_CHECK(NAME, VALUE) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
+ "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'.");
+#define _WSL_CHECK_EX(NAME) \
+ ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'.");
+ _WSL_CHECK("upgrade", "websocket");
+ _WSL_CHECK("sec-websocket-version", "13");
+ _WSL_CHECK_EX("sec-websocket-key");
+ _WSL_CHECK_EX("connection");
+#undef _WSL_CHECK_EX
+#undef _WSL_CHECK
key = headers["sec-websocket-key"];
if (headers.has("sec-websocket-protocol")) {
Vector<String> protos = headers["sec-websocket-protocol"].split(",");
diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp
index c18aa04336..04911301ff 100644
--- a/modules/xatlas_unwrap/register_types.cpp
+++ b/modules/xatlas_unwrap/register_types.cpp
@@ -29,11 +29,14 @@
/*************************************************************************/
#include "register_types.h"
+
#include "core/error_macros.h"
+
#include "thirdparty/xatlas/xatlas.h"
#include <stdio.h>
#include <stdlib.h>
+
extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);
bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) {
diff --git a/platform/android/SCsub b/platform/android/SCsub
index e355caf0f9..d2f27817c6 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -1,12 +1,11 @@
#!/usr/bin/env python
-Import('env')
-
-from distutils.version import LooseVersion
from detect import get_ndk_version
+from distutils.version import LooseVersion
-android_files = [
+Import('env')
+android_files = [
'os_android.cpp',
'file_access_android.cpp',
'audio_driver_opensl.cpp',
@@ -18,7 +17,7 @@ android_files = [
'java_class_wrapper.cpp',
'java_godot_wrapper.cpp',
'java_godot_io_wrapper.cpp',
-# 'power_android.cpp'
+ #'power_android.cpp'
]
env_android = env.Clone()
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 283791f336..8b62360888 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -32,14 +32,12 @@ def get_opts():
def get_flags():
-
return [
('tools', False),
]
def create(env):
-
tools = env['TOOLS']
if "mingw" in tools:
tools.remove('mingw')
@@ -50,7 +48,6 @@ def create(env):
def configure(env):
-
# Workaround for MinGW. See:
# http://www.scons.org/wiki/LongCmdLinesOnWin32
if (os.name == "nt"):
@@ -90,7 +87,7 @@ def configure(env):
env['SPAWN'] = mySpawn
- ## Architecture
+ # Architecture
if env['android_arch'] not in ['armv7', 'arm64v8', 'x86', 'x86_64']:
env['android_arch'] = 'armv7'
@@ -137,14 +134,14 @@ def configure(env):
arch_subpath = "arm64-v8a"
env.extra_suffix = ".armv8" + env.extra_suffix
- ## Build type
+ # Build type
if (env["target"].startswith("release")):
- if (env["optimize"] == "speed"): #optimize for speed (default)
+ if (env["optimize"] == "speed"): # optimize for speed (default)
env.Append(LINKFLAGS=['-O2'])
env.Append(CCFLAGS=['-O2', '-fomit-frame-pointer'])
env.Append(CPPDEFINES=['NDEBUG'])
- else: #optimize for size
+ else: # optimize for size
env.Append(CCFLAGS=['-Os'])
env.Append(CPPDEFINES=['NDEBUG'])
env.Append(LINKFLAGS=['-Os'])
@@ -159,7 +156,7 @@ def configure(env):
env.Append(CPPDEFINES=['_DEBUG', 'DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED'])
env.Append(CPPFLAGS=['-UNDEBUG'])
- ## Compiler configuration
+ # Compiler configuration
env['SHLIBSUFFIX'] = '.so'
@@ -204,7 +201,7 @@ def configure(env):
common_opts = ['-fno-integrated-as', '-gcc-toolchain', gcc_toolchain_path]
- ## Compile flags
+ # Compile flags
env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/include"])
env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"])
@@ -259,7 +256,7 @@ def configure(env):
env.Append(CCFLAGS=target_opts)
env.Append(CCFLAGS=common_opts)
- ## Link flags
+ # Link flags
ndk_version = get_ndk_version(env["ANDROID_NDK_ROOT"])
if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"):
@@ -268,7 +265,7 @@ def configure(env):
env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a"])
env.Append(LINKFLAGS=['-shared', '--sysroot=' + lib_sysroot, '-Wl,--warn-shared-textrel'])
env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/"])
- env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] +"/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"])
+ env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"])
if env["android_arch"] == "armv7":
env.Append(LINKFLAGS='-Wl,--fix-cortex-a8'.split())
@@ -287,6 +284,7 @@ def configure(env):
env.Append(CPPDEFINES=['ANDROID_ENABLED', 'UNIX_ENABLED', 'NO_FCNTL'])
env.Append(LIBS=['OpenSLES', 'EGL', 'GLESv3', 'GLESv2', 'android', 'log', 'z', 'dl'])
+
# Return NDK version string in source.properties (adapted from the Chromium project).
def get_ndk_version(path):
if path is None:
diff --git a/platform/android/java/AndroidManifest.xml b/platform/android/java/AndroidManifest.xml
index 3152ef12cd..5114aeb8c5 100644
--- a/platform/android/java/AndroidManifest.xml
+++ b/platform/android/java/AndroidManifest.xml
@@ -1,58 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- package="com.godot.game"
- android:versionCode="1"
- android:versionName="1.0"
- android:installLocation="auto"
- >
-<supports-screens android:smallScreens="true"
- android:normalScreens="true"
- android:largeScreens="true"
- android:xlargeScreens="true"/>
-
-<!--glEsVersion is modified by the exporter, changing this value here has no effect-->
- <uses-feature android:glEsVersion="0x00020000" android:required="true" />
-<!--Adding custom text to manifest is fine, but do it outside the custom user and application BEGIN/END regions, as that gets rewritten-->
-
-<!--Custom permissions XML added by add-ons. It's recommended to add them from the export preset, though-->
+ xmlns:tools="http://schemas.android.com/tools"
+ package="com.godot.game"
+ android:versionCode="1"
+ android:versionName="1.0"
+ android:installLocation="auto" >
+
+ <!-- Adding custom text to the manifest is fine, but do it outside the custom USER and APPLICATION BEGIN/END comments, -->
+ <!-- as that gets rewritten. -->
+
+ <supports-screens
+ android:smallScreens="true"
+ android:normalScreens="true"
+ android:largeScreens="true"
+ android:xlargeScreens="true" />
+
+ <!-- glEsVersion is modified by the exporter, changing this value here has no effect. -->
+ <uses-feature
+ android:glEsVersion="0x00020000"
+ android:required="true" />
+
+<!-- Custom user permissions XML added by add-ons. It's recommended to add them from the export preset, though. -->
<!--CHUNK_USER_PERMISSIONS_BEGIN-->
<!--CHUNK_USER_PERMISSIONS_END-->
-<!--Anything in this line after the icon will be erased when doing custom build. If you want to add tags manually, do before it.-->
- <application android:label="@string/godot_project_name_string" android:allowBackup="false" tools:ignore="GoogleAppIndexingWarning" android:icon="@drawable/icon">
+ <!-- Any tag in this line after android:icon will be erased when doing custom builds. -->
+ <!-- If you want to add tags manually, do before it. -->
+ <application
+ android:label="@string/godot_project_name_string"
+ android:allowBackup="false"
+ tools:ignore="GoogleAppIndexingWarning"
+ android:icon="@drawable/icon" >
-<!--The following values are replaced when Godot exports, modifying them here has no effect. Do these changes in the-->
-<!--export preset. Adding new ones is fine.-->
+ <!-- The following metadata values are replaced when Godot exports, modifying them here has no effect. -->
+ <!-- Do these changes in the export preset. Adding new ones is fine. -->
-<!-- XR mode metadata. This is modified by the exporter based on the selected xr mode. DO NOT CHANGE the values here. -->
- <meta-data android:name="xr_mode_metadata_name" android:value="xr_mode_metadata_value"/>
+ <!-- XR mode metadata. This is modified by the exporter based on the selected xr mode. DO NOT CHANGE the values here. -->
+ <meta-data
+ android:name="xr_mode_metadata_name"
+ android:value="xr_mode_metadata_value" />
- <activity android:name="org.godotengine.godot.Godot"
- android:label="@string/godot_project_name_string"
- android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
- android:launchMode="singleTask"
- android:screenOrientation="landscape"
- android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|density|keyboard|navigation|screenLayout|uiMode"
- android:resizeableActivity="false"
- tools:ignore="UnusedAttribute">
+ <activity
+ android:name="org.godotengine.godot.Godot"
+ android:label="@string/godot_project_name_string"
+ android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
+ android:launchMode="singleTask"
+ android:screenOrientation="landscape"
+ android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|density|keyboard|navigation|screenLayout|uiMode"
+ android:resizeableActivity="false"
+ tools:ignore="UnusedAttribute" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
- <service android:name="org.godotengine.godot.GodotDownloaderService" />
-<!--Custom application XML added by add-ons-->
+ <service android:name="org.godotengine.godot.GodotDownloaderService" />
+
+<!-- Custom application XML added by add-ons. -->
<!--CHUNK_APPLICATION_BEGIN-->
<!--CHUNK_APPLICATION_END-->
</application>
- <instrumentation android:icon="@drawable/icon"
- android:label="@string/godot_project_name_string"
- android:name="org.godotengine.godot.GodotInstrumentation"
- android:targetPackage="org.godotengine.game" />
+ <instrumentation
+ android:icon="@drawable/icon"
+ android:label="@string/godot_project_name_string"
+ android:name="org.godotengine.godot.GodotInstrumentation"
+ android:targetPackage="org.godotengine.game" />
</manifest>
diff --git a/platform/android/java/README.md b/platform/android/java/README.md
deleted file mode 100644
index 58d2b10706..0000000000
--- a/platform/android/java/README.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Third party libraries
-
-
-## Google's vending library
-
-- Upstream: https://github.com/google/play-licensing/tree/master/lvl_library/src/main/java/com/google/android/vending
-- Version: git (eb57657, 2018) with modifications
-- License: Apache 2.0
-
-Overwrite all files under `com/google/android/vending`
-
-### Modify some files to avoid compile error and lint warning
-
-#### com/google/android/vending/licensing/util/Base64.java
-```
-@@ -338,7 +338,8 @@ public class Base64 {
- e += 4;
- }
-
-- assert (e == outBuff.length);
-+ if (BuildConfig.DEBUG && e != outBuff.length)
-+ throw new RuntimeException();
- return outBuff;
- }
-```
-
-#### com/google/android/vending/licensing/LicenseChecker.java
-```
-@@ -29,8 +29,8 @@ import android.os.RemoteException;
- import android.provider.Settings.Secure;
- import android.util.Log;
-
--import com.android.vending.licensing.ILicenseResultListener;
--import com.android.vending.licensing.ILicensingService;
-+import com.google.android.vending.licensing.ILicenseResultListener;
-+import com.google.android.vending.licensing.ILicensingService;
- import com.google.android.vending.licensing.util.Base64;
- import com.google.android.vending.licensing.util.Base64DecoderException;
-```
-```
-@@ -287,13 +287,15 @@ public class LicenseChecker implements ServiceConnection {
- if (logResponse) {
-- String android_id = Secure.getString(mContext.getContentResolver(),
-- Secure.ANDROID_ID);
-+ String android_id = Secure.ANDROID_ID;
- Date date = new Date();
-```
diff --git a/platform/android/java/THIRDPARTY.md b/platform/android/java/THIRDPARTY.md
new file mode 100644
index 0000000000..2496b59263
--- /dev/null
+++ b/platform/android/java/THIRDPARTY.md
@@ -0,0 +1,39 @@
+# Third-party libraries
+
+This file list third-party libraries used in the Android source folder,
+with their provenance and, when relevant, modifications made to those files.
+
+## com.android.vending.billing
+
+- Upstream: https://github.com/googlesamples/android-play-billing/tree/master/TrivialDrive/app/src/main
+- Version: git (7a94c69, 2019)
+- License: Apache 2.0
+
+Overwrite the file `aidl/com/android/vending/billing/IInAppBillingService.aidl`.
+
+## com.google.android.vending.expansion.downloader
+
+- Upstream: https://github.com/google/play-apk-expansion/tree/master/apkx_library
+- Version: git (9ecf54e, 2017)
+- License: Apache 2.0
+
+Overwrite all files under:
+
+- `src/com/google/android/vending/expansion/downloader`
+
+Some files have been modified for yet unclear reasons.
+See the `patches/com.google.android.vending.expansion.downloader.patch` file.
+
+## com.google.android.vending.licensing
+
+- Upstream: https://github.com/google/play-licensing/tree/master/lvl_library/
+- Version: git (eb57657, 2018) with modifications
+- License: Apache 2.0
+
+Overwrite all files under:
+
+- `aidl/com/android/vending/licensing`
+- `src/com/google/android/vending/licensing`
+
+Some files have been modified to silence linter errors or fix downstream issues.
+See the `patches/com.google.android.vending.licensing.patch` file.
diff --git a/platform/android/java/aidl/com/android/vending/billing/IInAppBillingService.aidl b/platform/android/java/aidl/com/android/vending/billing/IInAppBillingService.aidl
index 2a492f7845..0f2bcae338 100644
--- a/platform/android/java/aidl/com/android/vending/billing/IInAppBillingService.aidl
+++ b/platform/android/java/aidl/com/android/vending/billing/IInAppBillingService.aidl
@@ -34,10 +34,11 @@ import android.os.Bundle;
*
* All calls will give a response code with the following possible values
* RESULT_OK = 0 - success
- * RESULT_USER_CANCELED = 1 - user pressed back or canceled a dialog
- * RESULT_BILLING_UNAVAILABLE = 3 - this billing API version is not supported for the type requested
- * RESULT_ITEM_UNAVAILABLE = 4 - requested SKU is not available for purchase
- * RESULT_DEVELOPER_ERROR = 5 - invalid arguments provided to the API
+ * RESULT_USER_CANCELED = 1 - User pressed back or canceled a dialog
+ * RESULT_SERVICE_UNAVAILABLE = 2 - The network connection is down
+ * RESULT_BILLING_UNAVAILABLE = 3 - This billing API version is not supported for the type requested
+ * RESULT_ITEM_UNAVAILABLE = 4 - Requested SKU is not available for purchase
+ * RESULT_DEVELOPER_ERROR = 5 - Invalid arguments provided to the API
* RESULT_ERROR = 6 - Fatal error during the API action
* RESULT_ITEM_ALREADY_OWNED = 7 - Failure to purchase since item is already owned
* RESULT_ITEM_NOT_OWNED = 8 - Failure to consume since item is not owned
@@ -46,11 +47,11 @@ interface IInAppBillingService {
/**
* Checks support for the requested billing API version, package and in-app type.
* Minimum API version supported by this interface is 3.
- * @param apiVersion the billing version which the app is using
+ * @param apiVersion billing API version that the app is using
* @param packageName the package name of the calling app
- * @param type type of the in-app item being purchased "inapp" for one-time purchases
- * and "subs" for subscription.
- * @return RESULT_OK(0) on success, corresponding result code on failures
+ * @param type type of the in-app item being purchased ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
+ * @return RESULT_OK(0) on success and appropriate response code on failures.
*/
int isBillingSupported(int apiVersion, String packageName, String type);
@@ -59,16 +60,23 @@ interface IInAppBillingService {
* Given a list of SKUs of a valid type in the skusBundle, this returns a bundle
* with a list JSON strings containing the productId, price, title and description.
* This API can be called with a maximum of 20 SKUs.
- * @param apiVersion billing API version that the Third-party is using
+ * @param apiVersion billing API version that the app is using
* @param packageName the package name of the calling app
+ * @param type of the in-app items ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
* @param skusBundle bundle containing a StringArrayList of SKUs with key "ITEM_ID_LIST"
* @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
- * failure as listed above.
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
+ * on failures.
* "DETAILS_LIST" with a StringArrayList containing purchase information
- * in JSON format similar to:
- * '{ "productId" : "exampleSku", "type" : "inapp", "price" : "$5.00",
- * "title : "Example Title", "description" : "This is an example description" }'
+ * in JSON format similar to:
+ * '{ "productId" : "exampleSku",
+ * "type" : "inapp",
+ * "price" : "$5.00",
+ * "price_currency": "USD",
+ * "price_amount_micros": 5000000,
+ * "title : "Example Title",
+ * "description" : "This is an example description" }'
*/
Bundle getSkuDetails(int apiVersion, String packageName, String type, in Bundle skusBundle);
@@ -78,29 +86,28 @@ interface IInAppBillingService {
* @param apiVersion billing API version that the app is using
* @param packageName package name of the calling app
* @param sku the SKU of the in-app item as published in the developer console
- * @param type the type of the in-app item ("inapp" for one-time purchases
- * and "subs" for subscription).
+ * @param type of the in-app item being purchased ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
* @param developerPayload optional argument to be sent back with the purchase information
* @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
- * failure as listed above.
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
+ * on failures.
* "BUY_INTENT" - PendingIntent to start the purchase flow
*
* The Pending intent should be launched with startIntentSenderForResult. When purchase flow
* has completed, the onActivityResult() will give a resultCode of OK or CANCELED.
* If the purchase is successful, the result data will contain the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
- * failure as listed above.
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response
+ * codes on failures.
* "INAPP_PURCHASE_DATA" - String in JSON format similar to
- * '{"orderId":"12999763169054705758.1371079406387615",
- * "packageName":"com.example.app",
- * "productId":"exampleSku",
- * "purchaseTime":1345678900000,
- * "purchaseToken" : "122333444455555",
- * "developerPayload":"example developer payload" }'
+ * '{"orderId":"12999763169054705758.1371079406387615",
+ * "packageName":"com.example.app",
+ * "productId":"exampleSku",
+ * "purchaseTime":1345678900000,
+ * "purchaseToken" : "122333444455555",
+ * "developerPayload":"example developer payload" }'
* "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that
* was signed with the private key of the developer
- * TODO: change this to app-specific keys.
*/
Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type,
String developerPayload);
@@ -112,15 +119,15 @@ interface IInAppBillingService {
* V1 and V2 that have not been consumed.
* @param apiVersion billing API version that the app is using
* @param packageName package name of the calling app
- * @param type the type of the in-app items being requested
- * ("inapp" for one-time purchases and "subs" for subscription).
+ * @param type of the in-app items being requested ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
* @param continuationToken to be set as null for the first call, if the number of owned
* skus are too many, a continuationToken is returned in the response bundle.
* This method can be called again with the continuation token to get the next set of
* owned skus.
* @return Bundle containing the following key-value pairs
- * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on
- * failure as listed above.
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
+ on failures.
* "INAPP_PURCHASE_ITEM_LIST" - StringArrayList containing the list of SKUs
* "INAPP_PURCHASE_DATA_LIST" - StringArrayList containing the purchase information
* "INAPP_DATA_SIGNATURE_LIST"- StringArrayList containing the signatures
@@ -138,7 +145,137 @@ interface IInAppBillingService {
* @param packageName package name of the calling app
* @param purchaseToken token in the purchase information JSON that identifies the purchase
* to be consumed
- * @return 0 if consumption succeeded. Appropriate error values for failures.
+ * @return RESULT_OK(0) if consumption succeeded, appropriate response codes on failures.
*/
int consumePurchase(int apiVersion, String packageName, String purchaseToken);
+
+ /**
+ * This API is currently under development.
+ */
+ int stub(int apiVersion, String packageName, String type);
+
+ /**
+ * Returns a pending intent to launch the purchase flow for upgrading or downgrading a
+ * subscription. The existing owned SKU(s) should be provided along with the new SKU that
+ * the user is upgrading or downgrading to.
+ * @param apiVersion billing API version that the app is using, must be 5 or later
+ * @param packageName package name of the calling app
+ * @param oldSkus the SKU(s) that the user is upgrading or downgrading from,
+ * if null or empty this method will behave like {@link #getBuyIntent}
+ * @param newSku the SKU that the user is upgrading or downgrading to
+ * @param type of the item being purchased, currently must be "subs"
+ * @param developerPayload optional argument to be sent back with the purchase information
+ * @return Bundle containing the following key-value pairs
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response codes
+ * on failures.
+ * "BUY_INTENT" - PendingIntent to start the purchase flow
+ *
+ * The Pending intent should be launched with startIntentSenderForResult. When purchase flow
+ * has completed, the onActivityResult() will give a resultCode of OK or CANCELED.
+ * If the purchase is successful, the result data will contain the following key-value pairs
+ * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, appropriate response
+ * codes on failures.
+ * "INAPP_PURCHASE_DATA" - String in JSON format similar to
+ * '{"orderId":"12999763169054705758.1371079406387615",
+ * "packageName":"com.example.app",
+ * "productId":"exampleSku",
+ * "purchaseTime":1345678900000,
+ * "purchaseToken" : "122333444455555",
+ * "developerPayload":"example developer payload" }'
+ * "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that
+ * was signed with the private key of the developer
+ */
+ Bundle getBuyIntentToReplaceSkus(int apiVersion, String packageName,
+ in List<String> oldSkus, String newSku, String type, String developerPayload);
+
+ /**
+ * Returns a pending intent to launch the purchase flow for an in-app item. This method is
+ * a variant of the {@link #getBuyIntent} method and takes an additional {@code extraParams}
+ * parameter. This parameter is a Bundle of optional keys and values that affect the
+ * operation of the method.
+ * @param apiVersion billing API version that the app is using, must be 6 or later
+ * @param packageName package name of the calling app
+ * @param sku the SKU of the in-app item as published in the developer console
+ * @param type of the in-app item being purchased ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
+ * @param developerPayload optional argument to be sent back with the purchase information
+ * @extraParams a Bundle with the following optional keys:
+ * "skusToReplace" - List<String> - an optional list of SKUs that the user is
+ * upgrading or downgrading from.
+ * Pass this field if the purchase is upgrading or downgrading
+ * existing subscriptions.
+ * The specified SKUs are replaced with the SKUs that the user is
+ * purchasing. Google Play replaces the specified SKUs at the start of
+ * the next billing cycle.
+ * "replaceSkusProration" - Boolean - whether the user should be credited for any unused
+ * subscription time on the SKUs they are upgrading or downgrading.
+ * If you set this field to true, Google Play swaps out the old SKUs
+ * and credits the user with the unused value of their subscription
+ * time on a pro-rated basis.
+ * Google Play applies this credit to the new subscription, and does
+ * not begin billing the user for the new subscription until after
+ * the credit is used up.
+ * If you set this field to false, the user does not receive credit for
+ * any unused subscription time and the recurrence date does not
+ * change.
+ * Default value is true. Ignored if you do not pass skusToReplace.
+ * "accountId" - String - an optional obfuscated string that is uniquely
+ * associated with the user's account in your app.
+ * If you pass this value, Google Play can use it to detect irregular
+ * activity, such as many devices making purchases on the same
+ * account in a short period of time.
+ * Do not use the developer ID or the user's Google ID for this field.
+ * In addition, this field should not contain the user's ID in
+ * cleartext.
+ * We recommend that you use a one-way hash to generate a string from
+ * the user's ID, and store the hashed string in this field.
+ * "vr" - Boolean - an optional flag indicating whether the returned intent
+ * should start a VR purchase flow. The apiVersion must also be 7 or
+ * later to use this flag.
+ */
+ Bundle getBuyIntentExtraParams(int apiVersion, String packageName, String sku,
+ String type, String developerPayload, in Bundle extraParams);
+
+ /**
+ * Returns the most recent purchase made by the user for each SKU, even if that purchase is
+ * expired, canceled, or consumed.
+ * @param apiVersion billing API version that the app is using, must be 6 or later
+ * @param packageName package name of the calling app
+ * @param type of the in-app items being requested ("inapp" for one-time purchases
+ * and "subs" for subscriptions)
+ * @param continuationToken to be set as null for the first call, if the number of owned
+ * skus is too large, a continuationToken is returned in the response bundle.
+ * This method can be called again with the continuation token to get the next set of
+ * owned skus.
+ * @param extraParams a Bundle with extra params that would be appended into http request
+ * query string. Not used at this moment. Reserved for future functionality.
+ * @return Bundle containing the following key-value pairs
+ * "RESPONSE_CODE" with int value: RESULT_OK(0) if success,
+ * {@link IabHelper#BILLING_RESPONSE_RESULT_*} response codes on failures.
+ *
+ * "INAPP_PURCHASE_ITEM_LIST" - ArrayList<String> containing the list of SKUs
+ * "INAPP_PURCHASE_DATA_LIST" - ArrayList<String> containing the purchase information
+ * "INAPP_DATA_SIGNATURE_LIST"- ArrayList<String> containing the signatures
+ * of the purchase information
+ * "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the
+ * next set of in-app purchases. Only set if the
+ * user has more owned skus than the current list.
+ */
+ Bundle getPurchaseHistory(int apiVersion, String packageName, String type,
+ String continuationToken, in Bundle extraParams);
+
+ /**
+ * This method is a variant of {@link #isBillingSupported}} that takes an additional
+ * {@code extraParams} parameter.
+ * @param apiVersion billing API version that the app is using, must be 7 or later
+ * @param packageName package name of the calling app
+ * @param type of the in-app item being purchased ("inapp" for one-time purchases and "subs"
+ * for subscriptions)
+ * @param extraParams a Bundle with the following optional keys:
+ * "vr" - Boolean - an optional flag to indicate whether {link #getBuyIntentExtraParams}
+ * supports returning a VR purchase flow.
+ * @return RESULT_OK(0) on success and appropriate response code on failures.
+ */
+ int isBillingSupportedExtraParams(int apiVersion, String packageName, String type,
+ in Bundle extraParams);
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.aidl b/platform/android/java/aidl/com/android/vending/licensing/ILicenseResultListener.aidl
index c816558afc..869cb16f68 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.aidl
+++ b/platform/android/java/aidl/com/android/vending/licensing/ILicenseResultListener.aidl
@@ -16,8 +16,6 @@
package com.android.vending.licensing;
-// Android library projects do not yet support AIDL, so this has been
-// precompiled into the src directory.
oneway interface ILicenseResultListener {
void verifyLicense(int responseCode, String signedData, String signature);
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ILicensingService.aidl b/platform/android/java/aidl/com/android/vending/licensing/ILicensingService.aidl
index 664510ce0c..9541a2090c 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/ILicensingService.aidl
+++ b/platform/android/java/aidl/com/android/vending/licensing/ILicensingService.aidl
@@ -18,8 +18,6 @@ package com.android.vending.licensing;
import com.android.vending.licensing.ILicenseResultListener;
-// Android library projects do not yet support AIDL, so this has been
-// precompiled into the src directory.
oneway interface ILicensingService {
void checkLicense(long nonce, String packageName, in ILicenseResultListener listener);
}
diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index c468277daa..0f8499ba91 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -1,113 +1,111 @@
-//Gradle project for Godot Engine Android port.
-//Do not modify code between the BEGIN/END sections, as it's autogenerated by add-ons
+// Gradle build config for Godot Engine's Android port.
+//
+// Do not remove/modify comments ending with BEGIN/END, they are used to inject
+// addon-specific configuration.
buildscript {
- repositories {
- google()
- jcenter()
+ repositories {
+ google()
+ jcenter()
//CHUNK_BUILDSCRIPT_REPOSITORIES_BEGIN
//CHUNK_BUILDSCRIPT_REPOSITORIES_END
- }
- dependencies {
- classpath 'com.android.tools.build:gradle:3.2.1'
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:3.4.2'
//CHUNK_BUILDSCRIPT_DEPENDENCIES_BEGIN
//CHUNK_BUILDSCRIPT_DEPENDENCIES_END
- }
+ }
}
apply plugin: 'com.android.application'
allprojects {
repositories {
- mavenCentral()
- google()
- jcenter()
+ mavenCentral()
+ google()
+ jcenter()
//CHUNK_ALLPROJECTS_REPOSITORIES_BEGIN
//CHUNK_ALLPROJECTS_REPOSITORIES_END
-
}
}
dependencies {
- implementation "com.android.support:support-core-utils:28.0.0"
+ implementation "com.android.support:support-core-utils:28.0.0"
//CHUNK_DEPENDENCIES_BEGIN
//CHUNK_DEPENDENCIES_END
}
android {
+ compileSdkVersion 28
+ buildToolsVersion "28.0.3"
+ useLibrary 'org.apache.http.legacy'
- lintOptions {
- abortOnError false
- disable 'MissingTranslation','UnusedResources'
- }
-
- compileSdkVersion 28
- buildToolsVersion "28.0.3"
- useLibrary 'org.apache.http.legacy'
-
- packagingOptions {
- exclude 'META-INF/LICENSE'
- exclude 'META-INF/NOTICE'
- }
- defaultConfig {
- minSdkVersion 18
- targetSdkVersion 28
+ defaultConfig {
+ minSdkVersion 18
+ targetSdkVersion 28
//CHUNK_ANDROID_DEFAULTCONFIG_BEGIN
//CHUNK_ANDROID_DEFAULTCONFIG_END
- }
- // Both signing and zip-aligning will be done at export time
- buildTypes.all { buildType ->
- buildType.zipAlignEnabled false
- buildType.signingConfig null
- }
- sourceSets {
- main {
- manifest.srcFile 'AndroidManifest.xml'
- java.srcDirs = ['src'
+ }
+
+ lintOptions {
+ abortOnError false
+ disable 'MissingTranslation', 'UnusedResources'
+ }
+
+ packagingOptions {
+ exclude 'META-INF/LICENSE'
+ exclude 'META-INF/NOTICE'
+ }
+
+ // Both signing and zip-aligning will be done at export time
+ buildTypes.all { buildType ->
+ buildType.zipAlignEnabled false
+ buildType.signingConfig null
+ }
+
+ sourceSets {
+ main {
+ manifest.srcFile 'AndroidManifest.xml'
+ java.srcDirs = [
+ 'src'
//DIR_SRC_BEGIN
//DIR_SRC_END
- ]
- res.srcDirs = [
- 'res'
+ ]
+ res.srcDirs = [
+ 'res'
//DIR_RES_BEGIN
//DIR_RES_END
- ]
- aidl.srcDirs = [
- 'aidl'
+ ]
+ aidl.srcDirs = [
+ 'aidl'
//DIR_AIDL_BEGIN
//DIR_AIDL_END
- ]
- assets.srcDirs = [
- 'assets'
+ ]
+ assets.srcDirs = [
+ 'assets'
//DIR_ASSETS_BEGIN
//DIR_ASSETS_END
-
- ]
- }
- debug.jniLibs.srcDirs = [
- 'libs/debug'
+ ]
+ }
+ debug.jniLibs.srcDirs = [
+ 'libs/debug'
//DIR_JNI_DEBUG_BEGIN
//DIR_JNI_DEBUG_END
- ]
- release.jniLibs.srcDirs = [
- 'libs/release'
+ ]
+ release.jniLibs.srcDirs = [
+ 'libs/release'
//DIR_JNI_RELEASE_BEGIN
//DIR_JNI_RELEASE_END
- ]
- }
-// No longer used, as it's not useful for build source template
-// applicationVariants.all { variant ->
-// variant.outputs.all { output ->
-// output.outputFileName = "../../../../../../../bin/android_${variant.name}.apk"
-// }
-// }
+ ]
+ }
+ // No longer used, as it's not useful for build source template
+ //applicationVariants.all { variant ->
+ // variant.outputs.all { output ->
+ // output.outputFileName = "../../../../../../../bin/android_${variant.name}.apk"
+ // }
+ //}
}
//CHUNK_GLOBAL_BEGIN
//CHUNK_GLOBAL_END
-
-
-
-
-
diff --git a/platform/android/java/gradle/wrapper/gradle-wrapper.properties b/platform/android/java/gradle/wrapper/gradle-wrapper.properties
index bf3de21830..558870dad5 100644
--- a/platform/android/java/gradle/wrapper/gradle-wrapper.properties
+++ b/platform/android/java/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/platform/android/java/patches/com.google.android.vending.expansion.downloader.patch b/platform/android/java/patches/com.google.android.vending.expansion.downloader.patch
new file mode 100644
index 0000000000..1189cfbfbb
--- /dev/null
+++ b/platform/android/java/patches/com.google.android.vending.expansion.downloader.patch
@@ -0,0 +1,300 @@
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
+index ad6ea0de6..452c7d148 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
+@@ -32,6 +32,9 @@ import android.os.Messenger;
+ import android.os.RemoteException;
+ import android.util.Log;
+
++// -- GODOT start --
++import java.lang.ref.WeakReference;
++// -- GODOT end --
+
+
+ /**
+@@ -118,29 +121,46 @@ public class DownloaderClientMarshaller {
+ /**
+ * Target we publish for clients to send messages to IncomingHandler.
+ */
+- final Messenger mMessenger = new Messenger(new Handler() {
++ // -- GODOT start --
++ private final MessengerHandlerClient mMsgHandler = new MessengerHandlerClient(this);
++ final Messenger mMessenger = new Messenger(mMsgHandler);
++
++ private static class MessengerHandlerClient extends Handler {
++ private final WeakReference<Stub> mDownloader;
++ public MessengerHandlerClient(Stub downloader) {
++ mDownloader = new WeakReference<>(downloader);
++ }
++
+ @Override
+ public void handleMessage(Message msg) {
+- switch (msg.what) {
+- case MSG_ONDOWNLOADPROGRESS:
+- Bundle bun = msg.getData();
+- if ( null != mContext ) {
+- bun.setClassLoader(mContext.getClassLoader());
+- DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
+- .getParcelable(PARAM_PROGRESS);
+- mItf.onDownloadProgress(dpi);
+- }
+- break;
+- case MSG_ONDOWNLOADSTATE_CHANGED:
+- mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
+- break;
+- case MSG_ONSERVICECONNECTED:
+- mItf.onServiceConnected(
+- (Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
+- break;
++ Stub downloader = mDownloader.get();
++ if (downloader != null) {
++ downloader.handleMessage(msg);
+ }
+ }
+- });
++ }
++
++ private void handleMessage(Message msg) {
++ switch (msg.what) {
++ case MSG_ONDOWNLOADPROGRESS:
++ Bundle bun = msg.getData();
++ if (null != mContext) {
++ bun.setClassLoader(mContext.getClassLoader());
++ DownloadProgressInfo dpi = (DownloadProgressInfo)msg.getData()
++ .getParcelable(PARAM_PROGRESS);
++ mItf.onDownloadProgress(dpi);
++ }
++ break;
++ case MSG_ONDOWNLOADSTATE_CHANGED:
++ mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
++ break;
++ case MSG_ONSERVICECONNECTED:
++ mItf.onServiceConnected(
++ (Messenger)msg.getData().getParcelable(PARAM_MESSENGER));
++ break;
++ }
++ }
++ // -- GODOT end --
+
+ public Stub(IDownloaderClient itf, Class<?> downloaderService) {
+ mItf = itf;
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
+index 979352299..3771d19c9 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
+@@ -25,6 +25,9 @@ import android.os.Message;
+ import android.os.Messenger;
+ import android.os.RemoteException;
+
++// -- GODOT start --
++import java.lang.ref.WeakReference;
++// -- GODOT end --
+
+
+ /**
+@@ -108,32 +111,49 @@ public class DownloaderServiceMarshaller {
+
+ private static class Stub implements IStub {
+ private IDownloaderService mItf = null;
+- final Messenger mMessenger = new Messenger(new Handler() {
++ // -- GODOT start --
++ private final MessengerHandlerServer mMsgHandler = new MessengerHandlerServer(this);
++ final Messenger mMessenger = new Messenger(mMsgHandler);
++
++ private static class MessengerHandlerServer extends Handler {
++ private final WeakReference<Stub> mDownloader;
++ public MessengerHandlerServer(Stub downloader) {
++ mDownloader = new WeakReference<>(downloader);
++ }
++
+ @Override
+ public void handleMessage(Message msg) {
+- switch (msg.what) {
+- case MSG_REQUEST_ABORT_DOWNLOAD:
+- mItf.requestAbortDownload();
+- break;
+- case MSG_REQUEST_CONTINUE_DOWNLOAD:
+- mItf.requestContinueDownload();
+- break;
+- case MSG_REQUEST_PAUSE_DOWNLOAD:
+- mItf.requestPauseDownload();
+- break;
+- case MSG_SET_DOWNLOAD_FLAGS:
+- mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
+- break;
+- case MSG_REQUEST_DOWNLOAD_STATE:
+- mItf.requestDownloadStatus();
+- break;
+- case MSG_REQUEST_CLIENT_UPDATE:
+- mItf.onClientUpdated((Messenger) msg.getData().getParcelable(
+- PARAM_MESSENGER));
+- break;
++ Stub downloader = mDownloader.get();
++ if (downloader != null) {
++ downloader.handleMessage(msg);
+ }
+ }
+- });
++ }
++
++ private void handleMessage(Message msg) {
++ switch (msg.what) {
++ case MSG_REQUEST_ABORT_DOWNLOAD:
++ mItf.requestAbortDownload();
++ break;
++ case MSG_REQUEST_CONTINUE_DOWNLOAD:
++ mItf.requestContinueDownload();
++ break;
++ case MSG_REQUEST_PAUSE_DOWNLOAD:
++ mItf.requestPauseDownload();
++ break;
++ case MSG_SET_DOWNLOAD_FLAGS:
++ mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
++ break;
++ case MSG_REQUEST_DOWNLOAD_STATE:
++ mItf.requestDownloadStatus();
++ break;
++ case MSG_REQUEST_CLIENT_UPDATE:
++ mItf.onClientUpdated((Messenger)msg.getData().getParcelable(
++ PARAM_MESSENGER));
++ break;
++ }
++ }
++ // -- GODOT end --
+
+ public Stub(IDownloaderService itf) {
+ mItf = itf;
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
+index e4b1b0f1c..36cd6aacf 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
+@@ -24,7 +24,10 @@ import android.os.StatFs;
+ import android.os.SystemClock;
+ import android.util.Log;
+
+-import com.android.vending.expansion.downloader.R;
++// -- GODOT start --
++//import com.android.vending.expansion.downloader.R;
++import com.godot.game.R;
++// -- GODOT end --
+
+ import java.io.File;
+ import java.text.SimpleDateFormat;
+@@ -146,12 +149,14 @@ public class Helpers {
+ }
+ return "";
+ }
+- return String.format("%.2f",
++ // -- GODOT start --
++ return String.format(Locale.ENGLISH, "%.2f",
+ (float) overallProgress / (1024.0f * 1024.0f))
+ + "MB /" +
+- String.format("%.2f", (float) overallTotal /
++ String.format(Locale.ENGLISH, "%.2f", (float) overallTotal /
+ (1024.0f * 1024.0f))
+ + "MB";
++ // -- GODOT end --
+ }
+
+ /**
+@@ -184,7 +189,9 @@ public class Helpers {
+ }
+
+ public static String getSpeedString(float bytesPerMillisecond) {
+- return String.format("%.2f", bytesPerMillisecond * 1000 / 1024);
++ // -- GODOT start --
++ return String.format(Locale.ENGLISH, "%.2f", bytesPerMillisecond * 1000 / 1024);
++ // -- GODOT end --
+ }
+
+ public static String getTimeRemaining(long durationInMilliseconds) {
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
+index 12edd97ab..a0e1165cc 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
+@@ -26,6 +26,10 @@ import android.net.NetworkInfo;
+ import android.telephony.TelephonyManager;
+ import android.util.Log;
+
++// -- GODOT start --
++import android.annotation.SuppressLint;
++// -- GODOT end --
++
+ /**
+ * Contains useful helper functions, typically tied to the application context.
+ */
+@@ -51,6 +55,7 @@ class SystemFacade {
+ return null;
+ }
+
++ @SuppressLint("MissingPermission")
+ NetworkInfo activeInfo = connectivity.getActiveNetworkInfo();
+ if (activeInfo == null) {
+ if (Constants.LOGVV) {
+@@ -69,6 +74,7 @@ class SystemFacade {
+ return false;
+ }
+
++ @SuppressLint("MissingPermission")
+ NetworkInfo info = connectivity.getActiveNetworkInfo();
+ boolean isMobile = (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE);
+ TelephonyManager tm = (TelephonyManager) mContext
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
+index f1536e80e..4b214b22d 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
+@@ -16,7 +16,11 @@
+
+ package com.google.android.vending.expansion.downloader.impl;
+
+-import com.android.vending.expansion.downloader.R;
++// -- GODOT start --
++//import com.android.vending.expansion.downloader.R;
++import com.godot.game.R;
++// -- GODOT end --
++
+ import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
+ import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
+ import com.google.android.vending.expansion.downloader.Helpers;
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
+index b2e0e7af0..c114b8a64 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
+@@ -146,8 +146,12 @@ public class DownloadThread {
+
+ try {
+ PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+- wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
+- wakeLock.acquire();
++ // -- GODOT start --
++ //wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
++ //wakeLock.acquire();
++ wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "org.godot.game:wakelock");
++ wakeLock.acquire(20 * 60 * 1000L /*20 minutes*/);
++ // -- GODOT end --
+
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
+diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
+index 4babe476f..8d41a7690 100644
+--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
++++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
+@@ -50,6 +50,10 @@ import android.provider.Settings.Secure;
+ import android.telephony.TelephonyManager;
+ import android.util.Log;
+
++// -- GODOT start --
++import android.annotation.SuppressLint;
++// -- GODOT end --
++
+ import java.io.File;
+
+ /**
+@@ -578,6 +582,7 @@ public abstract class DownloaderService extends CustomIntentService implements I
+ Log.w(Constants.TAG,
+ "couldn't get connectivity manager to poll network state");
+ } else {
++ @SuppressLint("MissingPermission")
+ NetworkInfo activeInfo = mConnectivityManager
+ .getActiveNetworkInfo();
+ updateNetworkState(activeInfo);
diff --git a/platform/android/java/patches/com.google.android.vending.licensing.patch b/platform/android/java/patches/com.google.android.vending.licensing.patch
new file mode 100644
index 0000000000..9f8e5b8eab
--- /dev/null
+++ b/platform/android/java/patches/com.google.android.vending.licensing.patch
@@ -0,0 +1,42 @@
+diff --git a/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java b/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
+index 7c42bfc28..feb579af0 100644
+--- a/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
++++ b/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
+@@ -45,6 +45,9 @@ public class PreferenceObfuscator {
+ public void putString(String key, String value) {
+ if (mEditor == null) {
+ mEditor = mPreferences.edit();
++ // -- GODOT start --
++ mEditor.apply();
++ // -- GODOT end --
+ }
+ String obfuscatedValue = mObfuscator.obfuscate(value, key);
+ mEditor.putString(key, obfuscatedValue);
+diff --git a/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java b/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
+index a0d2779af..a8bf65f9c 100644
+--- a/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
++++ b/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
+@@ -31,6 +31,10 @@ package com.google.android.vending.licensing.util;
+ * @version 1.3
+ */
+
++// -- GODOT start --
++import com.godot.game.BuildConfig;
++// -- GODOT end --
++
+ /**
+ * Base64 converter class. This code is not a full-blown MIME encoder;
+ * it simply converts binary data to base64 data and back.
+@@ -341,7 +345,11 @@ public class Base64 {
+ e += 4;
+ }
+
+- assert (e == outBuff.length);
++ // -- GODOT start --
++ //assert (e == outBuff.length);
++ if (BuildConfig.DEBUG && e != outBuff.length)
++ throw new RuntimeException();
++ // -- GODOT end --
+ return outBuff;
+ }
+
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/Constants.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/Constants.java
index ff1eee528f..1dcc370d83 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/Constants.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/Constants.java
@@ -18,113 +18,115 @@ package com.google.android.vending.expansion.downloader;
import java.io.File;
+
/**
* Contains the internal constants that are used in the download manager.
* As a general rule, modifying these constants should be done with care.
*/
public class Constants {
- /** Tag used for debugging/logging */
- public static final String TAG = "LVLDL";
+ /** Tag used for debugging/logging */
+ public static final String TAG = "LVLDL";
- /**
+ /**
* Expansion path where we store obb files
*/
- public static final String EXP_PATH = File.separator + "Android" + File.separator + "obb" + File.separator;
+ public static final String EXP_PATH = File.separator + "Android"
+ + File.separator + "obb" + File.separator;
- /** The intent that gets sent when the service must wake up for a retry */
- public static final String ACTION_RETRY = "android.intent.action.DOWNLOAD_WAKEUP";
+ /** The intent that gets sent when the service must wake up for a retry */
+ public static final String ACTION_RETRY = "android.intent.action.DOWNLOAD_WAKEUP";
- /** the intent that gets sent when clicking a successful download */
- public static final String ACTION_OPEN = "android.intent.action.DOWNLOAD_OPEN";
+ /** the intent that gets sent when clicking a successful download */
+ public static final String ACTION_OPEN = "android.intent.action.DOWNLOAD_OPEN";
- /** the intent that gets sent when clicking an incomplete/failed download */
- public static final String ACTION_LIST = "android.intent.action.DOWNLOAD_LIST";
+ /** the intent that gets sent when clicking an incomplete/failed download */
+ public static final String ACTION_LIST = "android.intent.action.DOWNLOAD_LIST";
- /** the intent that gets sent when deleting the notification of a completed download */
- public static final String ACTION_HIDE = "android.intent.action.DOWNLOAD_HIDE";
+ /** the intent that gets sent when deleting the notification of a completed download */
+ public static final String ACTION_HIDE = "android.intent.action.DOWNLOAD_HIDE";
- /**
+ /**
* When a number has to be appended to the filename, this string is used to separate the
* base filename from the sequence number
*/
- public static final String FILENAME_SEQUENCE_SEPARATOR = "-";
+ public static final String FILENAME_SEQUENCE_SEPARATOR = "-";
- /** The default user agent used for downloads */
- public static final String DEFAULT_USER_AGENT = "Android.LVLDM";
+ /** The default user agent used for downloads */
+ public static final String DEFAULT_USER_AGENT = "Android.LVLDM";
- /** The buffer size used to stream the data */
- public static final int BUFFER_SIZE = 4096;
+ /** The buffer size used to stream the data */
+ public static final int BUFFER_SIZE = 4096;
- /** The minimum amount of progress that has to be done before the progress bar gets updated */
- public static final int MIN_PROGRESS_STEP = 4096;
+ /** The minimum amount of progress that has to be done before the progress bar gets updated */
+ public static final int MIN_PROGRESS_STEP = 4096;
- /** The minimum amount of time that has to elapse before the progress bar gets updated, in ms */
- public static final long MIN_PROGRESS_TIME = 1000;
+ /** The minimum amount of time that has to elapse before the progress bar gets updated, in ms */
+ public static final long MIN_PROGRESS_TIME = 1000;
- /** The maximum number of rows in the database (FIFO) */
- public static final int MAX_DOWNLOADS = 1000;
+ /** The maximum number of rows in the database (FIFO) */
+ public static final int MAX_DOWNLOADS = 1000;
- /**
+ /**
* The number of times that the download manager will retry its network
* operations when no progress is happening before it gives up.
*/
- public static final int MAX_RETRIES = 5;
+ public static final int MAX_RETRIES = 5;
- /**
+ /**
* The minimum amount of time that the download manager accepts for
* a Retry-After response header with a parameter in delta-seconds.
*/
- public static final int MIN_RETRY_AFTER = 30; // 30s
+ public static final int MIN_RETRY_AFTER = 30; // 30s
- /**
+ /**
* The maximum amount of time that the download manager accepts for
* a Retry-After response header with a parameter in delta-seconds.
*/
- public static final int MAX_RETRY_AFTER = 24 * 60 * 60; // 24h
+ public static final int MAX_RETRY_AFTER = 24 * 60 * 60; // 24h
- /**
+ /**
* The maximum number of redirects.
*/
- public static final int MAX_REDIRECTS = 5; // can't be more than 7.
+ public static final int MAX_REDIRECTS = 5; // can't be more than 7.
- /**
+ /**
* The time between a failure and the first retry after an IOException.
* Each subsequent retry grows exponentially, doubling each time.
* The time is in seconds.
*/
- public static final int RETRY_FIRST_DELAY = 30;
+ public static final int RETRY_FIRST_DELAY = 30;
- /** Enable separate connectivity logging */
- public static final boolean LOGX = true;
+ /** Enable separate connectivity logging */
+ public static final boolean LOGX = true;
- /** Enable verbose logging */
- public static final boolean LOGV = false;
+ /** Enable verbose logging */
+ public static final boolean LOGV = false;
- /** Enable super-verbose logging */
- private static final boolean LOCAL_LOGVV = false;
- public static final boolean LOGVV = LOCAL_LOGVV && LOGV;
+ /** Enable super-verbose logging */
+ private static final boolean LOCAL_LOGVV = false;
+ public static final boolean LOGVV = LOCAL_LOGVV && LOGV;
- /**
+ /**
* This download has successfully completed.
* Warning: there might be other status values that indicate success
* in the future.
* Use isSucccess() to capture the entire category.
*/
- public static final int STATUS_SUCCESS = 200;
+ public static final int STATUS_SUCCESS = 200;
- /**
+ /**
* This request couldn't be parsed. This is also used when processing
* requests with unknown/unsupported URI schemes.
*/
- public static final int STATUS_BAD_REQUEST = 400;
+ public static final int STATUS_BAD_REQUEST = 400;
- /**
+ /**
* This download can't be performed because the content type cannot be
* handled.
*/
- public static final int STATUS_NOT_ACCEPTABLE = 406;
+ public static final int STATUS_NOT_ACCEPTABLE = 406;
- /**
+ /**
* This download cannot be performed because the length cannot be
* determined accurately. This is the code for the HTTP error "Length
* Required", which is typically used when making requests that require
@@ -133,101 +135,102 @@ public class Constants {
* accurately (therefore making it impossible to know when a download
* completes).
*/
- public static final int STATUS_LENGTH_REQUIRED = 411;
+ public static final int STATUS_LENGTH_REQUIRED = 411;
- /**
+ /**
* This download was interrupted and cannot be resumed.
* This is the code for the HTTP error "Precondition Failed", and it is
* also used in situations where the client doesn't have an ETag at all.
*/
- public static final int STATUS_PRECONDITION_FAILED = 412;
+ public static final int STATUS_PRECONDITION_FAILED = 412;
- /**
+ /**
* The lowest-valued error status that is not an actual HTTP status code.
*/
- public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488;
+ public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488;
- /**
+ /**
* The requested destination file already exists.
*/
- public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
+ public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
- /**
+ /**
* Some possibly transient error occurred, but we can't resume the download.
*/
- public static final int STATUS_CANNOT_RESUME = 489;
+ public static final int STATUS_CANNOT_RESUME = 489;
- /**
+ /**
* This download was canceled
*/
- public static final int STATUS_CANCELED = 490;
+ public static final int STATUS_CANCELED = 490;
- /**
+ /**
* This download has completed with an error.
* Warning: there will be other status values that indicate errors in
* the future. Use isStatusError() to capture the entire category.
*/
- public static final int STATUS_UNKNOWN_ERROR = 491;
+ public static final int STATUS_UNKNOWN_ERROR = 491;
- /**
+ /**
* This download couldn't be completed because of a storage issue.
* Typically, that's because the filesystem is missing or full.
* Use the more specific {@link #STATUS_INSUFFICIENT_SPACE_ERROR}
* and {@link #STATUS_DEVICE_NOT_FOUND_ERROR} when appropriate.
*/
- public static final int STATUS_FILE_ERROR = 492;
+ public static final int STATUS_FILE_ERROR = 492;
- /**
+ /**
* This download couldn't be completed because of an HTTP
* redirect response that the download manager couldn't
* handle.
*/
- public static final int STATUS_UNHANDLED_REDIRECT = 493;
+ public static final int STATUS_UNHANDLED_REDIRECT = 493;
- /**
+ /**
* This download couldn't be completed because of an
* unspecified unhandled HTTP code.
*/
- public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
+ public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
- /**
+ /**
* This download couldn't be completed because of an
* error receiving or processing data at the HTTP level.
*/
- public static final int STATUS_HTTP_DATA_ERROR = 495;
+ public static final int STATUS_HTTP_DATA_ERROR = 495;
- /**
+ /**
* This download couldn't be completed because of an
* HttpException while setting up the request.
*/
- public static final int STATUS_HTTP_EXCEPTION = 496;
+ public static final int STATUS_HTTP_EXCEPTION = 496;
- /**
+ /**
* This download couldn't be completed because there were
* too many redirects.
*/
- public static final int STATUS_TOO_MANY_REDIRECTS = 497;
+ public static final int STATUS_TOO_MANY_REDIRECTS = 497;
- /**
+ /**
* This download couldn't be completed due to insufficient storage
* space. Typically, this is because the SD card is full.
*/
- public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498;
+ public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498;
- /**
+ /**
* This download couldn't be completed because no external storage
* device was found. Typically, this is because the SD card is not
* mounted.
*/
- public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499;
+ public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499;
- /**
+ /**
* The wake duration to check to see if a download is possible.
*/
- public static final long WATCHDOG_WAKE_TIMER = 60 * 1000;
+ public static final long WATCHDOG_WAKE_TIMER = 60*1000;
- /**
+ /**
* The wake duration to check to see if the process was killed.
*/
- public static final long ACTIVE_THREAD_WATCHDOG = 5 * 1000;
+ public static final long ACTIVE_THREAD_WATCHDOG = 5*1000;
+
} \ No newline at end of file
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloadProgressInfo.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloadProgressInfo.java
index 9a78a6d3df..9cb294d721 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloadProgressInfo.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloadProgressInfo.java
@@ -19,6 +19,7 @@ package com.google.android.vending.expansion.downloader;
import android.os.Parcel;
import android.os.Parcelable;
+
/**
* This class contains progress information about the active download(s).
*
@@ -30,49 +31,50 @@ import android.os.Parcelable;
* as the progress so far, time remaining and current speed.
*/
public class DownloadProgressInfo implements Parcelable {
- public long mOverallTotal;
- public long mOverallProgress;
- public long mTimeRemaining; // time remaining
- public float mCurrentSpeed; // speed in KB/S
+ public long mOverallTotal;
+ public long mOverallProgress;
+ public long mTimeRemaining; // time remaining
+ public float mCurrentSpeed; // speed in KB/S
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
- @Override
- public int describeContents() {
- return 0;
- }
+ @Override
+ public void writeToParcel(Parcel p, int i) {
+ p.writeLong(mOverallTotal);
+ p.writeLong(mOverallProgress);
+ p.writeLong(mTimeRemaining);
+ p.writeFloat(mCurrentSpeed);
+ }
- @Override
- public void writeToParcel(Parcel p, int i) {
- p.writeLong(mOverallTotal);
- p.writeLong(mOverallProgress);
- p.writeLong(mTimeRemaining);
- p.writeFloat(mCurrentSpeed);
- }
+ public DownloadProgressInfo(Parcel p) {
+ mOverallTotal = p.readLong();
+ mOverallProgress = p.readLong();
+ mTimeRemaining = p.readLong();
+ mCurrentSpeed = p.readFloat();
+ }
- public DownloadProgressInfo(Parcel p) {
- mOverallTotal = p.readLong();
- mOverallProgress = p.readLong();
- mTimeRemaining = p.readLong();
- mCurrentSpeed = p.readFloat();
- }
+ public DownloadProgressInfo(long overallTotal, long overallProgress,
+ long timeRemaining,
+ float currentSpeed) {
+ this.mOverallTotal = overallTotal;
+ this.mOverallProgress = overallProgress;
+ this.mTimeRemaining = timeRemaining;
+ this.mCurrentSpeed = currentSpeed;
+ }
- public DownloadProgressInfo(long overallTotal, long overallProgress,
- long timeRemaining,
- float currentSpeed) {
- this.mOverallTotal = overallTotal;
- this.mOverallProgress = overallProgress;
- this.mTimeRemaining = timeRemaining;
- this.mCurrentSpeed = currentSpeed;
- }
+ public static final Creator<DownloadProgressInfo> CREATOR = new Creator<DownloadProgressInfo>() {
+ @Override
+ public DownloadProgressInfo createFromParcel(Parcel parcel) {
+ return new DownloadProgressInfo(parcel);
+ }
- public static final Creator<DownloadProgressInfo> CREATOR = new Creator<DownloadProgressInfo>() {
- @Override
- public DownloadProgressInfo createFromParcel(Parcel parcel) {
- return new DownloadProgressInfo(parcel);
- }
+ @Override
+ public DownloadProgressInfo[] newArray(int i) {
+ return new DownloadProgressInfo[i];
+ }
+ };
- @Override
- public DownloadProgressInfo[] newArray(int i) {
- return new DownloadProgressInfo[i];
- }
- };
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
index 146426ef83..452c7d1483 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderClientMarshaller.java
@@ -32,7 +32,10 @@ import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
+// -- GODOT start --
import java.lang.ref.WeakReference;
+// -- GODOT end --
+
/**
* This class binds the service API to your application client. It contains the IDownloaderClient proxy,
@@ -58,172 +61,175 @@ import java.lang.ref.WeakReference;
* interface.
*/
public class DownloaderClientMarshaller {
- public static final int MSG_ONDOWNLOADSTATE_CHANGED = 10;
- public static final int MSG_ONDOWNLOADPROGRESS = 11;
- public static final int MSG_ONSERVICECONNECTED = 12;
+ public static final int MSG_ONDOWNLOADSTATE_CHANGED = 10;
+ public static final int MSG_ONDOWNLOADPROGRESS = 11;
+ public static final int MSG_ONSERVICECONNECTED = 12;
- public static final String PARAM_NEW_STATE = "newState";
- public static final String PARAM_PROGRESS = "progress";
- public static final String PARAM_MESSENGER = DownloaderService.EXTRA_MESSAGE_HANDLER;
+ public static final String PARAM_NEW_STATE = "newState";
+ public static final String PARAM_PROGRESS = "progress";
+ public static final String PARAM_MESSENGER = DownloaderService.EXTRA_MESSAGE_HANDLER;
- public static final int NO_DOWNLOAD_REQUIRED = DownloaderService.NO_DOWNLOAD_REQUIRED;
- public static final int LVL_CHECK_REQUIRED = DownloaderService.LVL_CHECK_REQUIRED;
- public static final int DOWNLOAD_REQUIRED = DownloaderService.DOWNLOAD_REQUIRED;
+ public static final int NO_DOWNLOAD_REQUIRED = DownloaderService.NO_DOWNLOAD_REQUIRED;
+ public static final int LVL_CHECK_REQUIRED = DownloaderService.LVL_CHECK_REQUIRED;
+ public static final int DOWNLOAD_REQUIRED = DownloaderService.DOWNLOAD_REQUIRED;
- private static class Proxy implements IDownloaderClient {
- private Messenger mServiceMessenger;
+ private static class Proxy implements IDownloaderClient {
+ private Messenger mServiceMessenger;
- @Override
- public void onDownloadStateChanged(int newState) {
- Bundle params = new Bundle(1);
- params.putInt(PARAM_NEW_STATE, newState);
- send(MSG_ONDOWNLOADSTATE_CHANGED, params);
- }
+ @Override
+ public void onDownloadStateChanged(int newState) {
+ Bundle params = new Bundle(1);
+ params.putInt(PARAM_NEW_STATE, newState);
+ send(MSG_ONDOWNLOADSTATE_CHANGED, params);
+ }
- @Override
- public void onDownloadProgress(DownloadProgressInfo progress) {
- Bundle params = new Bundle(1);
- params.putParcelable(PARAM_PROGRESS, progress);
- send(MSG_ONDOWNLOADPROGRESS, params);
- }
+ @Override
+ public void onDownloadProgress(DownloadProgressInfo progress) {
+ Bundle params = new Bundle(1);
+ params.putParcelable(PARAM_PROGRESS, progress);
+ send(MSG_ONDOWNLOADPROGRESS, params);
+ }
- private void send(int method, Bundle params) {
- Message m = Message.obtain(null, method);
- m.setData(params);
- try {
- mServiceMessenger.send(m);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
+ private void send(int method, Bundle params) {
+ Message m = Message.obtain(null, method);
+ m.setData(params);
+ try {
+ mServiceMessenger.send(m);
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ }
+ }
- public Proxy(Messenger msg) {
- mServiceMessenger = msg;
- }
+ public Proxy(Messenger msg) {
+ mServiceMessenger = msg;
+ }
- @Override
- public void onServiceConnected(Messenger m) {
- /**
+ @Override
+ public void onServiceConnected(Messenger m) {
+ /**
* This is never called through the proxy.
*/
- }
- }
+ }
+ }
- private static class Stub implements IStub {
- private IDownloaderClient mItf = null;
- private Class<?> mDownloaderServiceClass;
- private boolean mBound;
- private Messenger mServiceMessenger;
- private Context mContext;
- /**
+ private static class Stub implements IStub {
+ private IDownloaderClient mItf = null;
+ private Class<?> mDownloaderServiceClass;
+ private boolean mBound;
+ private Messenger mServiceMessenger;
+ private Context mContext;
+ /**
* Target we publish for clients to send messages to IncomingHandler.
*/
- private final MessengerHandlerClient mMsgHandler = new MessengerHandlerClient(this);
- final Messenger mMessenger = new Messenger(mMsgHandler);
+ // -- GODOT start --
+ private final MessengerHandlerClient mMsgHandler = new MessengerHandlerClient(this);
+ final Messenger mMessenger = new Messenger(mMsgHandler);
- private static class MessengerHandlerClient extends Handler {
- private final WeakReference<Stub> mDownloader;
- public MessengerHandlerClient(Stub downloader) {
- mDownloader = new WeakReference<>(downloader);
- }
+ private static class MessengerHandlerClient extends Handler {
+ private final WeakReference<Stub> mDownloader;
+ public MessengerHandlerClient(Stub downloader) {
+ mDownloader = new WeakReference<>(downloader);
+ }
- @Override
- public void handleMessage(Message msg) {
- Stub downloader = mDownloader.get();
- if (downloader != null) {
- downloader.handleMessage(msg);
- }
- }
- }
+ @Override
+ public void handleMessage(Message msg) {
+ Stub downloader = mDownloader.get();
+ if (downloader != null) {
+ downloader.handleMessage(msg);
+ }
+ }
+ }
- private void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_ONDOWNLOADPROGRESS:
- Bundle bun = msg.getData();
- if (null != mContext) {
- bun.setClassLoader(mContext.getClassLoader());
- DownloadProgressInfo dpi = (DownloadProgressInfo)msg.getData()
- .getParcelable(PARAM_PROGRESS);
- mItf.onDownloadProgress(dpi);
- }
- break;
- case MSG_ONDOWNLOADSTATE_CHANGED:
- mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
- break;
- case MSG_ONSERVICECONNECTED:
- mItf.onServiceConnected(
- (Messenger)msg.getData().getParcelable(PARAM_MESSENGER));
- break;
- }
- }
+ private void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_ONDOWNLOADPROGRESS:
+ Bundle bun = msg.getData();
+ if (null != mContext) {
+ bun.setClassLoader(mContext.getClassLoader());
+ DownloadProgressInfo dpi = (DownloadProgressInfo)msg.getData()
+ .getParcelable(PARAM_PROGRESS);
+ mItf.onDownloadProgress(dpi);
+ }
+ break;
+ case MSG_ONDOWNLOADSTATE_CHANGED:
+ mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
+ break;
+ case MSG_ONSERVICECONNECTED:
+ mItf.onServiceConnected(
+ (Messenger)msg.getData().getParcelable(PARAM_MESSENGER));
+ break;
+ }
+ }
+ // -- GODOT end --
- public Stub(IDownloaderClient itf, Class<?> downloaderService) {
- mItf = itf;
- mDownloaderServiceClass = downloaderService;
- }
+ public Stub(IDownloaderClient itf, Class<?> downloaderService) {
+ mItf = itf;
+ mDownloaderServiceClass = downloaderService;
+ }
- /**
+ /**
* Class for interacting with the main interface of the service.
*/
- private ServiceConnection mConnection = new ServiceConnection() {
- public void onServiceConnected(ComponentName className, IBinder service) {
- // This is called when the connection with the service has been
- // established, giving us the object we can use to
- // interact with the service. We are communicating with the
- // service using a Messenger, so here we get a client-side
- // representation of that from the raw IBinder object.
- mServiceMessenger = new Messenger(service);
- mItf.onServiceConnected(
- mServiceMessenger);
- }
+ private ServiceConnection mConnection = new ServiceConnection() {
+ public void onServiceConnected(ComponentName className, IBinder service) {
+ // This is called when the connection with the service has been
+ // established, giving us the object we can use to
+ // interact with the service. We are communicating with the
+ // service using a Messenger, so here we get a client-side
+ // representation of that from the raw IBinder object.
+ mServiceMessenger = new Messenger(service);
+ mItf.onServiceConnected(
+ mServiceMessenger);
+ }
+
+ public void onServiceDisconnected(ComponentName className) {
+ // This is called when the connection with the service has been
+ // unexpectedly disconnected -- that is, its process crashed.
+ mServiceMessenger = null;
+ }
+ };
- public void onServiceDisconnected(ComponentName className) {
- // This is called when the connection with the service has been
- // unexpectedly disconnected -- that is, its process crashed.
- mServiceMessenger = null;
- }
- };
+ @Override
+ public void connect(Context c) {
+ mContext = c;
+ Intent bindIntent = new Intent(c, mDownloaderServiceClass);
+ bindIntent.putExtra(PARAM_MESSENGER, mMessenger);
+ if ( !c.bindService(bindIntent, mConnection, Context.BIND_DEBUG_UNBIND) ) {
+ if ( Constants.LOGVV ) {
+ Log.d(Constants.TAG, "Service Unbound");
+ }
+ } else {
+ mBound = true;
+ }
- @Override
- public void connect(Context c) {
- mContext = c;
- Intent bindIntent = new Intent(c, mDownloaderServiceClass);
- bindIntent.putExtra(PARAM_MESSENGER, mMessenger);
- if (!c.bindService(bindIntent, mConnection, Context.BIND_DEBUG_UNBIND)) {
- if (Constants.LOGVV) {
- Log.d(Constants.TAG, "Service Unbound");
- }
- } else {
- mBound = true;
- }
- }
+ }
- @Override
- public void disconnect(Context c) {
- if (mBound) {
- c.unbindService(mConnection);
- mBound = false;
- }
- mContext = null;
- }
+ @Override
+ public void disconnect(Context c) {
+ if (mBound) {
+ c.unbindService(mConnection);
+ mBound = false;
+ }
+ mContext = null;
+ }
- @Override
- public Messenger getMessenger() {
- return mMessenger;
- }
- }
+ @Override
+ public Messenger getMessenger() {
+ return mMessenger;
+ }
+ }
- /**
+ /**
* Returns a proxy that will marshal calls to IDownloaderClient methods
*
* @param msg
* @return
*/
- public static IDownloaderClient CreateProxy(Messenger msg) {
- return new Proxy(msg);
- }
+ public static IDownloaderClient CreateProxy(Messenger msg) {
+ return new Proxy(msg);
+ }
- /**
+ /**
* Returns a stub object that, when connected, will listen for marshaled
* {@link IDownloaderClient} methods and translate them into calls to the supplied
* interface.
@@ -235,11 +241,11 @@ public class DownloaderClientMarshaller {
* @return The {@link IStub} that allows you to connect to the service such that
* your {@link IDownloaderClient} receives status updates.
*/
- public static IStub CreateStub(IDownloaderClient itf, Class<?> downloaderService) {
- return new Stub(itf, downloaderService);
- }
+ public static IStub CreateStub(IDownloaderClient itf, Class<?> downloaderService) {
+ return new Stub(itf, downloaderService);
+ }
- /**
+ /**
* Starts the download if necessary. This function starts a flow that does `
* many things. 1) Checks to see if the APK version has been checked and
* the metadata database updated 2) If the APK version does not match,
@@ -262,14 +268,14 @@ public class DownloaderClientMarshaller {
* #DOWNLOAD_REQUIRED}.
* @throws NameNotFoundException
*/
- public static int startDownloadServiceIfRequired(Context context, PendingIntent notificationClient,
- Class<?> serviceClass)
- throws NameNotFoundException {
- return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
- serviceClass);
- }
+ public static int startDownloadServiceIfRequired(Context context, PendingIntent notificationClient,
+ Class<?> serviceClass)
+ throws NameNotFoundException {
+ return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
+ serviceClass);
+ }
- /**
+ /**
* This version assumes that the intent contains the pending intent as a parameter. This
* is used for responding to alarms.
* <p>The pending intent must be in an extra with the key {@link
@@ -281,10 +287,11 @@ public class DownloaderClientMarshaller {
* @return
* @throws NameNotFoundException
*/
- public static int startDownloadServiceIfRequired(Context context, Intent notificationClient,
- Class<?> serviceClass)
- throws NameNotFoundException {
- return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
- serviceClass);
- }
+ public static int startDownloadServiceIfRequired(Context context, Intent notificationClient,
+ Class<?> serviceClass)
+ throws NameNotFoundException {
+ return DownloaderService.startDownloadServiceIfRequired(context, notificationClient,
+ serviceClass);
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
index f75debe32d..3771d19c9b 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/DownloaderServiceMarshaller.java
@@ -25,7 +25,10 @@ import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
+// -- GODOT start --
import java.lang.ref.WeakReference;
+// -- GODOT end --
+
/**
* This class is used by the client activity to proxy requests to the Downloader
@@ -38,147 +41,151 @@ import java.lang.ref.WeakReference;
*/
public class DownloaderServiceMarshaller {
- public static final int MSG_REQUEST_ABORT_DOWNLOAD =
- 1;
- public static final int MSG_REQUEST_PAUSE_DOWNLOAD =
- 2;
- public static final int MSG_SET_DOWNLOAD_FLAGS =
- 3;
- public static final int MSG_REQUEST_CONTINUE_DOWNLOAD =
- 4;
- public static final int MSG_REQUEST_DOWNLOAD_STATE =
- 5;
- public static final int MSG_REQUEST_CLIENT_UPDATE =
- 6;
-
- public static final String PARAMS_FLAGS = "flags";
- public static final String PARAM_MESSENGER = DownloaderService.EXTRA_MESSAGE_HANDLER;
-
- private static class Proxy implements IDownloaderService {
- private Messenger mMsg;
-
- private void send(int method, Bundle params) {
- Message m = Message.obtain(null, method);
- m.setData(params);
- try {
- mMsg.send(m);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
-
- public Proxy(Messenger msg) {
- mMsg = msg;
- }
-
- @Override
- public void requestAbortDownload() {
- send(MSG_REQUEST_ABORT_DOWNLOAD, new Bundle());
- }
-
- @Override
- public void requestPauseDownload() {
- send(MSG_REQUEST_PAUSE_DOWNLOAD, new Bundle());
- }
-
- @Override
- public void setDownloadFlags(int flags) {
- Bundle params = new Bundle();
- params.putInt(PARAMS_FLAGS, flags);
- send(MSG_SET_DOWNLOAD_FLAGS, params);
- }
-
- @Override
- public void requestContinueDownload() {
- send(MSG_REQUEST_CONTINUE_DOWNLOAD, new Bundle());
- }
-
- @Override
- public void requestDownloadStatus() {
- send(MSG_REQUEST_DOWNLOAD_STATE, new Bundle());
- }
-
- @Override
- public void onClientUpdated(Messenger clientMessenger) {
- Bundle bundle = new Bundle(1);
- bundle.putParcelable(PARAM_MESSENGER, clientMessenger);
- send(MSG_REQUEST_CLIENT_UPDATE, bundle);
- }
- }
-
- private static class Stub implements IStub {
- private IDownloaderService mItf = null;
- private final MessengerHandlerServer mMsgHandler = new MessengerHandlerServer(this);
- final Messenger mMessenger = new Messenger(mMsgHandler);
-
- private static class MessengerHandlerServer extends Handler {
- private final WeakReference<Stub> mDownloader;
- public MessengerHandlerServer(Stub downloader) {
- mDownloader = new WeakReference<>(downloader);
- }
-
- @Override
- public void handleMessage(Message msg) {
- Stub downloader = mDownloader.get();
- if (downloader != null) {
- downloader.handleMessage(msg);
- }
- }
- }
-
- private void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_REQUEST_ABORT_DOWNLOAD:
- mItf.requestAbortDownload();
- break;
- case MSG_REQUEST_CONTINUE_DOWNLOAD:
- mItf.requestContinueDownload();
- break;
- case MSG_REQUEST_PAUSE_DOWNLOAD:
- mItf.requestPauseDownload();
- break;
- case MSG_SET_DOWNLOAD_FLAGS:
- mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
- break;
- case MSG_REQUEST_DOWNLOAD_STATE:
- mItf.requestDownloadStatus();
- break;
- case MSG_REQUEST_CLIENT_UPDATE:
- mItf.onClientUpdated((Messenger)msg.getData().getParcelable(
- PARAM_MESSENGER));
- break;
- }
- }
-
- public Stub(IDownloaderService itf) {
- mItf = itf;
- }
-
- @Override
- public Messenger getMessenger() {
- return mMessenger;
- }
-
- @Override
- public void connect(Context c) {
- }
-
- @Override
- public void disconnect(Context c) {
- }
- }
-
- /**
+ public static final int MSG_REQUEST_ABORT_DOWNLOAD =
+ 1;
+ public static final int MSG_REQUEST_PAUSE_DOWNLOAD =
+ 2;
+ public static final int MSG_SET_DOWNLOAD_FLAGS =
+ 3;
+ public static final int MSG_REQUEST_CONTINUE_DOWNLOAD =
+ 4;
+ public static final int MSG_REQUEST_DOWNLOAD_STATE =
+ 5;
+ public static final int MSG_REQUEST_CLIENT_UPDATE =
+ 6;
+
+ public static final String PARAMS_FLAGS = "flags";
+ public static final String PARAM_MESSENGER = DownloaderService.EXTRA_MESSAGE_HANDLER;
+
+ private static class Proxy implements IDownloaderService {
+ private Messenger mMsg;
+
+ private void send(int method, Bundle params) {
+ Message m = Message.obtain(null, method);
+ m.setData(params);
+ try {
+ mMsg.send(m);
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public Proxy(Messenger msg) {
+ mMsg = msg;
+ }
+
+ @Override
+ public void requestAbortDownload() {
+ send(MSG_REQUEST_ABORT_DOWNLOAD, new Bundle());
+ }
+
+ @Override
+ public void requestPauseDownload() {
+ send(MSG_REQUEST_PAUSE_DOWNLOAD, new Bundle());
+ }
+
+ @Override
+ public void setDownloadFlags(int flags) {
+ Bundle params = new Bundle();
+ params.putInt(PARAMS_FLAGS, flags);
+ send(MSG_SET_DOWNLOAD_FLAGS, params);
+ }
+
+ @Override
+ public void requestContinueDownload() {
+ send(MSG_REQUEST_CONTINUE_DOWNLOAD, new Bundle());
+ }
+
+ @Override
+ public void requestDownloadStatus() {
+ send(MSG_REQUEST_DOWNLOAD_STATE, new Bundle());
+ }
+
+ @Override
+ public void onClientUpdated(Messenger clientMessenger) {
+ Bundle bundle = new Bundle(1);
+ bundle.putParcelable(PARAM_MESSENGER, clientMessenger);
+ send(MSG_REQUEST_CLIENT_UPDATE, bundle);
+ }
+ }
+
+ private static class Stub implements IStub {
+ private IDownloaderService mItf = null;
+ // -- GODOT start --
+ private final MessengerHandlerServer mMsgHandler = new MessengerHandlerServer(this);
+ final Messenger mMessenger = new Messenger(mMsgHandler);
+
+ private static class MessengerHandlerServer extends Handler {
+ private final WeakReference<Stub> mDownloader;
+ public MessengerHandlerServer(Stub downloader) {
+ mDownloader = new WeakReference<>(downloader);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ Stub downloader = mDownloader.get();
+ if (downloader != null) {
+ downloader.handleMessage(msg);
+ }
+ }
+ }
+
+ private void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_REQUEST_ABORT_DOWNLOAD:
+ mItf.requestAbortDownload();
+ break;
+ case MSG_REQUEST_CONTINUE_DOWNLOAD:
+ mItf.requestContinueDownload();
+ break;
+ case MSG_REQUEST_PAUSE_DOWNLOAD:
+ mItf.requestPauseDownload();
+ break;
+ case MSG_SET_DOWNLOAD_FLAGS:
+ mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
+ break;
+ case MSG_REQUEST_DOWNLOAD_STATE:
+ mItf.requestDownloadStatus();
+ break;
+ case MSG_REQUEST_CLIENT_UPDATE:
+ mItf.onClientUpdated((Messenger)msg.getData().getParcelable(
+ PARAM_MESSENGER));
+ break;
+ }
+ }
+ // -- GODOT end --
+
+ public Stub(IDownloaderService itf) {
+ mItf = itf;
+ }
+
+ @Override
+ public Messenger getMessenger() {
+ return mMessenger;
+ }
+
+ @Override
+ public void connect(Context c) {
+
+ }
+
+ @Override
+ public void disconnect(Context c) {
+
+ }
+ }
+
+ /**
* Returns a proxy that will marshall calls to IDownloaderService methods
*
* @param ctx
* @return
*/
- public static IDownloaderService CreateProxy(Messenger msg) {
- return new Proxy(msg);
- }
+ public static IDownloaderService CreateProxy(Messenger msg) {
+ return new Proxy(msg);
+ }
- /**
+ /**
* Returns a stub object that, when connected, will listen for marshalled
* IDownloaderService methods and translate them into calls to the supplied
* interface.
@@ -187,7 +194,8 @@ public class DownloaderServiceMarshaller {
* when remote method calls are unmarshalled.
* @return
*/
- public static IStub CreateStub(IDownloaderService itf) {
- return new Stub(itf);
- }
+ public static IStub CreateStub(IDownloaderService itf) {
+ return new Stub(itf);
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
index cd8726533f..36cd6aacfe 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/Helpers.java
@@ -24,7 +24,10 @@ import android.os.StatFs;
import android.os.SystemClock;
import android.util.Log;
+// -- GODOT start --
+//import com.android.vending.expansion.downloader.R;
import com.godot.game.R;
+// -- GODOT end --
import java.io.File;
import java.text.SimpleDateFormat;
@@ -40,95 +43,96 @@ import java.util.regex.Pattern;
*/
public class Helpers {
- public static Random sRandom = new Random(SystemClock.uptimeMillis());
+ public static Random sRandom = new Random(SystemClock.uptimeMillis());
- /** Regex used to parse content-disposition headers */
- private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern
- .compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");
+ /** Regex used to parse content-disposition headers */
+ private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern
+ .compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");
- private Helpers() {
- }
+ private Helpers() {
+ }
- /*
+ /*
* Parse the Content-Disposition HTTP Header. The format of the header is defined here:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html This header provides a filename for
* content that is going to be downloaded to the file system. We only support the attachment
* type.
*/
- static String parseContentDisposition(String contentDisposition) {
- try {
- Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
- if (m.find()) {
- return m.group(1);
- }
- } catch (IllegalStateException ex) {
- // This function is defined as returning null when it can't parse
- // the header
- }
- return null;
- }
+ static String parseContentDisposition(String contentDisposition) {
+ try {
+ Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
+ if (m.find()) {
+ return m.group(1);
+ }
+ } catch (IllegalStateException ex) {
+ // This function is defined as returning null when it can't parse
+ // the header
+ }
+ return null;
+ }
- /**
+ /**
* @return the root of the filesystem containing the given path
*/
- public static File getFilesystemRoot(String path) {
- File cache = Environment.getDownloadCacheDirectory();
- if (path.startsWith(cache.getPath())) {
- return cache;
- }
- File external = Environment.getExternalStorageDirectory();
- if (path.startsWith(external.getPath())) {
- return external;
- }
- throw new IllegalArgumentException(
- "Cannot determine filesystem root for " + path);
- }
+ public static File getFilesystemRoot(String path) {
+ File cache = Environment.getDownloadCacheDirectory();
+ if (path.startsWith(cache.getPath())) {
+ return cache;
+ }
+ File external = Environment.getExternalStorageDirectory();
+ if (path.startsWith(external.getPath())) {
+ return external;
+ }
+ throw new IllegalArgumentException(
+ "Cannot determine filesystem root for " + path);
+ }
- public static boolean isExternalMediaMounted() {
- if (!Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED)) {
- // No SD card found.
- if (Constants.LOGVV) {
- Log.d(Constants.TAG, "no external storage");
- }
- return false;
- }
- return true;
- }
+ public static boolean isExternalMediaMounted() {
+ if (!Environment.getExternalStorageState().equals(
+ Environment.MEDIA_MOUNTED)) {
+ // No SD card found.
+ if (Constants.LOGVV) {
+ Log.d(Constants.TAG, "no external storage");
+ }
+ return false;
+ }
+ return true;
+ }
- /**
+ /**
* @return the number of bytes available on the filesystem rooted at the given File
*/
- public static long getAvailableBytes(File root) {
- StatFs stat = new StatFs(root.getPath());
- // put a bit of margin (in case creating the file grows the system by a
- // few blocks)
- long availableBlocks = (long)stat.getAvailableBlocks() - 4;
- return stat.getBlockSize() * availableBlocks;
- }
+ public static long getAvailableBytes(File root) {
+ StatFs stat = new StatFs(root.getPath());
+ // put a bit of margin (in case creating the file grows the system by a
+ // few blocks)
+ long availableBlocks = (long) stat.getAvailableBlocks() - 4;
+ return stat.getBlockSize() * availableBlocks;
+ }
- /**
+ /**
* Checks whether the filename looks legitimate
*/
- public static boolean isFilenameValid(String filename) {
- filename = filename.replaceFirst("/+", "/"); // normalize leading
- // slashes
- return filename.startsWith(Environment.getDownloadCacheDirectory().toString()) || filename.startsWith(Environment.getExternalStorageDirectory().toString());
- }
+ public static boolean isFilenameValid(String filename) {
+ filename = filename.replaceFirst("/+", "/"); // normalize leading
+ // slashes
+ return filename.startsWith(Environment.getDownloadCacheDirectory().toString())
+ || filename.startsWith(Environment.getExternalStorageDirectory().toString());
+ }
- /*
+ /*
* Delete the given file from device
*/
- /* package */ static void deleteFile(String path) {
- try {
- File file = new File(path);
- file.delete();
- } catch (Exception e) {
- Log.w(Constants.TAG, "file: '" + path + "' couldn't be deleted", e);
- }
- }
+ /* package */static void deleteFile(String path) {
+ try {
+ File file = new File(path);
+ file.delete();
+ } catch (Exception e) {
+ Log.w(Constants.TAG, "file: '" + path + "' couldn't be deleted", e);
+ }
+ }
- /**
+ /**
* Showing progress in MB here. It would be nice to choose the unit (KB, MB, GB) based on total
* file size, but given what we know about the expected ranges of file sizes for APK expansion
* files, it's probably not necessary.
@@ -138,63 +142,69 @@ public class Helpers {
* @return
*/
- static public String getDownloadProgressString(long overallProgress, long overallTotal) {
- if (overallTotal == 0) {
- if (Constants.LOGVV) {
- Log.e(Constants.TAG, "Notification called when total is zero");
- }
- return "";
- }
- return String.format(Locale.ENGLISH, "%.2f",
- (float)overallProgress / (1024.0f * 1024.0f)) +
- "MB /" +
- String.format(Locale.ENGLISH, "%.2f", (float)overallTotal / (1024.0f * 1024.0f)) + "MB";
- }
+ static public String getDownloadProgressString(long overallProgress, long overallTotal) {
+ if (overallTotal == 0) {
+ if (Constants.LOGVV) {
+ Log.e(Constants.TAG, "Notification called when total is zero");
+ }
+ return "";
+ }
+ // -- GODOT start --
+ return String.format(Locale.ENGLISH, "%.2f",
+ (float) overallProgress / (1024.0f * 1024.0f))
+ + "MB /" +
+ String.format(Locale.ENGLISH, "%.2f", (float) overallTotal /
+ (1024.0f * 1024.0f))
+ + "MB";
+ // -- GODOT end --
+ }
- /**
+ /**
* Adds a percentile to getDownloadProgressString.
*
* @param overallProgress
* @param overallTotal
* @return
*/
- static public String getDownloadProgressStringNotification(long overallProgress,
- long overallTotal) {
- if (overallTotal == 0) {
- if (Constants.LOGVV) {
- Log.e(Constants.TAG, "Notification called when total is zero");
- }
- return "";
- }
- return getDownloadProgressString(overallProgress, overallTotal) + " (" +
- getDownloadProgressPercent(overallProgress, overallTotal) + ")";
- }
+ static public String getDownloadProgressStringNotification(long overallProgress,
+ long overallTotal) {
+ if (overallTotal == 0) {
+ if (Constants.LOGVV) {
+ Log.e(Constants.TAG, "Notification called when total is zero");
+ }
+ return "";
+ }
+ return getDownloadProgressString(overallProgress, overallTotal) + " (" +
+ getDownloadProgressPercent(overallProgress, overallTotal) + ")";
+ }
- public static String getDownloadProgressPercent(long overallProgress, long overallTotal) {
- if (overallTotal == 0) {
- if (Constants.LOGVV) {
- Log.e(Constants.TAG, "Notification called when total is zero");
- }
- return "";
- }
- return Long.toString(overallProgress * 100 / overallTotal) + "%";
- }
+ public static String getDownloadProgressPercent(long overallProgress, long overallTotal) {
+ if (overallTotal == 0) {
+ if (Constants.LOGVV) {
+ Log.e(Constants.TAG, "Notification called when total is zero");
+ }
+ return "";
+ }
+ return Long.toString(overallProgress * 100 / overallTotal) + "%";
+ }
- public static String getSpeedString(float bytesPerMillisecond) {
- return String.format(Locale.ENGLISH, "%.2f", bytesPerMillisecond * 1000 / 1024);
- }
+ public static String getSpeedString(float bytesPerMillisecond) {
+ // -- GODOT start --
+ return String.format(Locale.ENGLISH, "%.2f", bytesPerMillisecond * 1000 / 1024);
+ // -- GODOT end --
+ }
- public static String getTimeRemaining(long durationInMilliseconds) {
- SimpleDateFormat sdf;
- if (durationInMilliseconds > 1000 * 60 * 60) {
- sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
- } else {
- sdf = new SimpleDateFormat("mm:ss", Locale.getDefault());
- }
- return sdf.format(new Date(durationInMilliseconds - TimeZone.getDefault().getRawOffset()));
- }
+ public static String getTimeRemaining(long durationInMilliseconds) {
+ SimpleDateFormat sdf;
+ if (durationInMilliseconds > 1000 * 60 * 60) {
+ sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
+ } else {
+ sdf = new SimpleDateFormat("mm:ss", Locale.getDefault());
+ }
+ return sdf.format(new Date(durationInMilliseconds - TimeZone.getDefault().getRawOffset()));
+ }
- /**
+ /**
* Returns the file name (without full path) for an Expansion APK file from the given context.
*
* @param c the context
@@ -202,33 +212,34 @@ public class Helpers {
* @param versionCode the version of the file
* @return String the file name of the expansion file
*/
- public static String getExpansionAPKFileName(Context c, boolean mainFile, int versionCode) {
- return (mainFile ? "main." : "patch.") + versionCode + "." + c.getPackageName() + ".obb";
- }
+ public static String getExpansionAPKFileName(Context c, boolean mainFile, int versionCode) {
+ return (mainFile ? "main." : "patch.") + versionCode + "." + c.getPackageName() + ".obb";
+ }
- /**
+ /**
* Returns the filename (where the file should be saved) from info about a download
*/
- static public String generateSaveFileName(Context c, String fileName) {
- String path = getSaveFilePath(c) + File.separator + fileName;
- return path;
- }
+ static public String generateSaveFileName(Context c, String fileName) {
+ String path = getSaveFilePath(c)
+ + File.separator + fileName;
+ return path;
+ }
- @TargetApi(Build.VERSION_CODES.HONEYCOMB)
- static public String getSaveFilePath(Context c) {
- // This technically existed since Honeycomb, but it is critical
- // on KitKat and greater versions since it will create the
- // directory if needed
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- return c.getObbDir().toString();
- } else {
- File root = Environment.getExternalStorageDirectory();
- String path = root.toString() + Constants.EXP_PATH + c.getPackageName();
- return path;
- }
- }
+ @TargetApi(Build.VERSION_CODES.HONEYCOMB)
+ static public String getSaveFilePath(Context c) {
+ // This technically existed since Honeycomb, but it is critical
+ // on KitKat and greater versions since it will create the
+ // directory if needed
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ return c.getObbDir().toString();
+ } else {
+ File root = Environment.getExternalStorageDirectory();
+ String path = root.toString() + Constants.EXP_PATH + c.getPackageName();
+ return path;
+ }
+ }
- /**
+ /**
* Helper function to ascertain the existence of a file and return true/false appropriately
*
* @param c the app/activity/service context
@@ -237,72 +248,72 @@ public class Helpers {
* @param deleteFileOnMismatch if the file sizes do not match, delete the file
* @return true if it does exist, false otherwise
*/
- static public boolean doesFileExist(Context c, String fileName, long fileSize,
- boolean deleteFileOnMismatch) {
- // the file may have been delivered by Play --- let's make sure
- // it's the size we expect
- File fileForNewFile = new File(Helpers.generateSaveFileName(c, fileName));
- if (fileForNewFile.exists()) {
- if (fileForNewFile.length() == fileSize) {
- return true;
- }
- if (deleteFileOnMismatch) {
- // delete the file --- we won't be able to resume
- // because we cannot confirm the integrity of the file
- fileForNewFile.delete();
- }
- }
- return false;
- }
+ static public boolean doesFileExist(Context c, String fileName, long fileSize,
+ boolean deleteFileOnMismatch) {
+ // the file may have been delivered by Play --- let's make sure
+ // it's the size we expect
+ File fileForNewFile = new File(Helpers.generateSaveFileName(c, fileName));
+ if (fileForNewFile.exists()) {
+ if (fileForNewFile.length() == fileSize) {
+ return true;
+ }
+ if (deleteFileOnMismatch) {
+ // delete the file --- we won't be able to resume
+ // because we cannot confirm the integrity of the file
+ fileForNewFile.delete();
+ }
+ }
+ return false;
+ }
- public static final int FS_READABLE = 0;
- public static final int FS_DOES_NOT_EXIST = 1;
- public static final int FS_CANNOT_READ = 2;
+ public static final int FS_READABLE = 0;
+ public static final int FS_DOES_NOT_EXIST = 1;
+ public static final int FS_CANNOT_READ = 2;
- /**
+ /**
* Helper function to ascertain whether a file can be read.
*
* @param c the app/activity/service context
* @param fileName the name (sans path) of the file to query
* @return true if it does exist, false otherwise
*/
- static public int getFileStatus(Context c, String fileName) {
- // the file may have been delivered by Play --- let's make sure
- // it's the size we expect
- File fileForNewFile = new File(Helpers.generateSaveFileName(c, fileName));
- int returnValue;
- if (fileForNewFile.exists()) {
- if (fileForNewFile.canRead()) {
- returnValue = FS_READABLE;
- } else {
- returnValue = FS_CANNOT_READ;
- }
- } else {
- returnValue = FS_DOES_NOT_EXIST;
- }
- return returnValue;
- }
+ static public int getFileStatus(Context c, String fileName) {
+ // the file may have been delivered by Play --- let's make sure
+ // it's the size we expect
+ File fileForNewFile = new File(Helpers.generateSaveFileName(c, fileName));
+ int returnValue;
+ if (fileForNewFile.exists()) {
+ if (fileForNewFile.canRead()) {
+ returnValue = FS_READABLE;
+ } else {
+ returnValue = FS_CANNOT_READ;
+ }
+ } else {
+ returnValue = FS_DOES_NOT_EXIST;
+ }
+ return returnValue;
+ }
- /**
+ /**
* Helper function to ascertain whether the application has the correct access to the OBB
* directory to allow an OBB file to be written.
*
* @param c the app/activity/service context
* @return true if the application can write an OBB file, false otherwise
*/
- static public boolean canWriteOBBFile(Context c) {
- String path = getSaveFilePath(c);
- File fileForNewFile = new File(path);
- boolean canWrite;
- if (fileForNewFile.exists()) {
- canWrite = fileForNewFile.isDirectory() && fileForNewFile.canWrite();
- } else {
- canWrite = fileForNewFile.mkdirs();
- }
- return canWrite;
- }
+ static public boolean canWriteOBBFile(Context c) {
+ String path = getSaveFilePath(c);
+ File fileForNewFile = new File(path);
+ boolean canWrite;
+ if (fileForNewFile.exists()) {
+ canWrite = fileForNewFile.isDirectory() && fileForNewFile.canWrite();
+ } else {
+ canWrite = fileForNewFile.mkdirs();
+ }
+ return canWrite;
+ }
- /**
+ /**
* Converts download states that are returned by the
* {@link IDownloaderClient#onDownloadStateChanged} callback into usable strings. This is useful
* if using the state strings built into the library to display user messages.
@@ -310,46 +321,47 @@ public class Helpers {
* @param state One of the STATE_* constants from {@link IDownloaderClient}.
* @return string resource ID for the corresponding string.
*/
- static public int getDownloaderStringResourceIDFromState(int state) {
- switch (state) {
- case IDownloaderClient.STATE_IDLE:
- return R.string.state_idle;
- case IDownloaderClient.STATE_FETCHING_URL:
- return R.string.state_fetching_url;
- case IDownloaderClient.STATE_CONNECTING:
- return R.string.state_connecting;
- case IDownloaderClient.STATE_DOWNLOADING:
- return R.string.state_downloading;
- case IDownloaderClient.STATE_COMPLETED:
- return R.string.state_completed;
- case IDownloaderClient.STATE_PAUSED_NETWORK_UNAVAILABLE:
- return R.string.state_paused_network_unavailable;
- case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
- return R.string.state_paused_by_request;
- case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
- return R.string.state_paused_wifi_disabled;
- case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
- return R.string.state_paused_wifi_unavailable;
- case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED:
- return R.string.state_paused_wifi_disabled;
- case IDownloaderClient.STATE_PAUSED_NEED_WIFI:
- return R.string.state_paused_wifi_unavailable;
- case IDownloaderClient.STATE_PAUSED_ROAMING:
- return R.string.state_paused_roaming;
- case IDownloaderClient.STATE_PAUSED_NETWORK_SETUP_FAILURE:
- return R.string.state_paused_network_setup_failure;
- case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
- return R.string.state_paused_sdcard_unavailable;
- case IDownloaderClient.STATE_FAILED_UNLICENSED:
- return R.string.state_failed_unlicensed;
- case IDownloaderClient.STATE_FAILED_FETCHING_URL:
- return R.string.state_failed_fetching_url;
- case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
- return R.string.state_failed_sdcard_full;
- case IDownloaderClient.STATE_FAILED_CANCELED:
- return R.string.state_failed_cancelled;
- default:
- return R.string.state_unknown;
- }
- }
+ static public int getDownloaderStringResourceIDFromState(int state) {
+ switch (state) {
+ case IDownloaderClient.STATE_IDLE:
+ return R.string.state_idle;
+ case IDownloaderClient.STATE_FETCHING_URL:
+ return R.string.state_fetching_url;
+ case IDownloaderClient.STATE_CONNECTING:
+ return R.string.state_connecting;
+ case IDownloaderClient.STATE_DOWNLOADING:
+ return R.string.state_downloading;
+ case IDownloaderClient.STATE_COMPLETED:
+ return R.string.state_completed;
+ case IDownloaderClient.STATE_PAUSED_NETWORK_UNAVAILABLE:
+ return R.string.state_paused_network_unavailable;
+ case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
+ return R.string.state_paused_by_request;
+ case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
+ return R.string.state_paused_wifi_disabled;
+ case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
+ return R.string.state_paused_wifi_unavailable;
+ case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED:
+ return R.string.state_paused_wifi_disabled;
+ case IDownloaderClient.STATE_PAUSED_NEED_WIFI:
+ return R.string.state_paused_wifi_unavailable;
+ case IDownloaderClient.STATE_PAUSED_ROAMING:
+ return R.string.state_paused_roaming;
+ case IDownloaderClient.STATE_PAUSED_NETWORK_SETUP_FAILURE:
+ return R.string.state_paused_network_setup_failure;
+ case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
+ return R.string.state_paused_sdcard_unavailable;
+ case IDownloaderClient.STATE_FAILED_UNLICENSED:
+ return R.string.state_failed_unlicensed;
+ case IDownloaderClient.STATE_FAILED_FETCHING_URL:
+ return R.string.state_failed_fetching_url;
+ case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
+ return R.string.state_failed_sdcard_full;
+ case IDownloaderClient.STATE_FAILED_CANCELED:
+ return R.string.state_failed_cancelled;
+ default:
+ return R.string.state_unknown;
+ }
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderClient.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderClient.java
index bae93f633a..cef3794701 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderClient.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderClient.java
@@ -23,26 +23,26 @@ import android.os.Messenger;
* downloader. It is used to pass status from the service to the client.
*/
public interface IDownloaderClient {
- static final int STATE_IDLE = 1;
- static final int STATE_FETCHING_URL = 2;
- static final int STATE_CONNECTING = 3;
- static final int STATE_DOWNLOADING = 4;
- static final int STATE_COMPLETED = 5;
+ static final int STATE_IDLE = 1;
+ static final int STATE_FETCHING_URL = 2;
+ static final int STATE_CONNECTING = 3;
+ static final int STATE_DOWNLOADING = 4;
+ static final int STATE_COMPLETED = 5;
- static final int STATE_PAUSED_NETWORK_UNAVAILABLE = 6;
- static final int STATE_PAUSED_BY_REQUEST = 7;
+ static final int STATE_PAUSED_NETWORK_UNAVAILABLE = 6;
+ static final int STATE_PAUSED_BY_REQUEST = 7;
- /**
+ /**
* Both STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION and
* STATE_PAUSED_NEED_CELLULAR_PERMISSION imply that Wi-Fi is unavailable and
* cellular permission will restart the service. Wi-Fi disabled means that
* the Wi-Fi manager is returning that Wi-Fi is not enabled, while in the
* other case Wi-Fi is enabled but not available.
*/
- static final int STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION = 8;
- static final int STATE_PAUSED_NEED_CELLULAR_PERMISSION = 9;
+ static final int STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION = 8;
+ static final int STATE_PAUSED_NEED_CELLULAR_PERMISSION = 9;
- /**
+ /**
* Both STATE_PAUSED_WIFI_DISABLED and STATE_PAUSED_NEED_WIFI imply that
* Wi-Fi is unavailable and cellular permission will NOT restart the
* service. Wi-Fi disabled means that the Wi-Fi manager is returning that
@@ -53,27 +53,27 @@ public interface IDownloaderClient {
* developers with very large payloads do not allow these payloads to be
* downloaded over cellular connections.
*/
- static final int STATE_PAUSED_WIFI_DISABLED = 10;
- static final int STATE_PAUSED_NEED_WIFI = 11;
+ static final int STATE_PAUSED_WIFI_DISABLED = 10;
+ static final int STATE_PAUSED_NEED_WIFI = 11;
- static final int STATE_PAUSED_ROAMING = 12;
+ static final int STATE_PAUSED_ROAMING = 12;
- /**
+ /**
* Scary case. We were on a network that redirected us to another website
* that delivered us the wrong file.
*/
- static final int STATE_PAUSED_NETWORK_SETUP_FAILURE = 13;
+ static final int STATE_PAUSED_NETWORK_SETUP_FAILURE = 13;
- static final int STATE_PAUSED_SDCARD_UNAVAILABLE = 14;
+ static final int STATE_PAUSED_SDCARD_UNAVAILABLE = 14;
- static final int STATE_FAILED_UNLICENSED = 15;
- static final int STATE_FAILED_FETCHING_URL = 16;
- static final int STATE_FAILED_SDCARD_FULL = 17;
- static final int STATE_FAILED_CANCELED = 18;
+ static final int STATE_FAILED_UNLICENSED = 15;
+ static final int STATE_FAILED_FETCHING_URL = 16;
+ static final int STATE_FAILED_SDCARD_FULL = 17;
+ static final int STATE_FAILED_CANCELED = 18;
- static final int STATE_FAILED = 19;
+ static final int STATE_FAILED = 19;
- /**
+ /**
* Called internally by the stub when the service is bound to the client.
* <p>
* Critical implementation detail. In onServiceConnected we create the
@@ -90,9 +90,9 @@ public interface IDownloaderClient {
* @param m the service Messenger. This Messenger is used to call the
* service API from the client.
*/
- void onServiceConnected(Messenger m);
+ void onServiceConnected(Messenger m);
- /**
+ /**
* Called when the download state changes. Depending on the state, there may
* be user requests. The service is free to change the download state in the
* middle of a user request, so the client should be able to handle this.
@@ -112,9 +112,9 @@ public interface IDownloaderClient {
*
* @param newState one of the STATE_* values defined in IDownloaderClient
*/
- void onDownloadStateChanged(int newState);
+ void onDownloadStateChanged(int newState);
- /**
+ /**
* Shows the download progress. This is intended to be used to fill out a
* client UI. This progress should only be shown in a few states such as
* STATE_DOWNLOADING.
@@ -122,5 +122,5 @@ public interface IDownloaderClient {
* @param progress the DownloadProgressInfo object containing the current
* progress of all downloads.
*/
- void onDownloadProgress(DownloadProgressInfo progress);
+ void onDownloadProgress(DownloadProgressInfo progress);
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderService.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderService.java
index a84fb32728..4de9de0c62 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderService.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/IDownloaderService.java
@@ -31,47 +31,47 @@ import android.os.Messenger;
* should immediately call {@link #onClientUpdated}.
*/
public interface IDownloaderService {
- /**
+ /**
* Set this flag in response to the
* IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION state and then
* call RequestContinueDownload to resume a download
*/
- public static final int FLAGS_DOWNLOAD_OVER_CELLULAR = 1;
+ public static final int FLAGS_DOWNLOAD_OVER_CELLULAR = 1;
- /**
+ /**
* Request that the service abort the current download. The service should
* respond by changing the state to {@link IDownloaderClient.STATE_ABORTED}.
*/
- void requestAbortDownload();
+ void requestAbortDownload();
- /**
+ /**
* Request that the service pause the current download. The service should
* respond by changing the state to
* {@link IDownloaderClient.STATE_PAUSED_BY_REQUEST}.
*/
- void requestPauseDownload();
+ void requestPauseDownload();
- /**
+ /**
* Request that the service continue a paused download, when in any paused
* or failed state, including
* {@link IDownloaderClient.STATE_PAUSED_BY_REQUEST}.
*/
- void requestContinueDownload();
+ void requestContinueDownload();
- /**
+ /**
* Set the flags for this download (e.g.
* {@link DownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR}).
*
* @param flags
*/
- void setDownloadFlags(int flags);
+ void setDownloadFlags(int flags);
- /**
+ /**
* Requests that the download status be sent to the client.
*/
- void requestDownloadStatus();
+ void requestDownloadStatus();
- /**
+ /**
* Call this when you get {@link
* IDownloaderClient.onServiceConnected(Messenger m)} from the
* DownloaderClient to register the client with the service. It will
@@ -79,5 +79,5 @@ public interface IDownloaderService {
*
* @param clientMessenger
*/
- void onClientUpdated(Messenger clientMessenger);
+ void onClientUpdated(Messenger clientMessenger);
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/IStub.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/IStub.java
index dcdef1bfcf..d5bc3a843e 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/IStub.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/IStub.java
@@ -33,9 +33,9 @@ import android.os.Messenger;
* {@link IDownloaderService#onClientUpdated}.
*/
public interface IStub {
- Messenger getMessenger();
+ Messenger getMessenger();
- void connect(Context c);
+ void connect(Context c);
- void disconnect(Context c);
+ void disconnect(Context c);
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
index c5577d4c2a..a0e1165cc4 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/SystemFacade.java
@@ -16,7 +16,6 @@
package com.google.android.vending.expansion.downloader;
-import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
@@ -27,100 +26,104 @@ import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
+// -- GODOT start --
+import android.annotation.SuppressLint;
+// -- GODOT end --
+
/**
* Contains useful helper functions, typically tied to the application context.
*/
class SystemFacade {
- private Context mContext;
- private NotificationManager mNotificationManager;
-
- public SystemFacade(Context context) {
- mContext = context;
- mNotificationManager = (NotificationManager)
- mContext.getSystemService(Context.NOTIFICATION_SERVICE);
- }
-
- public long currentTimeMillis() {
- return System.currentTimeMillis();
- }
-
- public Integer getActiveNetworkType() {
- ConnectivityManager connectivity =
- (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity == null) {
- Log.w(Constants.TAG, "couldn't get connectivity manager");
- return null;
- }
-
- @SuppressLint("MissingPermission")
- NetworkInfo activeInfo = connectivity.getActiveNetworkInfo();
- if (activeInfo == null) {
- if (Constants.LOGVV) {
- Log.v(Constants.TAG, "network is not available");
- }
- return null;
- }
- return activeInfo.getType();
- }
-
- public boolean isNetworkRoaming() {
- ConnectivityManager connectivity =
- (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity == null) {
- Log.w(Constants.TAG, "couldn't get connectivity manager");
- return false;
- }
-
- @SuppressLint("MissingPermission")
- NetworkInfo info = connectivity.getActiveNetworkInfo();
- boolean isMobile = (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE);
- TelephonyManager tm = (TelephonyManager)mContext
- .getSystemService(Context.TELEPHONY_SERVICE);
- if (null == tm) {
- Log.w(Constants.TAG, "couldn't get telephony manager");
- return false;
- }
- boolean isRoaming = isMobile && tm.isNetworkRoaming();
- if (Constants.LOGVV && isRoaming) {
- Log.v(Constants.TAG, "network is roaming");
- }
- return isRoaming;
- }
-
- public Long getMaxBytesOverMobile() {
- return (long)Integer.MAX_VALUE;
- }
-
- public Long getRecommendedMaxBytesOverMobile() {
- return 2097152L;
- }
-
- public void sendBroadcast(Intent intent) {
- mContext.sendBroadcast(intent);
- }
-
- public boolean userOwnsPackage(int uid, String packageName) throws NameNotFoundException {
- return mContext.getPackageManager().getApplicationInfo(packageName, 0).uid == uid;
- }
-
- public void postNotification(long id, Notification notification) {
- /**
+ private Context mContext;
+ private NotificationManager mNotificationManager;
+
+ public SystemFacade(Context context) {
+ mContext = context;
+ mNotificationManager = (NotificationManager)
+ mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+ }
+
+ public long currentTimeMillis() {
+ return System.currentTimeMillis();
+ }
+
+ public Integer getActiveNetworkType() {
+ ConnectivityManager connectivity =
+ (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+ if (connectivity == null) {
+ Log.w(Constants.TAG, "couldn't get connectivity manager");
+ return null;
+ }
+
+ @SuppressLint("MissingPermission")
+ NetworkInfo activeInfo = connectivity.getActiveNetworkInfo();
+ if (activeInfo == null) {
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG, "network is not available");
+ }
+ return null;
+ }
+ return activeInfo.getType();
+ }
+
+ public boolean isNetworkRoaming() {
+ ConnectivityManager connectivity =
+ (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+ if (connectivity == null) {
+ Log.w(Constants.TAG, "couldn't get connectivity manager");
+ return false;
+ }
+
+ @SuppressLint("MissingPermission")
+ NetworkInfo info = connectivity.getActiveNetworkInfo();
+ boolean isMobile = (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE);
+ TelephonyManager tm = (TelephonyManager) mContext
+ .getSystemService(Context.TELEPHONY_SERVICE);
+ if (null == tm) {
+ Log.w(Constants.TAG, "couldn't get telephony manager");
+ return false;
+ }
+ boolean isRoaming = isMobile && tm.isNetworkRoaming();
+ if (Constants.LOGVV && isRoaming) {
+ Log.v(Constants.TAG, "network is roaming");
+ }
+ return isRoaming;
+ }
+
+ public Long getMaxBytesOverMobile() {
+ return (long) Integer.MAX_VALUE;
+ }
+
+ public Long getRecommendedMaxBytesOverMobile() {
+ return 2097152L;
+ }
+
+ public void sendBroadcast(Intent intent) {
+ mContext.sendBroadcast(intent);
+ }
+
+ public boolean userOwnsPackage(int uid, String packageName) throws NameNotFoundException {
+ return mContext.getPackageManager().getApplicationInfo(packageName, 0).uid == uid;
+ }
+
+ public void postNotification(long id, Notification notification) {
+ /**
* TODO: The system notification manager takes ints, not longs, as IDs,
* but the download manager uses IDs take straight from the database,
* which are longs. This will have to be dealt with at some point.
*/
- mNotificationManager.notify((int)id, notification);
- }
+ mNotificationManager.notify((int) id, notification);
+ }
- public void cancelNotification(long id) {
- mNotificationManager.cancel((int)id);
- }
+ public void cancelNotification(long id) {
+ mNotificationManager.cancel((int) id);
+ }
- public void cancelAllNotifications() {
- mNotificationManager.cancelAll();
- }
+ public void cancelAllNotifications() {
+ mNotificationManager.cancelAll();
+ }
- public void startThread(Thread thread) {
- thread.start();
- }
+ public void startThread(Thread thread) {
+ thread.start();
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/CustomIntentService.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/CustomIntentService.java
index 6346d7703a..3ccc191c60 100755..100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/CustomIntentService.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/CustomIntentService.java
@@ -32,80 +32,81 @@ import android.util.Log;
* intent, it does not queue up batches of intents of the same type.
*/
public abstract class CustomIntentService extends Service {
- private String mName;
- private boolean mRedelivery;
- private volatile ServiceHandler mServiceHandler;
- private volatile Looper mServiceLooper;
- private static final String LOG_TAG = "CustomIntentService";
- private static final int WHAT_MESSAGE = -10;
+ private String mName;
+ private boolean mRedelivery;
+ private volatile ServiceHandler mServiceHandler;
+ private volatile Looper mServiceLooper;
+ private static final String LOG_TAG = "CustomIntentService";
+ private static final int WHAT_MESSAGE = -10;
- public CustomIntentService(String paramString) {
- this.mName = paramString;
- }
+ public CustomIntentService(String paramString) {
+ this.mName = paramString;
+ }
- @Override
- public IBinder onBind(Intent paramIntent) {
- return null;
- }
+ @Override
+ public IBinder onBind(Intent paramIntent) {
+ return null;
+ }
- @Override
- public void onCreate() {
- super.onCreate();
- HandlerThread localHandlerThread = new HandlerThread("IntentService[" + this.mName + "]");
- localHandlerThread.start();
- this.mServiceLooper = localHandlerThread.getLooper();
- this.mServiceHandler = new ServiceHandler(this.mServiceLooper);
- }
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ HandlerThread localHandlerThread = new HandlerThread("IntentService["
+ + this.mName + "]");
+ localHandlerThread.start();
+ this.mServiceLooper = localHandlerThread.getLooper();
+ this.mServiceHandler = new ServiceHandler(this.mServiceLooper);
+ }
- @Override
- public void onDestroy() {
- Thread localThread = this.mServiceLooper.getThread();
- if ((localThread != null) && (localThread.isAlive())) {
- localThread.interrupt();
- }
- this.mServiceLooper.quit();
- Log.d(LOG_TAG, "onDestroy");
- }
+ @Override
+ public void onDestroy() {
+ Thread localThread = this.mServiceLooper.getThread();
+ if ((localThread != null) && (localThread.isAlive())) {
+ localThread.interrupt();
+ }
+ this.mServiceLooper.quit();
+ Log.d(LOG_TAG, "onDestroy");
+ }
- protected abstract void onHandleIntent(Intent paramIntent);
+ protected abstract void onHandleIntent(Intent paramIntent);
- protected abstract boolean shouldStop();
+ protected abstract boolean shouldStop();
- @Override
- public void onStart(Intent paramIntent, int startId) {
- if (!this.mServiceHandler.hasMessages(WHAT_MESSAGE)) {
- Message localMessage = this.mServiceHandler.obtainMessage();
- localMessage.arg1 = startId;
- localMessage.obj = paramIntent;
- localMessage.what = WHAT_MESSAGE;
- this.mServiceHandler.sendMessage(localMessage);
- }
- }
+ @Override
+ public void onStart(Intent paramIntent, int startId) {
+ if (!this.mServiceHandler.hasMessages(WHAT_MESSAGE)) {
+ Message localMessage = this.mServiceHandler.obtainMessage();
+ localMessage.arg1 = startId;
+ localMessage.obj = paramIntent;
+ localMessage.what = WHAT_MESSAGE;
+ this.mServiceHandler.sendMessage(localMessage);
+ }
+ }
- @Override
- public int onStartCommand(Intent paramIntent, int flags, int startId) {
- onStart(paramIntent, startId);
- return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
- }
+ @Override
+ public int onStartCommand(Intent paramIntent, int flags, int startId) {
+ onStart(paramIntent, startId);
+ return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
+ }
- public void setIntentRedelivery(boolean enabled) {
- this.mRedelivery = enabled;
- }
+ public void setIntentRedelivery(boolean enabled) {
+ this.mRedelivery = enabled;
+ }
- private final class ServiceHandler extends Handler {
- public ServiceHandler(Looper looper) {
- super(looper);
- }
+ private final class ServiceHandler extends Handler {
+ public ServiceHandler(Looper looper) {
+ super(looper);
+ }
- @Override
- public void handleMessage(Message paramMessage) {
- CustomIntentService.this
- .onHandleIntent((Intent)paramMessage.obj);
- if (shouldStop()) {
- Log.d(LOG_TAG, "stopSelf");
- CustomIntentService.this.stopSelf(paramMessage.arg1);
- Log.d(LOG_TAG, "afterStopSelf");
- }
- }
- }
+ @Override
+ public void handleMessage(Message paramMessage) {
+ CustomIntentService.this
+ .onHandleIntent((Intent) paramMessage.obj);
+ if (shouldStop()) {
+ Log.d(LOG_TAG, "stopSelf");
+ CustomIntentService.this.stopSelf(paramMessage.arg1);
+ Log.d(LOG_TAG, "afterStopSelf");
+ }
+ }
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadInfo.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadInfo.java
index 0e72b7ae77..45111b16a3 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadInfo.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadInfo.java
@@ -25,68 +25,68 @@ import android.util.Log;
* Representation of information about an individual download from the database.
*/
public class DownloadInfo {
- public String mUri;
- public final int mIndex;
- public final String mFileName;
- public String mETag;
- public long mTotalBytes;
- public long mCurrentBytes;
- public long mLastMod;
- public int mStatus;
- public int mControl;
- public int mNumFailed;
- public int mRetryAfter;
- public int mRedirectCount;
+ public String mUri;
+ public final int mIndex;
+ public final String mFileName;
+ public String mETag;
+ public long mTotalBytes;
+ public long mCurrentBytes;
+ public long mLastMod;
+ public int mStatus;
+ public int mControl;
+ public int mNumFailed;
+ public int mRetryAfter;
+ public int mRedirectCount;
- boolean mInitialized;
+ boolean mInitialized;
- public int mFuzz;
+ public int mFuzz;
- public DownloadInfo(int index, String fileName, String pkg) {
- mFuzz = Helpers.sRandom.nextInt(1001);
- mFileName = fileName;
- mIndex = index;
- }
+ public DownloadInfo(int index, String fileName, String pkg) {
+ mFuzz = Helpers.sRandom.nextInt(1001);
+ mFileName = fileName;
+ mIndex = index;
+ }
- public void resetDownload() {
- mCurrentBytes = 0;
- mETag = "";
- mLastMod = 0;
- mStatus = 0;
- mControl = 0;
- mNumFailed = 0;
- mRetryAfter = 0;
- mRedirectCount = 0;
- }
+ public void resetDownload() {
+ mCurrentBytes = 0;
+ mETag = "";
+ mLastMod = 0;
+ mStatus = 0;
+ mControl = 0;
+ mNumFailed = 0;
+ mRetryAfter = 0;
+ mRedirectCount = 0;
+ }
- /**
+ /**
* Returns the time when a download should be restarted.
*/
- public long restartTime(long now) {
- if (mNumFailed == 0) {
- return now;
- }
- if (mRetryAfter > 0) {
- return mLastMod + mRetryAfter;
- }
- return mLastMod +
- Constants.RETRY_FIRST_DELAY *
- (1000 + mFuzz) * (1 << (mNumFailed - 1));
- }
+ public long restartTime(long now) {
+ if (mNumFailed == 0) {
+ return now;
+ }
+ if (mRetryAfter > 0) {
+ return mLastMod + mRetryAfter;
+ }
+ return mLastMod +
+ Constants.RETRY_FIRST_DELAY *
+ (1000 + mFuzz) * (1 << (mNumFailed - 1));
+ }
- public void logVerboseInfo() {
- Log.v(Constants.TAG, "Service adding new entry");
- Log.v(Constants.TAG, "FILENAME: " + mFileName);
- Log.v(Constants.TAG, "URI : " + mUri);
- Log.v(Constants.TAG, "FILENAME: " + mFileName);
- Log.v(Constants.TAG, "CONTROL : " + mControl);
- Log.v(Constants.TAG, "STATUS : " + mStatus);
- Log.v(Constants.TAG, "FAILED_C: " + mNumFailed);
- Log.v(Constants.TAG, "RETRY_AF: " + mRetryAfter);
- Log.v(Constants.TAG, "REDIRECT: " + mRedirectCount);
- Log.v(Constants.TAG, "LAST_MOD: " + mLastMod);
- Log.v(Constants.TAG, "TOTAL : " + mTotalBytes);
- Log.v(Constants.TAG, "CURRENT : " + mCurrentBytes);
- Log.v(Constants.TAG, "ETAG : " + mETag);
- }
+ public void logVerboseInfo() {
+ Log.v(Constants.TAG, "Service adding new entry");
+ Log.v(Constants.TAG, "FILENAME: " + mFileName);
+ Log.v(Constants.TAG, "URI : " + mUri);
+ Log.v(Constants.TAG, "FILENAME: " + mFileName);
+ Log.v(Constants.TAG, "CONTROL : " + mControl);
+ Log.v(Constants.TAG, "STATUS : " + mStatus);
+ Log.v(Constants.TAG, "FAILED_C: " + mNumFailed);
+ Log.v(Constants.TAG, "RETRY_AF: " + mRetryAfter);
+ Log.v(Constants.TAG, "REDIRECT: " + mRedirectCount);
+ Log.v(Constants.TAG, "LAST_MOD: " + mLastMod);
+ Log.v(Constants.TAG, "TOTAL : " + mTotalBytes);
+ Log.v(Constants.TAG, "CURRENT : " + mCurrentBytes);
+ Log.v(Constants.TAG, "ETAG : " + mETag);
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
index 099e3f05b3..4b214b22d7 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java
@@ -16,7 +16,11 @@
package com.google.android.vending.expansion.downloader.impl;
+// -- GODOT start --
+//import com.android.vending.expansion.downloader.R;
import com.godot.game.R;
+// -- GODOT end --
+
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
@@ -42,183 +46,184 @@ import android.support.v4.app.NotificationCompat;
*/
public class DownloadNotification implements IDownloaderClient {
- private int mState;
- private final Context mContext;
- private final NotificationManager mNotificationManager;
- private CharSequence mCurrentTitle;
-
- private IDownloaderClient mClientProxy;
- private NotificationCompat.Builder mActiveDownloadBuilder;
- private NotificationCompat.Builder mBuilder;
- private NotificationCompat.Builder mCurrentBuilder;
- private CharSequence mLabel;
- private String mCurrentText;
- private DownloadProgressInfo mProgressInfo;
- private PendingIntent mContentIntent;
-
- static final String LOGTAG = "DownloadNotification";
- static final int NOTIFICATION_ID = LOGTAG.hashCode();
-
- public PendingIntent getClientIntent() {
- return mContentIntent;
- }
-
- public void setClientIntent(PendingIntent clientIntent) {
- this.mBuilder.setContentIntent(clientIntent);
- this.mActiveDownloadBuilder.setContentIntent(clientIntent);
- this.mContentIntent = clientIntent;
- }
-
- public void resendState() {
- if (null != mClientProxy) {
- mClientProxy.onDownloadStateChanged(mState);
- }
- }
-
- @Override
- public void onDownloadStateChanged(int newState) {
- if (null != mClientProxy) {
- mClientProxy.onDownloadStateChanged(newState);
- }
- if (newState != mState) {
- mState = newState;
- if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
- return;
- }
- int stringDownloadID;
- int iconResource;
- boolean ongoingEvent;
-
- // get the new title string and paused text
- switch (newState) {
- case 0:
- iconResource = android.R.drawable.stat_sys_warning;
- stringDownloadID = R.string.state_unknown;
- ongoingEvent = false;
- break;
-
- case IDownloaderClient.STATE_DOWNLOADING:
- iconResource = android.R.drawable.stat_sys_download;
- stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
- ongoingEvent = true;
- break;
-
- case IDownloaderClient.STATE_FETCHING_URL:
- case IDownloaderClient.STATE_CONNECTING:
- iconResource = android.R.drawable.stat_sys_download_done;
- stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
- ongoingEvent = true;
- break;
-
- case IDownloaderClient.STATE_COMPLETED:
- case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
- iconResource = android.R.drawable.stat_sys_download_done;
- stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
- ongoingEvent = false;
- break;
-
- case IDownloaderClient.STATE_FAILED:
- case IDownloaderClient.STATE_FAILED_CANCELED:
- case IDownloaderClient.STATE_FAILED_FETCHING_URL:
- case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
- case IDownloaderClient.STATE_FAILED_UNLICENSED:
- iconResource = android.R.drawable.stat_sys_warning;
- stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
- ongoingEvent = false;
- break;
-
- default:
- iconResource = android.R.drawable.stat_sys_warning;
- stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
- ongoingEvent = true;
- break;
- }
-
- mCurrentText = mContext.getString(stringDownloadID);
- mCurrentTitle = mLabel;
- mCurrentBuilder.setTicker(mLabel + ": " + mCurrentText);
- mCurrentBuilder.setSmallIcon(iconResource);
- mCurrentBuilder.setContentTitle(mCurrentTitle);
- mCurrentBuilder.setContentText(mCurrentText);
- if (ongoingEvent) {
- mCurrentBuilder.setOngoing(true);
- } else {
- mCurrentBuilder.setOngoing(false);
- mCurrentBuilder.setAutoCancel(true);
- }
- mNotificationManager.notify(NOTIFICATION_ID, mCurrentBuilder.build());
- }
- }
-
- @Override
- public void onDownloadProgress(DownloadProgressInfo progress) {
- mProgressInfo = progress;
- if (null != mClientProxy) {
- mClientProxy.onDownloadProgress(progress);
- }
- if (progress.mOverallTotal <= 0) {
- // we just show the text
- mBuilder.setTicker(mCurrentTitle);
- mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
- mBuilder.setContentTitle(mCurrentTitle);
- mBuilder.setContentText(mCurrentText);
- mCurrentBuilder = mBuilder;
- } else {
- mActiveDownloadBuilder.setProgress((int)progress.mOverallTotal, (int)progress.mOverallProgress, false);
- mActiveDownloadBuilder.setContentText(Helpers.getDownloadProgressString(progress.mOverallProgress, progress.mOverallTotal));
- mActiveDownloadBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
- mActiveDownloadBuilder.setTicker(mLabel + ": " + mCurrentText);
- mActiveDownloadBuilder.setContentTitle(mLabel);
- mActiveDownloadBuilder.setContentInfo(mContext.getString(R.string.time_remaining_notification,
- Helpers.getTimeRemaining(progress.mTimeRemaining)));
- mCurrentBuilder = mActiveDownloadBuilder;
- }
- mNotificationManager.notify(NOTIFICATION_ID, mCurrentBuilder.build());
- }
-
- /**
+ private int mState;
+ private final Context mContext;
+ private final NotificationManager mNotificationManager;
+ private CharSequence mCurrentTitle;
+
+ private IDownloaderClient mClientProxy;
+ private NotificationCompat.Builder mActiveDownloadBuilder;
+ private NotificationCompat.Builder mBuilder;
+ private NotificationCompat.Builder mCurrentBuilder;
+ private CharSequence mLabel;
+ private String mCurrentText;
+ private DownloadProgressInfo mProgressInfo;
+ private PendingIntent mContentIntent;
+
+ static final String LOGTAG = "DownloadNotification";
+ static final int NOTIFICATION_ID = LOGTAG.hashCode();
+
+ public PendingIntent getClientIntent() {
+ return mContentIntent;
+ }
+
+ public void setClientIntent(PendingIntent clientIntent) {
+ this.mBuilder.setContentIntent(clientIntent);
+ this.mActiveDownloadBuilder.setContentIntent(clientIntent);
+ this.mContentIntent = clientIntent;
+ }
+
+ public void resendState() {
+ if (null != mClientProxy) {
+ mClientProxy.onDownloadStateChanged(mState);
+ }
+ }
+
+ @Override
+ public void onDownloadStateChanged(int newState) {
+ if (null != mClientProxy) {
+ mClientProxy.onDownloadStateChanged(newState);
+ }
+ if (newState != mState) {
+ mState = newState;
+ if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
+ return;
+ }
+ int stringDownloadID;
+ int iconResource;
+ boolean ongoingEvent;
+
+ // get the new title string and paused text
+ switch (newState) {
+ case 0:
+ iconResource = android.R.drawable.stat_sys_warning;
+ stringDownloadID = R.string.state_unknown;
+ ongoingEvent = false;
+ break;
+
+ case IDownloaderClient.STATE_DOWNLOADING:
+ iconResource = android.R.drawable.stat_sys_download;
+ stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
+ ongoingEvent = true;
+ break;
+
+ case IDownloaderClient.STATE_FETCHING_URL:
+ case IDownloaderClient.STATE_CONNECTING:
+ iconResource = android.R.drawable.stat_sys_download_done;
+ stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
+ ongoingEvent = true;
+ break;
+
+ case IDownloaderClient.STATE_COMPLETED:
+ case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
+ iconResource = android.R.drawable.stat_sys_download_done;
+ stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
+ ongoingEvent = false;
+ break;
+
+ case IDownloaderClient.STATE_FAILED:
+ case IDownloaderClient.STATE_FAILED_CANCELED:
+ case IDownloaderClient.STATE_FAILED_FETCHING_URL:
+ case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
+ case IDownloaderClient.STATE_FAILED_UNLICENSED:
+ iconResource = android.R.drawable.stat_sys_warning;
+ stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
+ ongoingEvent = false;
+ break;
+
+ default:
+ iconResource = android.R.drawable.stat_sys_warning;
+ stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
+ ongoingEvent = true;
+ break;
+ }
+
+ mCurrentText = mContext.getString(stringDownloadID);
+ mCurrentTitle = mLabel;
+ mCurrentBuilder.setTicker(mLabel + ": " + mCurrentText);
+ mCurrentBuilder.setSmallIcon(iconResource);
+ mCurrentBuilder.setContentTitle(mCurrentTitle);
+ mCurrentBuilder.setContentText(mCurrentText);
+ if (ongoingEvent) {
+ mCurrentBuilder.setOngoing(true);
+ } else {
+ mCurrentBuilder.setOngoing(false);
+ mCurrentBuilder.setAutoCancel(true);
+ }
+ mNotificationManager.notify(NOTIFICATION_ID, mCurrentBuilder.build());
+ }
+ }
+
+ @Override
+ public void onDownloadProgress(DownloadProgressInfo progress) {
+ mProgressInfo = progress;
+ if (null != mClientProxy) {
+ mClientProxy.onDownloadProgress(progress);
+ }
+ if (progress.mOverallTotal <= 0) {
+ // we just show the text
+ mBuilder.setTicker(mCurrentTitle);
+ mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
+ mBuilder.setContentTitle(mCurrentTitle);
+ mBuilder.setContentText(mCurrentText);
+ mCurrentBuilder = mBuilder;
+ } else {
+ mActiveDownloadBuilder.setProgress((int) progress.mOverallTotal, (int) progress.mOverallProgress, false);
+ mActiveDownloadBuilder.setContentText(Helpers.getDownloadProgressString(progress.mOverallProgress, progress.mOverallTotal));
+ mActiveDownloadBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
+ mActiveDownloadBuilder.setTicker(mLabel + ": " + mCurrentText);
+ mActiveDownloadBuilder.setContentTitle(mLabel);
+ mActiveDownloadBuilder.setContentInfo(mContext.getString(R.string.time_remaining_notification,
+ Helpers.getTimeRemaining(progress.mTimeRemaining)));
+ mCurrentBuilder = mActiveDownloadBuilder;
+ }
+ mNotificationManager.notify(NOTIFICATION_ID, mCurrentBuilder.build());
+ }
+
+ /**
* Called in response to onClientUpdated. Creates a new proxy and notifies
* it of the current state.
*
* @param msg the client Messenger to notify
*/
- public void setMessenger(Messenger msg) {
- mClientProxy = DownloaderClientMarshaller.CreateProxy(msg);
- if (null != mProgressInfo) {
- mClientProxy.onDownloadProgress(mProgressInfo);
- }
- if (mState != -1) {
- mClientProxy.onDownloadStateChanged(mState);
- }
- }
-
- /**
+ public void setMessenger(Messenger msg) {
+ mClientProxy = DownloaderClientMarshaller.CreateProxy(msg);
+ if (null != mProgressInfo) {
+ mClientProxy.onDownloadProgress(mProgressInfo);
+ }
+ if (mState != -1) {
+ mClientProxy.onDownloadStateChanged(mState);
+ }
+ }
+
+ /**
* Constructor
*
* @param ctx The context to use to obtain access to the Notification
* Service
*/
- DownloadNotification(Context ctx, CharSequence applicationLabel) {
- mState = -1;
- mContext = ctx;
- mLabel = applicationLabel;
- mNotificationManager = (NotificationManager)
- mContext.getSystemService(Context.NOTIFICATION_SERVICE);
- mActiveDownloadBuilder = new NotificationCompat.Builder(ctx);
- mBuilder = new NotificationCompat.Builder(ctx);
-
- // Set Notification category and priorities to something that makes sense for a long
- // lived background task.
- mActiveDownloadBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
- mActiveDownloadBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
-
- mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
- mBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
-
- mCurrentBuilder = mBuilder;
- }
-
- @Override
- public void onServiceConnected(Messenger m) {
- }
+ DownloadNotification(Context ctx, CharSequence applicationLabel) {
+ mState = -1;
+ mContext = ctx;
+ mLabel = applicationLabel;
+ mNotificationManager = (NotificationManager)
+ mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+ mActiveDownloadBuilder = new NotificationCompat.Builder(ctx);
+ mBuilder = new NotificationCompat.Builder(ctx);
+
+ // Set Notification category and priorities to something that makes sense for a long
+ // lived background task.
+ mActiveDownloadBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
+ mActiveDownloadBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
+
+ mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
+ mBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
+
+ mCurrentBuilder = mBuilder;
+ }
+
+ @Override
+ public void onServiceConnected(Messenger m) {
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
index 2fa146408b..c114b8a64a 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadThread.java
@@ -40,435 +40,447 @@ import java.util.Locale;
*/
public class DownloadThread {
- private Context mContext;
- private DownloadInfo mInfo;
- private DownloaderService mService;
- private final DownloadsDB mDB;
- private final DownloadNotification mNotification;
- private String mUserAgent;
-
- public DownloadThread(DownloadInfo info, DownloaderService service,
- DownloadNotification notification) {
- mContext = service;
- mInfo = info;
- mService = service;
- mNotification = notification;
- mDB = DownloadsDB.getDB(service);
- mUserAgent = "APKXDL (Linux; U; Android " + android.os.Build.VERSION.RELEASE + ";" + Locale.getDefault().toString() + "; " + android.os.Build.DEVICE + "/" + android.os.Build.ID + ")" +
- service.getPackageName();
- }
-
- /**
+ private Context mContext;
+ private DownloadInfo mInfo;
+ private DownloaderService mService;
+ private final DownloadsDB mDB;
+ private final DownloadNotification mNotification;
+ private String mUserAgent;
+
+ public DownloadThread(DownloadInfo info, DownloaderService service,
+ DownloadNotification notification) {
+ mContext = service;
+ mInfo = info;
+ mService = service;
+ mNotification = notification;
+ mDB = DownloadsDB.getDB(service);
+ mUserAgent = "APKXDL (Linux; U; Android " + android.os.Build.VERSION.RELEASE + ";"
+ + Locale.getDefault().toString() + "; " + android.os.Build.DEVICE + "/"
+ + android.os.Build.ID + ")" +
+ service.getPackageName();
+ }
+
+ /**
* Returns the default user agent
*/
- private String userAgent() {
- return mUserAgent;
- }
+ private String userAgent() {
+ return mUserAgent;
+ }
- /**
+ /**
* State for the entire run() method.
*/
- private static class State {
- public String mFilename;
- public FileOutputStream mStream;
- public boolean mCountRetry = false;
- public int mRetryAfter = 0;
- public int mRedirectCount = 0;
- public String mNewUri;
- public boolean mGotData = false;
- public String mRequestUri;
-
- public State(DownloadInfo info, DownloaderService service) {
- mRedirectCount = info.mRedirectCount;
- mRequestUri = info.mUri;
- mFilename = service.generateTempSaveFileName(info.mFileName);
- }
- }
-
- /**
+ private static class State {
+ public String mFilename;
+ public FileOutputStream mStream;
+ public boolean mCountRetry = false;
+ public int mRetryAfter = 0;
+ public int mRedirectCount = 0;
+ public String mNewUri;
+ public boolean mGotData = false;
+ public String mRequestUri;
+
+ public State(DownloadInfo info, DownloaderService service) {
+ mRedirectCount = info.mRedirectCount;
+ mRequestUri = info.mUri;
+ mFilename = service.generateTempSaveFileName(info.mFileName);
+ }
+ }
+
+ /**
* State within executeDownload()
*/
- private static class InnerState {
- public int mBytesSoFar = 0;
- public int mBytesThisSession = 0;
- public String mHeaderETag;
- public boolean mContinuingDownload = false;
- public String mHeaderContentLength;
- public String mHeaderContentDisposition;
- public String mHeaderContentLocation;
- public int mBytesNotified = 0;
- public long mTimeLastNotification = 0;
- }
-
- /**
+ private static class InnerState {
+ public int mBytesSoFar = 0;
+ public int mBytesThisSession = 0;
+ public String mHeaderETag;
+ public boolean mContinuingDownload = false;
+ public String mHeaderContentLength;
+ public String mHeaderContentDisposition;
+ public String mHeaderContentLocation;
+ public int mBytesNotified = 0;
+ public long mTimeLastNotification = 0;
+ }
+
+ /**
* Raised from methods called by run() to indicate that the current request
* should be stopped immediately. Note the message passed to this exception
* will be logged and therefore must be guaranteed not to contain any PII,
* meaning it generally can't include any information about the request URI,
* headers, or destination filename.
*/
- private class StopRequest extends Throwable {
-
- private static final long serialVersionUID = 6338592678988347973L;
- public int mFinalStatus;
-
- public StopRequest(int finalStatus, String message) {
- super(message);
- mFinalStatus = finalStatus;
- }
-
- public StopRequest(int finalStatus, String message, Throwable throwable) {
- super(message, throwable);
- mFinalStatus = finalStatus;
- }
- }
-
- /**
+ private class StopRequest extends Throwable {
+
+ private static final long serialVersionUID = 6338592678988347973L;
+ public int mFinalStatus;
+
+ public StopRequest(int finalStatus, String message) {
+ super(message);
+ mFinalStatus = finalStatus;
+ }
+
+ public StopRequest(int finalStatus, String message, Throwable throwable) {
+ super(message, throwable);
+ mFinalStatus = finalStatus;
+ }
+ }
+
+ /**
* Raised from methods called by executeDownload() to indicate that the
* download should be retried immediately.
*/
- private class RetryDownload extends Throwable {
+ private class RetryDownload extends Throwable {
- private static final long serialVersionUID = 6196036036517540229L;
- }
+ private static final long serialVersionUID = 6196036036517540229L;
+ }
- /**
+ /**
* Executes the download in a separate thread
*/
- public void run() {
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
-
- State state = new State(mInfo, mService);
- PowerManager.WakeLock wakeLock = null;
- int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
-
- try {
- PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
- wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "org.godot.game:wakelock");
- wakeLock.acquire(20 * 60 * 1000L /*20 minutes*/);
-
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
- Log.v(Constants.TAG, " at " + mInfo.mUri);
- }
-
- boolean finished = false;
- while (!finished) {
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
- Log.v(Constants.TAG, " at " + mInfo.mUri);
- }
- // Set or unset proxy, which may have changed since last GET
- // request.
- // setDefaultProxy() supports null as proxy parameter.
- URL url = new URL(state.mRequestUri);
- HttpURLConnection request = (HttpURLConnection)url.openConnection();
- request.setRequestProperty("User-Agent", userAgent());
- try {
- executeDownload(state, request);
- finished = true;
- } catch (RetryDownload exc) {
- // fall through
- } finally {
- request.disconnect();
- request = null;
- }
- }
-
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
- Log.v(Constants.TAG, " at " + mInfo.mUri);
- }
- finalizeDestinationFile(state);
- finalStatus = DownloaderService.STATUS_SUCCESS;
- } catch (StopRequest error) {
- // remove the cause before printing, in case it contains PII
- Log.w(Constants.TAG,
- "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
- error.printStackTrace();
- finalStatus = error.mFinalStatus;
- // fall through to finally block
- } catch (Throwable ex) { // sometimes the socket code throws unchecked
- // exceptions
- Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
- finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
- // falls through to the code that reports an error
- } finally {
- if (wakeLock != null) {
- wakeLock.release();
- wakeLock = null;
- }
- cleanupDestination(state, finalStatus);
- notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
- state.mRedirectCount, state.mGotData, state.mFilename);
- }
- }
-
- /**
+ public void run() {
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+
+ State state = new State(mInfo, mService);
+ PowerManager.WakeLock wakeLock = null;
+ int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
+
+ try {
+ PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+ // -- GODOT start --
+ //wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
+ //wakeLock.acquire();
+ wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "org.godot.game:wakelock");
+ wakeLock.acquire(20 * 60 * 1000L /*20 minutes*/);
+ // -- GODOT end --
+
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
+ Log.v(Constants.TAG, " at " + mInfo.mUri);
+ }
+
+ boolean finished = false;
+ while (!finished) {
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
+ Log.v(Constants.TAG, " at " + mInfo.mUri);
+ }
+ // Set or unset proxy, which may have changed since last GET
+ // request.
+ // setDefaultProxy() supports null as proxy parameter.
+ URL url = new URL(state.mRequestUri);
+ HttpURLConnection request = (HttpURLConnection)url.openConnection();
+ request.setRequestProperty("User-Agent", userAgent());
+ try {
+ executeDownload(state, request);
+ finished = true;
+ } catch (RetryDownload exc) {
+ // fall through
+ } finally {
+ request.disconnect();
+ request = null;
+ }
+ }
+
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
+ Log.v(Constants.TAG, " at " + mInfo.mUri);
+ }
+ finalizeDestinationFile(state);
+ finalStatus = DownloaderService.STATUS_SUCCESS;
+ } catch (StopRequest error) {
+ // remove the cause before printing, in case it contains PII
+ Log.w(Constants.TAG,
+ "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
+ error.printStackTrace();
+ finalStatus = error.mFinalStatus;
+ // fall through to finally block
+ } catch (Throwable ex) { // sometimes the socket code throws unchecked
+ // exceptions
+ Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
+ finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
+ // falls through to the code that reports an error
+ } finally {
+ if (wakeLock != null) {
+ wakeLock.release();
+ wakeLock = null;
+ }
+ cleanupDestination(state, finalStatus);
+ notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
+ state.mRedirectCount, state.mGotData, state.mFilename);
+ }
+ }
+
+ /**
* Fully execute a single download request - setup and send the request,
* handle the response, and transfer the data to the destination file.
*/
- private void executeDownload(State state, HttpURLConnection request)
- throws StopRequest, RetryDownload {
- InnerState innerState = new InnerState();
- byte data[] = new byte[Constants.BUFFER_SIZE];
+ private void executeDownload(State state, HttpURLConnection request)
+ throws StopRequest, RetryDownload {
+ InnerState innerState = new InnerState();
+ byte data[] = new byte[Constants.BUFFER_SIZE];
- checkPausedOrCanceled(state);
+ checkPausedOrCanceled(state);
- setupDestinationFile(state, innerState);
- addRequestHeaders(innerState, request);
+ setupDestinationFile(state, innerState);
+ addRequestHeaders(innerState, request);
- // check just before sending the request to avoid using an invalid
- // connection at all
- checkConnectivity(state);
+ // check just before sending the request to avoid using an invalid
+ // connection at all
+ checkConnectivity(state);
- mNotification.onDownloadStateChanged(IDownloaderClient.STATE_CONNECTING);
- int responseCode = sendRequest(state, request);
- handleExceptionalStatus(state, innerState, request, responseCode);
+ mNotification.onDownloadStateChanged(IDownloaderClient.STATE_CONNECTING);
+ int responseCode = sendRequest(state, request);
+ handleExceptionalStatus(state, innerState, request, responseCode);
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "received response for " + mInfo.mUri);
- }
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "received response for " + mInfo.mUri);
+ }
- processResponseHeaders(state, innerState, request);
- InputStream entityStream = openResponseEntity(state, request);
- mNotification.onDownloadStateChanged(IDownloaderClient.STATE_DOWNLOADING);
- transferData(state, innerState, data, entityStream);
- }
+ processResponseHeaders(state, innerState, request);
+ InputStream entityStream = openResponseEntity(state, request);
+ mNotification.onDownloadStateChanged(IDownloaderClient.STATE_DOWNLOADING);
+ transferData(state, innerState, data, entityStream);
+ }
- /**
+ /**
* Check if current connectivity is valid for this request.
*/
- private void checkConnectivity(State state) throws StopRequest {
- switch (mService.getNetworkAvailabilityState(mDB)) {
- case DownloaderService.NETWORK_OK:
- return;
- case DownloaderService.NETWORK_NO_CONNECTION:
- throw new StopRequest(DownloaderService.STATUS_WAITING_FOR_NETWORK,
- "waiting for network to return");
- case DownloaderService.NETWORK_TYPE_DISALLOWED_BY_REQUESTOR:
- throw new StopRequest(
- DownloaderService.STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION,
- "waiting for wifi or for download over cellular to be authorized");
- case DownloaderService.NETWORK_CANNOT_USE_ROAMING:
- throw new StopRequest(DownloaderService.STATUS_WAITING_FOR_NETWORK,
- "roaming is not allowed");
- case DownloaderService.NETWORK_UNUSABLE_DUE_TO_SIZE:
- throw new StopRequest(DownloaderService.STATUS_QUEUED_FOR_WIFI, "waiting for wifi");
- }
- }
-
- /**
+ private void checkConnectivity(State state) throws StopRequest {
+ switch (mService.getNetworkAvailabilityState(mDB)) {
+ case DownloaderService.NETWORK_OK:
+ return;
+ case DownloaderService.NETWORK_NO_CONNECTION:
+ throw new StopRequest(DownloaderService.STATUS_WAITING_FOR_NETWORK,
+ "waiting for network to return");
+ case DownloaderService.NETWORK_TYPE_DISALLOWED_BY_REQUESTOR:
+ throw new StopRequest(
+ DownloaderService.STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION,
+ "waiting for wifi or for download over cellular to be authorized");
+ case DownloaderService.NETWORK_CANNOT_USE_ROAMING:
+ throw new StopRequest(DownloaderService.STATUS_WAITING_FOR_NETWORK,
+ "roaming is not allowed");
+ case DownloaderService.NETWORK_UNUSABLE_DUE_TO_SIZE:
+ throw new StopRequest(DownloaderService.STATUS_QUEUED_FOR_WIFI, "waiting for wifi");
+ }
+ }
+
+ /**
* Transfer as much data as possible from the HTTP response to the
* destination file.
*
* @param data buffer to use to read data
* @param entityStream stream for reading the HTTP response entity
*/
- private void transferData(State state, InnerState innerState, byte[] data,
- InputStream entityStream) throws StopRequest {
- for (;;) {
- int bytesRead = readFromResponse(state, innerState, data, entityStream);
- if (bytesRead == -1) { // success, end of stream already reached
- handleEndOfStream(state, innerState);
- return;
- }
-
- state.mGotData = true;
- writeDataToDestination(state, data, bytesRead);
- innerState.mBytesSoFar += bytesRead;
- innerState.mBytesThisSession += bytesRead;
- reportProgress(state, innerState);
-
- checkPausedOrCanceled(state);
- }
- }
-
- /**
+ private void transferData(State state, InnerState innerState, byte[] data,
+ InputStream entityStream) throws StopRequest {
+ for (;;) {
+ int bytesRead = readFromResponse(state, innerState, data, entityStream);
+ if (bytesRead == -1) { // success, end of stream already reached
+ handleEndOfStream(state, innerState);
+ return;
+ }
+
+ state.mGotData = true;
+ writeDataToDestination(state, data, bytesRead);
+ innerState.mBytesSoFar += bytesRead;
+ innerState.mBytesThisSession += bytesRead;
+ reportProgress(state, innerState);
+
+ checkPausedOrCanceled(state);
+ }
+ }
+
+ /**
* Called after a successful completion to take any necessary action on the
* downloaded file.
*/
- private void finalizeDestinationFile(State state) throws StopRequest {
- syncDestination(state);
- String tempFilename = state.mFilename;
- String finalFilename = Helpers.generateSaveFileName(mService, mInfo.mFileName);
- if (!state.mFilename.equals(finalFilename)) {
- File startFile = new File(tempFilename);
- File destFile = new File(finalFilename);
- if (mInfo.mTotalBytes != -1 && mInfo.mCurrentBytes == mInfo.mTotalBytes) {
- if (!startFile.renameTo(destFile)) {
- throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
- "unable to finalize destination file");
- }
- } else {
- throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
- "file delivered with incorrect size. probably due to network not browser configured");
- }
- }
- }
-
- /**
+ private void finalizeDestinationFile(State state) throws StopRequest {
+ syncDestination(state);
+ String tempFilename = state.mFilename;
+ String finalFilename = Helpers.generateSaveFileName(mService, mInfo.mFileName);
+ if (!state.mFilename.equals(finalFilename)) {
+ File startFile = new File(tempFilename);
+ File destFile = new File(finalFilename);
+ if (mInfo.mTotalBytes != -1 && mInfo.mCurrentBytes == mInfo.mTotalBytes) {
+ if (!startFile.renameTo(destFile)) {
+ throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
+ "unable to finalize destination file");
+ }
+ } else {
+ throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
+ "file delivered with incorrect size. probably due to network not browser configured");
+ }
+ }
+ }
+
+ /**
* Called just before the thread finishes, regardless of status, to take any
* necessary action on the downloaded file.
*/
- private void cleanupDestination(State state, int finalStatus) {
- closeDestination(state);
- if (state.mFilename != null && DownloaderService.isStatusError(finalStatus)) {
- new File(state.mFilename).delete();
- state.mFilename = null;
- }
- }
-
- /**
+ private void cleanupDestination(State state, int finalStatus) {
+ closeDestination(state);
+ if (state.mFilename != null && DownloaderService.isStatusError(finalStatus)) {
+ new File(state.mFilename).delete();
+ state.mFilename = null;
+ }
+ }
+
+ /**
* Sync the destination file to storage.
*/
- private void syncDestination(State state) {
- FileOutputStream downloadedFileStream = null;
- try {
- downloadedFileStream = new FileOutputStream(state.mFilename, true);
- downloadedFileStream.getFD().sync();
- } catch (FileNotFoundException ex) {
- Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex);
- } catch (SyncFailedException ex) {
- Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex);
- } catch (IOException ex) {
- Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex);
- } catch (RuntimeException ex) {
- Log.w(Constants.TAG, "exception while syncing file: ", ex);
- } finally {
- if (downloadedFileStream != null) {
- try {
- downloadedFileStream.close();
- } catch (IOException ex) {
- Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
- } catch (RuntimeException ex) {
- Log.w(Constants.TAG, "exception while closing file: ", ex);
- }
- }
- }
- }
-
- /**
+ private void syncDestination(State state) {
+ FileOutputStream downloadedFileStream = null;
+ try {
+ downloadedFileStream = new FileOutputStream(state.mFilename, true);
+ downloadedFileStream.getFD().sync();
+ } catch (FileNotFoundException ex) {
+ Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex);
+ } catch (SyncFailedException ex) {
+ Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex);
+ } catch (IOException ex) {
+ Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex);
+ } catch (RuntimeException ex) {
+ Log.w(Constants.TAG, "exception while syncing file: ", ex);
+ } finally {
+ if (downloadedFileStream != null) {
+ try {
+ downloadedFileStream.close();
+ } catch (IOException ex) {
+ Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
+ } catch (RuntimeException ex) {
+ Log.w(Constants.TAG, "exception while closing file: ", ex);
+ }
+ }
+ }
+ }
+
+ /**
* Close the destination output stream.
*/
- private void closeDestination(State state) {
- try {
- // close the file
- if (state.mStream != null) {
- state.mStream.close();
- state.mStream = null;
- }
- } catch (IOException ex) {
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "exception when closing the file after download : " + ex);
- }
- // nothing can really be done if the file can't be closed
- }
- }
-
- /**
+ private void closeDestination(State state) {
+ try {
+ // close the file
+ if (state.mStream != null) {
+ state.mStream.close();
+ state.mStream = null;
+ }
+ } catch (IOException ex) {
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "exception when closing the file after download : " + ex);
+ }
+ // nothing can really be done if the file can't be closed
+ }
+ }
+
+ /**
* Check if the download has been paused or canceled, stopping the request
* appropriately if it has been.
*/
- private void checkPausedOrCanceled(State state) throws StopRequest {
- if (mService.getControl() == DownloaderService.CONTROL_PAUSED) {
- int status = mService.getStatus();
- switch (status) {
- case DownloaderService.STATUS_PAUSED_BY_APP:
- throw new StopRequest(mService.getStatus(),
- "download paused");
- }
- }
- }
-
- /**
+ private void checkPausedOrCanceled(State state) throws StopRequest {
+ if (mService.getControl() == DownloaderService.CONTROL_PAUSED) {
+ int status = mService.getStatus();
+ switch (status) {
+ case DownloaderService.STATUS_PAUSED_BY_APP:
+ throw new StopRequest(mService.getStatus(),
+ "download paused");
+ }
+ }
+ }
+
+ /**
* Report download progress through the database if necessary.
*/
- private void reportProgress(State state, InnerState innerState) {
- long now = System.currentTimeMillis();
- if (innerState.mBytesSoFar - innerState.mBytesNotified > Constants.MIN_PROGRESS_STEP && now - innerState.mTimeLastNotification > Constants.MIN_PROGRESS_TIME) {
- // we store progress updates to the database here
- mInfo.mCurrentBytes = innerState.mBytesSoFar;
- mDB.updateDownloadCurrentBytes(mInfo);
-
- innerState.mBytesNotified = innerState.mBytesSoFar;
- innerState.mTimeLastNotification = now;
-
- long totalBytesSoFar = innerState.mBytesThisSession + mService.mBytesSoFar;
-
- if (Constants.LOGVV) {
- Log.v(Constants.TAG, "downloaded " + mInfo.mCurrentBytes + " out of " + mInfo.mTotalBytes);
- Log.v(Constants.TAG, " total " + totalBytesSoFar + " out of " + mService.mTotalLength);
- }
-
- mService.notifyUpdateBytes(totalBytesSoFar);
- }
- }
-
- /**
+ private void reportProgress(State state, InnerState innerState) {
+ long now = System.currentTimeMillis();
+ if (innerState.mBytesSoFar - innerState.mBytesNotified
+ > Constants.MIN_PROGRESS_STEP
+ && now - innerState.mTimeLastNotification
+ > Constants.MIN_PROGRESS_TIME) {
+ // we store progress updates to the database here
+ mInfo.mCurrentBytes = innerState.mBytesSoFar;
+ mDB.updateDownloadCurrentBytes(mInfo);
+
+ innerState.mBytesNotified = innerState.mBytesSoFar;
+ innerState.mTimeLastNotification = now;
+
+ long totalBytesSoFar = innerState.mBytesThisSession + mService.mBytesSoFar;
+
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG, "downloaded " + mInfo.mCurrentBytes + " out of "
+ + mInfo.mTotalBytes);
+ Log.v(Constants.TAG, " total " + totalBytesSoFar + " out of "
+ + mService.mTotalLength);
+ }
+
+ mService.notifyUpdateBytes(totalBytesSoFar);
+ }
+ }
+
+ /**
* Write a data buffer to the destination file.
*
* @param data buffer containing the data to write
* @param bytesRead how many bytes to write from the buffer
*/
- private void writeDataToDestination(State state, byte[] data, int bytesRead)
- throws StopRequest {
- for (;;) {
- try {
- if (state.mStream == null) {
- state.mStream = new FileOutputStream(state.mFilename, true);
- }
- state.mStream.write(data, 0, bytesRead);
- // we close after every write --- this may be too inefficient
- closeDestination(state);
- return;
- } catch (IOException ex) {
- if (!Helpers.isExternalMediaMounted()) {
- throw new StopRequest(DownloaderService.STATUS_DEVICE_NOT_FOUND_ERROR,
- "external media not mounted while writing destination file");
- }
-
- long availableBytes =
- Helpers.getAvailableBytes(Helpers.getFilesystemRoot(state.mFilename));
- if (availableBytes < bytesRead) {
- throw new StopRequest(DownloaderService.STATUS_INSUFFICIENT_SPACE_ERROR,
- "insufficient space while writing destination file", ex);
- }
- throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
- "while writing destination file: " + ex.toString(), ex);
- }
- }
- }
-
- /**
+ private void writeDataToDestination(State state, byte[] data, int bytesRead)
+ throws StopRequest {
+ for (;;) {
+ try {
+ if (state.mStream == null) {
+ state.mStream = new FileOutputStream(state.mFilename, true);
+ }
+ state.mStream.write(data, 0, bytesRead);
+ // we close after every write --- this may be too inefficient
+ closeDestination(state);
+ return;
+ } catch (IOException ex) {
+ if (!Helpers.isExternalMediaMounted()) {
+ throw new StopRequest(DownloaderService.STATUS_DEVICE_NOT_FOUND_ERROR,
+ "external media not mounted while writing destination file");
+ }
+
+ long availableBytes =
+ Helpers.getAvailableBytes(Helpers.getFilesystemRoot(state.mFilename));
+ if (availableBytes < bytesRead) {
+ throw new StopRequest(DownloaderService.STATUS_INSUFFICIENT_SPACE_ERROR,
+ "insufficient space while writing destination file", ex);
+ }
+ throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
+ "while writing destination file: " + ex.toString(), ex);
+ }
+ }
+ }
+
+ /**
* Called when we've reached the end of the HTTP response stream, to update
* the database and check for consistency.
*/
- private void handleEndOfStream(State state, InnerState innerState) throws StopRequest {
- mInfo.mCurrentBytes = innerState.mBytesSoFar;
- // this should always be set from the market
- // if ( innerState.mHeaderContentLength == null ) {
- // mInfo.mTotalBytes = innerState.mBytesSoFar;
- // }
- mDB.updateDownload(mInfo);
-
- boolean lengthMismatched = (innerState.mHeaderContentLength != null) && (innerState.mBytesSoFar != Integer.parseInt(innerState.mHeaderContentLength));
- if (lengthMismatched) {
- if (cannotResume(innerState)) {
- throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
- "mismatched content length");
- } else {
- throw new StopRequest(getFinalStatusForHttpError(state),
- "closed socket before end of file");
- }
- }
- }
-
- private boolean cannotResume(InnerState innerState) {
- return innerState.mBytesSoFar > 0 && innerState.mHeaderETag == null;
- }
-
- /**
+ private void handleEndOfStream(State state, InnerState innerState) throws StopRequest {
+ mInfo.mCurrentBytes = innerState.mBytesSoFar;
+ // this should always be set from the market
+ // if ( innerState.mHeaderContentLength == null ) {
+ // mInfo.mTotalBytes = innerState.mBytesSoFar;
+ // }
+ mDB.updateDownload(mInfo);
+
+ boolean lengthMismatched = (innerState.mHeaderContentLength != null)
+ && (innerState.mBytesSoFar != Integer.parseInt(innerState.mHeaderContentLength));
+ if (lengthMismatched) {
+ if (cannotResume(innerState)) {
+ throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
+ "mismatched content length");
+ } else {
+ throw new StopRequest(getFinalStatusForHttpError(state),
+ "closed socket before end of file");
+ }
+ }
+ }
+
+ private boolean cannotResume(InnerState innerState) {
+ return innerState.mBytesSoFar > 0 && innerState.mHeaderETag == null;
+ }
+
+ /**
* Read some data from the HTTP response stream, handling I/O errors.
*
* @param data buffer to use to read data
@@ -476,358 +488,365 @@ public class DownloadThread {
* @return the number of bytes actually read or -1 if the end of the stream
* has been reached
*/
- private int readFromResponse(State state, InnerState innerState, byte[] data,
- InputStream entityStream) throws StopRequest {
- try {
- return entityStream.read(data);
- } catch (IOException ex) {
- logNetworkState();
- mInfo.mCurrentBytes = innerState.mBytesSoFar;
- mDB.updateDownload(mInfo);
- if (cannotResume(innerState)) {
- String message = "while reading response: " + ex.toString() + ", can't resume interrupted download with no ETag";
- throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
- message, ex);
- } else {
- throw new StopRequest(getFinalStatusForHttpError(state),
- "while reading response: " + ex.toString(), ex);
- }
- }
- }
-
- /**
+ private int readFromResponse(State state, InnerState innerState, byte[] data,
+ InputStream entityStream) throws StopRequest {
+ try {
+ return entityStream.read(data);
+ } catch (IOException ex) {
+ logNetworkState();
+ mInfo.mCurrentBytes = innerState.mBytesSoFar;
+ mDB.updateDownload(mInfo);
+ if (cannotResume(innerState)) {
+ String message = "while reading response: " + ex.toString()
+ + ", can't resume interrupted download with no ETag";
+ throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
+ message, ex);
+ } else {
+ throw new StopRequest(getFinalStatusForHttpError(state),
+ "while reading response: " + ex.toString(), ex);
+ }
+ }
+ }
+
+ /**
* Open a stream for the HTTP response entity, handling I/O errors.
*
* @return an InputStream to read the response entity
*/
- private InputStream openResponseEntity(State state, HttpURLConnection response)
- throws StopRequest {
- try {
- return response.getInputStream();
- } catch (IOException ex) {
- logNetworkState();
- throw new StopRequest(getFinalStatusForHttpError(state),
- "while getting entity: " + ex.toString(), ex);
- }
- }
-
- private void logNetworkState() {
- if (Constants.LOGX) {
- Log.i(Constants.TAG,
- "Net " + (mService.getNetworkAvailabilityState(mDB) == DownloaderService.NETWORK_OK ? "Up" : "Down"));
- }
- }
-
- /**
+ private InputStream openResponseEntity(State state, HttpURLConnection response)
+ throws StopRequest {
+ try {
+ return response.getInputStream();
+ } catch (IOException ex) {
+ logNetworkState();
+ throw new StopRequest(getFinalStatusForHttpError(state),
+ "while getting entity: " + ex.toString(), ex);
+ }
+ }
+
+ private void logNetworkState() {
+ if (Constants.LOGX) {
+ Log.i(Constants.TAG,
+ "Net "
+ + (mService.getNetworkAvailabilityState(mDB) == DownloaderService.NETWORK_OK ? "Up"
+ : "Down"));
+ }
+ }
+
+ /**
* Read HTTP response headers and take appropriate action, including setting
* up the destination file and updating the database.
*/
- private void processResponseHeaders(State state, InnerState innerState, HttpURLConnection response)
- throws StopRequest {
- if (innerState.mContinuingDownload) {
- // ignore response headers on resume requests
- return;
- }
-
- readResponseHeaders(state, innerState, response);
-
- try {
- state.mFilename = mService.generateSaveFile(mInfo.mFileName, mInfo.mTotalBytes);
- } catch (DownloaderService.GenerateSaveFileError exc) {
- throw new StopRequest(exc.mStatus, exc.mMessage);
- }
- try {
- state.mStream = new FileOutputStream(state.mFilename);
- } catch (FileNotFoundException exc) {
- // make sure the directory exists
- File pathFile = new File(Helpers.getSaveFilePath(mService));
- try {
- if (pathFile.mkdirs()) {
- state.mStream = new FileOutputStream(state.mFilename);
- }
- } catch (Exception ex) {
- throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
- "while opening destination file: " + exc.toString(), exc);
- }
- }
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + state.mFilename);
- }
-
- updateDatabaseFromHeaders(state, innerState);
- // check connectivity again now that we know the total size
- checkConnectivity(state);
- }
-
- /**
+ private void processResponseHeaders(State state, InnerState innerState, HttpURLConnection response)
+ throws StopRequest {
+ if (innerState.mContinuingDownload) {
+ // ignore response headers on resume requests
+ return;
+ }
+
+ readResponseHeaders(state, innerState, response);
+
+ try {
+ state.mFilename = mService.generateSaveFile(mInfo.mFileName, mInfo.mTotalBytes);
+ } catch (DownloaderService.GenerateSaveFileError exc) {
+ throw new StopRequest(exc.mStatus, exc.mMessage);
+ }
+ try {
+ state.mStream = new FileOutputStream(state.mFilename);
+ } catch (FileNotFoundException exc) {
+ // make sure the directory exists
+ File pathFile = new File(Helpers.getSaveFilePath(mService));
+ try {
+ if (pathFile.mkdirs()) {
+ state.mStream = new FileOutputStream(state.mFilename);
+ }
+ } catch (Exception ex) {
+ throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
+ "while opening destination file: " + exc.toString(), exc);
+ }
+ }
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + state.mFilename);
+ }
+
+ updateDatabaseFromHeaders(state, innerState);
+ // check connectivity again now that we know the total size
+ checkConnectivity(state);
+ }
+
+ /**
* Update necessary database fields based on values of HTTP response headers
* that have been read.
*/
- private void updateDatabaseFromHeaders(State state, InnerState innerState) {
- mInfo.mETag = innerState.mHeaderETag;
- mDB.updateDownload(mInfo);
- }
+ private void updateDatabaseFromHeaders(State state, InnerState innerState) {
+ mInfo.mETag = innerState.mHeaderETag;
+ mDB.updateDownload(mInfo);
+ }
- /**
+ /**
* Read headers from the HTTP response and store them into local state.
*/
- private void readResponseHeaders(State state, InnerState innerState, HttpURLConnection response)
- throws StopRequest {
- String value = response.getHeaderField("Content-Disposition");
- if (value != null) {
- innerState.mHeaderContentDisposition = value;
- }
- value = response.getHeaderField("Content-Location");
- if (value != null) {
- innerState.mHeaderContentLocation = value;
- }
- value = response.getHeaderField("ETag");
- if (value != null) {
- innerState.mHeaderETag = value;
- }
- String headerTransferEncoding = null;
- value = response.getHeaderField("Transfer-Encoding");
- if (value != null) {
- headerTransferEncoding = value;
- }
- String headerContentType = null;
- value = response.getHeaderField("Content-Type");
- if (value != null) {
- headerContentType = value;
- if (!headerContentType.equals("application/vnd.android.obb")) {
- throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
- "file delivered with incorrect Mime type");
- }
- }
-
- if (headerTransferEncoding == null) {
- long contentLength = response.getContentLength();
- if (value != null) {
- // this is always set from Market
- if (contentLength != -1 && contentLength != mInfo.mTotalBytes) {
- // we're most likely on a bad wifi connection -- we should
- // probably
- // also look at the mime type --- but the size mismatch is
- // enough
- // to tell us that something is wrong here
- Log.e(Constants.TAG, "Incorrect file size delivered.");
- } else {
- innerState.mHeaderContentLength = Long.toString(contentLength);
- }
- }
- } else {
- // Ignore content-length with transfer-encoding - 2616 4.4 3
- if (Constants.LOGVV) {
- Log.v(Constants.TAG,
- "ignoring content-length because of xfer-encoding");
- }
- }
- if (Constants.LOGVV) {
- Log.v(Constants.TAG, "Content-Disposition: " +
- innerState.mHeaderContentDisposition);
- Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
- Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
- Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
- Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
- }
-
- boolean noSizeInfo = innerState.mHeaderContentLength == null && (headerTransferEncoding == null || !headerTransferEncoding.equalsIgnoreCase("chunked"));
- if (noSizeInfo) {
- throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
- "can't know size of download, giving up");
- }
- }
-
- /**
+ private void readResponseHeaders(State state, InnerState innerState, HttpURLConnection response)
+ throws StopRequest {
+ String value = response.getHeaderField("Content-Disposition");
+ if (value != null) {
+ innerState.mHeaderContentDisposition = value;
+ }
+ value = response.getHeaderField("Content-Location");
+ if (value != null) {
+ innerState.mHeaderContentLocation = value;
+ }
+ value = response.getHeaderField("ETag");
+ if (value != null) {
+ innerState.mHeaderETag = value;
+ }
+ String headerTransferEncoding = null;
+ value = response.getHeaderField("Transfer-Encoding");
+ if (value != null) {
+ headerTransferEncoding = value;
+ }
+ String headerContentType = null;
+ value = response.getHeaderField("Content-Type");
+ if (value != null) {
+ headerContentType = value;
+ if (!headerContentType.equals("application/vnd.android.obb")) {
+ throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
+ "file delivered with incorrect Mime type");
+ }
+ }
+
+ if (headerTransferEncoding == null) {
+ long contentLength = response.getContentLength();
+ if (value != null) {
+ // this is always set from Market
+ if (contentLength != -1 && contentLength != mInfo.mTotalBytes) {
+ // we're most likely on a bad wifi connection -- we should
+ // probably
+ // also look at the mime type --- but the size mismatch is
+ // enough
+ // to tell us that something is wrong here
+ Log.e(Constants.TAG, "Incorrect file size delivered.");
+ } else {
+ innerState.mHeaderContentLength = Long.toString(contentLength);
+ }
+ }
+ } else {
+ // Ignore content-length with transfer-encoding - 2616 4.4 3
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG,
+ "ignoring content-length because of xfer-encoding");
+ }
+ }
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG, "Content-Disposition: " +
+ innerState.mHeaderContentDisposition);
+ Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
+ Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
+ Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
+ Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
+ }
+
+ boolean noSizeInfo = innerState.mHeaderContentLength == null
+ && (headerTransferEncoding == null
+ || !headerTransferEncoding.equalsIgnoreCase("chunked"));
+ if (noSizeInfo) {
+ throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
+ "can't know size of download, giving up");
+ }
+ }
+
+ /**
* Check the HTTP response status and handle anything unusual (e.g. not
* 200/206).
*/
- private void handleExceptionalStatus(State state, InnerState innerState, HttpURLConnection connection, int responseCode)
- throws StopRequest, RetryDownload {
- if (responseCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
- handleServiceUnavailable(state, connection);
- }
- int expectedStatus = innerState.mContinuingDownload ? 206 : DownloaderService.STATUS_SUCCESS;
- if (responseCode != expectedStatus) {
- handleOtherStatus(state, innerState, responseCode);
- } else {
- // no longer redirected
- state.mRedirectCount = 0;
- }
- }
-
- /**
+ private void handleExceptionalStatus(State state, InnerState innerState, HttpURLConnection connection, int responseCode)
+ throws StopRequest, RetryDownload {
+ if (responseCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
+ handleServiceUnavailable(state, connection);
+ }
+ int expectedStatus = innerState.mContinuingDownload ? 206
+ : DownloaderService.STATUS_SUCCESS;
+ if (responseCode != expectedStatus) {
+ handleOtherStatus(state, innerState, responseCode);
+ } else {
+ // no longer redirected
+ state.mRedirectCount = 0;
+ }
+ }
+
+ /**
* Handle a status that we don't know how to deal with properly.
*/
- private void handleOtherStatus(State state, InnerState innerState, int statusCode)
- throws StopRequest {
- int finalStatus;
- if (DownloaderService.isStatusError(statusCode)) {
- finalStatus = statusCode;
- } else if (statusCode >= 300 && statusCode < 400) {
- finalStatus = DownloaderService.STATUS_UNHANDLED_REDIRECT;
- } else if (innerState.mContinuingDownload && statusCode == DownloaderService.STATUS_SUCCESS) {
- finalStatus = DownloaderService.STATUS_CANNOT_RESUME;
- } else {
- finalStatus = DownloaderService.STATUS_UNHANDLED_HTTP_CODE;
- }
- throw new StopRequest(finalStatus, "http error " + statusCode);
- }
-
- /**
+ private void handleOtherStatus(State state, InnerState innerState, int statusCode)
+ throws StopRequest {
+ int finalStatus;
+ if (DownloaderService.isStatusError(statusCode)) {
+ finalStatus = statusCode;
+ } else if (statusCode >= 300 && statusCode < 400) {
+ finalStatus = DownloaderService.STATUS_UNHANDLED_REDIRECT;
+ } else if (innerState.mContinuingDownload && statusCode == DownloaderService.STATUS_SUCCESS) {
+ finalStatus = DownloaderService.STATUS_CANNOT_RESUME;
+ } else {
+ finalStatus = DownloaderService.STATUS_UNHANDLED_HTTP_CODE;
+ }
+ throw new StopRequest(finalStatus, "http error " + statusCode);
+ }
+
+ /**
* Add headers for this download to the HTTP request to allow for resume.
*/
- private void addRequestHeaders(InnerState innerState, HttpURLConnection request) {
- if (innerState.mContinuingDownload) {
- if (innerState.mHeaderETag != null) {
- request.setRequestProperty("If-Match", innerState.mHeaderETag);
- }
- request.setRequestProperty("Range", "bytes=" + innerState.mBytesSoFar + "-");
- }
- }
-
- /**
+ private void addRequestHeaders(InnerState innerState, HttpURLConnection request) {
+ if (innerState.mContinuingDownload) {
+ if (innerState.mHeaderETag != null) {
+ request.setRequestProperty("If-Match", innerState.mHeaderETag);
+ }
+ request.setRequestProperty("Range", "bytes=" + innerState.mBytesSoFar + "-");
+ }
+ }
+
+ /**
* Handle a 503 Service Unavailable status by processing the Retry-After
* header.
*/
- private void handleServiceUnavailable(State state, HttpURLConnection connection) throws StopRequest {
- if (Constants.LOGVV) {
- Log.v(Constants.TAG, "got HTTP response code 503");
- }
- state.mCountRetry = true;
- String retryAfterValue = connection.getHeaderField("Retry-After");
- if (retryAfterValue != null) {
- try {
- if (Constants.LOGVV) {
- Log.v(Constants.TAG, "Retry-After :" + retryAfterValue);
- }
- state.mRetryAfter = Integer.parseInt(retryAfterValue);
- if (state.mRetryAfter < 0) {
- state.mRetryAfter = 0;
- } else {
- if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
- state.mRetryAfter = Constants.MIN_RETRY_AFTER;
- } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
- state.mRetryAfter = Constants.MAX_RETRY_AFTER;
- }
- state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
- state.mRetryAfter *= 1000;
- }
- } catch (NumberFormatException ex) {
- // ignored - retryAfter stays 0 in this case.
- }
- }
- throw new StopRequest(DownloaderService.STATUS_WAITING_TO_RETRY,
- "got 503 Service Unavailable, will retry later");
- }
-
- /**
+ private void handleServiceUnavailable(State state, HttpURLConnection connection) throws StopRequest {
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG, "got HTTP response code 503");
+ }
+ state.mCountRetry = true;
+ String retryAfterValue = connection.getHeaderField("Retry-After");
+ if (retryAfterValue != null) {
+ try {
+ if (Constants.LOGVV) {
+ Log.v(Constants.TAG, "Retry-After :" + retryAfterValue);
+ }
+ state.mRetryAfter = Integer.parseInt(retryAfterValue);
+ if (state.mRetryAfter < 0) {
+ state.mRetryAfter = 0;
+ } else {
+ if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
+ state.mRetryAfter = Constants.MIN_RETRY_AFTER;
+ } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
+ state.mRetryAfter = Constants.MAX_RETRY_AFTER;
+ }
+ state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
+ state.mRetryAfter *= 1000;
+ }
+ } catch (NumberFormatException ex) {
+ // ignored - retryAfter stays 0 in this case.
+ }
+ }
+ throw new StopRequest(DownloaderService.STATUS_WAITING_TO_RETRY,
+ "got 503 Service Unavailable, will retry later");
+ }
+
+ /**
* Send the request to the server, handling any I/O exceptions.
*/
- private int sendRequest(State state, HttpURLConnection request)
- throws StopRequest {
- try {
- return request.getResponseCode();
- } catch (IllegalArgumentException ex) {
- throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
- "while trying to execute request: " + ex.toString(), ex);
- } catch (IOException ex) {
- logNetworkState();
- throw new StopRequest(getFinalStatusForHttpError(state),
- "while trying to execute request: " + ex.toString(), ex);
- }
- }
-
- private int getFinalStatusForHttpError(State state) {
- if (mService.getNetworkAvailabilityState(mDB) != DownloaderService.NETWORK_OK) {
- return DownloaderService.STATUS_WAITING_FOR_NETWORK;
- } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
- state.mCountRetry = true;
- return DownloaderService.STATUS_WAITING_TO_RETRY;
- } else {
- Log.w(Constants.TAG, "reached max retries for " + mInfo.mNumFailed);
- return DownloaderService.STATUS_HTTP_DATA_ERROR;
- }
- }
-
- /**
+ private int sendRequest(State state, HttpURLConnection request)
+ throws StopRequest {
+ try {
+ return request.getResponseCode();
+ } catch (IllegalArgumentException ex) {
+ throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
+ "while trying to execute request: " + ex.toString(), ex);
+ } catch (IOException ex) {
+ logNetworkState();
+ throw new StopRequest(getFinalStatusForHttpError(state),
+ "while trying to execute request: " + ex.toString(), ex);
+ }
+ }
+
+ private int getFinalStatusForHttpError(State state) {
+ if (mService.getNetworkAvailabilityState(mDB) != DownloaderService.NETWORK_OK) {
+ return DownloaderService.STATUS_WAITING_FOR_NETWORK;
+ } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
+ state.mCountRetry = true;
+ return DownloaderService.STATUS_WAITING_TO_RETRY;
+ } else {
+ Log.w(Constants.TAG, "reached max retries for " + mInfo.mNumFailed);
+ return DownloaderService.STATUS_HTTP_DATA_ERROR;
+ }
+ }
+
+ /**
* Prepare the destination file to receive data. If the file already exists,
* we'll set up appropriately for resumption.
*/
- private void setupDestinationFile(State state, InnerState innerState)
- throws StopRequest {
- if (state.mFilename != null) { // only true if we've already run a
- // thread for this download
- if (!Helpers.isFilenameValid(state.mFilename)) {
- // this should never happen
- throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
- "found invalid internal destination filename");
- }
- // We're resuming a download that got interrupted
- File f = new File(state.mFilename);
- if (f.exists()) {
- long fileLength = f.length();
- if (fileLength == 0) {
- // The download hadn't actually started, we can restart from
- // scratch
- f.delete();
- state.mFilename = null;
- } else if (mInfo.mETag == null) {
- // This should've been caught upon failure
- f.delete();
- throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
- "Trying to resume a download that can't be resumed");
- } else {
- // All right, we'll be able to resume this download
- try {
- state.mStream = new FileOutputStream(state.mFilename, true);
- } catch (FileNotFoundException exc) {
- throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
- "while opening destination for resuming: " + exc.toString(), exc);
- }
- innerState.mBytesSoFar = (int)fileLength;
- if (mInfo.mTotalBytes != -1) {
- innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
- }
- innerState.mHeaderETag = mInfo.mETag;
- innerState.mContinuingDownload = true;
- }
- }
- }
-
- if (state.mStream != null) {
- closeDestination(state);
- }
- }
-
- /**
+ private void setupDestinationFile(State state, InnerState innerState)
+ throws StopRequest {
+ if (state.mFilename != null) { // only true if we've already run a
+ // thread for this download
+ if (!Helpers.isFilenameValid(state.mFilename)) {
+ // this should never happen
+ throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
+ "found invalid internal destination filename");
+ }
+ // We're resuming a download that got interrupted
+ File f = new File(state.mFilename);
+ if (f.exists()) {
+ long fileLength = f.length();
+ if (fileLength == 0) {
+ // The download hadn't actually started, we can restart from
+ // scratch
+ f.delete();
+ state.mFilename = null;
+ } else if (mInfo.mETag == null) {
+ // This should've been caught upon failure
+ f.delete();
+ throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
+ "Trying to resume a download that can't be resumed");
+ } else {
+ // All right, we'll be able to resume this download
+ try {
+ state.mStream = new FileOutputStream(state.mFilename, true);
+ } catch (FileNotFoundException exc) {
+ throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
+ "while opening destination for resuming: " + exc.toString(), exc);
+ }
+ innerState.mBytesSoFar = (int) fileLength;
+ if (mInfo.mTotalBytes != -1) {
+ innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
+ }
+ innerState.mHeaderETag = mInfo.mETag;
+ innerState.mContinuingDownload = true;
+ }
+ }
+ }
+
+ if (state.mStream != null) {
+ closeDestination(state);
+ }
+ }
+
+ /**
* Stores information about the completed download, and notifies the
* initiating application.
*/
- private void notifyDownloadCompleted(
- int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
- String filename) {
- updateDownloadDatabase(
- status, countRetry, retryAfter, redirectCount, gotData, filename);
- if (DownloaderService.isStatusCompleted(status)) {
- // TBD: send status update?
- }
- }
-
- private void updateDownloadDatabase(
- int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
- String filename) {
- mInfo.mStatus = status;
- mInfo.mRetryAfter = retryAfter;
- mInfo.mRedirectCount = redirectCount;
- mInfo.mLastMod = System.currentTimeMillis();
- if (!countRetry) {
- mInfo.mNumFailed = 0;
- } else if (gotData) {
- mInfo.mNumFailed = 1;
- } else {
- mInfo.mNumFailed++;
- }
- mDB.updateDownload(mInfo);
- }
+ private void notifyDownloadCompleted(
+ int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
+ String filename) {
+ updateDownloadDatabase(
+ status, countRetry, retryAfter, redirectCount, gotData, filename);
+ if (DownloaderService.isStatusCompleted(status)) {
+ // TBD: send status update?
+ }
+ }
+
+ private void updateDownloadDatabase(
+ int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
+ String filename) {
+ mInfo.mStatus = status;
+ mInfo.mRetryAfter = retryAfter;
+ mInfo.mRedirectCount = redirectCount;
+ mInfo.mLastMod = System.currentTimeMillis();
+ if (!countRetry) {
+ mInfo.mNumFailed = 0;
+ } else if (gotData) {
+ mInfo.mNumFailed = 1;
+ } else {
+ mInfo.mNumFailed++;
+ }
+ mDB.updateDownload(mInfo);
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
index 25a561ccd4..8d41a76900 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloaderService.java
@@ -29,7 +29,6 @@ import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
-import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
@@ -51,6 +50,10 @@ import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
+// -- GODOT start --
+import android.annotation.SuppressLint;
+// -- GODOT end --
+
import java.io.File;
/**
@@ -62,82 +65,82 @@ import java.io.File;
*/
public abstract class DownloaderService extends CustomIntentService implements IDownloaderService {
- public DownloaderService() {
- super("LVLDownloadService");
- }
+ public DownloaderService() {
+ super("LVLDownloadService");
+ }
- private static final String LOG_TAG = "LVLDL";
+ private static final String LOG_TAG = "LVLDL";
- // the following NETWORK_* constants are used to indicates specific reasons
- // for disallowing a
- // download from using a network, since specific causes can require special
- // handling
+ // the following NETWORK_* constants are used to indicates specific reasons
+ // for disallowing a
+ // download from using a network, since specific causes can require special
+ // handling
- /**
+ /**
* The network is usable for the given download.
*/
- public static final int NETWORK_OK = 1;
+ public static final int NETWORK_OK = 1;
- /**
+ /**
* There is no network connectivity.
*/
- public static final int NETWORK_NO_CONNECTION = 2;
+ public static final int NETWORK_NO_CONNECTION = 2;
- /**
+ /**
* The download exceeds the maximum size for this network.
*/
- public static final int NETWORK_UNUSABLE_DUE_TO_SIZE = 3;
+ public static final int NETWORK_UNUSABLE_DUE_TO_SIZE = 3;
- /**
+ /**
* The download exceeds the recommended maximum size for this network, the
* user must confirm for this download to proceed without WiFi.
*/
- public static final int NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE = 4;
+ public static final int NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE = 4;
- /**
+ /**
* The current connection is roaming, and the download can't proceed over a
* roaming connection.
*/
- public static final int NETWORK_CANNOT_USE_ROAMING = 5;
+ public static final int NETWORK_CANNOT_USE_ROAMING = 5;
- /**
+ /**
* The app requesting the download specific that it can't use the current
* network connection.
*/
- public static final int NETWORK_TYPE_DISALLOWED_BY_REQUESTOR = 6;
+ public static final int NETWORK_TYPE_DISALLOWED_BY_REQUESTOR = 6;
- /**
+ /**
* For intents used to notify the user that a download exceeds a size
* threshold, if this extra is true, WiFi is required for this download
* size; otherwise, it is only recommended.
*/
- public static final String EXTRA_IS_WIFI_REQUIRED = "isWifiRequired";
- public static final String EXTRA_FILE_NAME = "downloadId";
+ public static final String EXTRA_IS_WIFI_REQUIRED = "isWifiRequired";
+ public static final String EXTRA_FILE_NAME = "downloadId";
- /**
+ /**
* Used with DOWNLOAD_STATUS
*/
- public static final String EXTRA_STATUS_STATE = "ESS";
- public static final String EXTRA_STATUS_TOTAL_SIZE = "ETS";
- public static final String EXTRA_STATUS_CURRENT_FILE_SIZE = "CFS";
- public static final String EXTRA_STATUS_TOTAL_PROGRESS = "TFP";
- public static final String EXTRA_STATUS_CURRENT_PROGRESS = "CFP";
+ public static final String EXTRA_STATUS_STATE = "ESS";
+ public static final String EXTRA_STATUS_TOTAL_SIZE = "ETS";
+ public static final String EXTRA_STATUS_CURRENT_FILE_SIZE = "CFS";
+ public static final String EXTRA_STATUS_TOTAL_PROGRESS = "TFP";
+ public static final String EXTRA_STATUS_CURRENT_PROGRESS = "CFP";
- public static final String ACTION_DOWNLOADS_CHANGED = "downloadsChanged";
+ public static final String ACTION_DOWNLOADS_CHANGED = "downloadsChanged";
- /**
+ /**
* Broadcast intent action sent by the download manager when a download
* completes.
*/
- public final static String ACTION_DOWNLOAD_COMPLETE = "lvldownloader.intent.action.DOWNLOAD_COMPLETE";
+ public final static String ACTION_DOWNLOAD_COMPLETE = "lvldownloader.intent.action.DOWNLOAD_COMPLETE";
- /**
+ /**
* Broadcast intent action sent by the download manager when download status
* changes.
*/
- public final static String ACTION_DOWNLOAD_STATUS = "lvldownloader.intent.action.DOWNLOAD_STATUS";
+ public final static String ACTION_DOWNLOAD_STATUS = "lvldownloader.intent.action.DOWNLOAD_STATUS";
- /*
+ /*
* Lists the states that the download manager can set on a download to
* notify applications of the download progress. The codes follow the HTTP
* families:<br> 1xx: informational<br> 2xx: success<br> 3xx: redirects (not
@@ -145,130 +148,131 @@ public abstract class DownloaderService extends CustomIntentService implements I
* errors
*/
- /**
+ /**
* Returns whether the status is informational (i.e. 1xx).
*/
- public static boolean isStatusInformational(int status) {
- return (status >= 100 && status < 200);
- }
+ public static boolean isStatusInformational(int status) {
+ return (status >= 100 && status < 200);
+ }
- /**
+ /**
* Returns whether the status is a success (i.e. 2xx).
*/
- public static boolean isStatusSuccess(int status) {
- return (status >= 200 && status < 300);
- }
+ public static boolean isStatusSuccess(int status) {
+ return (status >= 200 && status < 300);
+ }
- /**
+ /**
* Returns whether the status is an error (i.e. 4xx or 5xx).
*/
- public static boolean isStatusError(int status) {
- return (status >= 400 && status < 600);
- }
+ public static boolean isStatusError(int status) {
+ return (status >= 400 && status < 600);
+ }
- /**
+ /**
* Returns whether the status is a client error (i.e. 4xx).
*/
- public static boolean isStatusClientError(int status) {
- return (status >= 400 && status < 500);
- }
+ public static boolean isStatusClientError(int status) {
+ return (status >= 400 && status < 500);
+ }
- /**
+ /**
* Returns whether the status is a server error (i.e. 5xx).
*/
- public static boolean isStatusServerError(int status) {
- return (status >= 500 && status < 600);
- }
+ public static boolean isStatusServerError(int status) {
+ return (status >= 500 && status < 600);
+ }
- /**
+ /**
* Returns whether the download has completed (either with success or
* error).
*/
- public static boolean isStatusCompleted(int status) {
- return (status >= 200 && status < 300) || (status >= 400 && status < 600);
- }
+ public static boolean isStatusCompleted(int status) {
+ return (status >= 200 && status < 300)
+ || (status >= 400 && status < 600);
+ }
- /**
+ /**
* This download hasn't stated yet
*/
- public static final int STATUS_PENDING = 190;
+ public static final int STATUS_PENDING = 190;
- /**
+ /**
* This download has started
*/
- public static final int STATUS_RUNNING = 192;
+ public static final int STATUS_RUNNING = 192;
- /**
+ /**
* This download has been paused by the owning app.
*/
- public static final int STATUS_PAUSED_BY_APP = 193;
+ public static final int STATUS_PAUSED_BY_APP = 193;
- /**
+ /**
* This download encountered some network error and is waiting before
* retrying the request.
*/
- public static final int STATUS_WAITING_TO_RETRY = 194;
+ public static final int STATUS_WAITING_TO_RETRY = 194;
- /**
+ /**
* This download is waiting for network connectivity to proceed.
*/
- public static final int STATUS_WAITING_FOR_NETWORK = 195;
+ public static final int STATUS_WAITING_FOR_NETWORK = 195;
- /**
+ /**
* This download is waiting for a Wi-Fi connection to proceed or for
* permission to download over cellular.
*/
- public static final int STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION = 196;
+ public static final int STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION = 196;
- /**
+ /**
* This download is waiting for a Wi-Fi connection to proceed.
*/
- public static final int STATUS_QUEUED_FOR_WIFI = 197;
+ public static final int STATUS_QUEUED_FOR_WIFI = 197;
- /**
+ /**
* This download has successfully completed. Warning: there might be other
* status values that indicate success in the future. Use isSucccess() to
* capture the entire category.
*
* @hide
*/
- public static final int STATUS_SUCCESS = 200;
+ public static final int STATUS_SUCCESS = 200;
- /**
+ /**
* The requested URL is no longer available
*/
- public static final int STATUS_FORBIDDEN = 403;
+ public static final int STATUS_FORBIDDEN = 403;
- /**
+ /**
* The file was delivered incorrectly
*/
- public static final int STATUS_FILE_DELIVERED_INCORRECTLY = 487;
+ public static final int STATUS_FILE_DELIVERED_INCORRECTLY = 487;
- /**
+ /**
* The requested destination file already exists.
*/
- public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
+ public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488;
- /**
+ /**
* Some possibly transient error occurred, but we can't resume the download.
*/
- public static final int STATUS_CANNOT_RESUME = 489;
+ public static final int STATUS_CANNOT_RESUME = 489;
- /**
+ /**
* This download was canceled
*
* @hide
*/
- public static final int STATUS_CANCELED = 490;
+ public static final int STATUS_CANCELED = 490;
- /**
+ /**
* This download has completed with an error. Warning: there will be other
* status values that indicate errors in the future. Use isStatusError() to
* capture the entire category.
*/
- public static final int STATUS_UNKNOWN_ERROR = 491;
+ public static final int STATUS_UNKNOWN_ERROR = 491;
- /**
+ /**
* This download couldn't be completed because of a storage issue.
* Typically, that's because the filesystem is missing or full. Use the more
* specific {@link #STATUS_INSUFFICIENT_SPACE_ERROR} and
@@ -276,367 +280,372 @@ public abstract class DownloaderService extends CustomIntentService implements I
*
* @hide
*/
- public static final int STATUS_FILE_ERROR = 492;
+ public static final int STATUS_FILE_ERROR = 492;
- /**
+ /**
* This download couldn't be completed because of an HTTP redirect response
* that the download manager couldn't handle.
*
* @hide
*/
- public static final int STATUS_UNHANDLED_REDIRECT = 493;
+ public static final int STATUS_UNHANDLED_REDIRECT = 493;
- /**
+ /**
* This download couldn't be completed because of an unspecified unhandled
* HTTP code.
*
* @hide
*/
- public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
+ public static final int STATUS_UNHANDLED_HTTP_CODE = 494;
- /**
+ /**
* This download couldn't be completed because of an error receiving or
* processing data at the HTTP level.
*
* @hide
*/
- public static final int STATUS_HTTP_DATA_ERROR = 495;
+ public static final int STATUS_HTTP_DATA_ERROR = 495;
- /**
+ /**
* This download couldn't be completed because of an HttpException while
* setting up the request.
*
* @hide
*/
- public static final int STATUS_HTTP_EXCEPTION = 496;
+ public static final int STATUS_HTTP_EXCEPTION = 496;
- /**
+ /**
* This download couldn't be completed because there were too many
* redirects.
*
* @hide
*/
- public static final int STATUS_TOO_MANY_REDIRECTS = 497;
+ public static final int STATUS_TOO_MANY_REDIRECTS = 497;
- /**
+ /**
* This download couldn't be completed due to insufficient storage space.
* Typically, this is because the SD card is full.
*
* @hide
*/
- public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498;
+ public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498;
- /**
+ /**
* This download couldn't be completed because no external storage device
* was found. Typically, this is because the SD card is not mounted.
*
* @hide
*/
- public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499;
+ public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499;
- /**
+ /**
* This download is allowed to run.
*
* @hide
*/
- public static final int CONTROL_RUN = 0;
+ public static final int CONTROL_RUN = 0;
- /**
+ /**
* This download must pause at the first opportunity.
*
* @hide
*/
- public static final int CONTROL_PAUSED = 1;
+ public static final int CONTROL_PAUSED = 1;
- /**
+ /**
* This download is visible but only shows in the notifications while it's
* in progress.
*
* @hide
*/
- public static final int VISIBILITY_VISIBLE = 0;
+ public static final int VISIBILITY_VISIBLE = 0;
- /**
+ /**
* This download is visible and shows in the notifications while in progress
* and after completion.
*
* @hide
*/
- public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
+ public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
- /**
+ /**
* This download doesn't show in the UI or in the notifications.
*
* @hide
*/
- public static final int VISIBILITY_HIDDEN = 2;
+ public static final int VISIBILITY_HIDDEN = 2;
- /**
+ /**
* Bit flag for setAllowedNetworkTypes corresponding to
* {@link ConnectivityManager#TYPE_MOBILE}.
*/
- public static final int NETWORK_MOBILE = 1 << 0;
+ public static final int NETWORK_MOBILE = 1 << 0;
- /**
+ /**
* Bit flag for setAllowedNetworkTypes corresponding to
* {@link ConnectivityManager#TYPE_WIFI}.
*/
- public static final int NETWORK_WIFI = 1 << 1;
+ public static final int NETWORK_WIFI = 1 << 1;
- private final static String TEMP_EXT = ".tmp";
+ private final static String TEMP_EXT = ".tmp";
- /**
+ /**
* Service thread status
*/
- private static boolean sIsRunning;
+ private static boolean sIsRunning;
- @Override
- public IBinder onBind(Intent paramIntent) {
- Log.d(Constants.TAG, "Service Bound");
- return this.mServiceMessenger.getBinder();
- }
+ @Override
+ public IBinder onBind(Intent paramIntent) {
+ Log.d(Constants.TAG, "Service Bound");
+ return this.mServiceMessenger.getBinder();
+ }
- /**
+ /**
* Network state.
*/
- private boolean mIsConnected;
- private boolean mIsFailover;
- private boolean mIsCellularConnection;
- private boolean mIsRoaming;
- private boolean mIsAtLeast3G;
- private boolean mIsAtLeast4G;
- private boolean mStateChanged;
+ private boolean mIsConnected;
+ private boolean mIsFailover;
+ private boolean mIsCellularConnection;
+ private boolean mIsRoaming;
+ private boolean mIsAtLeast3G;
+ private boolean mIsAtLeast4G;
+ private boolean mStateChanged;
- /**
+ /**
* Download state
*/
- private int mControl;
- private int mStatus;
+ private int mControl;
+ private int mStatus;
- public boolean isWiFi() {
- return mIsConnected && !mIsCellularConnection;
- }
+ public boolean isWiFi() {
+ return mIsConnected && !mIsCellularConnection;
+ }
- /**
+ /**
* Bindings to important services
*/
- private ConnectivityManager mConnectivityManager;
- private WifiManager mWifiManager;
+ private ConnectivityManager mConnectivityManager;
+ private WifiManager mWifiManager;
- /**
+ /**
* Package we are downloading for (defaults to package of application)
*/
- private PackageInfo mPackageInfo;
+ private PackageInfo mPackageInfo;
- /**
+ /**
* Byte counts
*/
- long mBytesSoFar;
- long mTotalLength;
- int mFileCount;
+ long mBytesSoFar;
+ long mTotalLength;
+ int mFileCount;
- /**
+ /**
* Used for calculating time remaining and speed
*/
- long mBytesAtSample;
- long mMillisecondsAtSample;
- float mAverageDownloadSpeed;
+ long mBytesAtSample;
+ long mMillisecondsAtSample;
+ float mAverageDownloadSpeed;
- /**
+ /**
* Our binding to the network state broadcasts
*/
- private BroadcastReceiver mConnReceiver;
- final private IStub mServiceStub = DownloaderServiceMarshaller.CreateStub(this);
- final private Messenger mServiceMessenger = mServiceStub.getMessenger();
- private Messenger mClientMessenger;
- private DownloadNotification mNotification;
- private PendingIntent mPendingIntent;
- private PendingIntent mAlarmIntent;
+ private BroadcastReceiver mConnReceiver;
+ final private IStub mServiceStub = DownloaderServiceMarshaller.CreateStub(this);
+ final private Messenger mServiceMessenger = mServiceStub.getMessenger();
+ private Messenger mClientMessenger;
+ private DownloadNotification mNotification;
+ private PendingIntent mPendingIntent;
+ private PendingIntent mAlarmIntent;
- /**
+ /**
* Updates the network type based upon the type and subtype returned from
* the connectivity manager. Subtype is only used for cellular signals.
*
* @param type
* @param subType
*/
- private void updateNetworkType(int type, int subType) {
- switch (type) {
- case ConnectivityManager.TYPE_WIFI:
- case ConnectivityManager.TYPE_ETHERNET:
- case ConnectivityManager.TYPE_BLUETOOTH:
- mIsCellularConnection = false;
- mIsAtLeast3G = false;
- mIsAtLeast4G = false;
- break;
- case ConnectivityManager.TYPE_WIMAX:
- mIsCellularConnection = true;
- mIsAtLeast3G = true;
- mIsAtLeast4G = true;
- break;
- case ConnectivityManager.TYPE_MOBILE:
- mIsCellularConnection = true;
- switch (subType) {
- case TelephonyManager.NETWORK_TYPE_1xRTT:
- case TelephonyManager.NETWORK_TYPE_CDMA:
- case TelephonyManager.NETWORK_TYPE_EDGE:
- case TelephonyManager.NETWORK_TYPE_GPRS:
- case TelephonyManager.NETWORK_TYPE_IDEN:
- mIsAtLeast3G = false;
- mIsAtLeast4G = false;
- break;
- case TelephonyManager.NETWORK_TYPE_HSDPA:
- case TelephonyManager.NETWORK_TYPE_HSUPA:
- case TelephonyManager.NETWORK_TYPE_HSPA:
- case TelephonyManager.NETWORK_TYPE_EVDO_0:
- case TelephonyManager.NETWORK_TYPE_EVDO_A:
- case TelephonyManager.NETWORK_TYPE_UMTS:
- mIsAtLeast3G = true;
- mIsAtLeast4G = false;
- break;
- case TelephonyManager.NETWORK_TYPE_LTE: // 4G
- case TelephonyManager.NETWORK_TYPE_EHRPD: // 3G ++ interop
- // with 4G
- case TelephonyManager.NETWORK_TYPE_HSPAP: // 3G ++ but
- // marketed as
- // 4G
- mIsAtLeast3G = true;
- mIsAtLeast4G = true;
- break;
- default:
- mIsCellularConnection = false;
- mIsAtLeast3G = false;
- mIsAtLeast4G = false;
- }
- }
- }
-
- private void updateNetworkState(NetworkInfo info) {
- boolean isConnected = mIsConnected;
- boolean isFailover = mIsFailover;
- boolean isCellularConnection = mIsCellularConnection;
- boolean isRoaming = mIsRoaming;
- boolean isAtLeast3G = mIsAtLeast3G;
- if (null != info) {
- mIsRoaming = info.isRoaming();
- mIsFailover = info.isFailover();
- mIsConnected = info.isConnected();
- updateNetworkType(info.getType(), info.getSubtype());
- } else {
- mIsRoaming = false;
- mIsFailover = false;
- mIsConnected = false;
- updateNetworkType(-1, -1);
- }
- mStateChanged = (mStateChanged || isConnected != mIsConnected || isFailover != mIsFailover || isCellularConnection != mIsCellularConnection || isRoaming != mIsRoaming || isAtLeast3G != mIsAtLeast3G);
- if (Constants.LOGVV) {
- if (mStateChanged) {
- Log.v(LOG_TAG, "Network state changed: ");
- Log.v(LOG_TAG, "Starting State: " +
- (isConnected ? "Connected " : "Not Connected ") +
- (isCellularConnection ? "Cellular " : "WiFi ") +
- (isRoaming ? "Roaming " : "Local ") +
- (isAtLeast3G ? "3G+ " : "<3G "));
- Log.v(LOG_TAG, "Ending State: " +
- (mIsConnected ? "Connected " : "Not Connected ") +
- (mIsCellularConnection ? "Cellular " : "WiFi ") +
- (mIsRoaming ? "Roaming " : "Local ") +
- (mIsAtLeast3G ? "3G+ " : "<3G "));
-
- if (isServiceRunning()) {
- if (mIsRoaming) {
- mStatus = STATUS_WAITING_FOR_NETWORK;
- mControl = CONTROL_PAUSED;
- } else if (mIsCellularConnection) {
- DownloadsDB db = DownloadsDB.getDB(this);
- int flags = db.getFlags();
- if (0 == (flags & FLAGS_DOWNLOAD_OVER_CELLULAR)) {
- mStatus = STATUS_QUEUED_FOR_WIFI;
- mControl = CONTROL_PAUSED;
- }
- }
- }
- }
- }
- }
-
- /**
+ private void updateNetworkType(int type, int subType) {
+ switch (type) {
+ case ConnectivityManager.TYPE_WIFI:
+ case ConnectivityManager.TYPE_ETHERNET:
+ case ConnectivityManager.TYPE_BLUETOOTH:
+ mIsCellularConnection = false;
+ mIsAtLeast3G = false;
+ mIsAtLeast4G = false;
+ break;
+ case ConnectivityManager.TYPE_WIMAX:
+ mIsCellularConnection = true;
+ mIsAtLeast3G = true;
+ mIsAtLeast4G = true;
+ break;
+ case ConnectivityManager.TYPE_MOBILE:
+ mIsCellularConnection = true;
+ switch (subType) {
+ case TelephonyManager.NETWORK_TYPE_1xRTT:
+ case TelephonyManager.NETWORK_TYPE_CDMA:
+ case TelephonyManager.NETWORK_TYPE_EDGE:
+ case TelephonyManager.NETWORK_TYPE_GPRS:
+ case TelephonyManager.NETWORK_TYPE_IDEN:
+ mIsAtLeast3G = false;
+ mIsAtLeast4G = false;
+ break;
+ case TelephonyManager.NETWORK_TYPE_HSDPA:
+ case TelephonyManager.NETWORK_TYPE_HSUPA:
+ case TelephonyManager.NETWORK_TYPE_HSPA:
+ case TelephonyManager.NETWORK_TYPE_EVDO_0:
+ case TelephonyManager.NETWORK_TYPE_EVDO_A:
+ case TelephonyManager.NETWORK_TYPE_UMTS:
+ mIsAtLeast3G = true;
+ mIsAtLeast4G = false;
+ break;
+ case TelephonyManager.NETWORK_TYPE_LTE: // 4G
+ case TelephonyManager.NETWORK_TYPE_EHRPD: // 3G ++ interop
+ // with 4G
+ case TelephonyManager.NETWORK_TYPE_HSPAP: // 3G ++ but
+ // marketed as
+ // 4G
+ mIsAtLeast3G = true;
+ mIsAtLeast4G = true;
+ break;
+ default:
+ mIsCellularConnection = false;
+ mIsAtLeast3G = false;
+ mIsAtLeast4G = false;
+ }
+ }
+ }
+
+ private void updateNetworkState(NetworkInfo info) {
+ boolean isConnected = mIsConnected;
+ boolean isFailover = mIsFailover;
+ boolean isCellularConnection = mIsCellularConnection;
+ boolean isRoaming = mIsRoaming;
+ boolean isAtLeast3G = mIsAtLeast3G;
+ if (null != info) {
+ mIsRoaming = info.isRoaming();
+ mIsFailover = info.isFailover();
+ mIsConnected = info.isConnected();
+ updateNetworkType(info.getType(), info.getSubtype());
+ } else {
+ mIsRoaming = false;
+ mIsFailover = false;
+ mIsConnected = false;
+ updateNetworkType(-1, -1);
+ }
+ mStateChanged = (mStateChanged || isConnected != mIsConnected
+ || isFailover != mIsFailover
+ || isCellularConnection != mIsCellularConnection
+ || isRoaming != mIsRoaming || isAtLeast3G != mIsAtLeast3G);
+ if (Constants.LOGVV) {
+ if (mStateChanged) {
+ Log.v(LOG_TAG, "Network state changed: ");
+ Log.v(LOG_TAG, "Starting State: " +
+ (isConnected ? "Connected " : "Not Connected ") +
+ (isCellularConnection ? "Cellular " : "WiFi ") +
+ (isRoaming ? "Roaming " : "Local ") +
+ (isAtLeast3G ? "3G+ " : "<3G "));
+ Log.v(LOG_TAG, "Ending State: " +
+ (mIsConnected ? "Connected " : "Not Connected ") +
+ (mIsCellularConnection ? "Cellular " : "WiFi ") +
+ (mIsRoaming ? "Roaming " : "Local ") +
+ (mIsAtLeast3G ? "3G+ " : "<3G "));
+
+ if (isServiceRunning()) {
+ if (mIsRoaming) {
+ mStatus = STATUS_WAITING_FOR_NETWORK;
+ mControl = CONTROL_PAUSED;
+ } else if (mIsCellularConnection) {
+ DownloadsDB db = DownloadsDB.getDB(this);
+ int flags = db.getFlags();
+ if (0 == (flags & FLAGS_DOWNLOAD_OVER_CELLULAR)) {
+ mStatus = STATUS_QUEUED_FOR_WIFI;
+ mControl = CONTROL_PAUSED;
+ }
+ }
+ }
+
+ }
+ }
+ }
+
+ /**
* Polls the network state, setting the flags appropriately.
*/
- void pollNetworkState() {
- if (null == mConnectivityManager) {
- mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
- }
- if (null == mWifiManager) {
- mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
- }
- if (mConnectivityManager == null) {
- Log.w(Constants.TAG,
- "couldn't get connectivity manager to poll network state");
- } else {
- @SuppressLint("MissingPermission")
- NetworkInfo activeInfo = mConnectivityManager
- .getActiveNetworkInfo();
- updateNetworkState(activeInfo);
- }
- }
-
- public static final int NO_DOWNLOAD_REQUIRED = 0;
- public static final int LVL_CHECK_REQUIRED = 1;
- public static final int DOWNLOAD_REQUIRED = 2;
-
- public static final String EXTRA_PACKAGE_NAME = "EPN";
- public static final String EXTRA_PENDING_INTENT = "EPI";
- public static final String EXTRA_MESSAGE_HANDLER = "EMH";
-
- /**
+ void pollNetworkState() {
+ if (null == mConnectivityManager) {
+ mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ }
+ if (null == mWifiManager) {
+ mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
+ }
+ if (mConnectivityManager == null) {
+ Log.w(Constants.TAG,
+ "couldn't get connectivity manager to poll network state");
+ } else {
+ @SuppressLint("MissingPermission")
+ NetworkInfo activeInfo = mConnectivityManager
+ .getActiveNetworkInfo();
+ updateNetworkState(activeInfo);
+ }
+ }
+
+ public static final int NO_DOWNLOAD_REQUIRED = 0;
+ public static final int LVL_CHECK_REQUIRED = 1;
+ public static final int DOWNLOAD_REQUIRED = 2;
+
+ public static final String EXTRA_PACKAGE_NAME = "EPN";
+ public static final String EXTRA_PENDING_INTENT = "EPI";
+ public static final String EXTRA_MESSAGE_HANDLER = "EMH";
+
+ /**
* Returns true if the LVL check is required
*
* @param db a downloads DB synchronized with the latest state
* @param pi the package info for the project
* @return returns true if the filenames need to be returned
*/
- private static boolean isLVLCheckRequired(DownloadsDB db, PackageInfo pi) {
- // we need to update the LVL check and get a successful status to
- // proceed
- if (db.mVersionCode != pi.versionCode) {
- return true;
- }
- return false;
- }
+ private static boolean isLVLCheckRequired(DownloadsDB db, PackageInfo pi) {
+ // we need to update the LVL check and get a successful status to
+ // proceed
+ if (db.mVersionCode != pi.versionCode) {
+ return true;
+ }
+ return false;
+ }
- /**
+ /**
* Careful! Only use this internally.
*
* @return whether we think the service is running
*/
- private static synchronized boolean isServiceRunning() {
- return sIsRunning;
- }
-
- private static synchronized void setServiceRunning(boolean isRunning) {
- sIsRunning = isRunning;
- }
-
- public static int startDownloadServiceIfRequired(Context context,
- Intent intent, Class<?> serviceClass) throws NameNotFoundException {
- final PendingIntent pendingIntent = (PendingIntent)intent
- .getParcelableExtra(EXTRA_PENDING_INTENT);
- return startDownloadServiceIfRequired(context, pendingIntent,
- serviceClass);
- }
-
- public static int startDownloadServiceIfRequired(Context context,
- PendingIntent pendingIntent, Class<?> serviceClass)
- throws NameNotFoundException {
- String packageName = context.getPackageName();
- String className = serviceClass.getName();
-
- return startDownloadServiceIfRequired(context, pendingIntent,
- packageName, className);
- }
-
- /**
+ private static synchronized boolean isServiceRunning() {
+ return sIsRunning;
+ }
+
+ private static synchronized void setServiceRunning(boolean isRunning) {
+ sIsRunning = isRunning;
+ }
+
+ public static int startDownloadServiceIfRequired(Context context,
+ Intent intent, Class<?> serviceClass) throws NameNotFoundException {
+ final PendingIntent pendingIntent = (PendingIntent) intent
+ .getParcelableExtra(EXTRA_PENDING_INTENT);
+ return startDownloadServiceIfRequired(context, pendingIntent,
+ serviceClass);
+ }
+
+ public static int startDownloadServiceIfRequired(Context context,
+ PendingIntent pendingIntent, Class<?> serviceClass)
+ throws NameNotFoundException
+ {
+ String packageName = context.getPackageName();
+ String className = serviceClass.getName();
+
+ return startDownloadServiceIfRequired(context, pendingIntent,
+ packageName, className);
+ }
+
+ /**
* Starts the download if necessary. This function starts a flow that does `
* many things. 1) Checks to see if the APK version has been checked and the
* metadata database updated 2) If the APK version does not match, checks
@@ -655,246 +664,254 @@ public abstract class DownloaderService extends CustomIntentService implements I
* downloader, false if the app can continue
* @throws NameNotFoundException
*/
- public static int startDownloadServiceIfRequired(Context context,
- PendingIntent pendingIntent, String classPackage, String className)
- throws NameNotFoundException {
- // first: do we need to do an LVL update?
- // we begin by getting our APK version from the package manager
- final PackageInfo pi = context.getPackageManager().getPackageInfo(
- context.getPackageName(), 0);
-
- int status = NO_DOWNLOAD_REQUIRED;
-
- // the database automatically reads the metadata for version code
- // and download status when the instance is created
- DownloadsDB db = DownloadsDB.getDB(context);
-
- // we need to update the LVL check and get a successful status to
- // proceed
- if (isLVLCheckRequired(db, pi)) {
- status = LVL_CHECK_REQUIRED;
- }
- // we don't have to update LVL. do we still have a download to start?
- if (db.mStatus == 0) {
- DownloadInfo[] infos = db.getDownloads();
- if (null != infos) {
- for (DownloadInfo info : infos) {
- if (!Helpers.doesFileExist(context, info.mFileName, info.mTotalBytes, true)) {
- status = DOWNLOAD_REQUIRED;
- db.updateStatus(-1);
- break;
- }
- }
- }
- } else {
- status = DOWNLOAD_REQUIRED;
- }
- switch (status) {
- case DOWNLOAD_REQUIRED:
- case LVL_CHECK_REQUIRED:
- Intent fileIntent = new Intent();
- fileIntent.setClassName(classPackage, className);
- fileIntent.putExtra(EXTRA_PENDING_INTENT, pendingIntent);
- context.startService(fileIntent);
- break;
- }
- return status;
- }
-
- @Override
- public void requestAbortDownload() {
- mControl = CONTROL_PAUSED;
- mStatus = STATUS_CANCELED;
- }
-
- @Override
- public void requestPauseDownload() {
- mControl = CONTROL_PAUSED;
- mStatus = STATUS_PAUSED_BY_APP;
- }
-
- @Override
- public void setDownloadFlags(int flags) {
- DownloadsDB.getDB(this).updateFlags(flags);
- }
-
- @Override
- public void requestContinueDownload() {
- if (mControl == CONTROL_PAUSED) {
- mControl = CONTROL_RUN;
- }
- Intent fileIntent = new Intent(this, this.getClass());
- fileIntent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
- this.startService(fileIntent);
- }
-
- public abstract String getPublicKey();
-
- public abstract byte[] getSALT();
-
- public abstract String getAlarmReceiverClassName();
-
- private class LVLRunnable implements Runnable {
- LVLRunnable(Context context, PendingIntent intent) {
- mContext = context;
- mPendingIntent = intent;
- }
-
- final Context mContext;
-
- @Override
- public void run() {
- setServiceRunning(true);
- mNotification.onDownloadStateChanged(IDownloaderClient.STATE_FETCHING_URL);
- String deviceId = Secure.ANDROID_ID;
-
- final APKExpansionPolicy aep = new APKExpansionPolicy(mContext,
- new AESObfuscator(getSALT(), mContext.getPackageName(), deviceId));
-
- // reset our policy back to the start of the world to force a
- // re-check
- aep.resetPolicy();
-
- // let's try and get the OBB file from LVL first
- // Construct the LicenseChecker with a Policy.
- final LicenseChecker checker = new LicenseChecker(mContext, aep,
- getPublicKey() // Your public licensing key.
- );
- checker.checkAccess(new LicenseCheckerCallback() {
- @Override
- public void allow(int reason) {
- try {
- int count = aep.getExpansionURLCount();
- DownloadsDB db = DownloadsDB.getDB(mContext);
- int status = 0;
- if (count != 0) {
- for (int i = 0; i < count; i++) {
- String currentFileName = aep
- .getExpansionFileName(i);
- if (null != currentFileName) {
- DownloadInfo di = new DownloadInfo(i,
- currentFileName, mContext.getPackageName());
-
- long fileSize = aep.getExpansionFileSize(i);
- if (handleFileUpdated(db, i, currentFileName,
- fileSize)) {
- status |= -1;
- di.resetDownload();
- di.mUri = aep.getExpansionURL(i);
- di.mTotalBytes = fileSize;
- di.mStatus = status;
- db.updateDownload(di);
- } else {
- // we need to read the download
- // information
- // from
- // the database
- DownloadInfo dbdi = db
- .getDownloadInfoByFileName(di.mFileName);
- if (null == dbdi) {
- // the file exists already and is
- // the
- // correct size
- // was delivered by Market or
- // through
- // another mechanism
- Log.d(LOG_TAG, "file " + di.mFileName + " found. Not downloading.");
- di.mStatus = STATUS_SUCCESS;
- di.mTotalBytes = fileSize;
- di.mCurrentBytes = fileSize;
- di.mUri = aep.getExpansionURL(i);
- db.updateDownload(di);
- } else if (dbdi.mStatus != STATUS_SUCCESS) {
- // we just update the URL
- dbdi.mUri = aep.getExpansionURL(i);
- db.updateDownload(dbdi);
- status |= -1;
- }
- }
- }
- }
- }
- // first: do we need to do an LVL update?
- // we begin by getting our APK version from the package
- // manager
- PackageInfo pi;
- try {
- pi = mContext.getPackageManager().getPackageInfo(
- mContext.getPackageName(), 0);
- db.updateMetadata(pi.versionCode, status);
- Class<?> serviceClass = DownloaderService.this.getClass();
- switch (startDownloadServiceIfRequired(mContext, mPendingIntent,
- serviceClass)) {
- case NO_DOWNLOAD_REQUIRED:
- mNotification
- .onDownloadStateChanged(IDownloaderClient.STATE_COMPLETED);
- break;
- case LVL_CHECK_REQUIRED:
- // DANGER WILL ROBINSON!
- Log.e(LOG_TAG, "In LVL checking loop!");
- mNotification
- .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_UNLICENSED);
- throw new RuntimeException(
- "Error with LVL checking and database integrity");
- case DOWNLOAD_REQUIRED:
- // do nothing. the download will notify the
- // application
- // when things are done
- break;
- }
- } catch (NameNotFoundException e1) {
- e1.printStackTrace();
- throw new RuntimeException(
- "Error with getting information from package name");
- }
- } finally {
- setServiceRunning(false);
- }
- }
-
- @Override
- public void dontAllow(int reason) {
- try {
- switch (reason) {
- case Policy.NOT_LICENSED:
- mNotification
- .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_UNLICENSED);
- break;
- case Policy.RETRY:
- mNotification
- .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_FETCHING_URL);
- break;
- }
- } finally {
- setServiceRunning(false);
- }
- }
-
- @Override
- public void applicationError(int errorCode) {
- try {
- mNotification
- .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_FETCHING_URL);
- } finally {
- setServiceRunning(false);
- }
- }
- });
- }
- };
-
- /**
+ public static int startDownloadServiceIfRequired(Context context,
+ PendingIntent pendingIntent, String classPackage, String className)
+ throws NameNotFoundException {
+ // first: do we need to do an LVL update?
+ // we begin by getting our APK version from the package manager
+ final PackageInfo pi = context.getPackageManager().getPackageInfo(
+ context.getPackageName(), 0);
+
+ int status = NO_DOWNLOAD_REQUIRED;
+
+ // the database automatically reads the metadata for version code
+ // and download status when the instance is created
+ DownloadsDB db = DownloadsDB.getDB(context);
+
+ // we need to update the LVL check and get a successful status to
+ // proceed
+ if (isLVLCheckRequired(db, pi)) {
+ status = LVL_CHECK_REQUIRED;
+ }
+ // we don't have to update LVL. do we still have a download to start?
+ if (db.mStatus == 0) {
+ DownloadInfo[] infos = db.getDownloads();
+ if (null != infos) {
+ for (DownloadInfo info : infos) {
+ if (!Helpers.doesFileExist(context, info.mFileName, info.mTotalBytes, true)) {
+ status = DOWNLOAD_REQUIRED;
+ db.updateStatus(-1);
+ break;
+ }
+ }
+ }
+ } else {
+ status = DOWNLOAD_REQUIRED;
+ }
+ switch (status) {
+ case DOWNLOAD_REQUIRED:
+ case LVL_CHECK_REQUIRED:
+ Intent fileIntent = new Intent();
+ fileIntent.setClassName(classPackage, className);
+ fileIntent.putExtra(EXTRA_PENDING_INTENT, pendingIntent);
+ context.startService(fileIntent);
+ break;
+ }
+ return status;
+ }
+
+ @Override
+ public void requestAbortDownload() {
+ mControl = CONTROL_PAUSED;
+ mStatus = STATUS_CANCELED;
+ }
+
+ @Override
+ public void requestPauseDownload() {
+ mControl = CONTROL_PAUSED;
+ mStatus = STATUS_PAUSED_BY_APP;
+ }
+
+ @Override
+ public void setDownloadFlags(int flags) {
+ DownloadsDB.getDB(this).updateFlags(flags);
+ }
+
+ @Override
+ public void requestContinueDownload() {
+ if (mControl == CONTROL_PAUSED) {
+ mControl = CONTROL_RUN;
+ }
+ Intent fileIntent = new Intent(this, this.getClass());
+ fileIntent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
+ this.startService(fileIntent);
+ }
+
+ public abstract String getPublicKey();
+
+ public abstract byte[] getSALT();
+
+ public abstract String getAlarmReceiverClassName();
+
+ private class LVLRunnable implements Runnable {
+ LVLRunnable(Context context, PendingIntent intent) {
+ mContext = context;
+ mPendingIntent = intent;
+ }
+
+ final Context mContext;
+
+ @Override
+ public void run() {
+ setServiceRunning(true);
+ mNotification.onDownloadStateChanged(IDownloaderClient.STATE_FETCHING_URL);
+ String deviceId = Secure.getString(mContext.getContentResolver(),
+ Secure.ANDROID_ID);
+
+ final APKExpansionPolicy aep = new APKExpansionPolicy(mContext,
+ new AESObfuscator(getSALT(), mContext.getPackageName(), deviceId));
+
+ // reset our policy back to the start of the world to force a
+ // re-check
+ aep.resetPolicy();
+
+ // let's try and get the OBB file from LVL first
+ // Construct the LicenseChecker with a Policy.
+ final LicenseChecker checker = new LicenseChecker(mContext, aep,
+ getPublicKey() // Your public licensing key.
+ );
+ checker.checkAccess(new LicenseCheckerCallback() {
+
+ @Override
+ public void allow(int reason) {
+ try {
+ int count = aep.getExpansionURLCount();
+ DownloadsDB db = DownloadsDB.getDB(mContext);
+ int status = 0;
+ if (count != 0) {
+ for (int i = 0; i < count; i++) {
+ String currentFileName = aep
+ .getExpansionFileName(i);
+ if (null != currentFileName) {
+ DownloadInfo di = new DownloadInfo(i,
+ currentFileName, mContext.getPackageName());
+
+ long fileSize = aep.getExpansionFileSize(i);
+ if (handleFileUpdated(db, i, currentFileName,
+ fileSize)) {
+ status |= -1;
+ di.resetDownload();
+ di.mUri = aep.getExpansionURL(i);
+ di.mTotalBytes = fileSize;
+ di.mStatus = status;
+ db.updateDownload(di);
+ } else {
+ // we need to read the download
+ // information
+ // from
+ // the database
+ DownloadInfo dbdi = db
+ .getDownloadInfoByFileName(di.mFileName);
+ if (null == dbdi) {
+ // the file exists already and is
+ // the
+ // correct size
+ // was delivered by Market or
+ // through
+ // another mechanism
+ Log.d(LOG_TAG, "file " + di.mFileName
+ + " found. Not downloading.");
+ di.mStatus = STATUS_SUCCESS;
+ di.mTotalBytes = fileSize;
+ di.mCurrentBytes = fileSize;
+ di.mUri = aep.getExpansionURL(i);
+ db.updateDownload(di);
+ } else if (dbdi.mStatus != STATUS_SUCCESS) {
+ // we just update the URL
+ dbdi.mUri = aep.getExpansionURL(i);
+ db.updateDownload(dbdi);
+ status |= -1;
+ }
+ }
+ }
+ }
+ }
+ // first: do we need to do an LVL update?
+ // we begin by getting our APK version from the package
+ // manager
+ PackageInfo pi;
+ try {
+ pi = mContext.getPackageManager().getPackageInfo(
+ mContext.getPackageName(), 0);
+ db.updateMetadata(pi.versionCode, status);
+ Class<?> serviceClass = DownloaderService.this.getClass();
+ switch (startDownloadServiceIfRequired(mContext, mPendingIntent,
+ serviceClass)) {
+ case NO_DOWNLOAD_REQUIRED:
+ mNotification
+ .onDownloadStateChanged(IDownloaderClient.STATE_COMPLETED);
+ break;
+ case LVL_CHECK_REQUIRED:
+ // DANGER WILL ROBINSON!
+ Log.e(LOG_TAG, "In LVL checking loop!");
+ mNotification
+ .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_UNLICENSED);
+ throw new RuntimeException(
+ "Error with LVL checking and database integrity");
+ case DOWNLOAD_REQUIRED:
+ // do nothing. the download will notify the
+ // application
+ // when things are done
+ break;
+ }
+ } catch (NameNotFoundException e1) {
+ e1.printStackTrace();
+ throw new RuntimeException(
+ "Error with getting information from package name");
+ }
+ } finally {
+ setServiceRunning(false);
+ }
+ }
+
+ @Override
+ public void dontAllow(int reason) {
+ try
+ {
+ switch (reason) {
+ case Policy.NOT_LICENSED:
+ mNotification
+ .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_UNLICENSED);
+ break;
+ case Policy.RETRY:
+ mNotification
+ .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_FETCHING_URL);
+ break;
+ }
+ } finally {
+ setServiceRunning(false);
+ }
+
+ }
+
+ @Override
+ public void applicationError(int errorCode) {
+ try {
+ mNotification
+ .onDownloadStateChanged(IDownloaderClient.STATE_FAILED_FETCHING_URL);
+ } finally {
+ setServiceRunning(false);
+ }
+ }
+
+ });
+
+ }
+
+ };
+
+ /**
* Updates the LVL information from the server.
*
* @param context
*/
- public void updateLVL(final Context context) {
- Context c = context.getApplicationContext();
- Handler h = new Handler(c.getMainLooper());
- h.post(new LVLRunnable(c, mPendingIntent));
- }
+ public void updateLVL(final Context context) {
+ Context c = context.getApplicationContext();
+ Handler h = new Handler(c.getMainLooper());
+ h.post(new LVLRunnable(c, mPendingIntent));
+ }
- /**
+ /**
* The APK has been updated and a filename has been sent down from the
* Market call. If the file has the same name as the previous file, we do
* nothing as the file is guaranteed to be the same. If the file does not
@@ -906,415 +923,424 @@ public abstract class DownloaderService extends CustomIntentService implements I
* @param fileSize the size of the new file
* @return
*/
- public boolean handleFileUpdated(DownloadsDB db, int index,
- String filename, long fileSize) {
- DownloadInfo di = db.getDownloadInfoByFileName(filename);
- if (null != di) {
- String oldFile = di.mFileName;
- // cleanup
- if (null != oldFile) {
- if (filename.equals(oldFile)) {
- return false;
- }
-
- // remove partially downloaded file if it is there
- String deleteFile = Helpers.generateSaveFileName(this, oldFile);
- File f = new File(deleteFile);
- if (f.exists())
- f.delete();
- }
- }
- return !Helpers.doesFileExist(this, filename, fileSize, true);
- }
-
- private void scheduleAlarm(long wakeUp) {
- AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
- if (alarms == null) {
- Log.e(Constants.TAG, "couldn't get alarm manager");
- return;
- }
-
- if (Constants.LOGV) {
- Log.v(Constants.TAG, "scheduling retry in " + wakeUp + "ms");
- }
-
- String className = getAlarmReceiverClassName();
- Intent intent = new Intent(Constants.ACTION_RETRY);
- intent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
- intent.setClassName(this.getPackageName(),
- className);
- mAlarmIntent = PendingIntent.getBroadcast(this, 0, intent,
- PendingIntent.FLAG_ONE_SHOT);
- alarms.set(
- AlarmManager.RTC_WAKEUP,
- System.currentTimeMillis() + wakeUp, mAlarmIntent);
- }
-
- private void cancelAlarms() {
- if (null != mAlarmIntent) {
- AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
- if (alarms == null) {
- Log.e(Constants.TAG, "couldn't get alarm manager");
- return;
- }
- alarms.cancel(mAlarmIntent);
- mAlarmIntent = null;
- }
- }
-
- /**
+ public boolean handleFileUpdated(DownloadsDB db, int index,
+ String filename, long fileSize) {
+ DownloadInfo di = db.getDownloadInfoByFileName(filename);
+ if (null != di) {
+ String oldFile = di.mFileName;
+ // cleanup
+ if (null != oldFile) {
+ if (filename.equals(oldFile)) {
+ return false;
+ }
+
+ // remove partially downloaded file if it is there
+ String deleteFile = Helpers.generateSaveFileName(this, oldFile);
+ File f = new File(deleteFile);
+ if (f.exists())
+ f.delete();
+ }
+ }
+ return !Helpers.doesFileExist(this, filename, fileSize, true);
+ }
+
+ private void scheduleAlarm(long wakeUp) {
+ AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+ if (alarms == null) {
+ Log.e(Constants.TAG, "couldn't get alarm manager");
+ return;
+ }
+
+ if (Constants.LOGV) {
+ Log.v(Constants.TAG, "scheduling retry in " + wakeUp + "ms");
+ }
+
+ String className = getAlarmReceiverClassName();
+ Intent intent = new Intent(Constants.ACTION_RETRY);
+ intent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
+ intent.setClassName(this.getPackageName(),
+ className);
+ mAlarmIntent = PendingIntent.getBroadcast(this, 0, intent,
+ PendingIntent.FLAG_ONE_SHOT);
+ alarms.set(
+ AlarmManager.RTC_WAKEUP,
+ System.currentTimeMillis() + wakeUp, mAlarmIntent
+ );
+ }
+
+ private void cancelAlarms() {
+ if (null != mAlarmIntent) {
+ AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+ if (alarms == null) {
+ Log.e(Constants.TAG, "couldn't get alarm manager");
+ return;
+ }
+ alarms.cancel(mAlarmIntent);
+ mAlarmIntent = null;
+ }
+ }
+
+ /**
* We use this to track network state, such as when WiFi, Cellular, etc. is
* enabled when downloads are paused or in progress.
*/
- private class InnerBroadcastReceiver extends BroadcastReceiver {
- final Service mService;
-
- InnerBroadcastReceiver(Service service) {
- mService = service;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- pollNetworkState();
- if (mStateChanged && !isServiceRunning()) {
- Log.d(Constants.TAG, "InnerBroadcastReceiver Called");
- Intent fileIntent = new Intent(context, mService.getClass());
- fileIntent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
- // send a new intent to the service
- context.startService(fileIntent);
- }
- }
- };
-
- /**
+ private class InnerBroadcastReceiver extends BroadcastReceiver {
+ final Service mService;
+
+ InnerBroadcastReceiver(Service service) {
+ mService = service;
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ pollNetworkState();
+ if (mStateChanged
+ && !isServiceRunning()) {
+ Log.d(Constants.TAG, "InnerBroadcastReceiver Called");
+ Intent fileIntent = new Intent(context, mService.getClass());
+ fileIntent.putExtra(EXTRA_PENDING_INTENT, mPendingIntent);
+ // send a new intent to the service
+ context.startService(fileIntent);
+ }
+ }
+ };
+
+ /**
* This is the main thread for the Downloader. This thread is responsible
* for queuing up downloads and other goodness.
*/
- @Override
- protected void onHandleIntent(Intent intent) {
- setServiceRunning(true);
- try {
- // the database automatically reads the metadata for version code
- // and download status when the instance is created
- DownloadsDB db = DownloadsDB.getDB(this);
- final PendingIntent pendingIntent = (PendingIntent)intent
- .getParcelableExtra(EXTRA_PENDING_INTENT);
-
- if (null != pendingIntent) {
- mNotification.setClientIntent(pendingIntent);
- mPendingIntent = pendingIntent;
- } else if (null != mPendingIntent) {
- mNotification.setClientIntent(mPendingIntent);
- } else {
- Log.e(LOG_TAG, "Downloader started in bad state without notification intent.");
- return;
- }
-
- // when the LVL check completes, a successful response will update
- // the service
- if (isLVLCheckRequired(db, mPackageInfo)) {
- updateLVL(this);
- return;
- }
-
- // get each download
- DownloadInfo[] infos = db.getDownloads();
- mBytesSoFar = 0;
- mTotalLength = 0;
- mFileCount = infos.length;
- for (DownloadInfo info : infos) {
- // We do an (simple) integrity check on each file, just to make
- // sure
- if (info.mStatus == STATUS_SUCCESS) {
- // verify that the file matches the state
- if (!Helpers.doesFileExist(this, info.mFileName, info.mTotalBytes, true)) {
- info.mStatus = 0;
- info.mCurrentBytes = 0;
- }
- }
- // get aggregate data
- mTotalLength += info.mTotalBytes;
- mBytesSoFar += info.mCurrentBytes;
- }
-
- // loop through all downloads and fetch them
- pollNetworkState();
- if (null == mConnReceiver) {
-
- /**
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ setServiceRunning(true);
+ try {
+ // the database automatically reads the metadata for version code
+ // and download status when the instance is created
+ DownloadsDB db = DownloadsDB.getDB(this);
+ final PendingIntent pendingIntent = (PendingIntent) intent
+ .getParcelableExtra(EXTRA_PENDING_INTENT);
+
+ if (null != pendingIntent)
+ {
+ mNotification.setClientIntent(pendingIntent);
+ mPendingIntent = pendingIntent;
+ } else if (null != mPendingIntent) {
+ mNotification.setClientIntent(mPendingIntent);
+ } else {
+ Log.e(LOG_TAG, "Downloader started in bad state without notification intent.");
+ return;
+ }
+
+ // when the LVL check completes, a successful response will update
+ // the service
+ if (isLVLCheckRequired(db, mPackageInfo)) {
+ updateLVL(this);
+ return;
+ }
+
+ // get each download
+ DownloadInfo[] infos = db.getDownloads();
+ mBytesSoFar = 0;
+ mTotalLength = 0;
+ mFileCount = infos.length;
+ for (DownloadInfo info : infos) {
+ // We do an (simple) integrity check on each file, just to make
+ // sure
+ if (info.mStatus == STATUS_SUCCESS) {
+ // verify that the file matches the state
+ if (!Helpers.doesFileExist(this, info.mFileName, info.mTotalBytes, true)) {
+ info.mStatus = 0;
+ info.mCurrentBytes = 0;
+ }
+ }
+ // get aggregate data
+ mTotalLength += info.mTotalBytes;
+ mBytesSoFar += info.mCurrentBytes;
+ }
+
+ // loop through all downloads and fetch them
+ pollNetworkState();
+ if (null == mConnReceiver) {
+
+ /**
* We use this to track network state, such as when WiFi,
* Cellular, etc. is enabled when downloads are paused or in
* progress.
*/
- mConnReceiver = new InnerBroadcastReceiver(this);
- IntentFilter intentFilter = new IntentFilter(
- ConnectivityManager.CONNECTIVITY_ACTION);
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- registerReceiver(mConnReceiver, intentFilter);
- }
-
- for (DownloadInfo info : infos) {
- long startingCount = info.mCurrentBytes;
-
- if (info.mStatus != STATUS_SUCCESS) {
- DownloadThread dt = new DownloadThread(info, this, mNotification);
- cancelAlarms();
- scheduleAlarm(Constants.ACTIVE_THREAD_WATCHDOG);
- dt.run();
- cancelAlarms();
- }
- db.updateFromDb(info);
- boolean setWakeWatchdog = false;
- int notifyStatus;
- switch (info.mStatus) {
- case STATUS_FORBIDDEN:
- // the URL is out of date
- updateLVL(this);
- return;
- case STATUS_SUCCESS:
- mBytesSoFar += info.mCurrentBytes - startingCount;
- db.updateMetadata(mPackageInfo.versionCode, 0);
- continue;
- case STATUS_FILE_DELIVERED_INCORRECTLY:
- // we may be on a network that is returning us a web
- // page on redirect
- notifyStatus = IDownloaderClient.STATE_PAUSED_NETWORK_SETUP_FAILURE;
- info.mCurrentBytes = 0;
- db.updateDownload(info);
- setWakeWatchdog = true;
- break;
- case STATUS_PAUSED_BY_APP:
- notifyStatus = IDownloaderClient.STATE_PAUSED_BY_REQUEST;
- break;
- case STATUS_WAITING_FOR_NETWORK:
- case STATUS_WAITING_TO_RETRY:
- notifyStatus = IDownloaderClient.STATE_PAUSED_NETWORK_UNAVAILABLE;
- setWakeWatchdog = true;
- break;
- case STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION:
- case STATUS_QUEUED_FOR_WIFI:
- // look for more detail here
- if (null != mWifiManager) {
- if (!mWifiManager.isWifiEnabled()) {
- notifyStatus = IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION;
- setWakeWatchdog = true;
- break;
- }
- }
- notifyStatus = IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION;
- setWakeWatchdog = true;
- break;
- case STATUS_CANCELED:
- notifyStatus = IDownloaderClient.STATE_FAILED_CANCELED;
- setWakeWatchdog = true;
- break;
-
- case STATUS_INSUFFICIENT_SPACE_ERROR:
- notifyStatus = IDownloaderClient.STATE_FAILED_SDCARD_FULL;
- setWakeWatchdog = true;
- break;
-
- case STATUS_DEVICE_NOT_FOUND_ERROR:
- notifyStatus = IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE;
- setWakeWatchdog = true;
- break;
-
- default:
- notifyStatus = IDownloaderClient.STATE_FAILED;
- break;
- }
- if (setWakeWatchdog) {
- scheduleAlarm(Constants.WATCHDOG_WAKE_TIMER);
- } else {
- cancelAlarms();
- }
- // failure or pause state
- mNotification.onDownloadStateChanged(notifyStatus);
- return;
- }
-
- // all downloads complete
- mNotification.onDownloadStateChanged(IDownloaderClient.STATE_COMPLETED);
- } finally {
- setServiceRunning(false);
- }
- }
-
- @Override
- public void onDestroy() {
- if (null != mConnReceiver) {
- unregisterReceiver(mConnReceiver);
- mConnReceiver = null;
- }
- mServiceStub.disconnect(this);
- super.onDestroy();
- }
-
- public int getNetworkAvailabilityState(DownloadsDB db) {
- if (mIsConnected) {
- if (!mIsCellularConnection)
- return NETWORK_OK;
- int flags = db.mFlags;
- if (mIsRoaming)
- return NETWORK_CANNOT_USE_ROAMING;
- if (0 != (flags & FLAGS_DOWNLOAD_OVER_CELLULAR)) {
- return NETWORK_OK;
- } else {
- return NETWORK_TYPE_DISALLOWED_BY_REQUESTOR;
- }
- }
- return NETWORK_NO_CONNECTION;
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- try {
- mPackageInfo = getPackageManager().getPackageInfo(
- getPackageName(), 0);
- ApplicationInfo ai = getApplicationInfo();
- CharSequence applicationLabel = getPackageManager().getApplicationLabel(ai);
- mNotification = new DownloadNotification(this, applicationLabel);
-
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- }
-
- /**
+ mConnReceiver = new InnerBroadcastReceiver(this);
+ IntentFilter intentFilter = new IntentFilter(
+ ConnectivityManager.CONNECTIVITY_ACTION);
+ intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
+ registerReceiver(mConnReceiver, intentFilter);
+ }
+
+ for (DownloadInfo info : infos) {
+ long startingCount = info.mCurrentBytes;
+
+ if (info.mStatus != STATUS_SUCCESS) {
+ DownloadThread dt = new DownloadThread(info, this, mNotification);
+ cancelAlarms();
+ scheduleAlarm(Constants.ACTIVE_THREAD_WATCHDOG);
+ dt.run();
+ cancelAlarms();
+ }
+ db.updateFromDb(info);
+ boolean setWakeWatchdog = false;
+ int notifyStatus;
+ switch (info.mStatus) {
+ case STATUS_FORBIDDEN:
+ // the URL is out of date
+ updateLVL(this);
+ return;
+ case STATUS_SUCCESS:
+ mBytesSoFar += info.mCurrentBytes - startingCount;
+ db.updateMetadata(mPackageInfo.versionCode, 0);
+ continue;
+ case STATUS_FILE_DELIVERED_INCORRECTLY:
+ // we may be on a network that is returning us a web
+ // page on redirect
+ notifyStatus = IDownloaderClient.STATE_PAUSED_NETWORK_SETUP_FAILURE;
+ info.mCurrentBytes = 0;
+ db.updateDownload(info);
+ setWakeWatchdog = true;
+ break;
+ case STATUS_PAUSED_BY_APP:
+ notifyStatus = IDownloaderClient.STATE_PAUSED_BY_REQUEST;
+ break;
+ case STATUS_WAITING_FOR_NETWORK:
+ case STATUS_WAITING_TO_RETRY:
+ notifyStatus = IDownloaderClient.STATE_PAUSED_NETWORK_UNAVAILABLE;
+ setWakeWatchdog = true;
+ break;
+ case STATUS_QUEUED_FOR_WIFI_OR_CELLULAR_PERMISSION:
+ case STATUS_QUEUED_FOR_WIFI:
+ // look for more detail here
+ if (null != mWifiManager) {
+ if (!mWifiManager.isWifiEnabled()) {
+ notifyStatus = IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION;
+ setWakeWatchdog = true;
+ break;
+ }
+ }
+ notifyStatus = IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION;
+ setWakeWatchdog = true;
+ break;
+ case STATUS_CANCELED:
+ notifyStatus = IDownloaderClient.STATE_FAILED_CANCELED;
+ setWakeWatchdog = true;
+ break;
+
+ case STATUS_INSUFFICIENT_SPACE_ERROR:
+ notifyStatus = IDownloaderClient.STATE_FAILED_SDCARD_FULL;
+ setWakeWatchdog = true;
+ break;
+
+ case STATUS_DEVICE_NOT_FOUND_ERROR:
+ notifyStatus = IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE;
+ setWakeWatchdog = true;
+ break;
+
+ default:
+ notifyStatus = IDownloaderClient.STATE_FAILED;
+ break;
+ }
+ if (setWakeWatchdog) {
+ scheduleAlarm(Constants.WATCHDOG_WAKE_TIMER);
+ } else {
+ cancelAlarms();
+ }
+ // failure or pause state
+ mNotification.onDownloadStateChanged(notifyStatus);
+ return;
+ }
+
+ // all downloads complete
+ mNotification.onDownloadStateChanged(IDownloaderClient.STATE_COMPLETED);
+ } finally {
+ setServiceRunning(false);
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ if (null != mConnReceiver) {
+ unregisterReceiver(mConnReceiver);
+ mConnReceiver = null;
+ }
+ mServiceStub.disconnect(this);
+ super.onDestroy();
+ }
+
+ public int getNetworkAvailabilityState(DownloadsDB db) {
+ if (mIsConnected) {
+ if (!mIsCellularConnection)
+ return NETWORK_OK;
+ int flags = db.mFlags;
+ if (mIsRoaming)
+ return NETWORK_CANNOT_USE_ROAMING;
+ if (0 != (flags & FLAGS_DOWNLOAD_OVER_CELLULAR)) {
+ return NETWORK_OK;
+ } else {
+ return NETWORK_TYPE_DISALLOWED_BY_REQUESTOR;
+ }
+ }
+ return NETWORK_NO_CONNECTION;
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ try {
+ mPackageInfo = getPackageManager().getPackageInfo(
+ getPackageName(), 0);
+ ApplicationInfo ai = getApplicationInfo();
+ CharSequence applicationLabel = getPackageManager().getApplicationLabel(ai);
+ mNotification = new DownloadNotification(this, applicationLabel);
+
+ } catch (NameNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
* Exception thrown from methods called by generateSaveFile() for any fatal
* error.
*/
- public static class GenerateSaveFileError extends Exception {
- private static final long serialVersionUID = 3465966015408936540L;
- int mStatus;
- String mMessage;
+ public static class GenerateSaveFileError extends Exception {
+ private static final long serialVersionUID = 3465966015408936540L;
+ int mStatus;
+ String mMessage;
- public GenerateSaveFileError(int status, String message) {
- mStatus = status;
- mMessage = message;
- }
- }
+ public GenerateSaveFileError(int status, String message) {
+ mStatus = status;
+ mMessage = message;
+ }
+ }
- /**
+ /**
* Returns the filename (where the file should be saved) from info about a
* download
*/
- public String generateTempSaveFileName(String fileName) {
- String path = Helpers.getSaveFilePath(this) + File.separator + fileName + TEMP_EXT;
- return path;
- }
+ public String generateTempSaveFileName(String fileName) {
+ String path = Helpers.getSaveFilePath(this)
+ + File.separator + fileName + TEMP_EXT;
+ return path;
+ }
- /**
+ /**
* Creates a filename (where the file should be saved) from info about a
* download.
*/
- public String generateSaveFile(String filename, long filesize)
- throws GenerateSaveFileError {
- String path = generateTempSaveFileName(filename);
- File expPath = new File(path);
- if (!Helpers.isExternalMediaMounted()) {
- Log.d(Constants.TAG, "External media not mounted: " + path);
- throw new GenerateSaveFileError(STATUS_DEVICE_NOT_FOUND_ERROR,
- "external media is not yet mounted");
- }
- if (expPath.exists()) {
- Log.d(Constants.TAG, "File already exists: " + path);
- throw new GenerateSaveFileError(STATUS_FILE_ALREADY_EXISTS_ERROR,
- "requested destination file already exists");
- }
- if (Helpers.getAvailableBytes(Helpers.getFilesystemRoot(path)) < filesize) {
- throw new GenerateSaveFileError(STATUS_INSUFFICIENT_SPACE_ERROR,
- "insufficient space on external storage");
- }
- return path;
- }
-
- /**
+ public String generateSaveFile(String filename, long filesize)
+ throws GenerateSaveFileError {
+ String path = generateTempSaveFileName(filename);
+ File expPath = new File(path);
+ if (!Helpers.isExternalMediaMounted()) {
+ Log.d(Constants.TAG, "External media not mounted: " + path);
+ throw new GenerateSaveFileError(STATUS_DEVICE_NOT_FOUND_ERROR,
+ "external media is not yet mounted");
+
+ }
+ if (expPath.exists()) {
+ Log.d(Constants.TAG, "File already exists: " + path);
+ throw new GenerateSaveFileError(STATUS_FILE_ALREADY_EXISTS_ERROR,
+ "requested destination file already exists");
+ }
+ if (Helpers.getAvailableBytes(Helpers.getFilesystemRoot(path)) < filesize) {
+ throw new GenerateSaveFileError(STATUS_INSUFFICIENT_SPACE_ERROR,
+ "insufficient space on external storage");
+ }
+ return path;
+ }
+
+ /**
* @return a non-localized string appropriate for logging corresponding to
* one of the NETWORK_* constants.
*/
- public String getLogMessageForNetworkError(int networkError) {
- switch (networkError) {
- case NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE:
- return "download size exceeds recommended limit for mobile network";
+ public String getLogMessageForNetworkError(int networkError) {
+ switch (networkError) {
+ case NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE:
+ return "download size exceeds recommended limit for mobile network";
- case NETWORK_UNUSABLE_DUE_TO_SIZE:
- return "download size exceeds limit for mobile network";
+ case NETWORK_UNUSABLE_DUE_TO_SIZE:
+ return "download size exceeds limit for mobile network";
- case NETWORK_NO_CONNECTION:
- return "no network connection available";
+ case NETWORK_NO_CONNECTION:
+ return "no network connection available";
- case NETWORK_CANNOT_USE_ROAMING:
- return "download cannot use the current network connection because it is roaming";
+ case NETWORK_CANNOT_USE_ROAMING:
+ return "download cannot use the current network connection because it is roaming";
- case NETWORK_TYPE_DISALLOWED_BY_REQUESTOR:
- return "download was requested to not use the current network type";
+ case NETWORK_TYPE_DISALLOWED_BY_REQUESTOR:
+ return "download was requested to not use the current network type";
- default:
- return "unknown error with network connectivity";
- }
- }
+ default:
+ return "unknown error with network connectivity";
+ }
+ }
- public int getControl() {
- return mControl;
- }
+ public int getControl() {
+ return mControl;
+ }
- public int getStatus() {
- return mStatus;
- }
+ public int getStatus() {
+ return mStatus;
+ }
- /**
+ /**
* Calculating a moving average for the speed so we don't get jumpy
* calculations for time etc.
*/
- static private final float SMOOTHING_FACTOR = 0.005f;
-
- public void notifyUpdateBytes(long totalBytesSoFar) {
- long timeRemaining;
- long currentTime = SystemClock.uptimeMillis();
- if (0 != mMillisecondsAtSample) {
- // we have a sample.
- long timePassed = currentTime - mMillisecondsAtSample;
- long bytesInSample = totalBytesSoFar - mBytesAtSample;
- float currentSpeedSample = (float)bytesInSample / (float)timePassed;
- if (0 != mAverageDownloadSpeed) {
- mAverageDownloadSpeed = SMOOTHING_FACTOR * currentSpeedSample + (1 - SMOOTHING_FACTOR) * mAverageDownloadSpeed;
- } else {
- mAverageDownloadSpeed = currentSpeedSample;
- }
- timeRemaining = (long)((mTotalLength - totalBytesSoFar) / mAverageDownloadSpeed);
- } else {
- timeRemaining = -1;
- }
- mMillisecondsAtSample = currentTime;
- mBytesAtSample = totalBytesSoFar;
- mNotification.onDownloadProgress(
- new DownloadProgressInfo(mTotalLength,
- totalBytesSoFar,
- timeRemaining,
- mAverageDownloadSpeed));
- }
-
- @Override
- protected boolean shouldStop() {
- // the database automatically reads the metadata for version code
- // and download status when the instance is created
- DownloadsDB db = DownloadsDB.getDB(this);
- if (db.mStatus == 0) {
- return true;
- }
- return false;
- }
-
- @Override
- public void requestDownloadStatus() {
- mNotification.resendState();
- }
-
- @Override
- public void onClientUpdated(Messenger clientMessenger) {
- this.mClientMessenger = clientMessenger;
- mNotification.setMessenger(mClientMessenger);
- }
+ static private final float SMOOTHING_FACTOR = 0.005f;
+
+ public void notifyUpdateBytes(long totalBytesSoFar) {
+ long timeRemaining;
+ long currentTime = SystemClock.uptimeMillis();
+ if (0 != mMillisecondsAtSample) {
+ // we have a sample.
+ long timePassed = currentTime - mMillisecondsAtSample;
+ long bytesInSample = totalBytesSoFar - mBytesAtSample;
+ float currentSpeedSample = (float) bytesInSample / (float) timePassed;
+ if (0 != mAverageDownloadSpeed) {
+ mAverageDownloadSpeed = SMOOTHING_FACTOR * currentSpeedSample
+ + (1 - SMOOTHING_FACTOR) * mAverageDownloadSpeed;
+ } else {
+ mAverageDownloadSpeed = currentSpeedSample;
+ }
+ timeRemaining = (long) ((mTotalLength - totalBytesSoFar) / mAverageDownloadSpeed);
+ } else {
+ timeRemaining = -1;
+ }
+ mMillisecondsAtSample = currentTime;
+ mBytesAtSample = totalBytesSoFar;
+ mNotification.onDownloadProgress(
+ new DownloadProgressInfo(mTotalLength,
+ totalBytesSoFar,
+ timeRemaining,
+ mAverageDownloadSpeed)
+ );
+
+ }
+
+ @Override
+ protected boolean shouldStop() {
+ // the database automatically reads the metadata for version code
+ // and download status when the instance is created
+ DownloadsDB db = DownloadsDB.getDB(this);
+ if (db.mStatus == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void requestDownloadStatus() {
+ mNotification.resendState();
+ }
+
+ @Override
+ public void onClientUpdated(Messenger clientMessenger) {
+ this.mClientMessenger = clientMessenger;
+ mNotification.setMessenger(mClientMessenger);
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadsDB.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadsDB.java
index 5d8dce0bac..c658b4cc43 100755..100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadsDB.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/DownloadsDB.java
@@ -27,443 +27,484 @@ import android.provider.BaseColumns;
import android.util.Log;
public class DownloadsDB {
- private static final String DATABASE_NAME = "DownloadsDB";
- private static final int DATABASE_VERSION = 7;
- public static final String LOG_TAG = DownloadsDB.class.getName();
- final SQLiteOpenHelper mHelper;
- SQLiteStatement mGetDownloadByIndex;
- SQLiteStatement mUpdateCurrentBytes;
- private static DownloadsDB mDownloadsDB;
- long mMetadataRowID = -1;
- int mVersionCode = -1;
- int mStatus = -1;
- int mFlags;
-
- static public synchronized DownloadsDB getDB(Context paramContext) {
- if (null == mDownloadsDB) {
- return new DownloadsDB(paramContext);
- }
- return mDownloadsDB;
- }
-
- private SQLiteStatement getDownloadByIndexStatement() {
- if (null == mGetDownloadByIndex) {
- mGetDownloadByIndex = mHelper.getReadableDatabase().compileStatement(
- "SELECT " + BaseColumns._ID + " FROM " + DownloadColumns.TABLE_NAME + " WHERE " + DownloadColumns.INDEX + " = ?");
- }
- return mGetDownloadByIndex;
- }
-
- private SQLiteStatement getUpdateCurrentBytesStatement() {
- if (null == mUpdateCurrentBytes) {
- mUpdateCurrentBytes = mHelper.getReadableDatabase().compileStatement(
- "UPDATE " + DownloadColumns.TABLE_NAME + " SET " + DownloadColumns.CURRENTBYTES + " = ?"
- +
- " WHERE " + DownloadColumns.INDEX + " = ?");
- }
- return mUpdateCurrentBytes;
- }
-
- private DownloadsDB(Context paramContext) {
- this.mHelper = new DownloadsContentDBHelper(paramContext);
- final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
- // Query for the version code, the row ID of the metadata (for future
- // updating) the status and the flags
- Cursor cur = sqldb.rawQuery("SELECT " +
- MetadataColumns.APKVERSION + "," +
- BaseColumns._ID + "," +
- MetadataColumns.DOWNLOAD_STATUS + "," +
- MetadataColumns.FLAGS +
- " FROM " + MetadataColumns.TABLE_NAME + " LIMIT 1",
- null);
- if (null != cur && cur.moveToFirst()) {
- mVersionCode = cur.getInt(0);
- mMetadataRowID = cur.getLong(1);
- mStatus = cur.getInt(2);
- mFlags = cur.getInt(3);
- cur.close();
- }
- mDownloadsDB = this;
- }
-
- protected DownloadInfo getDownloadInfoByFileName(String fileName) {
- final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
- Cursor itemcur = null;
- try {
- itemcur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION,
- DownloadColumns.FILENAME + " = ?",
- new String[] {
- fileName },
- null, null, null);
- if (null != itemcur && itemcur.moveToFirst()) {
- return getDownloadInfoFromCursor(itemcur);
- }
- } finally {
- if (null != itemcur)
- itemcur.close();
- }
- return null;
- }
-
- public long getIDForDownloadInfo(final DownloadInfo di) {
- return getIDByIndex(di.mIndex);
- }
-
- public long getIDByIndex(int index) {
- SQLiteStatement downloadByIndex = getDownloadByIndexStatement();
- downloadByIndex.clearBindings();
- downloadByIndex.bindLong(1, index);
- try {
- return downloadByIndex.simpleQueryForLong();
- } catch (SQLiteDoneException e) {
- return -1;
- }
- }
-
- public void updateDownloadCurrentBytes(final DownloadInfo di) {
- SQLiteStatement downloadCurrentBytes = getUpdateCurrentBytesStatement();
- downloadCurrentBytes.clearBindings();
- downloadCurrentBytes.bindLong(1, di.mCurrentBytes);
- downloadCurrentBytes.bindLong(2, di.mIndex);
- downloadCurrentBytes.execute();
- }
-
- public void close() {
- this.mHelper.close();
- }
-
- protected static class DownloadsContentDBHelper extends SQLiteOpenHelper {
- DownloadsContentDBHelper(Context paramContext) {
- super(paramContext, DATABASE_NAME, null, DATABASE_VERSION);
- }
-
- private String createTableQueryFromArray(String paramString,
- String[][] paramArrayOfString) {
- StringBuilder localStringBuilder = new StringBuilder();
- localStringBuilder.append("CREATE TABLE ");
- localStringBuilder.append(paramString);
- localStringBuilder.append(" (");
- int i = paramArrayOfString.length;
- for (int j = 0;; j++) {
- if (j >= i) {
- localStringBuilder
- .setLength(localStringBuilder.length() - 1);
- localStringBuilder.append(");");
- return localStringBuilder.toString();
- }
- String[] arrayOfString = paramArrayOfString[j];
- localStringBuilder.append(' ');
- localStringBuilder.append(arrayOfString[0]);
- localStringBuilder.append(' ');
- localStringBuilder.append(arrayOfString[1]);
- localStringBuilder.append(',');
- }
- }
-
- /**
+ private static final String DATABASE_NAME = "DownloadsDB";
+ private static final int DATABASE_VERSION = 7;
+ public static final String LOG_TAG = DownloadsDB.class.getName();
+ final SQLiteOpenHelper mHelper;
+ SQLiteStatement mGetDownloadByIndex;
+ SQLiteStatement mUpdateCurrentBytes;
+ private static DownloadsDB mDownloadsDB;
+ long mMetadataRowID = -1;
+ int mVersionCode = -1;
+ int mStatus = -1;
+ int mFlags;
+
+ static public synchronized DownloadsDB getDB(Context paramContext) {
+ if (null == mDownloadsDB) {
+ return new DownloadsDB(paramContext);
+ }
+ return mDownloadsDB;
+ }
+
+ private SQLiteStatement getDownloadByIndexStatement() {
+ if (null == mGetDownloadByIndex) {
+ mGetDownloadByIndex = mHelper.getReadableDatabase().compileStatement(
+ "SELECT " + BaseColumns._ID + " FROM "
+ + DownloadColumns.TABLE_NAME + " WHERE "
+ + DownloadColumns.INDEX + " = ?");
+ }
+ return mGetDownloadByIndex;
+ }
+
+ private SQLiteStatement getUpdateCurrentBytesStatement() {
+ if (null == mUpdateCurrentBytes) {
+ mUpdateCurrentBytes = mHelper.getReadableDatabase().compileStatement(
+ "UPDATE " + DownloadColumns.TABLE_NAME + " SET " + DownloadColumns.CURRENTBYTES
+ + " = ?" +
+ " WHERE " + DownloadColumns.INDEX + " = ?");
+ }
+ return mUpdateCurrentBytes;
+ }
+
+ private DownloadsDB(Context paramContext) {
+ this.mHelper = new DownloadsContentDBHelper(paramContext);
+ final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
+ // Query for the version code, the row ID of the metadata (for future
+ // updating) the status and the flags
+ Cursor cur = sqldb.rawQuery("SELECT " +
+ MetadataColumns.APKVERSION + "," +
+ BaseColumns._ID + "," +
+ MetadataColumns.DOWNLOAD_STATUS + "," +
+ MetadataColumns.FLAGS +
+ " FROM "
+ + MetadataColumns.TABLE_NAME + " LIMIT 1", null);
+ if (null != cur && cur.moveToFirst()) {
+ mVersionCode = cur.getInt(0);
+ mMetadataRowID = cur.getLong(1);
+ mStatus = cur.getInt(2);
+ mFlags = cur.getInt(3);
+ cur.close();
+ }
+ mDownloadsDB = this;
+ }
+
+ protected DownloadInfo getDownloadInfoByFileName(String fileName) {
+ final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
+ Cursor itemcur = null;
+ try {
+ itemcur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION,
+ DownloadColumns.FILENAME + " = ?",
+ new String[] {
+ fileName
+ }, null, null, null);
+ if (null != itemcur && itemcur.moveToFirst()) {
+ return getDownloadInfoFromCursor(itemcur);
+ }
+ } finally {
+ if (null != itemcur)
+ itemcur.close();
+ }
+ return null;
+ }
+
+ public long getIDForDownloadInfo(final DownloadInfo di) {
+ return getIDByIndex(di.mIndex);
+ }
+
+ public long getIDByIndex(int index) {
+ SQLiteStatement downloadByIndex = getDownloadByIndexStatement();
+ downloadByIndex.clearBindings();
+ downloadByIndex.bindLong(1, index);
+ try {
+ return downloadByIndex.simpleQueryForLong();
+ } catch (SQLiteDoneException e) {
+ return -1;
+ }
+ }
+
+ public void updateDownloadCurrentBytes(final DownloadInfo di) {
+ SQLiteStatement downloadCurrentBytes = getUpdateCurrentBytesStatement();
+ downloadCurrentBytes.clearBindings();
+ downloadCurrentBytes.bindLong(1, di.mCurrentBytes);
+ downloadCurrentBytes.bindLong(2, di.mIndex);
+ downloadCurrentBytes.execute();
+ }
+
+ public void close() {
+ this.mHelper.close();
+ }
+
+ protected static class DownloadsContentDBHelper extends SQLiteOpenHelper {
+ DownloadsContentDBHelper(Context paramContext) {
+ super(paramContext, DATABASE_NAME, null, DATABASE_VERSION);
+ }
+
+ private String createTableQueryFromArray(String paramString,
+ String[][] paramArrayOfString) {
+ StringBuilder localStringBuilder = new StringBuilder();
+ localStringBuilder.append("CREATE TABLE ");
+ localStringBuilder.append(paramString);
+ localStringBuilder.append(" (");
+ int i = paramArrayOfString.length;
+ for (int j = 0;; j++) {
+ if (j >= i) {
+ localStringBuilder
+ .setLength(localStringBuilder.length() - 1);
+ localStringBuilder.append(");");
+ return localStringBuilder.toString();
+ }
+ String[] arrayOfString = paramArrayOfString[j];
+ localStringBuilder.append(' ');
+ localStringBuilder.append(arrayOfString[0]);
+ localStringBuilder.append(' ');
+ localStringBuilder.append(arrayOfString[1]);
+ localStringBuilder.append(',');
+ }
+ }
+
+ /**
* These two arrays must match and have the same order. For every Schema
* there must be a corresponding table name.
*/
- static final private String[][][] sSchemas = {
- DownloadColumns.SCHEMA, MetadataColumns.SCHEMA
- };
+ static final private String[][][] sSchemas = {
+ DownloadColumns.SCHEMA, MetadataColumns.SCHEMA
+ };
- static final private String[] sTables = {
- DownloadColumns.TABLE_NAME, MetadataColumns.TABLE_NAME
- };
+ static final private String[] sTables = {
+ DownloadColumns.TABLE_NAME, MetadataColumns.TABLE_NAME
+ };
- /**
+ /**
* Goes through all of the tables in sTables and drops each table if it
* exists. Altered to no longer make use of reflection.
*/
- private void dropTables(SQLiteDatabase paramSQLiteDatabase) {
- for (String table : sTables) {
- try {
- paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table);
- } catch (Exception localException) {
- localException.printStackTrace();
- }
- }
- }
-
- /**
+ private void dropTables(SQLiteDatabase paramSQLiteDatabase) {
+ for (String table : sTables) {
+ try {
+ paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table);
+ } catch (Exception localException) {
+ localException.printStackTrace();
+ }
+ }
+ }
+
+ /**
* Goes through all of the tables in sTables and creates a database with
* the corresponding schema described in sSchemas. Altered to no longer
* make use of reflection.
*/
- public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
- int numSchemas = sSchemas.length;
- for (int i = 0; i < numSchemas; i++) {
- try {
- String[][] schema = (String[][])sSchemas[i];
- paramSQLiteDatabase.execSQL(createTableQueryFromArray(
- sTables[i], schema));
- } catch (Exception localException) {
- while (true)
- localException.printStackTrace();
- }
- }
- }
-
- public void onUpgrade(SQLiteDatabase paramSQLiteDatabase,
- int paramInt1, int paramInt2) {
- Log.w(DownloadsContentDBHelper.class.getName(),
- "Upgrading database from version " + paramInt1 + " to " + paramInt2 + ", which will destroy all old data");
- dropTables(paramSQLiteDatabase);
- onCreate(paramSQLiteDatabase);
- }
- }
-
- public static class MetadataColumns implements BaseColumns {
- public static final String APKVERSION = "APKVERSION";
- public static final String DOWNLOAD_STATUS = "DOWNLOADSTATUS";
- public static final String FLAGS = "DOWNLOADFLAGS";
-
- public static final String[][] SCHEMA = {
- { BaseColumns._ID, "INTEGER PRIMARY KEY" },
- { APKVERSION, "INTEGER" }, { DOWNLOAD_STATUS, "INTEGER" },
- { FLAGS, "INTEGER" }
- };
- public static final String TABLE_NAME = "MetadataColumns";
- public static final String _ID = "MetadataColumns._id";
- }
-
- public static class DownloadColumns implements BaseColumns {
- public static final String INDEX = "FILEIDX";
- public static final String URI = "URI";
- public static final String FILENAME = "FN";
- public static final String ETAG = "ETAG";
-
- public static final String TOTALBYTES = "TOTALBYTES";
- public static final String CURRENTBYTES = "CURRENTBYTES";
- public static final String LASTMOD = "LASTMOD";
-
- public static final String STATUS = "STATUS";
- public static final String CONTROL = "CONTROL";
- public static final String NUM_FAILED = "FAILCOUNT";
- public static final String RETRY_AFTER = "RETRYAFTER";
- public static final String REDIRECT_COUNT = "REDIRECTCOUNT";
-
- public static final String[][] SCHEMA = {
- { BaseColumns._ID, "INTEGER PRIMARY KEY" },
- { INDEX, "INTEGER UNIQUE" }, { URI, "TEXT" },
- { FILENAME, "TEXT UNIQUE" }, { ETAG, "TEXT" },
- { TOTALBYTES, "INTEGER" }, { CURRENTBYTES, "INTEGER" },
- { LASTMOD, "INTEGER" }, { STATUS, "INTEGER" },
- { CONTROL, "INTEGER" }, { NUM_FAILED, "INTEGER" },
- { RETRY_AFTER, "INTEGER" }, { REDIRECT_COUNT, "INTEGER" }
- };
- public static final String TABLE_NAME = "DownloadColumns";
- public static final String _ID = "DownloadColumns._id";
- }
-
- private static final String[] DC_PROJECTION = {
- DownloadColumns.FILENAME,
- DownloadColumns.URI, DownloadColumns.ETAG,
- DownloadColumns.TOTALBYTES, DownloadColumns.CURRENTBYTES,
- DownloadColumns.LASTMOD, DownloadColumns.STATUS,
- DownloadColumns.CONTROL, DownloadColumns.NUM_FAILED,
- DownloadColumns.RETRY_AFTER, DownloadColumns.REDIRECT_COUNT,
- DownloadColumns.INDEX
- };
-
- private static final int FILENAME_IDX = 0;
- private static final int URI_IDX = 1;
- private static final int ETAG_IDX = 2;
- private static final int TOTALBYTES_IDX = 3;
- private static final int CURRENTBYTES_IDX = 4;
- private static final int LASTMOD_IDX = 5;
- private static final int STATUS_IDX = 6;
- private static final int CONTROL_IDX = 7;
- private static final int NUM_FAILED_IDX = 8;
- private static final int RETRY_AFTER_IDX = 9;
- private static final int REDIRECT_COUNT_IDX = 10;
- private static final int INDEX_IDX = 11;
-
- /**
+ public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
+ int numSchemas = sSchemas.length;
+ for (int i = 0; i < numSchemas; i++) {
+ try {
+ String[][] schema = (String[][]) sSchemas[i];
+ paramSQLiteDatabase.execSQL(createTableQueryFromArray(
+ sTables[i], schema));
+ } catch (Exception localException) {
+ while (true)
+ localException.printStackTrace();
+ }
+ }
+ }
+
+ public void onUpgrade(SQLiteDatabase paramSQLiteDatabase,
+ int paramInt1, int paramInt2) {
+ Log.w(DownloadsContentDBHelper.class.getName(),
+ "Upgrading database from version " + paramInt1 + " to "
+ + paramInt2 + ", which will destroy all old data");
+ dropTables(paramSQLiteDatabase);
+ onCreate(paramSQLiteDatabase);
+ }
+ }
+
+ public static class MetadataColumns implements BaseColumns {
+ public static final String APKVERSION = "APKVERSION";
+ public static final String DOWNLOAD_STATUS = "DOWNLOADSTATUS";
+ public static final String FLAGS = "DOWNLOADFLAGS";
+
+ public static final String[][] SCHEMA = {
+ {
+ BaseColumns._ID, "INTEGER PRIMARY KEY"
+ },
+ {
+ APKVERSION, "INTEGER"
+ }, {
+ DOWNLOAD_STATUS, "INTEGER"
+ },
+ {
+ FLAGS, "INTEGER"
+ }
+ };
+ public static final String TABLE_NAME = "MetadataColumns";
+ public static final String _ID = "MetadataColumns._id";
+ }
+
+ public static class DownloadColumns implements BaseColumns {
+ public static final String INDEX = "FILEIDX";
+ public static final String URI = "URI";
+ public static final String FILENAME = "FN";
+ public static final String ETAG = "ETAG";
+
+ public static final String TOTALBYTES = "TOTALBYTES";
+ public static final String CURRENTBYTES = "CURRENTBYTES";
+ public static final String LASTMOD = "LASTMOD";
+
+ public static final String STATUS = "STATUS";
+ public static final String CONTROL = "CONTROL";
+ public static final String NUM_FAILED = "FAILCOUNT";
+ public static final String RETRY_AFTER = "RETRYAFTER";
+ public static final String REDIRECT_COUNT = "REDIRECTCOUNT";
+
+ public static final String[][] SCHEMA = {
+ {
+ BaseColumns._ID, "INTEGER PRIMARY KEY"
+ },
+ {
+ INDEX, "INTEGER UNIQUE"
+ }, {
+ URI, "TEXT"
+ },
+ {
+ FILENAME, "TEXT UNIQUE"
+ }, {
+ ETAG, "TEXT"
+ },
+ {
+ TOTALBYTES, "INTEGER"
+ }, {
+ CURRENTBYTES, "INTEGER"
+ },
+ {
+ LASTMOD, "INTEGER"
+ }, {
+ STATUS, "INTEGER"
+ },
+ {
+ CONTROL, "INTEGER"
+ }, {
+ NUM_FAILED, "INTEGER"
+ },
+ {
+ RETRY_AFTER, "INTEGER"
+ }, {
+ REDIRECT_COUNT, "INTEGER"
+ }
+ };
+ public static final String TABLE_NAME = "DownloadColumns";
+ public static final String _ID = "DownloadColumns._id";
+ }
+
+ private static final String[] DC_PROJECTION = {
+ DownloadColumns.FILENAME,
+ DownloadColumns.URI, DownloadColumns.ETAG,
+ DownloadColumns.TOTALBYTES, DownloadColumns.CURRENTBYTES,
+ DownloadColumns.LASTMOD, DownloadColumns.STATUS,
+ DownloadColumns.CONTROL, DownloadColumns.NUM_FAILED,
+ DownloadColumns.RETRY_AFTER, DownloadColumns.REDIRECT_COUNT,
+ DownloadColumns.INDEX
+ };
+
+ private static final int FILENAME_IDX = 0;
+ private static final int URI_IDX = 1;
+ private static final int ETAG_IDX = 2;
+ private static final int TOTALBYTES_IDX = 3;
+ private static final int CURRENTBYTES_IDX = 4;
+ private static final int LASTMOD_IDX = 5;
+ private static final int STATUS_IDX = 6;
+ private static final int CONTROL_IDX = 7;
+ private static final int NUM_FAILED_IDX = 8;
+ private static final int RETRY_AFTER_IDX = 9;
+ private static final int REDIRECT_COUNT_IDX = 10;
+ private static final int INDEX_IDX = 11;
+
+ /**
* This function will add a new file to the database if it does not exist.
*
* @param di DownloadInfo that we wish to store
* @return the row id of the record to be updated/inserted, or -1
*/
- public boolean updateDownload(DownloadInfo di) {
- ContentValues cv = new ContentValues();
- cv.put(DownloadColumns.INDEX, di.mIndex);
- cv.put(DownloadColumns.FILENAME, di.mFileName);
- cv.put(DownloadColumns.URI, di.mUri);
- cv.put(DownloadColumns.ETAG, di.mETag);
- cv.put(DownloadColumns.TOTALBYTES, di.mTotalBytes);
- cv.put(DownloadColumns.CURRENTBYTES, di.mCurrentBytes);
- cv.put(DownloadColumns.LASTMOD, di.mLastMod);
- cv.put(DownloadColumns.STATUS, di.mStatus);
- cv.put(DownloadColumns.CONTROL, di.mControl);
- cv.put(DownloadColumns.NUM_FAILED, di.mNumFailed);
- cv.put(DownloadColumns.RETRY_AFTER, di.mRetryAfter);
- cv.put(DownloadColumns.REDIRECT_COUNT, di.mRedirectCount);
- return updateDownload(di, cv);
- }
-
- public boolean updateDownload(DownloadInfo di, ContentValues cv) {
- long id = di == null ? -1 : getIDForDownloadInfo(di);
- try {
- final SQLiteDatabase sqldb = mHelper.getWritableDatabase();
- if (id != -1) {
- if (1 != sqldb.update(DownloadColumns.TABLE_NAME,
- cv, DownloadColumns._ID + " = " + id, null)) {
- return false;
- }
- } else {
- return -1 != sqldb.insert(DownloadColumns.TABLE_NAME,
- DownloadColumns.URI, cv);
- }
- } catch (android.database.sqlite.SQLiteException ex) {
- ex.printStackTrace();
- }
- return false;
- }
-
- public int getLastCheckedVersionCode() {
- return mVersionCode;
- }
-
- public boolean isDownloadRequired() {
- final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
- Cursor cur = sqldb.rawQuery("SELECT Count(*) FROM " + DownloadColumns.TABLE_NAME + " WHERE " + DownloadColumns.STATUS + " <> 0", null);
- try {
- if (null != cur && cur.moveToFirst()) {
- return 0 == cur.getInt(0);
- }
- } finally {
- if (null != cur)
- cur.close();
- }
- return true;
- }
-
- public int getFlags() {
- return mFlags;
- }
-
- public boolean updateFlags(int flags) {
- if (mFlags != flags) {
- ContentValues cv = new ContentValues();
- cv.put(MetadataColumns.FLAGS, flags);
- if (updateMetadata(cv)) {
- mFlags = flags;
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- };
-
- public boolean updateStatus(int status) {
- if (mStatus != status) {
- ContentValues cv = new ContentValues();
- cv.put(MetadataColumns.DOWNLOAD_STATUS, status);
- if (updateMetadata(cv)) {
- mStatus = status;
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- };
-
- public boolean updateMetadata(ContentValues cv) {
- final SQLiteDatabase sqldb = mHelper.getWritableDatabase();
- if (-1 == this.mMetadataRowID) {
- long newID = sqldb.insert(MetadataColumns.TABLE_NAME,
- MetadataColumns.APKVERSION, cv);
- if (-1 == newID)
- return false;
- mMetadataRowID = newID;
- } else {
- if (0 == sqldb.update(MetadataColumns.TABLE_NAME, cv,
- BaseColumns._ID + " = " + mMetadataRowID, null))
- return false;
- }
- return true;
- }
-
- public boolean updateMetadata(int apkVersion, int downloadStatus) {
- ContentValues cv = new ContentValues();
- cv.put(MetadataColumns.APKVERSION, apkVersion);
- cv.put(MetadataColumns.DOWNLOAD_STATUS, downloadStatus);
- if (updateMetadata(cv)) {
- mVersionCode = apkVersion;
- mStatus = downloadStatus;
- return true;
- } else {
- return false;
- }
- };
-
- public boolean updateFromDb(DownloadInfo di) {
- final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
- Cursor cur = null;
- try {
- cur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION,
- DownloadColumns.FILENAME + "= ?",
- new String[] {
- di.mFileName },
- null, null, null);
- if (null != cur && cur.moveToFirst()) {
- setDownloadInfoFromCursor(di, cur);
- return true;
- }
- return false;
- } finally {
- if (null != cur) {
- cur.close();
- }
- }
- }
-
- public void setDownloadInfoFromCursor(DownloadInfo di, Cursor cur) {
- di.mUri = cur.getString(URI_IDX);
- di.mETag = cur.getString(ETAG_IDX);
- di.mTotalBytes = cur.getLong(TOTALBYTES_IDX);
- di.mCurrentBytes = cur.getLong(CURRENTBYTES_IDX);
- di.mLastMod = cur.getLong(LASTMOD_IDX);
- di.mStatus = cur.getInt(STATUS_IDX);
- di.mControl = cur.getInt(CONTROL_IDX);
- di.mNumFailed = cur.getInt(NUM_FAILED_IDX);
- di.mRetryAfter = cur.getInt(RETRY_AFTER_IDX);
- di.mRedirectCount = cur.getInt(REDIRECT_COUNT_IDX);
- }
-
- public DownloadInfo getDownloadInfoFromCursor(Cursor cur) {
- DownloadInfo di = new DownloadInfo(cur.getInt(INDEX_IDX),
- cur.getString(FILENAME_IDX), this.getClass().getPackage().getName());
- setDownloadInfoFromCursor(di, cur);
- return di;
- }
-
- public DownloadInfo[] getDownloads() {
- final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
- Cursor cur = null;
- try {
- cur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION, null,
- null, null, null, null);
- if (null != cur && cur.moveToFirst()) {
- DownloadInfo[] retInfos = new DownloadInfo[cur.getCount()];
- int idx = 0;
- do {
- DownloadInfo di = getDownloadInfoFromCursor(cur);
- retInfos[idx++] = di;
- } while (cur.moveToNext());
- return retInfos;
- }
- return null;
- } finally {
- if (null != cur) {
- cur.close();
- }
- }
- }
+ public boolean updateDownload(DownloadInfo di) {
+ ContentValues cv = new ContentValues();
+ cv.put(DownloadColumns.INDEX, di.mIndex);
+ cv.put(DownloadColumns.FILENAME, di.mFileName);
+ cv.put(DownloadColumns.URI, di.mUri);
+ cv.put(DownloadColumns.ETAG, di.mETag);
+ cv.put(DownloadColumns.TOTALBYTES, di.mTotalBytes);
+ cv.put(DownloadColumns.CURRENTBYTES, di.mCurrentBytes);
+ cv.put(DownloadColumns.LASTMOD, di.mLastMod);
+ cv.put(DownloadColumns.STATUS, di.mStatus);
+ cv.put(DownloadColumns.CONTROL, di.mControl);
+ cv.put(DownloadColumns.NUM_FAILED, di.mNumFailed);
+ cv.put(DownloadColumns.RETRY_AFTER, di.mRetryAfter);
+ cv.put(DownloadColumns.REDIRECT_COUNT, di.mRedirectCount);
+ return updateDownload(di, cv);
+ }
+
+ public boolean updateDownload(DownloadInfo di, ContentValues cv) {
+ long id = di == null ? -1 : getIDForDownloadInfo(di);
+ try {
+ final SQLiteDatabase sqldb = mHelper.getWritableDatabase();
+ if (id != -1) {
+ if (1 != sqldb.update(DownloadColumns.TABLE_NAME,
+ cv, DownloadColumns._ID + " = " + id, null)) {
+ return false;
+ }
+ } else {
+ return -1 != sqldb.insert(DownloadColumns.TABLE_NAME,
+ DownloadColumns.URI, cv);
+ }
+ } catch (android.database.sqlite.SQLiteException ex) {
+ ex.printStackTrace();
+ }
+ return false;
+ }
+
+ public int getLastCheckedVersionCode() {
+ return mVersionCode;
+ }
+
+ public boolean isDownloadRequired() {
+ final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
+ Cursor cur = sqldb.rawQuery("SELECT Count(*) FROM "
+ + DownloadColumns.TABLE_NAME + " WHERE "
+ + DownloadColumns.STATUS + " <> 0", null);
+ try {
+ if (null != cur && cur.moveToFirst()) {
+ return 0 == cur.getInt(0);
+ }
+ } finally {
+ if (null != cur)
+ cur.close();
+ }
+ return true;
+ }
+
+ public int getFlags() {
+ return mFlags;
+ }
+
+ public boolean updateFlags(int flags) {
+ if (mFlags != flags) {
+ ContentValues cv = new ContentValues();
+ cv.put(MetadataColumns.FLAGS, flags);
+ if (updateMetadata(cv)) {
+ mFlags = flags;
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return true;
+ }
+ };
+
+ public boolean updateStatus(int status) {
+ if (mStatus != status) {
+ ContentValues cv = new ContentValues();
+ cv.put(MetadataColumns.DOWNLOAD_STATUS, status);
+ if (updateMetadata(cv)) {
+ mStatus = status;
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return true;
+ }
+ };
+
+ public boolean updateMetadata(ContentValues cv) {
+ final SQLiteDatabase sqldb = mHelper.getWritableDatabase();
+ if (-1 == this.mMetadataRowID) {
+ long newID = sqldb.insert(MetadataColumns.TABLE_NAME,
+ MetadataColumns.APKVERSION, cv);
+ if (-1 == newID)
+ return false;
+ mMetadataRowID = newID;
+ } else {
+ if (0 == sqldb.update(MetadataColumns.TABLE_NAME, cv,
+ BaseColumns._ID + " = " + mMetadataRowID, null))
+ return false;
+ }
+ return true;
+ }
+
+ public boolean updateMetadata(int apkVersion, int downloadStatus) {
+ ContentValues cv = new ContentValues();
+ cv.put(MetadataColumns.APKVERSION, apkVersion);
+ cv.put(MetadataColumns.DOWNLOAD_STATUS, downloadStatus);
+ if (updateMetadata(cv)) {
+ mVersionCode = apkVersion;
+ mStatus = downloadStatus;
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ public boolean updateFromDb(DownloadInfo di) {
+ final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
+ Cursor cur = null;
+ try {
+ cur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION,
+ DownloadColumns.FILENAME + "= ?",
+ new String[] {
+ di.mFileName
+ }, null, null, null);
+ if (null != cur && cur.moveToFirst()) {
+ setDownloadInfoFromCursor(di, cur);
+ return true;
+ }
+ return false;
+ } finally {
+ if (null != cur) {
+ cur.close();
+ }
+ }
+ }
+
+ public void setDownloadInfoFromCursor(DownloadInfo di, Cursor cur) {
+ di.mUri = cur.getString(URI_IDX);
+ di.mETag = cur.getString(ETAG_IDX);
+ di.mTotalBytes = cur.getLong(TOTALBYTES_IDX);
+ di.mCurrentBytes = cur.getLong(CURRENTBYTES_IDX);
+ di.mLastMod = cur.getLong(LASTMOD_IDX);
+ di.mStatus = cur.getInt(STATUS_IDX);
+ di.mControl = cur.getInt(CONTROL_IDX);
+ di.mNumFailed = cur.getInt(NUM_FAILED_IDX);
+ di.mRetryAfter = cur.getInt(RETRY_AFTER_IDX);
+ di.mRedirectCount = cur.getInt(REDIRECT_COUNT_IDX);
+ }
+
+ public DownloadInfo getDownloadInfoFromCursor(Cursor cur) {
+ DownloadInfo di = new DownloadInfo(cur.getInt(INDEX_IDX),
+ cur.getString(FILENAME_IDX), this.getClass().getPackage()
+ .getName());
+ setDownloadInfoFromCursor(di, cur);
+ return di;
+ }
+
+ public DownloadInfo[] getDownloads() {
+ final SQLiteDatabase sqldb = mHelper.getReadableDatabase();
+ Cursor cur = null;
+ try {
+ cur = sqldb.query(DownloadColumns.TABLE_NAME, DC_PROJECTION, null,
+ null, null, null, null);
+ if (null != cur && cur.moveToFirst()) {
+ DownloadInfo[] retInfos = new DownloadInfo[cur.getCount()];
+ int idx = 0;
+ do {
+ DownloadInfo di = getDownloadInfoFromCursor(cur);
+ retInfos[idx++] = di;
+ } while (cur.moveToNext());
+ return retInfos;
+ }
+ return null;
+ } finally {
+ if (null != cur) {
+ cur.close();
+ }
+ }
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/HttpDateTime.java b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/HttpDateTime.java
index 02bd1f27f6..3f440e9893 100644
--- a/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/HttpDateTime.java
+++ b/platform/android/java/src/com/google/android/vending/expansion/downloader/impl/HttpDateTime.java
@@ -27,7 +27,7 @@ import java.util.regex.Pattern;
*/
public final class HttpDateTime {
- /*
+ /*
* Regular expression for parsing HTTP-date. Wdy, DD Mon YYYY HH:MM:SS GMT
* RFC 822, updated by RFC 1123 Weekday, DD-Mon-YY HH:MM:SS GMT RFC 850,
* obsoleted by RFC 1036 Wdy Mon DD HH:MM:SS YYYY ANSI C's asctime() format
@@ -37,155 +37,164 @@ public final class HttpDateTime {
* (SP)D HH:MM:SS YYYY Wdy Mon DD HH:MM:SS YYYY GMT HH can be H if the first
* digit is zero. Mon can be the full name of the month.
*/
- private static final String HTTP_DATE_RFC_REGEXP =
- "([0-9]{1,2})[- ]([A-Za-z]{3,9})[- ]([0-9]{2,4})[ ]"
- + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])";
+ private static final String HTTP_DATE_RFC_REGEXP =
+ "([0-9]{1,2})[- ]([A-Za-z]{3,9})[- ]([0-9]{2,4})[ ]"
+ + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])";
- private static final String HTTP_DATE_ANSIC_REGEXP =
- "[ ]([A-Za-z]{3,9})[ ]+([0-9]{1,2})[ ]"
- + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])[ ]([0-9]{2,4})";
+ private static final String HTTP_DATE_ANSIC_REGEXP =
+ "[ ]([A-Za-z]{3,9})[ ]+([0-9]{1,2})[ ]"
+ + "([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])[ ]([0-9]{2,4})";
- /**
+ /**
* The compiled version of the HTTP-date regular expressions.
*/
- private static final Pattern HTTP_DATE_RFC_PATTERN =
- Pattern.compile(HTTP_DATE_RFC_REGEXP);
- private static final Pattern HTTP_DATE_ANSIC_PATTERN =
- Pattern.compile(HTTP_DATE_ANSIC_REGEXP);
-
- private static class TimeOfDay {
- TimeOfDay(int h, int m, int s) {
- this.hour = h;
- this.minute = m;
- this.second = s;
- }
-
- int hour;
- int minute;
- int second;
- }
-
- public static long parse(String timeString)
- throws IllegalArgumentException {
-
- int date = 1;
- int month = Calendar.JANUARY;
- int year = 1970;
- TimeOfDay timeOfDay;
-
- Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
- if (rfcMatcher.find()) {
- date = getDate(rfcMatcher.group(1));
- month = getMonth(rfcMatcher.group(2));
- year = getYear(rfcMatcher.group(3));
- timeOfDay = getTime(rfcMatcher.group(4));
- } else {
- Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
- if (ansicMatcher.find()) {
- month = getMonth(ansicMatcher.group(1));
- date = getDate(ansicMatcher.group(2));
- timeOfDay = getTime(ansicMatcher.group(3));
- year = getYear(ansicMatcher.group(4));
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- // FIXME: Y2038 BUG!
- if (year >= 2038) {
- year = 2038;
- month = Calendar.JANUARY;
- date = 1;
- }
-
- Time time = new Time(Time.TIMEZONE_UTC);
- time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
- month, year);
- return time.toMillis(false /* use isDst */);
- }
-
- private static int getDate(String dateString) {
- if (dateString.length() == 2) {
- return (dateString.charAt(0) - '0') * 10 + (dateString.charAt(1) - '0');
- } else {
- return (dateString.charAt(0) - '0');
- }
- }
-
- /*
+ private static final Pattern HTTP_DATE_RFC_PATTERN =
+ Pattern.compile(HTTP_DATE_RFC_REGEXP);
+ private static final Pattern HTTP_DATE_ANSIC_PATTERN =
+ Pattern.compile(HTTP_DATE_ANSIC_REGEXP);
+
+ private static class TimeOfDay {
+ TimeOfDay(int h, int m, int s) {
+ this.hour = h;
+ this.minute = m;
+ this.second = s;
+ }
+
+ int hour;
+ int minute;
+ int second;
+ }
+
+ public static long parse(String timeString)
+ throws IllegalArgumentException {
+
+ int date = 1;
+ int month = Calendar.JANUARY;
+ int year = 1970;
+ TimeOfDay timeOfDay;
+
+ Matcher rfcMatcher = HTTP_DATE_RFC_PATTERN.matcher(timeString);
+ if (rfcMatcher.find()) {
+ date = getDate(rfcMatcher.group(1));
+ month = getMonth(rfcMatcher.group(2));
+ year = getYear(rfcMatcher.group(3));
+ timeOfDay = getTime(rfcMatcher.group(4));
+ } else {
+ Matcher ansicMatcher = HTTP_DATE_ANSIC_PATTERN.matcher(timeString);
+ if (ansicMatcher.find()) {
+ month = getMonth(ansicMatcher.group(1));
+ date = getDate(ansicMatcher.group(2));
+ timeOfDay = getTime(ansicMatcher.group(3));
+ year = getYear(ansicMatcher.group(4));
+ } else {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ // FIXME: Y2038 BUG!
+ if (year >= 2038) {
+ year = 2038;
+ month = Calendar.JANUARY;
+ date = 1;
+ }
+
+ Time time = new Time(Time.TIMEZONE_UTC);
+ time.set(timeOfDay.second, timeOfDay.minute, timeOfDay.hour, date,
+ month, year);
+ return time.toMillis(false /* use isDst */);
+ }
+
+ private static int getDate(String dateString) {
+ if (dateString.length() == 2) {
+ return (dateString.charAt(0) - '0') * 10
+ + (dateString.charAt(1) - '0');
+ } else {
+ return (dateString.charAt(0) - '0');
+ }
+ }
+
+ /*
* jan = 9 + 0 + 13 = 22 feb = 5 + 4 + 1 = 10 mar = 12 + 0 + 17 = 29 apr = 0
* + 15 + 17 = 32 may = 12 + 0 + 24 = 36 jun = 9 + 20 + 13 = 42 jul = 9 + 20
* + 11 = 40 aug = 0 + 20 + 6 = 26 sep = 18 + 4 + 15 = 37 oct = 14 + 2 + 19
* = 35 nov = 13 + 14 + 21 = 48 dec = 3 + 4 + 2 = 9
*/
- private static int getMonth(String monthString) {
- int hash = Character.toLowerCase(monthString.charAt(0)) +
- Character.toLowerCase(monthString.charAt(1)) +
- Character.toLowerCase(monthString.charAt(2)) - 3 * 'a';
- switch (hash) {
- case 22:
- return Calendar.JANUARY;
- case 10:
- return Calendar.FEBRUARY;
- case 29:
- return Calendar.MARCH;
- case 32:
- return Calendar.APRIL;
- case 36:
- return Calendar.MAY;
- case 42:
- return Calendar.JUNE;
- case 40:
- return Calendar.JULY;
- case 26:
- return Calendar.AUGUST;
- case 37:
- return Calendar.SEPTEMBER;
- case 35:
- return Calendar.OCTOBER;
- case 48:
- return Calendar.NOVEMBER;
- case 9:
- return Calendar.DECEMBER;
- default:
- throw new IllegalArgumentException();
- }
- }
-
- private static int getYear(String yearString) {
- if (yearString.length() == 2) {
- int year = (yearString.charAt(0) - '0') * 10 + (yearString.charAt(1) - '0');
- if (year >= 70) {
- return year + 1900;
- } else {
- return year + 2000;
- }
- } else if (yearString.length() == 3) {
- // According to RFC 2822, three digit years should be added to 1900.
- int year = (yearString.charAt(0) - '0') * 100 + (yearString.charAt(1) - '0') * 10 + (yearString.charAt(2) - '0');
- return year + 1900;
- } else if (yearString.length() == 4) {
- return (yearString.charAt(0) - '0') * 1000 + (yearString.charAt(1) - '0') * 100 + (yearString.charAt(2) - '0') * 10 + (yearString.charAt(3) - '0');
- } else {
- return 1970;
- }
- }
-
- private static TimeOfDay getTime(String timeString) {
- // HH might be H
- int i = 0;
- int hour = timeString.charAt(i++) - '0';
- if (timeString.charAt(i) != ':')
- hour = hour * 10 + (timeString.charAt(i++) - '0');
- // Skip ':'
- i++;
-
- int minute = (timeString.charAt(i++) - '0') * 10 + (timeString.charAt(i++) - '0');
- // Skip ':'
- i++;
-
- int second = (timeString.charAt(i++) - '0') * 10 + (timeString.charAt(i++) - '0');
-
- return new TimeOfDay(hour, minute, second);
- }
+ private static int getMonth(String monthString) {
+ int hash = Character.toLowerCase(monthString.charAt(0)) +
+ Character.toLowerCase(monthString.charAt(1)) +
+ Character.toLowerCase(monthString.charAt(2)) - 3 * 'a';
+ switch (hash) {
+ case 22:
+ return Calendar.JANUARY;
+ case 10:
+ return Calendar.FEBRUARY;
+ case 29:
+ return Calendar.MARCH;
+ case 32:
+ return Calendar.APRIL;
+ case 36:
+ return Calendar.MAY;
+ case 42:
+ return Calendar.JUNE;
+ case 40:
+ return Calendar.JULY;
+ case 26:
+ return Calendar.AUGUST;
+ case 37:
+ return Calendar.SEPTEMBER;
+ case 35:
+ return Calendar.OCTOBER;
+ case 48:
+ return Calendar.NOVEMBER;
+ case 9:
+ return Calendar.DECEMBER;
+ default:
+ throw new IllegalArgumentException();
+ }
+ }
+
+ private static int getYear(String yearString) {
+ if (yearString.length() == 2) {
+ int year = (yearString.charAt(0) - '0') * 10
+ + (yearString.charAt(1) - '0');
+ if (year >= 70) {
+ return year + 1900;
+ } else {
+ return year + 2000;
+ }
+ } else if (yearString.length() == 3) {
+ // According to RFC 2822, three digit years should be added to 1900.
+ int year = (yearString.charAt(0) - '0') * 100
+ + (yearString.charAt(1) - '0') * 10
+ + (yearString.charAt(2) - '0');
+ return year + 1900;
+ } else if (yearString.length() == 4) {
+ return (yearString.charAt(0) - '0') * 1000
+ + (yearString.charAt(1) - '0') * 100
+ + (yearString.charAt(2) - '0') * 10
+ + (yearString.charAt(3) - '0');
+ } else {
+ return 1970;
+ }
+ }
+
+ private static TimeOfDay getTime(String timeString) {
+ // HH might be H
+ int i = 0;
+ int hour = timeString.charAt(i++) - '0';
+ if (timeString.charAt(i) != ':')
+ hour = hour * 10 + (timeString.charAt(i++) - '0');
+ // Skip ':'
+ i++;
+
+ int minute = (timeString.charAt(i++) - '0') * 10
+ + (timeString.charAt(i++) - '0');
+ // Skip ':'
+ i++;
+
+ int second = (timeString.charAt(i++) - '0') * 10
+ + (timeString.charAt(i++) - '0');
+
+ return new TimeOfDay(hour, minute, second);
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/AESObfuscator.java b/platform/android/java/src/com/google/android/vending/licensing/AESObfuscator.java
index feba3034c3..d6ccb0c5e4 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/AESObfuscator.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/AESObfuscator.java
@@ -36,75 +36,75 @@ import javax.crypto.spec.SecretKeySpec;
* An Obfuscator that uses AES to encrypt data.
*/
public class AESObfuscator implements Obfuscator {
- private static final String UTF8 = "UTF-8";
- private static final String KEYGEN_ALGORITHM = "PBEWITHSHAAND256BITAES-CBC-BC";
- private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
- private static final byte[] IV = { 16, 74, 71, -80, 32, 101, -47, 72, 117, -14, 0, -29, 70, 65, -12, 74 };
- private static final String header = "com.google.android.vending.licensing.AESObfuscator-1|";
+ private static final String UTF8 = "UTF-8";
+ private static final String KEYGEN_ALGORITHM = "PBEWITHSHAAND256BITAES-CBC-BC";
+ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
+ private static final byte[] IV =
+ { 16, 74, 71, -80, 32, 101, -47, 72, 117, -14, 0, -29, 70, 65, -12, 74 };
+ private static final String header = "com.google.android.vending.licensing.AESObfuscator-1|";
- private Cipher mEncryptor;
- private Cipher mDecryptor;
+ private Cipher mEncryptor;
+ private Cipher mDecryptor;
- /**
+ /**
* @param salt an array of random bytes to use for each (un)obfuscation
* @param applicationId application identifier, e.g. the package name
* @param deviceId device identifier. Use as many sources as possible to
* create this unique identifier.
*/
- public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
- try {
- SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
- KeySpec keySpec =
- new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
- SecretKey tmp = factory.generateSecret(keySpec);
- SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
- mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
- mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
- mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
- mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
- } catch (GeneralSecurityException e) {
- // This can't happen on a compatible Android device.
- throw new RuntimeException("Invalid environment", e);
- }
- }
+ public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
+ try {
+ SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
+ KeySpec keySpec =
+ new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
+ SecretKey tmp = factory.generateSecret(keySpec);
+ SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
+ mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
+ mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
+ mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
+ mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
+ } catch (GeneralSecurityException e) {
+ // This can't happen on a compatible Android device.
+ throw new RuntimeException("Invalid environment", e);
+ }
+ }
- public String obfuscate(String original, String key) {
- if (original == null) {
- return null;
- }
- try {
- // Header is appended as an integrity check
- return Base64.encode(mEncryptor.doFinal((header + key + original).getBytes(UTF8)));
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException("Invalid environment", e);
- } catch (GeneralSecurityException e) {
- throw new RuntimeException("Invalid environment", e);
- }
- }
+ public String obfuscate(String original, String key) {
+ if (original == null) {
+ return null;
+ }
+ try {
+ // Header is appended as an integrity check
+ return Base64.encode(mEncryptor.doFinal((header + key + original).getBytes(UTF8)));
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException("Invalid environment", e);
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException("Invalid environment", e);
+ }
+ }
- public String unobfuscate(String obfuscated, String key) throws ValidationException {
- if (obfuscated == null) {
- return null;
- }
- try {
- String result = new String(mDecryptor.doFinal(Base64.decode(obfuscated)), UTF8);
- // Check for presence of header. This serves as a final integrity check, for cases
- // where the block size is correct during decryption.
- int headerIndex = result.indexOf(header + key);
- if (headerIndex != 0) {
- throw new ValidationException("Header not found (invalid data or key)"
- + ":" +
- obfuscated);
- }
- return result.substring(header.length() + key.length(), result.length());
- } catch (Base64DecoderException e) {
- throw new ValidationException(e.getMessage() + ":" + obfuscated);
- } catch (IllegalBlockSizeException e) {
- throw new ValidationException(e.getMessage() + ":" + obfuscated);
- } catch (BadPaddingException e) {
- throw new ValidationException(e.getMessage() + ":" + obfuscated);
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException("Invalid environment", e);
- }
- }
+ public String unobfuscate(String obfuscated, String key) throws ValidationException {
+ if (obfuscated == null) {
+ return null;
+ }
+ try {
+ String result = new String(mDecryptor.doFinal(Base64.decode(obfuscated)), UTF8);
+ // Check for presence of header. This serves as a final integrity check, for cases
+ // where the block size is correct during decryption.
+ int headerIndex = result.indexOf(header+key);
+ if (headerIndex != 0) {
+ throw new ValidationException("Header not found (invalid data or key)" + ":" +
+ obfuscated);
+ }
+ return result.substring(header.length()+key.length(), result.length());
+ } catch (Base64DecoderException e) {
+ throw new ValidationException(e.getMessage() + ":" + obfuscated);
+ } catch (IllegalBlockSizeException e) {
+ throw new ValidationException(e.getMessage() + ":" + obfuscated);
+ } catch (BadPaddingException e) {
+ throw new ValidationException(e.getMessage() + ":" + obfuscated);
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException("Invalid environment", e);
+ }
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/APKExpansionPolicy.java b/platform/android/java/src/com/google/android/vending/licensing/APKExpansionPolicy.java
index 2c60e7e4b8..37fad8926a 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/APKExpansionPolicy.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/APKExpansionPolicy.java
@@ -46,73 +46,73 @@ import java.util.Vector;
*/
public class APKExpansionPolicy implements Policy {
- private static final String TAG = "APKExpansionPolicy";
- private static final String PREFS_FILE = "com.google.android.vending.licensing.APKExpansionPolicy";
- private static final String PREF_LAST_RESPONSE = "lastResponse";
- private static final String PREF_VALIDITY_TIMESTAMP = "validityTimestamp";
- private static final String PREF_RETRY_UNTIL = "retryUntil";
- private static final String PREF_MAX_RETRIES = "maxRetries";
- private static final String PREF_RETRY_COUNT = "retryCount";
- private static final String PREF_LICENSING_URL = "licensingUrl";
- private static final String DEFAULT_VALIDITY_TIMESTAMP = "0";
- private static final String DEFAULT_RETRY_UNTIL = "0";
- private static final String DEFAULT_MAX_RETRIES = "0";
- private static final String DEFAULT_RETRY_COUNT = "0";
-
- private static final long MILLIS_PER_MINUTE = 60 * 1000;
-
- private long mValidityTimestamp;
- private long mRetryUntil;
- private long mMaxRetries;
- private long mRetryCount;
- private long mLastResponseTime = 0;
- private int mLastResponse;
- private String mLicensingUrl;
- private PreferenceObfuscator mPreferences;
- private Vector<String> mExpansionURLs = new Vector<String>();
- private Vector<String> mExpansionFileNames = new Vector<String>();
- private Vector<Long> mExpansionFileSizes = new Vector<Long>();
-
- /**
+ private static final String TAG = "APKExpansionPolicy";
+ private static final String PREFS_FILE = "com.google.android.vending.licensing.APKExpansionPolicy";
+ private static final String PREF_LAST_RESPONSE = "lastResponse";
+ private static final String PREF_VALIDITY_TIMESTAMP = "validityTimestamp";
+ private static final String PREF_RETRY_UNTIL = "retryUntil";
+ private static final String PREF_MAX_RETRIES = "maxRetries";
+ private static final String PREF_RETRY_COUNT = "retryCount";
+ private static final String PREF_LICENSING_URL = "licensingUrl";
+ private static final String DEFAULT_VALIDITY_TIMESTAMP = "0";
+ private static final String DEFAULT_RETRY_UNTIL = "0";
+ private static final String DEFAULT_MAX_RETRIES = "0";
+ private static final String DEFAULT_RETRY_COUNT = "0";
+
+ private static final long MILLIS_PER_MINUTE = 60 * 1000;
+
+ private long mValidityTimestamp;
+ private long mRetryUntil;
+ private long mMaxRetries;
+ private long mRetryCount;
+ private long mLastResponseTime = 0;
+ private int mLastResponse;
+ private String mLicensingUrl;
+ private PreferenceObfuscator mPreferences;
+ private Vector<String> mExpansionURLs = new Vector<String>();
+ private Vector<String> mExpansionFileNames = new Vector<String>();
+ private Vector<Long> mExpansionFileSizes = new Vector<Long>();
+
+ /**
* The design of the protocol supports n files. Currently the market can
* only deliver two files. To accommodate this, we have these two constants,
* but the order is the only relevant thing here.
*/
- public static final int MAIN_FILE_URL_INDEX = 0;
- public static final int PATCH_FILE_URL_INDEX = 1;
+ public static final int MAIN_FILE_URL_INDEX = 0;
+ public static final int PATCH_FILE_URL_INDEX = 1;
- /**
+ /**
* @param context The context for the current application
* @param obfuscator An obfuscator to be used with preferences.
*/
- public APKExpansionPolicy(Context context, Obfuscator obfuscator) {
- // Import old values
- SharedPreferences sp = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
- mPreferences = new PreferenceObfuscator(sp, obfuscator);
- mLastResponse = Integer.parseInt(
- mPreferences.getString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY)));
- mValidityTimestamp = Long.parseLong(mPreferences.getString(PREF_VALIDITY_TIMESTAMP,
- DEFAULT_VALIDITY_TIMESTAMP));
- mRetryUntil = Long.parseLong(mPreferences.getString(PREF_RETRY_UNTIL, DEFAULT_RETRY_UNTIL));
- mMaxRetries = Long.parseLong(mPreferences.getString(PREF_MAX_RETRIES, DEFAULT_MAX_RETRIES));
- mRetryCount = Long.parseLong(mPreferences.getString(PREF_RETRY_COUNT, DEFAULT_RETRY_COUNT));
- mLicensingUrl = mPreferences.getString(PREF_LICENSING_URL, null);
- }
-
- /**
+ public APKExpansionPolicy(Context context, Obfuscator obfuscator) {
+ // Import old values
+ SharedPreferences sp = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
+ mPreferences = new PreferenceObfuscator(sp, obfuscator);
+ mLastResponse = Integer.parseInt(
+ mPreferences.getString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY)));
+ mValidityTimestamp = Long.parseLong(mPreferences.getString(PREF_VALIDITY_TIMESTAMP,
+ DEFAULT_VALIDITY_TIMESTAMP));
+ mRetryUntil = Long.parseLong(mPreferences.getString(PREF_RETRY_UNTIL, DEFAULT_RETRY_UNTIL));
+ mMaxRetries = Long.parseLong(mPreferences.getString(PREF_MAX_RETRIES, DEFAULT_MAX_RETRIES));
+ mRetryCount = Long.parseLong(mPreferences.getString(PREF_RETRY_COUNT, DEFAULT_RETRY_COUNT));
+ mLicensingUrl = mPreferences.getString(PREF_LICENSING_URL, null);
+ }
+
+ /**
* We call this to guarantee that we fetch a fresh policy from the server.
* This is to be used if the URL is invalid.
*/
- public void resetPolicy() {
- mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY));
- setRetryUntil(DEFAULT_RETRY_UNTIL);
- setMaxRetries(DEFAULT_MAX_RETRIES);
- setRetryCount(Long.parseLong(DEFAULT_RETRY_COUNT));
- setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
- mPreferences.commit();
- }
-
- /**
+ public void resetPolicy() {
+ mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY));
+ setRetryUntil(DEFAULT_RETRY_UNTIL);
+ setMaxRetries(DEFAULT_MAX_RETRIES);
+ setRetryCount(Long.parseLong(DEFAULT_RETRY_COUNT));
+ setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
+ mPreferences.commit();
+ }
+
+ /**
* Process a new response from the license server.
* <p>
* This data will be used for computing future policy decisions. The
@@ -129,187 +129,187 @@ public class APKExpansionPolicy implements Policy {
* @param response the result from validating the server response
* @param rawData the raw server response data
*/
- public void processServerResponse(int response,
- com.google.android.vending.licensing.ResponseData rawData) {
-
- // Update retry counter
- if (response != Policy.RETRY) {
- setRetryCount(0);
- } else {
- setRetryCount(mRetryCount + 1);
- }
-
- // Update server policy data
- Map<String, String> extras = decodeExtras(rawData);
- if (response == Policy.LICENSED) {
- mLastResponse = response;
- // Reset the licensing URL since it is only applicable for NOT_LICENSED responses.
- setLicensingUrl(null);
- setValidityTimestamp(Long.toString(System.currentTimeMillis() + MILLIS_PER_MINUTE));
- Set<String> keys = extras.keySet();
- for (String key : keys) {
- if (key.equals("VT")) {
- setValidityTimestamp(extras.get(key));
- } else if (key.equals("GT")) {
- setRetryUntil(extras.get(key));
- } else if (key.equals("GR")) {
- setMaxRetries(extras.get(key));
- } else if (key.startsWith("FILE_URL")) {
- int index = Integer.parseInt(key.substring("FILE_URL".length())) - 1;
- setExpansionURL(index, extras.get(key));
- } else if (key.startsWith("FILE_NAME")) {
- int index = Integer.parseInt(key.substring("FILE_NAME".length())) - 1;
- setExpansionFileName(index, extras.get(key));
- } else if (key.startsWith("FILE_SIZE")) {
- int index = Integer.parseInt(key.substring("FILE_SIZE".length())) - 1;
- setExpansionFileSize(index, Long.parseLong(extras.get(key)));
- }
- }
- } else if (response == Policy.NOT_LICENSED) {
- // Clear out stale retry params
- setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
- setRetryUntil(DEFAULT_RETRY_UNTIL);
- setMaxRetries(DEFAULT_MAX_RETRIES);
- // Update the licensing URL
- setLicensingUrl(extras.get("LU"));
- }
-
- setLastResponse(response);
- mPreferences.commit();
- }
-
- /**
+ public void processServerResponse(int response,
+ com.google.android.vending.licensing.ResponseData rawData) {
+
+ // Update retry counter
+ if (response != Policy.RETRY) {
+ setRetryCount(0);
+ } else {
+ setRetryCount(mRetryCount + 1);
+ }
+
+ // Update server policy data
+ Map<String, String> extras = decodeExtras(rawData);
+ if (response == Policy.LICENSED) {
+ mLastResponse = response;
+ // Reset the licensing URL since it is only applicable for NOT_LICENSED responses.
+ setLicensingUrl(null);
+ setValidityTimestamp(Long.toString(System.currentTimeMillis() + MILLIS_PER_MINUTE));
+ Set<String> keys = extras.keySet();
+ for (String key : keys) {
+ if (key.equals("VT")) {
+ setValidityTimestamp(extras.get(key));
+ } else if (key.equals("GT")) {
+ setRetryUntil(extras.get(key));
+ } else if (key.equals("GR")) {
+ setMaxRetries(extras.get(key));
+ } else if (key.startsWith("FILE_URL")) {
+ int index = Integer.parseInt(key.substring("FILE_URL".length())) - 1;
+ setExpansionURL(index, extras.get(key));
+ } else if (key.startsWith("FILE_NAME")) {
+ int index = Integer.parseInt(key.substring("FILE_NAME".length())) - 1;
+ setExpansionFileName(index, extras.get(key));
+ } else if (key.startsWith("FILE_SIZE")) {
+ int index = Integer.parseInt(key.substring("FILE_SIZE".length())) - 1;
+ setExpansionFileSize(index, Long.parseLong(extras.get(key)));
+ }
+ }
+ } else if (response == Policy.NOT_LICENSED) {
+ // Clear out stale retry params
+ setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
+ setRetryUntil(DEFAULT_RETRY_UNTIL);
+ setMaxRetries(DEFAULT_MAX_RETRIES);
+ // Update the licensing URL
+ setLicensingUrl(extras.get("LU"));
+ }
+
+ setLastResponse(response);
+ mPreferences.commit();
+ }
+
+ /**
* Set the last license response received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param l the response
*/
- private void setLastResponse(int l) {
- mLastResponseTime = System.currentTimeMillis();
- mLastResponse = l;
- mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(l));
- }
+ private void setLastResponse(int l) {
+ mLastResponseTime = System.currentTimeMillis();
+ mLastResponse = l;
+ mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(l));
+ }
- /**
+ /**
* Set the current retry count and add to preferences. You must manually
* call PreferenceObfuscator.commit() to commit these changes to disk.
*
* @param c the new retry count
*/
- private void setRetryCount(long c) {
- mRetryCount = c;
- mPreferences.putString(PREF_RETRY_COUNT, Long.toString(c));
- }
+ private void setRetryCount(long c) {
+ mRetryCount = c;
+ mPreferences.putString(PREF_RETRY_COUNT, Long.toString(c));
+ }
- public long getRetryCount() {
- return mRetryCount;
- }
+ public long getRetryCount() {
+ return mRetryCount;
+ }
- /**
+ /**
* Set the last validity timestamp (VT) received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param validityTimestamp the VT string received
*/
- private void setValidityTimestamp(String validityTimestamp) {
- Long lValidityTimestamp;
- try {
- lValidityTimestamp = Long.parseLong(validityTimestamp);
- } catch (NumberFormatException e) {
- // No response or not parseable, expire in one minute.
- Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
- lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
- validityTimestamp = Long.toString(lValidityTimestamp);
- }
-
- mValidityTimestamp = lValidityTimestamp;
- mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
- }
-
- public long getValidityTimestamp() {
- return mValidityTimestamp;
- }
-
- /**
+ private void setValidityTimestamp(String validityTimestamp) {
+ Long lValidityTimestamp;
+ try {
+ lValidityTimestamp = Long.parseLong(validityTimestamp);
+ } catch (NumberFormatException e) {
+ // No response or not parseable, expire in one minute.
+ Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
+ lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
+ validityTimestamp = Long.toString(lValidityTimestamp);
+ }
+
+ mValidityTimestamp = lValidityTimestamp;
+ mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
+ }
+
+ public long getValidityTimestamp() {
+ return mValidityTimestamp;
+ }
+
+ /**
* Set the retry until timestamp (GT) received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param retryUntil the GT string received
*/
- private void setRetryUntil(String retryUntil) {
- Long lRetryUntil;
- try {
- lRetryUntil = Long.parseLong(retryUntil);
- } catch (NumberFormatException e) {
- // No response or not parseable, expire immediately
- Log.w(TAG, "License retry timestamp (GT) missing, grace period disabled");
- retryUntil = "0";
- lRetryUntil = 0l;
- }
-
- mRetryUntil = lRetryUntil;
- mPreferences.putString(PREF_RETRY_UNTIL, retryUntil);
- }
-
- public long getRetryUntil() {
- return mRetryUntil;
- }
-
- /**
+ private void setRetryUntil(String retryUntil) {
+ Long lRetryUntil;
+ try {
+ lRetryUntil = Long.parseLong(retryUntil);
+ } catch (NumberFormatException e) {
+ // No response or not parseable, expire immediately
+ Log.w(TAG, "License retry timestamp (GT) missing, grace period disabled");
+ retryUntil = "0";
+ lRetryUntil = 0l;
+ }
+
+ mRetryUntil = lRetryUntil;
+ mPreferences.putString(PREF_RETRY_UNTIL, retryUntil);
+ }
+
+ public long getRetryUntil() {
+ return mRetryUntil;
+ }
+
+ /**
* Set the max retries value (GR) as received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param maxRetries the GR string received
*/
- private void setMaxRetries(String maxRetries) {
- Long lMaxRetries;
- try {
- lMaxRetries = Long.parseLong(maxRetries);
- } catch (NumberFormatException e) {
- // No response or not parseable, expire immediately
- Log.w(TAG, "Licence retry count (GR) missing, grace period disabled");
- maxRetries = "0";
- lMaxRetries = 0l;
- }
-
- mMaxRetries = lMaxRetries;
- mPreferences.putString(PREF_MAX_RETRIES, maxRetries);
- }
-
- public long getMaxRetries() {
- return mMaxRetries;
- }
-
- /**
+ private void setMaxRetries(String maxRetries) {
+ Long lMaxRetries;
+ try {
+ lMaxRetries = Long.parseLong(maxRetries);
+ } catch (NumberFormatException e) {
+ // No response or not parseable, expire immediately
+ Log.w(TAG, "Licence retry count (GR) missing, grace period disabled");
+ maxRetries = "0";
+ lMaxRetries = 0l;
+ }
+
+ mMaxRetries = lMaxRetries;
+ mPreferences.putString(PREF_MAX_RETRIES, maxRetries);
+ }
+
+ public long getMaxRetries() {
+ return mMaxRetries;
+ }
+
+ /**
* Set the licensing URL that displays a Play Store UI for the user to regain app access.
*
* @param url the LU string received
*/
- private void setLicensingUrl(String url) {
- mLicensingUrl = url;
- mPreferences.putString(PREF_LICENSING_URL, url);
- }
+ private void setLicensingUrl(String url) {
+ mLicensingUrl = url;
+ mPreferences.putString(PREF_LICENSING_URL, url);
+ }
- public String getLicensingUrl() {
- return mLicensingUrl;
- }
+ public String getLicensingUrl() {
+ return mLicensingUrl;
+ }
- /**
+ /**
* Gets the count of expansion URLs. Since expansionURLs are not committed
* to preferences, this will return zero if there has been no LVL fetch
* in the current session.
*
* @return the number of expansion URLs. (0,1,2)
*/
- public int getExpansionURLCount() {
- return mExpansionURLs.size();
- }
+ public int getExpansionURLCount() {
+ return mExpansionURLs.size();
+ }
- /**
+ /**
* Gets the expansion URL. Since these URLs are not committed to
* preferences, this will always return null if there has not been an LVL
* fetch in the current session.
@@ -317,14 +317,14 @@ public class APKExpansionPolicy implements Policy {
* @param index the index of the URL to fetch. This value will be either
* MAIN_FILE_URL_INDEX or PATCH_FILE_URL_INDEX
*/
- public String getExpansionURL(int index) {
- if (index < mExpansionURLs.size()) {
- return mExpansionURLs.elementAt(index);
- }
- return null;
- }
-
- /**
+ public String getExpansionURL(int index) {
+ if (index < mExpansionURLs.size()) {
+ return mExpansionURLs.elementAt(index);
+ }
+ return null;
+ }
+
+ /**
* Sets the expansion URL. Expansion URL's are not committed to preferences,
* but are instead intended to be stored when the license response is
* processed by the front-end.
@@ -333,42 +333,42 @@ public class APKExpansionPolicy implements Policy {
* MAIN_FILE_URL_INDEX or PATCH_FILE_URL_INDEX
* @param URL the URL to set
*/
- public void setExpansionURL(int index, String URL) {
- if (index >= mExpansionURLs.size()) {
- mExpansionURLs.setSize(index + 1);
- }
- mExpansionURLs.set(index, URL);
- }
-
- public String getExpansionFileName(int index) {
- if (index < mExpansionFileNames.size()) {
- return mExpansionFileNames.elementAt(index);
- }
- return null;
- }
-
- public void setExpansionFileName(int index, String name) {
- if (index >= mExpansionFileNames.size()) {
- mExpansionFileNames.setSize(index + 1);
- }
- mExpansionFileNames.set(index, name);
- }
-
- public long getExpansionFileSize(int index) {
- if (index < mExpansionFileSizes.size()) {
- return mExpansionFileSizes.elementAt(index);
- }
- return -1;
- }
-
- public void setExpansionFileSize(int index, long size) {
- if (index >= mExpansionFileSizes.size()) {
- mExpansionFileSizes.setSize(index + 1);
- }
- mExpansionFileSizes.set(index, size);
- }
-
- /**
+ public void setExpansionURL(int index, String URL) {
+ if (index >= mExpansionURLs.size()) {
+ mExpansionURLs.setSize(index + 1);
+ }
+ mExpansionURLs.set(index, URL);
+ }
+
+ public String getExpansionFileName(int index) {
+ if (index < mExpansionFileNames.size()) {
+ return mExpansionFileNames.elementAt(index);
+ }
+ return null;
+ }
+
+ public void setExpansionFileName(int index, String name) {
+ if (index >= mExpansionFileNames.size()) {
+ mExpansionFileNames.setSize(index + 1);
+ }
+ mExpansionFileNames.set(index, name);
+ }
+
+ public long getExpansionFileSize(int index) {
+ if (index < mExpansionFileSizes.size()) {
+ return mExpansionFileSizes.elementAt(index);
+ }
+ return -1;
+ }
+
+ public void setExpansionFileSize(int index, long size) {
+ if (index >= mExpansionFileSizes.size()) {
+ mExpansionFileSizes.setSize(index + 1);
+ }
+ mExpansionFileSizes.set(index, size);
+ }
+
+ /**
* {@inheritDoc} This implementation allows access if either:<br>
* <ol>
* <li>a LICENSED response was received within the validity period
@@ -376,38 +376,39 @@ public class APKExpansionPolicy implements Policy {
* the RETRY count or in the RETRY period.
* </ol>
*/
- public boolean allowAccess() {
- long ts = System.currentTimeMillis();
- if (mLastResponse == Policy.LICENSED) {
- // Check if the LICENSED response occurred within the validity
- // timeout.
- if (ts <= mValidityTimestamp) {
- // Cached LICENSED response is still valid.
- return true;
- }
- } else if (mLastResponse == Policy.RETRY &&
- ts < mLastResponseTime + MILLIS_PER_MINUTE) {
- // Only allow access if we are within the retry period or we haven't
- // used up our
- // max retries.
- return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
- }
- return false;
- }
-
- private Map<String, String> decodeExtras(
- com.google.android.vending.licensing.ResponseData rawData) {
- Map<String, String> results = new HashMap<String, String>();
- if (rawData == null) {
- return results;
- }
-
- try {
- URI rawExtras = new URI("?" + rawData.extra);
- URIQueryDecoder.DecodeQuery(rawExtras, results);
- } catch (URISyntaxException e) {
- Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
- }
- return results;
- }
+ public boolean allowAccess() {
+ long ts = System.currentTimeMillis();
+ if (mLastResponse == Policy.LICENSED) {
+ // Check if the LICENSED response occurred within the validity
+ // timeout.
+ if (ts <= mValidityTimestamp) {
+ // Cached LICENSED response is still valid.
+ return true;
+ }
+ } else if (mLastResponse == Policy.RETRY &&
+ ts < mLastResponseTime + MILLIS_PER_MINUTE) {
+ // Only allow access if we are within the retry period or we haven't
+ // used up our
+ // max retries.
+ return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
+ }
+ return false;
+ }
+
+ private Map<String, String> decodeExtras(
+ com.google.android.vending.licensing.ResponseData rawData) {
+ Map<String, String> results = new HashMap<String, String>();
+ if (rawData == null) {
+ return results;
+ }
+
+ try {
+ URI rawExtras = new URI("?" + rawData.extra);
+ URIQueryDecoder.DecodeQuery(rawExtras, results);
+ } catch (URISyntaxException e) {
+ Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
+ }
+ return results;
+ }
+
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/DeviceLimiter.java b/platform/android/java/src/com/google/android/vending/licensing/DeviceLimiter.java
index 2384b8b82f..e5c5e2d7ca 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/DeviceLimiter.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/DeviceLimiter.java
@@ -37,11 +37,11 @@ package com.google.android.vending.licensing;
*/
public interface DeviceLimiter {
- /**
+ /**
* Checks if this device is allowed to use the given user's license.
*
* @param userId the user whose license the server responded with
* @return LICENSED if the device is allowed, NOT_LICENSED if not, RETRY if an error occurs
*/
- int isDeviceAllowed(String userId);
+ int isDeviceAllowed(String userId);
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.java b/platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.java
deleted file mode 100644
index 89edeae1b4..0000000000
--- a/platform/android/java/src/com/google/android/vending/licensing/ILicenseResultListener.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-*/
-
-/*
- * This file is auto-generated. DO NOT MODIFY.
- * Original file: aidl/ILicenseResultListener.aidl
- */
-package com.google.android.vending.licensing;
-import java.lang.String;
-import android.os.RemoteException;
-import android.os.IBinder;
-import android.os.IInterface;
-import android.os.Binder;
-import android.os.Parcel;
-public interface ILicenseResultListener extends android.os.IInterface {
- /** Local-side IPC implementation stub class. */
- public static abstract class Stub extends android.os.Binder implements com.google.android.vending.licensing.ILicenseResultListener {
- private static final java.lang.String DESCRIPTOR = "com.android.vending.licensing.ILicenseResultListener";
- /** Construct the stub at attach it to the interface. */
- public Stub() {
- this.attachInterface(this, DESCRIPTOR);
- }
- /**
- * Cast an IBinder object into an ILicenseResultListener interface,
- * generating a proxy if needed.
- */
- public static com.google.android.vending.licensing.ILicenseResultListener asInterface(android.os.IBinder obj) {
- if ((obj == null)) {
- return null;
- }
- android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
- if (((iin != null) && (iin instanceof com.google.android.vending.licensing.ILicenseResultListener))) {
- return ((com.google.android.vending.licensing.ILicenseResultListener)iin);
- }
- return new com.google.android.vending.licensing.ILicenseResultListener.Stub.Proxy(obj);
- }
- public android.os.IBinder asBinder() {
- return this;
- }
- public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
- switch (code) {
- case INTERFACE_TRANSACTION: {
- reply.writeString(DESCRIPTOR);
- return true;
- }
- case TRANSACTION_verifyLicense: {
- data.enforceInterface(DESCRIPTOR);
- int _arg0;
- _arg0 = data.readInt();
- java.lang.String _arg1;
- _arg1 = data.readString();
- java.lang.String _arg2;
- _arg2 = data.readString();
- this.verifyLicense(_arg0, _arg1, _arg2);
- return true;
- }
- }
- return super.onTransact(code, data, reply, flags);
- }
- private static class Proxy implements com.google.android.vending.licensing.ILicenseResultListener {
- private android.os.IBinder mRemote;
- Proxy(android.os.IBinder remote) {
- mRemote = remote;
- }
- public android.os.IBinder asBinder() {
- return mRemote;
- }
- public java.lang.String getInterfaceDescriptor() {
- return DESCRIPTOR;
- }
- public void verifyLicense(int responseCode, java.lang.String signedData, java.lang.String signature) throws android.os.RemoteException {
- android.os.Parcel _data = android.os.Parcel.obtain();
- try {
- _data.writeInterfaceToken(DESCRIPTOR);
- _data.writeInt(responseCode);
- _data.writeString(signedData);
- _data.writeString(signature);
- mRemote.transact(Stub.TRANSACTION_verifyLicense, _data, null, IBinder.FLAG_ONEWAY);
- } finally {
- _data.recycle();
- }
- }
- }
- static final int TRANSACTION_verifyLicense = (IBinder.FIRST_CALL_TRANSACTION + 0);
- }
- public void verifyLicense(int responseCode, java.lang.String signedData, java.lang.String signature) throws android.os.RemoteException;
-}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ILicensingService.java b/platform/android/java/src/com/google/android/vending/licensing/ILicensingService.java
deleted file mode 100644
index 8b7cc83541..0000000000
--- a/platform/android/java/src/com/google/android/vending/licensing/ILicensingService.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-*/
-
-/*
- * This file is auto-generated. DO NOT MODIFY.
- * Original file: aidl/ILicensingService.aidl
- */
-package com.google.android.vending.licensing;
-import java.lang.String;
-import android.os.RemoteException;
-import android.os.IBinder;
-import android.os.IInterface;
-import android.os.Binder;
-import android.os.Parcel;
-public interface ILicensingService extends android.os.IInterface {
- /** Local-side IPC implementation stub class. */
- public static abstract class Stub extends android.os.Binder implements com.google.android.vending.licensing.ILicensingService {
- private static final java.lang.String DESCRIPTOR = "com.android.vending.licensing.ILicensingService";
- /** Construct the stub at attach it to the interface. */
- public Stub() {
- this.attachInterface(this, DESCRIPTOR);
- }
- /**
- * Cast an IBinder object into an ILicensingService interface,
- * generating a proxy if needed.
- */
- public static com.google.android.vending.licensing.ILicensingService asInterface(android.os.IBinder obj) {
- if ((obj == null)) {
- return null;
- }
- android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
- if (((iin != null) && (iin instanceof com.google.android.vending.licensing.ILicensingService))) {
- return ((com.google.android.vending.licensing.ILicensingService)iin);
- }
- return new com.google.android.vending.licensing.ILicensingService.Stub.Proxy(obj);
- }
- public android.os.IBinder asBinder() {
- return this;
- }
- public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
- switch (code) {
- case INTERFACE_TRANSACTION: {
- reply.writeString(DESCRIPTOR);
- return true;
- }
- case TRANSACTION_checkLicense: {
- data.enforceInterface(DESCRIPTOR);
- long _arg0;
- _arg0 = data.readLong();
- java.lang.String _arg1;
- _arg1 = data.readString();
- com.google.android.vending.licensing.ILicenseResultListener _arg2;
- _arg2 = com.google.android.vending.licensing.ILicenseResultListener.Stub.asInterface(data.readStrongBinder());
- this.checkLicense(_arg0, _arg1, _arg2);
- return true;
- }
- }
- return super.onTransact(code, data, reply, flags);
- }
- private static class Proxy implements com.google.android.vending.licensing.ILicensingService {
- private android.os.IBinder mRemote;
- Proxy(android.os.IBinder remote) {
- mRemote = remote;
- }
- public android.os.IBinder asBinder() {
- return mRemote;
- }
- public java.lang.String getInterfaceDescriptor() {
- return DESCRIPTOR;
- }
- public void checkLicense(long nonce, java.lang.String packageName, com.google.android.vending.licensing.ILicenseResultListener listener) throws android.os.RemoteException {
- android.os.Parcel _data = android.os.Parcel.obtain();
- try {
- _data.writeInterfaceToken(DESCRIPTOR);
- _data.writeLong(nonce);
- _data.writeString(packageName);
- _data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
- mRemote.transact(Stub.TRANSACTION_checkLicense, _data, null, IBinder.FLAG_ONEWAY);
- } finally {
- _data.recycle();
- }
- }
- }
- static final int TRANSACTION_checkLicense = (IBinder.FIRST_CALL_TRANSACTION + 0);
- }
- public void checkLicense(long nonce, java.lang.String packageName, com.google.android.vending.licensing.ILicenseResultListener listener) throws android.os.RemoteException;
-}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/LicenseChecker.java b/platform/android/java/src/com/google/android/vending/licensing/LicenseChecker.java
index 38aab9f4f5..15017b3425 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/LicenseChecker.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/LicenseChecker.java
@@ -29,8 +29,8 @@ import android.os.RemoteException;
import android.provider.Settings.Secure;
import android.util.Log;
-import com.google.android.vending.licensing.ILicenseResultListener;
-import com.google.android.vending.licensing.ILicensingService;
+import com.android.vending.licensing.ILicenseResultListener;
+import com.android.vending.licensing.ILicensingService;
import com.google.android.vending.licensing.util.Base64;
import com.google.android.vending.licensing.util.Base64DecoderException;
@@ -58,73 +58,73 @@ import java.util.Set;
* public key is obtainable from the publisher site.
*/
public class LicenseChecker implements ServiceConnection {
- private static final String TAG = "LicenseChecker";
+ private static final String TAG = "LicenseChecker";
- private static final String KEY_FACTORY_ALGORITHM = "RSA";
+ private static final String KEY_FACTORY_ALGORITHM = "RSA";
- // Timeout value (in milliseconds) for calls to service.
- private static final int TIMEOUT_MS = 10 * 1000;
+ // Timeout value (in milliseconds) for calls to service.
+ private static final int TIMEOUT_MS = 10 * 1000;
- private static final SecureRandom RANDOM = new SecureRandom();
- private static final boolean DEBUG_LICENSE_ERROR = false;
+ private static final SecureRandom RANDOM = new SecureRandom();
+ private static final boolean DEBUG_LICENSE_ERROR = false;
- private ILicensingService mService;
+ private ILicensingService mService;
- private PublicKey mPublicKey;
- private final Context mContext;
- private final Policy mPolicy;
- /**
+ private PublicKey mPublicKey;
+ private final Context mContext;
+ private final Policy mPolicy;
+ /**
* A handler for running tasks on a background thread. We don't want license processing to block
* the UI thread.
*/
- private Handler mHandler;
- private final String mPackageName;
- private final String mVersionCode;
- private final Set<LicenseValidator> mChecksInProgress = new HashSet<LicenseValidator>();
- private final Queue<LicenseValidator> mPendingChecks = new LinkedList<LicenseValidator>();
+ private Handler mHandler;
+ private final String mPackageName;
+ private final String mVersionCode;
+ private final Set<LicenseValidator> mChecksInProgress = new HashSet<LicenseValidator>();
+ private final Queue<LicenseValidator> mPendingChecks = new LinkedList<LicenseValidator>();
- /**
+ /**
* @param context a Context
* @param policy implementation of Policy
* @param encodedPublicKey Base64-encoded RSA public key
* @throws IllegalArgumentException if encodedPublicKey is invalid
*/
- public LicenseChecker(Context context, Policy policy, String encodedPublicKey) {
- mContext = context;
- mPolicy = policy;
- mPublicKey = generatePublicKey(encodedPublicKey);
- mPackageName = mContext.getPackageName();
- mVersionCode = getVersionCode(context, mPackageName);
- HandlerThread handlerThread = new HandlerThread("background thread");
- handlerThread.start();
- mHandler = new Handler(handlerThread.getLooper());
- }
-
- /**
+ public LicenseChecker(Context context, Policy policy, String encodedPublicKey) {
+ mContext = context;
+ mPolicy = policy;
+ mPublicKey = generatePublicKey(encodedPublicKey);
+ mPackageName = mContext.getPackageName();
+ mVersionCode = getVersionCode(context, mPackageName);
+ HandlerThread handlerThread = new HandlerThread("background thread");
+ handlerThread.start();
+ mHandler = new Handler(handlerThread.getLooper());
+ }
+
+ /**
* Generates a PublicKey instance from a string containing the Base64-encoded public key.
*
* @param encodedPublicKey Base64-encoded public key
* @throws IllegalArgumentException if encodedPublicKey is invalid
*/
- private static PublicKey generatePublicKey(String encodedPublicKey) {
- try {
- byte[] decodedKey = Base64.decode(encodedPublicKey);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
-
- return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
- } catch (NoSuchAlgorithmException e) {
- // This won't happen in an Android-compatible environment.
- throw new RuntimeException(e);
- } catch (Base64DecoderException e) {
- Log.e(TAG, "Could not decode from Base64.");
- throw new IllegalArgumentException(e);
- } catch (InvalidKeySpecException e) {
- Log.e(TAG, "Invalid key specification.");
- throw new IllegalArgumentException(e);
- }
- }
-
- /**
+ private static PublicKey generatePublicKey(String encodedPublicKey) {
+ try {
+ byte[] decodedKey = Base64.decode(encodedPublicKey);
+ KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
+
+ return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
+ } catch (NoSuchAlgorithmException e) {
+ // This won't happen in an Android-compatible environment.
+ throw new RuntimeException(e);
+ } catch (Base64DecoderException e) {
+ Log.e(TAG, "Could not decode from Base64.");
+ throw new IllegalArgumentException(e);
+ } catch (InvalidKeySpecException e) {
+ Log.e(TAG, "Invalid key specification.");
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ /**
* Checks if the user should have access to the app. Binds the service if necessary.
* <p>
* NOTE: This call uses a trivially obfuscated string (base64-encoded). For best security, we
@@ -136,221 +136,223 @@ public class LicenseChecker implements ServiceConnection {
*
* @param callback
*/
- public synchronized void checkAccess(LicenseCheckerCallback callback) {
- // If we have a valid recent LICENSED response, we can skip asking
- // Market.
- if (mPolicy.allowAccess()) {
- Log.i(TAG, "Using cached license response");
- callback.allow(Policy.LICENSED);
- } else {
- LicenseValidator validator = new LicenseValidator(mPolicy, new NullDeviceLimiter(),
- callback, generateNonce(), mPackageName, mVersionCode);
-
- if (mService == null) {
- Log.i(TAG, "Binding to licensing service.");
- try {
- boolean bindResult = mContext
- .bindService(
- new Intent(
- new String(
- // Base64 encoded -
- // com.android.vending.licensing.ILicensingService
- // Consider encoding this in another way in your
- // code to improve security
- Base64.decode(
- "Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
- // As of Android 5.0, implicit
- // Service Intents are no longer
- // allowed because it's not
- // possible for the user to
- // participate in disambiguating
- // them. This does mean we break
- // compatibility with Android
- // Cupcake devices with this
- // release, since setPackage was
- // added in Donut.
- .setPackage(
- new String(
- // Base64
- // encoded -
- // com.android.vending
- Base64.decode(
- "Y29tLmFuZHJvaWQudmVuZGluZw=="))),
- this, // ServiceConnection.
- Context.BIND_AUTO_CREATE);
- if (bindResult) {
- mPendingChecks.offer(validator);
- } else {
- Log.e(TAG, "Could not bind to service.");
- handleServiceConnectionError(validator);
- }
- } catch (SecurityException e) {
- callback.applicationError(LicenseCheckerCallback.ERROR_MISSING_PERMISSION);
- } catch (Base64DecoderException e) {
- e.printStackTrace();
- }
- } else {
- mPendingChecks.offer(validator);
- runChecks();
- }
- }
- }
-
- /**
+ public synchronized void checkAccess(LicenseCheckerCallback callback) {
+ // If we have a valid recent LICENSED response, we can skip asking
+ // Market.
+ if (mPolicy.allowAccess()) {
+ Log.i(TAG, "Using cached license response");
+ callback.allow(Policy.LICENSED);
+ } else {
+ LicenseValidator validator = new LicenseValidator(mPolicy, new NullDeviceLimiter(),
+ callback, generateNonce(), mPackageName, mVersionCode);
+
+ if (mService == null) {
+ Log.i(TAG, "Binding to licensing service.");
+ try {
+ boolean bindResult = mContext
+ .bindService(
+ new Intent(
+ new String(
+ // Base64 encoded -
+ // com.android.vending.licensing.ILicensingService
+ // Consider encoding this in another way in your
+ // code to improve security
+ Base64.decode(
+ "Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
+ // As of Android 5.0, implicit
+ // Service Intents are no longer
+ // allowed because it's not
+ // possible for the user to
+ // participate in disambiguating
+ // them. This does mean we break
+ // compatibility with Android
+ // Cupcake devices with this
+ // release, since setPackage was
+ // added in Donut.
+ .setPackage(
+ new String(
+ // Base64
+ // encoded -
+ // com.android.vending
+ Base64.decode(
+ "Y29tLmFuZHJvaWQudmVuZGluZw=="))),
+ this, // ServiceConnection.
+ Context.BIND_AUTO_CREATE);
+ if (bindResult) {
+ mPendingChecks.offer(validator);
+ } else {
+ Log.e(TAG, "Could not bind to service.");
+ handleServiceConnectionError(validator);
+ }
+ } catch (SecurityException e) {
+ callback.applicationError(LicenseCheckerCallback.ERROR_MISSING_PERMISSION);
+ } catch (Base64DecoderException e) {
+ e.printStackTrace();
+ }
+ } else {
+ mPendingChecks.offer(validator);
+ runChecks();
+ }
+ }
+ }
+
+ /**
* Triggers the last deep link licensing URL returned from the server, which redirects users to a
* page which enables them to gain access to the app. If no such URL is returned by the server, it
* will go to the details page of the app in the Play Store.
*/
- public void followLastLicensingUrl(Context context) {
- String licensingUrl = mPolicy.getLicensingUrl();
- if (licensingUrl == null) {
- licensingUrl = "https://play.google.com/store/apps/details?id=" + context.getPackageName();
- }
- Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(licensingUrl));
- context.startActivity(marketIntent);
- }
-
- private void runChecks() {
- LicenseValidator validator;
- while ((validator = mPendingChecks.poll()) != null) {
- try {
- Log.i(TAG, "Calling checkLicense on service for " + validator.getPackageName());
- mService.checkLicense(
- validator.getNonce(), validator.getPackageName(),
- new ResultListener(validator));
- mChecksInProgress.add(validator);
- } catch (RemoteException e) {
- Log.w(TAG, "RemoteException in checkLicense call.", e);
- handleServiceConnectionError(validator);
- }
- }
- }
-
- private synchronized void finishCheck(LicenseValidator validator) {
- mChecksInProgress.remove(validator);
- if (mChecksInProgress.isEmpty()) {
- cleanupService();
- }
- }
-
- private class ResultListener extends ILicenseResultListener.Stub {
- private final LicenseValidator mValidator;
- private Runnable mOnTimeout;
-
- public ResultListener(LicenseValidator validator) {
- mValidator = validator;
- mOnTimeout = new Runnable() {
- public void run() {
- Log.i(TAG, "Check timed out.");
- handleServiceConnectionError(mValidator);
- finishCheck(mValidator);
- }
- };
- startTimeout();
- }
-
- private static final int ERROR_CONTACTING_SERVER = 0x101;
- private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
- private static final int ERROR_NON_MATCHING_UID = 0x103;
-
- // Runs in IPC thread pool. Post it to the Handler, so we can guarantee
- // either this or the timeout runs.
- public void verifyLicense(final int responseCode, final String signedData,
- final String signature) {
- mHandler.post(new Runnable() {
- public void run() {
- Log.i(TAG, "Received response.");
- // Make sure it hasn't already timed out.
- if (mChecksInProgress.contains(mValidator)) {
- clearTimeout();
- mValidator.verify(mPublicKey, responseCode, signedData, signature);
- finishCheck(mValidator);
- }
- if (DEBUG_LICENSE_ERROR) {
- boolean logResponse;
- String stringError = null;
- switch (responseCode) {
- case ERROR_CONTACTING_SERVER:
- logResponse = true;
- stringError = "ERROR_CONTACTING_SERVER";
- break;
- case ERROR_INVALID_PACKAGE_NAME:
- logResponse = true;
- stringError = "ERROR_INVALID_PACKAGE_NAME";
- break;
- case ERROR_NON_MATCHING_UID:
- logResponse = true;
- stringError = "ERROR_NON_MATCHING_UID";
- break;
- default:
- logResponse = false;
- }
-
- if (logResponse) {
- String android_id = Secure.ANDROID_ID;
- Date date = new Date();
- Log.d(TAG, "Server Failure: " + stringError);
- Log.d(TAG, "Android ID: " + android_id);
- Log.d(TAG, "Time: " + date.toGMTString());
- }
- }
- }
- });
- }
-
- private void startTimeout() {
- Log.i(TAG, "Start monitoring timeout.");
- mHandler.postDelayed(mOnTimeout, TIMEOUT_MS);
- }
-
- private void clearTimeout() {
- Log.i(TAG, "Clearing timeout.");
- mHandler.removeCallbacks(mOnTimeout);
- }
- }
-
- public synchronized void onServiceConnected(ComponentName name, IBinder service) {
- mService = ILicensingService.Stub.asInterface(service);
- runChecks();
- }
-
- public synchronized void onServiceDisconnected(ComponentName name) {
- // Called when the connection with the service has been
- // unexpectedly disconnected. That is, Market crashed.
- // If there are any checks in progress, the timeouts will handle them.
- Log.w(TAG, "Service unexpectedly disconnected.");
- mService = null;
- }
-
- /**
+ public void followLastLicensingUrl(Context context) {
+ String licensingUrl = mPolicy.getLicensingUrl();
+ if (licensingUrl == null) {
+ licensingUrl = "https://play.google.com/store/apps/details?id=" + context.getPackageName();
+ }
+ Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(licensingUrl));
+ context.startActivity(marketIntent);
+ }
+
+ private void runChecks() {
+ LicenseValidator validator;
+ while ((validator = mPendingChecks.poll()) != null) {
+ try {
+ Log.i(TAG, "Calling checkLicense on service for " + validator.getPackageName());
+ mService.checkLicense(
+ validator.getNonce(), validator.getPackageName(),
+ new ResultListener(validator));
+ mChecksInProgress.add(validator);
+ } catch (RemoteException e) {
+ Log.w(TAG, "RemoteException in checkLicense call.", e);
+ handleServiceConnectionError(validator);
+ }
+ }
+ }
+
+ private synchronized void finishCheck(LicenseValidator validator) {
+ mChecksInProgress.remove(validator);
+ if (mChecksInProgress.isEmpty()) {
+ cleanupService();
+ }
+ }
+
+ private class ResultListener extends ILicenseResultListener.Stub {
+ private final LicenseValidator mValidator;
+ private Runnable mOnTimeout;
+
+ public ResultListener(LicenseValidator validator) {
+ mValidator = validator;
+ mOnTimeout = new Runnable() {
+ public void run() {
+ Log.i(TAG, "Check timed out.");
+ handleServiceConnectionError(mValidator);
+ finishCheck(mValidator);
+ }
+ };
+ startTimeout();
+ }
+
+ private static final int ERROR_CONTACTING_SERVER = 0x101;
+ private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
+ private static final int ERROR_NON_MATCHING_UID = 0x103;
+
+ // Runs in IPC thread pool. Post it to the Handler, so we can guarantee
+ // either this or the timeout runs.
+ public void verifyLicense(final int responseCode, final String signedData,
+ final String signature) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ Log.i(TAG, "Received response.");
+ // Make sure it hasn't already timed out.
+ if (mChecksInProgress.contains(mValidator)) {
+ clearTimeout();
+ mValidator.verify(mPublicKey, responseCode, signedData, signature);
+ finishCheck(mValidator);
+ }
+ if (DEBUG_LICENSE_ERROR) {
+ boolean logResponse;
+ String stringError = null;
+ switch (responseCode) {
+ case ERROR_CONTACTING_SERVER:
+ logResponse = true;
+ stringError = "ERROR_CONTACTING_SERVER";
+ break;
+ case ERROR_INVALID_PACKAGE_NAME:
+ logResponse = true;
+ stringError = "ERROR_INVALID_PACKAGE_NAME";
+ break;
+ case ERROR_NON_MATCHING_UID:
+ logResponse = true;
+ stringError = "ERROR_NON_MATCHING_UID";
+ break;
+ default:
+ logResponse = false;
+ }
+
+ if (logResponse) {
+ String android_id = Secure.getString(mContext.getContentResolver(),
+ Secure.ANDROID_ID);
+ Date date = new Date();
+ Log.d(TAG, "Server Failure: " + stringError);
+ Log.d(TAG, "Android ID: " + android_id);
+ Log.d(TAG, "Time: " + date.toGMTString());
+ }
+ }
+
+ }
+ });
+ }
+
+ private void startTimeout() {
+ Log.i(TAG, "Start monitoring timeout.");
+ mHandler.postDelayed(mOnTimeout, TIMEOUT_MS);
+ }
+
+ private void clearTimeout() {
+ Log.i(TAG, "Clearing timeout.");
+ mHandler.removeCallbacks(mOnTimeout);
+ }
+ }
+
+ public synchronized void onServiceConnected(ComponentName name, IBinder service) {
+ mService = ILicensingService.Stub.asInterface(service);
+ runChecks();
+ }
+
+ public synchronized void onServiceDisconnected(ComponentName name) {
+ // Called when the connection with the service has been
+ // unexpectedly disconnected. That is, Market crashed.
+ // If there are any checks in progress, the timeouts will handle them.
+ Log.w(TAG, "Service unexpectedly disconnected.");
+ mService = null;
+ }
+
+ /**
* Generates policy response for service connection errors, as a result of disconnections or
* timeouts.
*/
- private synchronized void handleServiceConnectionError(LicenseValidator validator) {
- mPolicy.processServerResponse(Policy.RETRY, null);
-
- if (mPolicy.allowAccess()) {
- validator.getCallback().allow(Policy.RETRY);
- } else {
- validator.getCallback().dontAllow(Policy.RETRY);
- }
- }
-
- /** Unbinds service if necessary and removes reference to it. */
- private void cleanupService() {
- if (mService != null) {
- try {
- mContext.unbindService(this);
- } catch (IllegalArgumentException e) {
- // Somehow we've already been unbound. This is a non-fatal
- // error.
- Log.e(TAG, "Unable to unbind from licensing service (already unbound)");
- }
- mService = null;
- }
- }
-
- /**
+ private synchronized void handleServiceConnectionError(LicenseValidator validator) {
+ mPolicy.processServerResponse(Policy.RETRY, null);
+
+ if (mPolicy.allowAccess()) {
+ validator.getCallback().allow(Policy.RETRY);
+ } else {
+ validator.getCallback().dontAllow(Policy.RETRY);
+ }
+ }
+
+ /** Unbinds service if necessary and removes reference to it. */
+ private void cleanupService() {
+ if (mService != null) {
+ try {
+ mContext.unbindService(this);
+ } catch (IllegalArgumentException e) {
+ // Somehow we've already been unbound. This is a non-fatal
+ // error.
+ Log.e(TAG, "Unable to unbind from licensing service (already unbound)");
+ }
+ mService = null;
+ }
+ }
+
+ /**
* Inform the library that the context is about to be destroyed, so that any open connections
* can be cleaned up.
* <p>
@@ -358,30 +360,30 @@ public class LicenseChecker implements ServiceConnection {
* screen rotation if an Activity requests the license check or when the user exits the
* application.
*/
- public synchronized void onDestroy() {
- cleanupService();
- mHandler.getLooper().quit();
- }
+ public synchronized void onDestroy() {
+ cleanupService();
+ mHandler.getLooper().quit();
+ }
- /** Generates a nonce (number used once). */
- private int generateNonce() {
- return RANDOM.nextInt();
- }
+ /** Generates a nonce (number used once). */
+ private int generateNonce() {
+ return RANDOM.nextInt();
+ }
- /**
+ /**
* Get version code for the application package name.
*
* @param context
* @param packageName application package name
* @return the version code or empty string if package not found
*/
- private static String getVersionCode(Context context, String packageName) {
- try {
- return String.valueOf(
- context.getPackageManager().getPackageInfo(packageName, 0).versionCode);
- } catch (NameNotFoundException e) {
- Log.e(TAG, "Package not found. could not get version code.");
- return "";
- }
- }
+ private static String getVersionCode(Context context, String packageName) {
+ try {
+ return String.valueOf(
+ context.getPackageManager().getPackageInfo(packageName, 0).versionCode);
+ } catch (NameNotFoundException e) {
+ Log.e(TAG, "Package not found. could not get version code.");
+ return "";
+ }
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/LicenseCheckerCallback.java b/platform/android/java/src/com/google/android/vending/licensing/LicenseCheckerCallback.java
index dc2c2d70bf..8b869ddaaf 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/LicenseCheckerCallback.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/LicenseCheckerCallback.java
@@ -34,34 +34,34 @@ package com.google.android.vending.licensing;
*/
public interface LicenseCheckerCallback {
- /**
+ /**
* Allow use. App should proceed as normal.
*
* @param reason Policy.LICENSED or Policy.RETRY typically. (although in
* theory the policy can return Policy.NOT_LICENSED here as well)
*/
- public void allow(int reason);
+ public void allow(int reason);
- /**
+ /**
* Don't allow use. App should inform user and take appropriate action.
*
* @param reason Policy.NOT_LICENSED or Policy.RETRY. (although in theory
* the policy can return Policy.LICENSED here as well ---
* perhaps the call to the LVL took too long, for example)
*/
- public void dontAllow(int reason);
+ public void dontAllow(int reason);
- /** Application error codes. */
- public static final int ERROR_INVALID_PACKAGE_NAME = 1;
- public static final int ERROR_NON_MATCHING_UID = 2;
- public static final int ERROR_NOT_MARKET_MANAGED = 3;
- public static final int ERROR_CHECK_IN_PROGRESS = 4;
- public static final int ERROR_INVALID_PUBLIC_KEY = 5;
- public static final int ERROR_MISSING_PERMISSION = 6;
+ /** Application error codes. */
+ public static final int ERROR_INVALID_PACKAGE_NAME = 1;
+ public static final int ERROR_NON_MATCHING_UID = 2;
+ public static final int ERROR_NOT_MARKET_MANAGED = 3;
+ public static final int ERROR_CHECK_IN_PROGRESS = 4;
+ public static final int ERROR_INVALID_PUBLIC_KEY = 5;
+ public static final int ERROR_MISSING_PERMISSION = 6;
- /**
+ /**
* Error in application code. Caller did not call or set up license checker
* correctly. Should be considered fatal.
*/
- public void applicationError(int errorCode);
+ public void applicationError(int errorCode);
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/LicenseValidator.java b/platform/android/java/src/com/google/android/vending/licensing/LicenseValidator.java
index 77f7dc7295..11a00786d0 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/LicenseValidator.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/LicenseValidator.java
@@ -33,52 +33,52 @@ import java.security.SignatureException;
* and process the response.
*/
class LicenseValidator {
- private static final String TAG = "LicenseValidator";
-
- // Server response codes.
- private static final int LICENSED = 0x0;
- private static final int NOT_LICENSED = 0x1;
- private static final int LICENSED_OLD_KEY = 0x2;
- private static final int ERROR_NOT_MARKET_MANAGED = 0x3;
- private static final int ERROR_SERVER_FAILURE = 0x4;
- private static final int ERROR_OVER_QUOTA = 0x5;
-
- private static final int ERROR_CONTACTING_SERVER = 0x101;
- private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
- private static final int ERROR_NON_MATCHING_UID = 0x103;
-
- private final Policy mPolicy;
- private final LicenseCheckerCallback mCallback;
- private final int mNonce;
- private final String mPackageName;
- private final String mVersionCode;
- private final DeviceLimiter mDeviceLimiter;
-
- LicenseValidator(Policy policy, DeviceLimiter deviceLimiter, LicenseCheckerCallback callback,
- int nonce, String packageName, String versionCode) {
- mPolicy = policy;
- mDeviceLimiter = deviceLimiter;
- mCallback = callback;
- mNonce = nonce;
- mPackageName = packageName;
- mVersionCode = versionCode;
- }
-
- public LicenseCheckerCallback getCallback() {
- return mCallback;
- }
-
- public int getNonce() {
- return mNonce;
- }
-
- public String getPackageName() {
- return mPackageName;
- }
-
- private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
-
- /**
+ private static final String TAG = "LicenseValidator";
+
+ // Server response codes.
+ private static final int LICENSED = 0x0;
+ private static final int NOT_LICENSED = 0x1;
+ private static final int LICENSED_OLD_KEY = 0x2;
+ private static final int ERROR_NOT_MARKET_MANAGED = 0x3;
+ private static final int ERROR_SERVER_FAILURE = 0x4;
+ private static final int ERROR_OVER_QUOTA = 0x5;
+
+ private static final int ERROR_CONTACTING_SERVER = 0x101;
+ private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
+ private static final int ERROR_NON_MATCHING_UID = 0x103;
+
+ private final Policy mPolicy;
+ private final LicenseCheckerCallback mCallback;
+ private final int mNonce;
+ private final String mPackageName;
+ private final String mVersionCode;
+ private final DeviceLimiter mDeviceLimiter;
+
+ LicenseValidator(Policy policy, DeviceLimiter deviceLimiter, LicenseCheckerCallback callback,
+ int nonce, String packageName, String versionCode) {
+ mPolicy = policy;
+ mDeviceLimiter = deviceLimiter;
+ mCallback = callback;
+ mNonce = nonce;
+ mPackageName = packageName;
+ mVersionCode = versionCode;
+ }
+
+ public LicenseCheckerCallback getCallback() {
+ return mCallback;
+ }
+
+ public int getNonce() {
+ return mNonce;
+ }
+
+ public String getPackageName() {
+ return mPackageName;
+ }
+
+ private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
+
+ /**
* Verifies the response from server and calls appropriate callback method.
*
* @param publicKey public key associated with the developer account
@@ -86,147 +86,146 @@ class LicenseValidator {
* @param signedData signed data from server
* @param signature server signature
*/
- public void verify(PublicKey publicKey, int responseCode, String signedData, String signature) {
- String userId = null;
- // Skip signature check for unsuccessful requests
- ResponseData data = null;
- if (responseCode == LICENSED || responseCode == NOT_LICENSED ||
- responseCode == LICENSED_OLD_KEY) {
- // Verify signature.
- try {
- if (TextUtils.isEmpty(signedData)) {
- Log.e(TAG, "Signature verification failed: signedData is empty. "
- +
- "(Device not signed-in to any Google accounts?)");
- handleInvalidResponse();
- return;
- }
-
- Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
- sig.initVerify(publicKey);
- sig.update(signedData.getBytes());
-
- if (!sig.verify(Base64.decode(signature))) {
- Log.e(TAG, "Signature verification failed.");
- handleInvalidResponse();
- return;
- }
- } catch (NoSuchAlgorithmException e) {
- // This can't happen on an Android compatible device.
- throw new RuntimeException(e);
- } catch (InvalidKeyException e) {
- handleApplicationError(LicenseCheckerCallback.ERROR_INVALID_PUBLIC_KEY);
- return;
- } catch (SignatureException e) {
- throw new RuntimeException(e);
- } catch (Base64DecoderException e) {
- Log.e(TAG, "Could not Base64-decode signature.");
- handleInvalidResponse();
- return;
- }
-
- // Parse and validate response.
- try {
- data = ResponseData.parse(signedData);
- } catch (IllegalArgumentException e) {
- Log.e(TAG, "Could not parse response.");
- handleInvalidResponse();
- return;
- }
-
- if (data.responseCode != responseCode) {
- Log.e(TAG, "Response codes don't match.");
- handleInvalidResponse();
- return;
- }
-
- if (data.nonce != mNonce) {
- Log.e(TAG, "Nonce doesn't match.");
- handleInvalidResponse();
- return;
- }
-
- if (!data.packageName.equals(mPackageName)) {
- Log.e(TAG, "Package name doesn't match.");
- handleInvalidResponse();
- return;
- }
-
- if (!data.versionCode.equals(mVersionCode)) {
- Log.e(TAG, "Version codes don't match.");
- handleInvalidResponse();
- return;
- }
-
- // Application-specific user identifier.
- userId = data.userId;
- if (TextUtils.isEmpty(userId)) {
- Log.e(TAG, "User identifier is empty.");
- handleInvalidResponse();
- return;
- }
- }
-
- switch (responseCode) {
- case LICENSED:
- case LICENSED_OLD_KEY:
- int limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
- handleResponse(limiterResponse, data);
- break;
- case NOT_LICENSED:
- handleResponse(Policy.NOT_LICENSED, data);
- break;
- case ERROR_CONTACTING_SERVER:
- Log.w(TAG, "Error contacting licensing server.");
- handleResponse(Policy.RETRY, data);
- break;
- case ERROR_SERVER_FAILURE:
- Log.w(TAG, "An error has occurred on the licensing server.");
- handleResponse(Policy.RETRY, data);
- break;
- case ERROR_OVER_QUOTA:
- Log.w(TAG, "Licensing server is refusing to talk to this device, over quota.");
- handleResponse(Policy.RETRY, data);
- break;
- case ERROR_INVALID_PACKAGE_NAME:
- handleApplicationError(LicenseCheckerCallback.ERROR_INVALID_PACKAGE_NAME);
- break;
- case ERROR_NON_MATCHING_UID:
- handleApplicationError(LicenseCheckerCallback.ERROR_NON_MATCHING_UID);
- break;
- case ERROR_NOT_MARKET_MANAGED:
- handleApplicationError(LicenseCheckerCallback.ERROR_NOT_MARKET_MANAGED);
- break;
- default:
- Log.e(TAG, "Unknown response code for license check.");
- handleInvalidResponse();
- }
- }
-
- /**
+ public void verify(PublicKey publicKey, int responseCode, String signedData, String signature) {
+ String userId = null;
+ // Skip signature check for unsuccessful requests
+ ResponseData data = null;
+ if (responseCode == LICENSED || responseCode == NOT_LICENSED ||
+ responseCode == LICENSED_OLD_KEY) {
+ // Verify signature.
+ try {
+ if (TextUtils.isEmpty(signedData)) {
+ Log.e(TAG, "Signature verification failed: signedData is empty. " +
+ "(Device not signed-in to any Google accounts?)");
+ handleInvalidResponse();
+ return;
+ }
+
+ Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
+ sig.initVerify(publicKey);
+ sig.update(signedData.getBytes());
+
+ if (!sig.verify(Base64.decode(signature))) {
+ Log.e(TAG, "Signature verification failed.");
+ handleInvalidResponse();
+ return;
+ }
+ } catch (NoSuchAlgorithmException e) {
+ // This can't happen on an Android compatible device.
+ throw new RuntimeException(e);
+ } catch (InvalidKeyException e) {
+ handleApplicationError(LicenseCheckerCallback.ERROR_INVALID_PUBLIC_KEY);
+ return;
+ } catch (SignatureException e) {
+ throw new RuntimeException(e);
+ } catch (Base64DecoderException e) {
+ Log.e(TAG, "Could not Base64-decode signature.");
+ handleInvalidResponse();
+ return;
+ }
+
+ // Parse and validate response.
+ try {
+ data = ResponseData.parse(signedData);
+ } catch (IllegalArgumentException e) {
+ Log.e(TAG, "Could not parse response.");
+ handleInvalidResponse();
+ return;
+ }
+
+ if (data.responseCode != responseCode) {
+ Log.e(TAG, "Response codes don't match.");
+ handleInvalidResponse();
+ return;
+ }
+
+ if (data.nonce != mNonce) {
+ Log.e(TAG, "Nonce doesn't match.");
+ handleInvalidResponse();
+ return;
+ }
+
+ if (!data.packageName.equals(mPackageName)) {
+ Log.e(TAG, "Package name doesn't match.");
+ handleInvalidResponse();
+ return;
+ }
+
+ if (!data.versionCode.equals(mVersionCode)) {
+ Log.e(TAG, "Version codes don't match.");
+ handleInvalidResponse();
+ return;
+ }
+
+ // Application-specific user identifier.
+ userId = data.userId;
+ if (TextUtils.isEmpty(userId)) {
+ Log.e(TAG, "User identifier is empty.");
+ handleInvalidResponse();
+ return;
+ }
+ }
+
+ switch (responseCode) {
+ case LICENSED:
+ case LICENSED_OLD_KEY:
+ int limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
+ handleResponse(limiterResponse, data);
+ break;
+ case NOT_LICENSED:
+ handleResponse(Policy.NOT_LICENSED, data);
+ break;
+ case ERROR_CONTACTING_SERVER:
+ Log.w(TAG, "Error contacting licensing server.");
+ handleResponse(Policy.RETRY, data);
+ break;
+ case ERROR_SERVER_FAILURE:
+ Log.w(TAG, "An error has occurred on the licensing server.");
+ handleResponse(Policy.RETRY, data);
+ break;
+ case ERROR_OVER_QUOTA:
+ Log.w(TAG, "Licensing server is refusing to talk to this device, over quota.");
+ handleResponse(Policy.RETRY, data);
+ break;
+ case ERROR_INVALID_PACKAGE_NAME:
+ handleApplicationError(LicenseCheckerCallback.ERROR_INVALID_PACKAGE_NAME);
+ break;
+ case ERROR_NON_MATCHING_UID:
+ handleApplicationError(LicenseCheckerCallback.ERROR_NON_MATCHING_UID);
+ break;
+ case ERROR_NOT_MARKET_MANAGED:
+ handleApplicationError(LicenseCheckerCallback.ERROR_NOT_MARKET_MANAGED);
+ break;
+ default:
+ Log.e(TAG, "Unknown response code for license check.");
+ handleInvalidResponse();
+ }
+ }
+
+ /**
* Confers with policy and calls appropriate callback method.
*
* @param response
* @param rawData
*/
- private void handleResponse(int response, ResponseData rawData) {
- // Update policy data and increment retry counter (if needed)
- mPolicy.processServerResponse(response, rawData);
-
- // Given everything we know, including cached data, ask the policy if we should grant
- // access.
- if (mPolicy.allowAccess()) {
- mCallback.allow(response);
- } else {
- mCallback.dontAllow(response);
- }
- }
-
- private void handleApplicationError(int code) {
- mCallback.applicationError(code);
- }
-
- private void handleInvalidResponse() {
- mCallback.dontAllow(Policy.NOT_LICENSED);
- }
+ private void handleResponse(int response, ResponseData rawData) {
+ // Update policy data and increment retry counter (if needed)
+ mPolicy.processServerResponse(response, rawData);
+
+ // Given everything we know, including cached data, ask the policy if we should grant
+ // access.
+ if (mPolicy.allowAccess()) {
+ mCallback.allow(response);
+ } else {
+ mCallback.dontAllow(response);
+ }
+ }
+
+ private void handleApplicationError(int code) {
+ mCallback.applicationError(code);
+ }
+
+ private void handleInvalidResponse() {
+ mCallback.dontAllow(Policy.NOT_LICENSED);
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/NullDeviceLimiter.java b/platform/android/java/src/com/google/android/vending/licensing/NullDeviceLimiter.java
index a43e454228..d87af3153f 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/NullDeviceLimiter.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/NullDeviceLimiter.java
@@ -26,7 +26,7 @@ package com.google.android.vending.licensing;
*/
public class NullDeviceLimiter implements DeviceLimiter {
- public int isDeviceAllowed(String userId) {
- return Policy.LICENSED;
- }
+ public int isDeviceAllowed(String userId) {
+ return Policy.LICENSED;
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/Obfuscator.java b/platform/android/java/src/com/google/android/vending/licensing/Obfuscator.java
index 8731d03aa6..008c150a8e 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/Obfuscator.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/Obfuscator.java
@@ -27,16 +27,16 @@ package com.google.android.vending.licensing;
*/
public interface Obfuscator {
- /**
+ /**
* Obfuscate a string that is being stored into shared preferences.
*
* @param original The data that is to be obfuscated.
* @param key The key for the data that is to be obfuscated.
* @return A transformed version of the original data.
*/
- String obfuscate(String original, String key);
+ String obfuscate(String original, String key);
- /**
+ /**
* Undo the transformation applied to data by the obfuscate() method.
*
* @param obfuscated The data that is to be un-obfuscated.
@@ -44,5 +44,5 @@ public interface Obfuscator {
* @return The original data transformed by the obfuscate() method.
* @throws ValidationException Optionally thrown if a data integrity check fails.
*/
- String unobfuscate(String obfuscated, String key) throws ValidationException;
+ String unobfuscate(String obfuscated, String key) throws ValidationException;
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/Policy.java b/platform/android/java/src/com/google/android/vending/licensing/Policy.java
index 65202aceb9..b672a078b7 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/Policy.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/Policy.java
@@ -22,27 +22,27 @@ package com.google.android.vending.licensing;
*/
public interface Policy {
- /**
+ /**
* Change these values to make it more difficult for tools to automatically
* strip LVL protection from your APK.
*/
- /**
+ /**
* LICENSED means that the server returned back a valid license response
*/
- public static final int LICENSED = 0x0100;
- /**
+ public static final int LICENSED = 0x0100;
+ /**
* NOT_LICENSED means that the server returned back a valid license response
* that indicated that the user definitively is not licensed
*/
- public static final int NOT_LICENSED = 0x0231;
- /**
+ public static final int NOT_LICENSED = 0x0231;
+ /**
* RETRY means that the license response was unable to be determined ---
* perhaps as a result of faulty networking
*/
- public static final int RETRY = 0x0123;
+ public static final int RETRY = 0x0123;
- /**
+ /**
* Provide results from contact with the license server. Retry counts are
* incremented if the current value of response is RETRY. Results will be
* used for any future policy decisions.
@@ -50,16 +50,16 @@ public interface Policy {
* @param response the result from validating the server response
* @param rawData the raw server response data, can be null for RETRY
*/
- void processServerResponse(int response, ResponseData rawData);
+ void processServerResponse(int response, ResponseData rawData);
- /**
+ /**
* Check if the user should be allowed access to the application.
*/
- boolean allowAccess();
+ boolean allowAccess();
- /**
+ /**
* Gets the licensing URL returned by the server that can enable access for unlicensed apps (e.g.
* buy app on the Play Store).
*/
- String getLicensingUrl();
+ String getLicensingUrl();
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java b/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
index 099bb1c48b..feb579af04 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/PreferenceObfuscator.java
@@ -24,55 +24,57 @@ import android.util.Log;
*/
public class PreferenceObfuscator {
- private static final String TAG = "PreferenceObfuscator";
+ private static final String TAG = "PreferenceObfuscator";
- private final SharedPreferences mPreferences;
- private final Obfuscator mObfuscator;
- private SharedPreferences.Editor mEditor;
+ private final SharedPreferences mPreferences;
+ private final Obfuscator mObfuscator;
+ private SharedPreferences.Editor mEditor;
- /**
+ /**
* Constructor.
*
* @param sp A SharedPreferences instance provided by the system.
* @param o The Obfuscator to use when reading or writing data.
*/
- public PreferenceObfuscator(SharedPreferences sp, Obfuscator o) {
- mPreferences = sp;
- mObfuscator = o;
- mEditor = null;
- }
+ public PreferenceObfuscator(SharedPreferences sp, Obfuscator o) {
+ mPreferences = sp;
+ mObfuscator = o;
+ mEditor = null;
+ }
- public void putString(String key, String value) {
- if (mEditor == null) {
- mEditor = mPreferences.edit();
- mEditor.apply();
- }
- String obfuscatedValue = mObfuscator.obfuscate(value, key);
- mEditor.putString(key, obfuscatedValue);
- }
+ public void putString(String key, String value) {
+ if (mEditor == null) {
+ mEditor = mPreferences.edit();
+ // -- GODOT start --
+ mEditor.apply();
+ // -- GODOT end --
+ }
+ String obfuscatedValue = mObfuscator.obfuscate(value, key);
+ mEditor.putString(key, obfuscatedValue);
+ }
- public String getString(String key, String defValue) {
- String result;
- String value = mPreferences.getString(key, null);
- if (value != null) {
- try {
- result = mObfuscator.unobfuscate(value, key);
- } catch (ValidationException e) {
- // Unable to unobfuscate, data corrupt or tampered
- Log.w(TAG, "Validation error while reading preference: " + key);
- result = defValue;
- }
- } else {
- // Preference not found
- result = defValue;
- }
- return result;
- }
+ public String getString(String key, String defValue) {
+ String result;
+ String value = mPreferences.getString(key, null);
+ if (value != null) {
+ try {
+ result = mObfuscator.unobfuscate(value, key);
+ } catch (ValidationException e) {
+ // Unable to unobfuscate, data corrupt or tampered
+ Log.w(TAG, "Validation error while reading preference: " + key);
+ result = defValue;
+ }
+ } else {
+ // Preference not found
+ result = defValue;
+ }
+ return result;
+ }
- public void commit() {
- if (mEditor != null) {
- mEditor.commit();
- mEditor = null;
- }
- }
+ public void commit() {
+ if (mEditor != null) {
+ mEditor.commit();
+ mEditor = null;
+ }
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ResponseData.java b/platform/android/java/src/com/google/android/vending/licensing/ResponseData.java
index 1c802f8e45..3b5d557e76 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/ResponseData.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/ResponseData.java
@@ -25,56 +25,57 @@ import java.util.regex.Pattern;
*/
public class ResponseData {
- public int responseCode;
- public int nonce;
- public String packageName;
- public String versionCode;
- public String userId;
- public long timestamp;
- /** Response-specific data. */
- public String extra;
+ public int responseCode;
+ public int nonce;
+ public String packageName;
+ public String versionCode;
+ public String userId;
+ public long timestamp;
+ /** Response-specific data. */
+ public String extra;
- /**
+ /**
* Parses response string into ResponseData.
*
* @param responseData response data string
* @throws IllegalArgumentException upon parsing error
* @return ResponseData object
*/
- public static ResponseData parse(String responseData) {
- // Must parse out main response data and response-specific data.
- int index = responseData.indexOf(':');
- String mainData, extraData;
- if (-1 == index) {
- mainData = responseData;
- extraData = "";
- } else {
- mainData = responseData.substring(0, index);
- extraData = index >= responseData.length() ? "" : responseData.substring(index + 1);
- }
+ public static ResponseData parse(String responseData) {
+ // Must parse out main response data and response-specific data.
+ int index = responseData.indexOf(':');
+ String mainData, extraData;
+ if (-1 == index) {
+ mainData = responseData;
+ extraData = "";
+ } else {
+ mainData = responseData.substring(0, index);
+ extraData = index >= responseData.length() ? "" : responseData.substring(index + 1);
+ }
- String[] fields = TextUtils.split(mainData, Pattern.quote("|"));
- if (fields.length < 6) {
- throw new IllegalArgumentException("Wrong number of fields.");
- }
+ String[] fields = TextUtils.split(mainData, Pattern.quote("|"));
+ if (fields.length < 6) {
+ throw new IllegalArgumentException("Wrong number of fields.");
+ }
- ResponseData data = new ResponseData();
- data.extra = extraData;
- data.responseCode = Integer.parseInt(fields[0]);
- data.nonce = Integer.parseInt(fields[1]);
- data.packageName = fields[2];
- data.versionCode = fields[3];
- // Application-specific user identifier.
- data.userId = fields[4];
- data.timestamp = Long.parseLong(fields[5]);
+ ResponseData data = new ResponseData();
+ data.extra = extraData;
+ data.responseCode = Integer.parseInt(fields[0]);
+ data.nonce = Integer.parseInt(fields[1]);
+ data.packageName = fields[2];
+ data.versionCode = fields[3];
+ // Application-specific user identifier.
+ data.userId = fields[4];
+ data.timestamp = Long.parseLong(fields[5]);
- return data;
- }
+ return data;
+ }
- @Override
- public String toString() {
- return TextUtils.join("|", new Object[] {
- responseCode, nonce, packageName, versionCode,
- userId, timestamp });
- }
+ @Override
+ public String toString() {
+ return TextUtils.join("|", new Object[] {
+ responseCode, nonce, packageName, versionCode,
+ userId, timestamp
+ });
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ServerManagedPolicy.java b/platform/android/java/src/com/google/android/vending/licensing/ServerManagedPolicy.java
index b9a50c1104..e2f0bfdca8 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/ServerManagedPolicy.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/ServerManagedPolicy.java
@@ -43,49 +43,49 @@ import com.google.android.vending.licensing.util.URIQueryDecoder;
*/
public class ServerManagedPolicy implements Policy {
- private static final String TAG = "ServerManagedPolicy";
- private static final String PREFS_FILE = "com.google.android.vending.licensing.ServerManagedPolicy";
- private static final String PREF_LAST_RESPONSE = "lastResponse";
- private static final String PREF_VALIDITY_TIMESTAMP = "validityTimestamp";
- private static final String PREF_RETRY_UNTIL = "retryUntil";
- private static final String PREF_MAX_RETRIES = "maxRetries";
- private static final String PREF_RETRY_COUNT = "retryCount";
- private static final String PREF_LICENSING_URL = "licensingUrl";
- private static final String DEFAULT_VALIDITY_TIMESTAMP = "0";
- private static final String DEFAULT_RETRY_UNTIL = "0";
- private static final String DEFAULT_MAX_RETRIES = "0";
- private static final String DEFAULT_RETRY_COUNT = "0";
+ private static final String TAG = "ServerManagedPolicy";
+ private static final String PREFS_FILE = "com.google.android.vending.licensing.ServerManagedPolicy";
+ private static final String PREF_LAST_RESPONSE = "lastResponse";
+ private static final String PREF_VALIDITY_TIMESTAMP = "validityTimestamp";
+ private static final String PREF_RETRY_UNTIL = "retryUntil";
+ private static final String PREF_MAX_RETRIES = "maxRetries";
+ private static final String PREF_RETRY_COUNT = "retryCount";
+ private static final String PREF_LICENSING_URL = "licensingUrl";
+ private static final String DEFAULT_VALIDITY_TIMESTAMP = "0";
+ private static final String DEFAULT_RETRY_UNTIL = "0";
+ private static final String DEFAULT_MAX_RETRIES = "0";
+ private static final String DEFAULT_RETRY_COUNT = "0";
- private static final long MILLIS_PER_MINUTE = 60 * 1000;
+ private static final long MILLIS_PER_MINUTE = 60 * 1000;
- private long mValidityTimestamp;
- private long mRetryUntil;
- private long mMaxRetries;
- private long mRetryCount;
- private long mLastResponseTime = 0;
- private int mLastResponse;
- private String mLicensingUrl;
- private PreferenceObfuscator mPreferences;
+ private long mValidityTimestamp;
+ private long mRetryUntil;
+ private long mMaxRetries;
+ private long mRetryCount;
+ private long mLastResponseTime = 0;
+ private int mLastResponse;
+ private String mLicensingUrl;
+ private PreferenceObfuscator mPreferences;
- /**
+ /**
* @param context The context for the current application
* @param obfuscator An obfuscator to be used with preferences.
*/
- public ServerManagedPolicy(Context context, Obfuscator obfuscator) {
- // Import old values
- SharedPreferences sp = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
- mPreferences = new PreferenceObfuscator(sp, obfuscator);
- mLastResponse = Integer.parseInt(
- mPreferences.getString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY)));
- mValidityTimestamp = Long.parseLong(mPreferences.getString(PREF_VALIDITY_TIMESTAMP,
- DEFAULT_VALIDITY_TIMESTAMP));
- mRetryUntil = Long.parseLong(mPreferences.getString(PREF_RETRY_UNTIL, DEFAULT_RETRY_UNTIL));
- mMaxRetries = Long.parseLong(mPreferences.getString(PREF_MAX_RETRIES, DEFAULT_MAX_RETRIES));
- mRetryCount = Long.parseLong(mPreferences.getString(PREF_RETRY_COUNT, DEFAULT_RETRY_COUNT));
- mLicensingUrl = mPreferences.getString(PREF_LICENSING_URL, null);
- }
+ public ServerManagedPolicy(Context context, Obfuscator obfuscator) {
+ // Import old values
+ SharedPreferences sp = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
+ mPreferences = new PreferenceObfuscator(sp, obfuscator);
+ mLastResponse = Integer.parseInt(
+ mPreferences.getString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY)));
+ mValidityTimestamp = Long.parseLong(mPreferences.getString(PREF_VALIDITY_TIMESTAMP,
+ DEFAULT_VALIDITY_TIMESTAMP));
+ mRetryUntil = Long.parseLong(mPreferences.getString(PREF_RETRY_UNTIL, DEFAULT_RETRY_UNTIL));
+ mMaxRetries = Long.parseLong(mPreferences.getString(PREF_MAX_RETRIES, DEFAULT_MAX_RETRIES));
+ mRetryCount = Long.parseLong(mPreferences.getString(PREF_RETRY_COUNT, DEFAULT_RETRY_COUNT));
+ mLicensingUrl = mPreferences.getString(PREF_LICENSING_URL, null);
+ }
- /**
+ /**
* Process a new response from the license server.
* <p>
* This data will be used for computing future policy decisions. The
@@ -102,159 +102,159 @@ public class ServerManagedPolicy implements Policy {
* @param response the result from validating the server response
* @param rawData the raw server response data
*/
- public void processServerResponse(int response, ResponseData rawData) {
+ public void processServerResponse(int response, ResponseData rawData) {
- // Update retry counter
- if (response != Policy.RETRY) {
- setRetryCount(0);
- } else {
- setRetryCount(mRetryCount + 1);
- }
+ // Update retry counter
+ if (response != Policy.RETRY) {
+ setRetryCount(0);
+ } else {
+ setRetryCount(mRetryCount + 1);
+ }
- // Update server policy data
- Map<String, String> extras = decodeExtras(rawData);
- if (response == Policy.LICENSED) {
- mLastResponse = response;
- // Reset the licensing URL since it is only applicable for NOT_LICENSED responses.
- setLicensingUrl(null);
- setValidityTimestamp(extras.get("VT"));
- setRetryUntil(extras.get("GT"));
- setMaxRetries(extras.get("GR"));
- } else if (response == Policy.NOT_LICENSED) {
- // Clear out stale retry params
- setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
- setRetryUntil(DEFAULT_RETRY_UNTIL);
- setMaxRetries(DEFAULT_MAX_RETRIES);
- // Update the licensing URL
- setLicensingUrl(extras.get("LU"));
- }
+ // Update server policy data
+ Map<String, String> extras = decodeExtras(rawData);
+ if (response == Policy.LICENSED) {
+ mLastResponse = response;
+ // Reset the licensing URL since it is only applicable for NOT_LICENSED responses.
+ setLicensingUrl(null);
+ setValidityTimestamp(extras.get("VT"));
+ setRetryUntil(extras.get("GT"));
+ setMaxRetries(extras.get("GR"));
+ } else if (response == Policy.NOT_LICENSED) {
+ // Clear out stale retry params
+ setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
+ setRetryUntil(DEFAULT_RETRY_UNTIL);
+ setMaxRetries(DEFAULT_MAX_RETRIES);
+ // Update the licensing URL
+ setLicensingUrl(extras.get("LU"));
+ }
- setLastResponse(response);
- mPreferences.commit();
- }
+ setLastResponse(response);
+ mPreferences.commit();
+ }
- /**
+ /**
* Set the last license response received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param l the response
*/
- private void setLastResponse(int l) {
- mLastResponseTime = System.currentTimeMillis();
- mLastResponse = l;
- mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(l));
- }
+ private void setLastResponse(int l) {
+ mLastResponseTime = System.currentTimeMillis();
+ mLastResponse = l;
+ mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(l));
+ }
- /**
+ /**
* Set the current retry count and add to preferences. You must manually
* call PreferenceObfuscator.commit() to commit these changes to disk.
*
* @param c the new retry count
*/
- private void setRetryCount(long c) {
- mRetryCount = c;
- mPreferences.putString(PREF_RETRY_COUNT, Long.toString(c));
- }
+ private void setRetryCount(long c) {
+ mRetryCount = c;
+ mPreferences.putString(PREF_RETRY_COUNT, Long.toString(c));
+ }
- public long getRetryCount() {
- return mRetryCount;
- }
+ public long getRetryCount() {
+ return mRetryCount;
+ }
- /**
+ /**
* Set the last validity timestamp (VT) received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param validityTimestamp the VT string received
*/
- private void setValidityTimestamp(String validityTimestamp) {
- Long lValidityTimestamp;
- try {
- lValidityTimestamp = Long.parseLong(validityTimestamp);
- } catch (NumberFormatException e) {
- // No response or not parsable, expire in one minute.
- Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
- lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
- validityTimestamp = Long.toString(lValidityTimestamp);
- }
+ private void setValidityTimestamp(String validityTimestamp) {
+ Long lValidityTimestamp;
+ try {
+ lValidityTimestamp = Long.parseLong(validityTimestamp);
+ } catch (NumberFormatException e) {
+ // No response or not parsable, expire in one minute.
+ Log.w(TAG, "License validity timestamp (VT) missing, caching for a minute");
+ lValidityTimestamp = System.currentTimeMillis() + MILLIS_PER_MINUTE;
+ validityTimestamp = Long.toString(lValidityTimestamp);
+ }
- mValidityTimestamp = lValidityTimestamp;
- mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
- }
+ mValidityTimestamp = lValidityTimestamp;
+ mPreferences.putString(PREF_VALIDITY_TIMESTAMP, validityTimestamp);
+ }
- public long getValidityTimestamp() {
- return mValidityTimestamp;
- }
+ public long getValidityTimestamp() {
+ return mValidityTimestamp;
+ }
- /**
+ /**
* Set the retry until timestamp (GT) received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param retryUntil the GT string received
*/
- private void setRetryUntil(String retryUntil) {
- Long lRetryUntil;
- try {
- lRetryUntil = Long.parseLong(retryUntil);
- } catch (NumberFormatException e) {
- // No response or not parsable, expire immediately
- Log.w(TAG, "License retry timestamp (GT) missing, grace period disabled");
- retryUntil = "0";
- lRetryUntil = 0l;
- }
+ private void setRetryUntil(String retryUntil) {
+ Long lRetryUntil;
+ try {
+ lRetryUntil = Long.parseLong(retryUntil);
+ } catch (NumberFormatException e) {
+ // No response or not parsable, expire immediately
+ Log.w(TAG, "License retry timestamp (GT) missing, grace period disabled");
+ retryUntil = "0";
+ lRetryUntil = 0l;
+ }
- mRetryUntil = lRetryUntil;
- mPreferences.putString(PREF_RETRY_UNTIL, retryUntil);
- }
+ mRetryUntil = lRetryUntil;
+ mPreferences.putString(PREF_RETRY_UNTIL, retryUntil);
+ }
- public long getRetryUntil() {
- return mRetryUntil;
- }
+ public long getRetryUntil() {
+ return mRetryUntil;
+ }
- /**
+ /**
* Set the max retries value (GR) as received from the server and add to
* preferences. You must manually call PreferenceObfuscator.commit() to
* commit these changes to disk.
*
* @param maxRetries the GR string received
*/
- private void setMaxRetries(String maxRetries) {
- Long lMaxRetries;
- try {
- lMaxRetries = Long.parseLong(maxRetries);
- } catch (NumberFormatException e) {
- // No response or not parsable, expire immediately
- Log.w(TAG, "Licence retry count (GR) missing, grace period disabled");
- maxRetries = "0";
- lMaxRetries = 0l;
- }
+ private void setMaxRetries(String maxRetries) {
+ Long lMaxRetries;
+ try {
+ lMaxRetries = Long.parseLong(maxRetries);
+ } catch (NumberFormatException e) {
+ // No response or not parsable, expire immediately
+ Log.w(TAG, "Licence retry count (GR) missing, grace period disabled");
+ maxRetries = "0";
+ lMaxRetries = 0l;
+ }
- mMaxRetries = lMaxRetries;
- mPreferences.putString(PREF_MAX_RETRIES, maxRetries);
- }
+ mMaxRetries = lMaxRetries;
+ mPreferences.putString(PREF_MAX_RETRIES, maxRetries);
+ }
- public long getMaxRetries() {
- return mMaxRetries;
- }
+ public long getMaxRetries() {
+ return mMaxRetries;
+ }
- /**
+ /**
* Set the license URL value (LU) as received from the server and add to preferences. You must
* manually call PreferenceObfuscator.commit() to commit these changes to disk.
*
* @param url the LU string received
*/
- private void setLicensingUrl(String url) {
- mLicensingUrl = url;
- mPreferences.putString(PREF_LICENSING_URL, url);
- }
+ private void setLicensingUrl(String url) {
+ mLicensingUrl = url;
+ mPreferences.putString(PREF_LICENSING_URL, url);
+ }
- public String getLicensingUrl() {
- return mLicensingUrl;
- }
+ public String getLicensingUrl() {
+ return mLicensingUrl;
+ }
- /**
+ /**
* {@inheritDoc}
*
* This implementation allows access if either:<br>
@@ -264,36 +264,37 @@ public class ServerManagedPolicy implements Policy {
* the RETRY count or in the RETRY period.
* </ol>
*/
- public boolean allowAccess() {
- long ts = System.currentTimeMillis();
- if (mLastResponse == Policy.LICENSED) {
- // Check if the LICENSED response occurred within the validity timeout.
- if (ts <= mValidityTimestamp) {
- // Cached LICENSED response is still valid.
- return true;
- }
- } else if (mLastResponse == Policy.RETRY &&
- ts < mLastResponseTime + MILLIS_PER_MINUTE) {
- // Only allow access if we are within the retry period or we haven't used up our
- // max retries.
- return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
- }
- return false;
- }
+ public boolean allowAccess() {
+ long ts = System.currentTimeMillis();
+ if (mLastResponse == Policy.LICENSED) {
+ // Check if the LICENSED response occurred within the validity timeout.
+ if (ts <= mValidityTimestamp) {
+ // Cached LICENSED response is still valid.
+ return true;
+ }
+ } else if (mLastResponse == Policy.RETRY &&
+ ts < mLastResponseTime + MILLIS_PER_MINUTE) {
+ // Only allow access if we are within the retry period or we haven't used up our
+ // max retries.
+ return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
+ }
+ return false;
+ }
- private Map<String, String> decodeExtras(
- com.google.android.vending.licensing.ResponseData rawData) {
- Map<String, String> results = new HashMap<String, String>();
- if (rawData == null) {
- return results;
- }
+ private Map<String, String> decodeExtras(
+ com.google.android.vending.licensing.ResponseData rawData) {
+ Map<String, String> results = new HashMap<String, String>();
+ if (rawData == null) {
+ return results;
+ }
+
+ try {
+ URI rawExtras = new URI("?" + rawData.extra);
+ URIQueryDecoder.DecodeQuery(rawExtras, results);
+ } catch (URISyntaxException e) {
+ Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
+ }
+ return results;
+ }
- try {
- URI rawExtras = new URI("?" + rawData.extra);
- URIQueryDecoder.DecodeQuery(rawExtras, results);
- } catch (URISyntaxException e) {
- Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
- }
- return results;
- }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/StrictPolicy.java b/platform/android/java/src/com/google/android/vending/licensing/StrictPolicy.java
index 9849730c38..c2d55c37f1 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/StrictPolicy.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/StrictPolicy.java
@@ -38,18 +38,18 @@ import java.util.Map;
*/
public class StrictPolicy implements Policy {
- private static final String TAG = "StrictPolicy";
+ private static final String TAG = "StrictPolicy";
- private int mLastResponse;
- private String mLicensingUrl;
+ private int mLastResponse;
+ private String mLicensingUrl;
- public StrictPolicy() {
- // Set default policy. This will force the application to check the policy on launch.
- mLastResponse = Policy.RETRY;
- mLicensingUrl = null;
- }
+ public StrictPolicy() {
+ // Set default policy. This will force the application to check the policy on launch.
+ mLastResponse = Policy.RETRY;
+ mLicensingUrl = null;
+ }
- /**
+ /**
* Process a new response from the license server. Since we aren't
* performing any caching, this equates to reading the LicenseResponse.
* Any cache-related ResponseData is ignored, but the licensing URL
@@ -58,42 +58,43 @@ public class StrictPolicy implements Policy {
* @param response the result from validating the server response
* @param rawData the raw server response data
*/
- public void processServerResponse(int response, ResponseData rawData) {
- mLastResponse = response;
+ public void processServerResponse(int response, ResponseData rawData) {
+ mLastResponse = response;
- if (response == Policy.NOT_LICENSED) {
- Map<String, String> extras = decodeExtras(rawData);
- mLicensingUrl = extras.get("LU");
- }
- }
+ if (response == Policy.NOT_LICENSED) {
+ Map<String, String> extras = decodeExtras(rawData);
+ mLicensingUrl = extras.get("LU");
+ }
+ }
- /**
+ /**
* {@inheritDoc}
*
* This implementation allows access if and only if a LICENSED response
* was received the last time the server was contacted.
*/
- public boolean allowAccess() {
- return (mLastResponse == Policy.LICENSED);
- }
+ public boolean allowAccess() {
+ return (mLastResponse == Policy.LICENSED);
+ }
- public String getLicensingUrl() {
- return mLicensingUrl;
- }
+ public String getLicensingUrl() {
+ return mLicensingUrl;
+ }
- private Map<String, String> decodeExtras(
- com.google.android.vending.licensing.ResponseData rawData) {
- Map<String, String> results = new HashMap<String, String>();
- if (rawData == null) {
- return results;
- }
+ private Map<String, String> decodeExtras(
+ com.google.android.vending.licensing.ResponseData rawData) {
+ Map<String, String> results = new HashMap<String, String>();
+ if (rawData == null) {
+ return results;
+ }
+
+ try {
+ URI rawExtras = new URI("?" + rawData.extra);
+ URIQueryDecoder.DecodeQuery(rawExtras, results);
+ } catch (URISyntaxException e) {
+ Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
+ }
+ return results;
+ }
- try {
- URI rawExtras = new URI("?" + rawData.extra);
- URIQueryDecoder.DecodeQuery(rawExtras, results);
- } catch (URISyntaxException e) {
- Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
- }
- return results;
- }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/ValidationException.java b/platform/android/java/src/com/google/android/vending/licensing/ValidationException.java
index 79b70e6804..ee4df47c68 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/ValidationException.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/ValidationException.java
@@ -21,13 +21,13 @@ package com.google.android.vending.licensing;
* {@link Obfuscator}.}
*/
public class ValidationException extends Exception {
- public ValidationException() {
- super();
- }
+ public ValidationException() {
+ super();
+ }
- public ValidationException(String s) {
- super(s);
- }
+ public ValidationException(String s) {
+ super(s);
+ }
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java b/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
index bd711aadf5..a8bf65f9ca 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/util/Base64.java
@@ -31,7 +31,9 @@ package com.google.android.vending.licensing.util;
* @version 1.3
*/
+// -- GODOT start --
import com.godot.game.BuildConfig;
+// -- GODOT end --
/**
* Base64 converter class. This code is not a full-blown MIME encoder;
@@ -41,79 +43,80 @@ import com.godot.game.BuildConfig;
* class.
*/
public class Base64 {
- /** Specify encoding (value is {@code true}). */
- public final static boolean ENCODE = true;
+ /** Specify encoding (value is {@code true}). */
+ public final static boolean ENCODE = true;
- /** Specify decoding (value is {@code false}). */
- public final static boolean DECODE = false;
+ /** Specify decoding (value is {@code false}). */
+ public final static boolean DECODE = false;
- /** The equals sign (=) as a byte. */
- private final static byte EQUALS_SIGN = (byte)'=';
+ /** The equals sign (=) as a byte. */
+ private final static byte EQUALS_SIGN = (byte) '=';
- /** The new line character (\n) as a byte. */
- private final static byte NEW_LINE = (byte)'\n';
+ /** The new line character (\n) as a byte. */
+ private final static byte NEW_LINE = (byte) '\n';
- /**
+ /**
* The 64 valid Base64 values.
*/
- private final static byte[] ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
- (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K',
- (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P',
- (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
- (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
- (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e',
- (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j',
- (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o',
- (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t',
- (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y',
- (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3',
- (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8',
- (byte)'9', (byte)'+', (byte)'/' };
-
- /**
+ private final static byte[] ALPHABET =
+ {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
+ (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
+ (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
+ (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
+ (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
+ (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
+ (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
+ (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
+ (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
+ (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
+ (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
+ (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
+ (byte) '9', (byte) '+', (byte) '/'};
+
+ /**
* The 64 valid web safe Base64 values.
*/
- private final static byte[] WEBSAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
- (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K',
- (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P',
- (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
- (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
- (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e',
- (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j',
- (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o',
- (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t',
- (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y',
- (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3',
- (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8',
- (byte)'9', (byte)'-', (byte)'_' };
-
- /**
+ private final static byte[] WEBSAFE_ALPHABET =
+ {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
+ (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
+ (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
+ (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
+ (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
+ (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
+ (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
+ (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
+ (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
+ (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
+ (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
+ (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
+ (byte) '9', (byte) '-', (byte) '_'};
+
+ /**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
- private final static byte[] DECODABET = {
- -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
- -5, -5, // Whitespace: Tab and Linefeed
- -9, -9, // Decimal 11 - 12
- -5, // Whitespace: Carriage Return
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
- -9, -9, -9, -9, -9, // Decimal 27 - 31
- -5, // Whitespace: Space
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
- 62, // Plus sign at decimal 43
- -9, -9, -9, // Decimal 44 - 46
- 63, // Slash at decimal 47
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
- -9, -9, -9, // Decimal 58 - 60
- -1, // Equals sign at decimal 61
- -9, -9, -9, // Decimal 62 - 64
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
- 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
- -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
- 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
- -9, -9, -9, -9, -9 // Decimal 123 - 127
- /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
+ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
+ -5, -5, // Whitespace: Tab and Linefeed
+ -9, -9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
+ -9, -9, -9, -9, -9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
+ 62, // Plus sign at decimal 43
+ -9, -9, -9, // Decimal 44 - 46
+ 63, // Slash at decimal 47
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
+ -9, -9, -9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9, -9, -9, // Decimal 62 - 64
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
+ -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
+ -9, -9, -9, -9, -9 // Decimal 123 - 127
+ /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
@@ -123,33 +126,33 @@ public class Base64 {
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
- };
-
- /** The web safe decodabet */
- private final static byte[] WEBSAFE_DECODABET = {
- -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
- -5, -5, // Whitespace: Tab and Linefeed
- -9, -9, // Decimal 11 - 12
- -5, // Whitespace: Carriage Return
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
- -9, -9, -9, -9, -9, // Decimal 27 - 31
- -5, // Whitespace: Space
- -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44
- 62, // Dash '-' sign at decimal 45
- -9, -9, // Decimal 46-47
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
- -9, -9, -9, // Decimal 58 - 60
- -1, // Equals sign at decimal 61
- -9, -9, -9, // Decimal 62 - 64
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
- 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
- -9, -9, -9, -9, // Decimal 91-94
- 63, // Underscore '_' at decimal 95
- -9, // Decimal 96
- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
- 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
- -9, -9, -9, -9, -9 // Decimal 123 - 127
- /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
+ };
+
+ /** The web safe decodabet */
+ private final static byte[] WEBSAFE_DECODABET =
+ {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
+ -5, -5, // Whitespace: Tab and Linefeed
+ -9, -9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
+ -9, -9, -9, -9, -9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44
+ 62, // Dash '-' sign at decimal 45
+ -9, -9, // Decimal 46-47
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
+ -9, -9, -9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9, -9, -9, // Decimal 62 - 64
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
+ -9, -9, -9, -9, // Decimal 91-94
+ 63, // Underscore '_' at decimal 95
+ -9, // Decimal 96
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
+ -9, -9, -9, -9, -9 // Decimal 123 - 127
+ /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
@@ -159,20 +162,20 @@ public class Base64 {
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
- };
+ };
- // Indicates white space in encoding
- private final static byte WHITE_SPACE_ENC = -5;
- // Indicates equals sign in encoding
- private final static byte EQUALS_SIGN_ENC = -1;
+ // Indicates white space in encoding
+ private final static byte WHITE_SPACE_ENC = -5;
+ // Indicates equals sign in encoding
+ private final static byte EQUALS_SIGN_ENC = -1;
- /** Defeats instantiation. */
- private Base64() {
- }
+ /** Defeats instantiation. */
+ private Base64() {
+ }
- /* ******** E N C O D I N G M E T H O D S ******** */
+ /* ******** E N C O D I N G M E T H O D S ******** */
- /**
+ /**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
@@ -194,47 +197,49 @@ public class Base64 {
* @return the <var>destination</var> array
* @since 1.3
*/
- private static byte[] encode3to4(byte[] source, int srcOffset,
- int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) {
- // 1 2 3
- // 01234567890123456789012345678901 Bit position
- // --------000000001111111122222222 Array position from threeBytes
- // --------| || || || | Six bit groups to index alphabet
- // >>18 >>12 >> 6 >> 0 Right shift necessary
- // 0x3f 0x3f 0x3f Additional AND
-
- // Create buffer with zero-padding if there are only one or two
- // significant bytes passed in the array.
- // We have to shift left 24 in order to flush out the 1's that appear
- // when Java treats a value as negative that is cast from a byte to an int.
- int inBuff =
- (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
-
- switch (numSigBytes) {
- case 3:
- destination[destOffset] = alphabet[(inBuff >>> 18)];
- destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
- destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
- destination[destOffset + 3] = alphabet[(inBuff)&0x3f];
- return destination;
- case 2:
- destination[destOffset] = alphabet[(inBuff >>> 18)];
- destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
- destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
- destination[destOffset + 3] = EQUALS_SIGN;
- return destination;
- case 1:
- destination[destOffset] = alphabet[(inBuff >>> 18)];
- destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
- destination[destOffset + 2] = EQUALS_SIGN;
- destination[destOffset + 3] = EQUALS_SIGN;
- return destination;
- default:
- return destination;
- } // end switch
- } // end encode3to4
-
- /**
+ private static byte[] encode3to4(byte[] source, int srcOffset,
+ int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) {
+ // 1 2 3
+ // 01234567890123456789012345678901 Bit position
+ // --------000000001111111122222222 Array position from threeBytes
+ // --------| || || || | Six bit groups to index alphabet
+ // >>18 >>12 >> 6 >> 0 Right shift necessary
+ // 0x3f 0x3f 0x3f Additional AND
+
+ // Create buffer with zero-padding if there are only one or two
+ // significant bytes passed in the array.
+ // We have to shift left 24 in order to flush out the 1's that appear
+ // when Java treats a value as negative that is cast from a byte to an int.
+ int inBuff =
+ (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
+ | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
+ | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
+
+ switch (numSigBytes) {
+ case 3:
+ destination[destOffset] = alphabet[(inBuff >>> 18)];
+ destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
+ destination[destOffset + 3] = alphabet[(inBuff) & 0x3f];
+ return destination;
+ case 2:
+ destination[destOffset] = alphabet[(inBuff >>> 18)];
+ destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
+ destination[destOffset + 3] = EQUALS_SIGN;
+ return destination;
+ case 1:
+ destination[destOffset] = alphabet[(inBuff >>> 18)];
+ destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = EQUALS_SIGN;
+ destination[destOffset + 3] = EQUALS_SIGN;
+ return destination;
+ default:
+ return destination;
+ } // end switch
+ } // end encode3to4
+
+ /**
* Encodes a byte array into Base64 notation.
* Equivalent to calling
* {@code encodeBytes(source, 0, source.length)}
@@ -242,22 +247,22 @@ public class Base64 {
* @param source The data to convert
* @since 1.4
*/
- public static String encode(byte[] source) {
- return encode(source, 0, source.length, ALPHABET, true);
- }
+ public static String encode(byte[] source) {
+ return encode(source, 0, source.length, ALPHABET, true);
+ }
- /**
+ /**
* Encodes a byte array into web safe Base64 notation.
*
* @param source The data to convert
* @param doPadding is {@code true} to pad result with '=' chars
* if it does not fall on 3 byte boundaries
*/
- public static String encodeWebSafe(byte[] source, boolean doPadding) {
- return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding);
- }
+ public static String encodeWebSafe(byte[] source, boolean doPadding) {
+ return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding);
+ }
- /**
+ /**
* Encodes a byte array into Base64 notation.
*
* @param source The data to convert
@@ -268,24 +273,24 @@ public class Base64 {
* if it does not fall on 3 byte boundaries
* @since 1.4
*/
- public static String encode(byte[] source, int off, int len, byte[] alphabet,
- boolean doPadding) {
- byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE);
- int outLen = outBuff.length;
-
- // If doPadding is false, set length to truncate '='
- // padding characters
- while (doPadding == false && outLen > 0) {
- if (outBuff[outLen - 1] != '=') {
- break;
- }
- outLen -= 1;
- }
-
- return new String(outBuff, 0, outLen);
- }
-
- /**
+ public static String encode(byte[] source, int off, int len, byte[] alphabet,
+ boolean doPadding) {
+ byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE);
+ int outLen = outBuff.length;
+
+ // If doPadding is false, set length to truncate '='
+ // padding characters
+ while (doPadding == false && outLen > 0) {
+ if (outBuff[outLen - 1] != '=') {
+ break;
+ }
+ outLen -= 1;
+ }
+
+ return new String(outBuff, 0, outLen);
+ }
+
+ /**
* Encodes a byte array into Base64 notation.
*
* @param source The data to convert
@@ -295,57 +300,64 @@ public class Base64 {
* @param maxLineLength maximum length of one line.
* @return the BASE64-encoded byte array
*/
- public static byte[] encode(byte[] source, int off, int len, byte[] alphabet,
- int maxLineLength) {
- int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
- int len43 = lenDiv3 * 4;
- byte[] outBuff = new byte[len43 // Main 4:3
- + (len43 / maxLineLength)]; // New lines
-
- int d = 0;
- int e = 0;
- int len2 = len - 2;
- int lineLength = 0;
- for (; d < len2; d += 3, e += 4) {
-
- // The following block of code is the same as
- // encode3to4( source, d + off, 3, outBuff, e, alphabet );
- // but inlined for faster encoding (~20% improvement)
- int inBuff =
- ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24);
- outBuff[e] = alphabet[(inBuff >>> 18)];
- outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
- outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
- outBuff[e + 3] = alphabet[(inBuff)&0x3f];
-
- lineLength += 4;
- if (lineLength == maxLineLength) {
- outBuff[e + 4] = NEW_LINE;
- e++;
- lineLength = 0;
- } // end if: end of line
- } // end for: each piece of array
-
- if (d < len) {
- encode3to4(source, d + off, len - d, outBuff, e, alphabet);
-
- lineLength += 4;
- if (lineLength == maxLineLength) {
- // Add a last newline
- outBuff[e + 4] = NEW_LINE;
- e++;
- }
- e += 4;
- }
-
- if (BuildConfig.DEBUG && e != outBuff.length)
- throw new RuntimeException();
- return outBuff;
- }
-
- /* ******** D E C O D I N G M E T H O D S ******** */
-
- /**
+ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet,
+ int maxLineLength) {
+ int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
+ int len43 = lenDiv3 * 4;
+ byte[] outBuff = new byte[len43 // Main 4:3
+ + (len43 / maxLineLength)]; // New lines
+
+ int d = 0;
+ int e = 0;
+ int len2 = len - 2;
+ int lineLength = 0;
+ for (; d < len2; d += 3, e += 4) {
+
+ // The following block of code is the same as
+ // encode3to4( source, d + off, 3, outBuff, e, alphabet );
+ // but inlined for faster encoding (~20% improvement)
+ int inBuff =
+ ((source[d + off] << 24) >>> 8)
+ | ((source[d + 1 + off] << 24) >>> 16)
+ | ((source[d + 2 + off] << 24) >>> 24);
+ outBuff[e] = alphabet[(inBuff >>> 18)];
+ outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
+ outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
+ outBuff[e + 3] = alphabet[(inBuff) & 0x3f];
+
+ lineLength += 4;
+ if (lineLength == maxLineLength) {
+ outBuff[e + 4] = NEW_LINE;
+ e++;
+ lineLength = 0;
+ } // end if: end of line
+ } // end for: each piece of array
+
+ if (d < len) {
+ encode3to4(source, d + off, len - d, outBuff, e, alphabet);
+
+ lineLength += 4;
+ if (lineLength == maxLineLength) {
+ // Add a last newline
+ outBuff[e + 4] = NEW_LINE;
+ e++;
+ }
+ e += 4;
+ }
+
+ // -- GODOT start --
+ //assert (e == outBuff.length);
+ if (BuildConfig.DEBUG && e != outBuff.length)
+ throw new RuntimeException();
+ // -- GODOT end --
+ return outBuff;
+ }
+
+
+ /* ******** D E C O D I N G M E T H O D S ******** */
+
+
+ /**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
@@ -368,60 +380,67 @@ public class Base64 {
* @return the number of decoded bytes converted
* @since 1.3
*/
- private static int decode4to3(byte[] source, int srcOffset,
- byte[] destination, int destOffset, byte[] decodabet) {
- // Example: Dk==
- if (source[srcOffset + 2] == EQUALS_SIGN) {
- int outBuff =
- ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12);
-
- destination[destOffset] = (byte)(outBuff >>> 16);
- return 1;
- } else if (source[srcOffset + 3] == EQUALS_SIGN) {
- // Example: DkL=
- int outBuff =
- ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18);
-
- destination[destOffset] = (byte)(outBuff >>> 16);
- destination[destOffset + 1] = (byte)(outBuff >>> 8);
- return 2;
- } else {
- // Example: DkLE
- int outBuff =
- ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24);
-
- destination[destOffset] = (byte)(outBuff >> 16);
- destination[destOffset + 1] = (byte)(outBuff >> 8);
- destination[destOffset + 2] = (byte)(outBuff);
- return 3;
- }
- } // end decodeToBytes
-
- /**
+ private static int decode4to3(byte[] source, int srcOffset,
+ byte[] destination, int destOffset, byte[] decodabet) {
+ // Example: Dk==
+ if (source[srcOffset + 2] == EQUALS_SIGN) {
+ int outBuff =
+ ((decodabet[source[srcOffset]] << 24) >>> 6)
+ | ((decodabet[source[srcOffset + 1]] << 24) >>> 12);
+
+ destination[destOffset] = (byte) (outBuff >>> 16);
+ return 1;
+ } else if (source[srcOffset + 3] == EQUALS_SIGN) {
+ // Example: DkL=
+ int outBuff =
+ ((decodabet[source[srcOffset]] << 24) >>> 6)
+ | ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
+ | ((decodabet[source[srcOffset + 2]] << 24) >>> 18);
+
+ destination[destOffset] = (byte) (outBuff >>> 16);
+ destination[destOffset + 1] = (byte) (outBuff >>> 8);
+ return 2;
+ } else {
+ // Example: DkLE
+ int outBuff =
+ ((decodabet[source[srcOffset]] << 24) >>> 6)
+ | ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
+ | ((decodabet[source[srcOffset + 2]] << 24) >>> 18)
+ | ((decodabet[source[srcOffset + 3]] << 24) >>> 24);
+
+ destination[destOffset] = (byte) (outBuff >> 16);
+ destination[destOffset + 1] = (byte) (outBuff >> 8);
+ destination[destOffset + 2] = (byte) (outBuff);
+ return 3;
+ }
+ } // end decodeToBytes
+
+
+ /**
* Decodes data from Base64 notation.
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
* @since 1.4
*/
- public static byte[] decode(String s) throws Base64DecoderException {
- byte[] bytes = s.getBytes();
- return decode(bytes, 0, bytes.length);
- }
+ public static byte[] decode(String s) throws Base64DecoderException {
+ byte[] bytes = s.getBytes();
+ return decode(bytes, 0, bytes.length);
+ }
- /**
+ /**
* Decodes data from web safe Base64 notation.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
*/
- public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
- byte[] bytes = s.getBytes();
- return decodeWebSafe(bytes, 0, bytes.length);
- }
+ public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
+ byte[] bytes = s.getBytes();
+ return decodeWebSafe(bytes, 0, bytes.length);
+ }
- /**
+ /**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
@@ -430,11 +449,11 @@ public class Base64 {
* @since 1.3
* @throws Base64DecoderException
*/
- public static byte[] decode(byte[] source) throws Base64DecoderException {
- return decode(source, 0, source.length);
- }
+ public static byte[] decode(byte[] source) throws Base64DecoderException {
+ return decode(source, 0, source.length);
+ }
- /**
+ /**
* Decodes web safe Base64 content in byte array format and returns
* the decoded data.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
@@ -442,12 +461,12 @@ public class Base64 {
* @param source the string to decode (decoded in default encoding)
* @return the decoded data
*/
- public static byte[] decodeWebSafe(byte[] source)
- throws Base64DecoderException {
- return decodeWebSafe(source, 0, source.length);
- }
+ public static byte[] decodeWebSafe(byte[] source)
+ throws Base64DecoderException {
+ return decodeWebSafe(source, 0, source.length);
+ }
- /**
+ /**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
@@ -458,12 +477,12 @@ public class Base64 {
* @since 1.3
* @throws Base64DecoderException
*/
- public static byte[] decode(byte[] source, int off, int len)
- throws Base64DecoderException {
- return decode(source, off, len, DECODABET);
- }
+ public static byte[] decode(byte[] source, int off, int len)
+ throws Base64DecoderException {
+ return decode(source, off, len, DECODABET);
+ }
- /**
+ /**
* Decodes web safe Base64 content in byte array format and returns
* the decoded byte array.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
@@ -473,12 +492,12 @@ public class Base64 {
* @param len The length of characters to decode
* @return decoded data
*/
- public static byte[] decodeWebSafe(byte[] source, int off, int len)
- throws Base64DecoderException {
- return decode(source, off, len, WEBSAFE_DECODABET);
- }
+ public static byte[] decodeWebSafe(byte[] source, int off, int len)
+ throws Base64DecoderException {
+ return decode(source, off, len, WEBSAFE_DECODABET);
+ }
- /**
+ /**
* Decodes Base64 content using the supplied decodabet and returns
* the decoded byte array.
*
@@ -488,69 +507,72 @@ public class Base64 {
* @param decodabet the decodabet for decoding Base64 content
* @return decoded data
*/
- public static byte[] decode(byte[] source, int off, int len, byte[] decodabet)
- throws Base64DecoderException {
- int len34 = len * 3 / 4;
- byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output
- int outBuffPosn = 0;
-
- byte[] b4 = new byte[4];
- int b4Posn = 0;
- int i = 0;
- byte sbiCrop = 0;
- byte sbiDecode = 0;
- for (i = 0; i < len; i++) {
- sbiCrop = (byte)(source[i + off] & 0x7f); // Only the low seven bits
- sbiDecode = decodabet[sbiCrop];
-
- if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better
- if (sbiDecode >= EQUALS_SIGN_ENC) {
- // An equals sign (for padding) must not occur at position 0 or 1
- // and must be the last byte[s] in the encoded value
- if (sbiCrop == EQUALS_SIGN) {
- int bytesLeft = len - i;
- byte lastByte = (byte)(source[len - 1 + off] & 0x7f);
- if (b4Posn == 0 || b4Posn == 1) {
- throw new Base64DecoderException(
- "invalid padding byte '=' at byte offset " + i);
- } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) {
- throw new Base64DecoderException(
- "padding byte '=' falsely signals end of encoded value "
- + "at offset " + i);
- } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) {
- throw new Base64DecoderException(
- "encoded value has invalid trailing byte");
- }
- break;
- }
-
- b4[b4Posn++] = sbiCrop;
- if (b4Posn == 4) {
- outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
- b4Posn = 0;
- }
- }
- } else {
- throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)");
- }
- }
-
- // Because web safe encoding allows non padding base64 encodes, we
- // need to pad the rest of the b4 buffer with equal signs when
- // b4Posn != 0. There can be at most 2 equal signs at the end of
- // four characters, so the b4 buffer must have two or three
- // characters. This also catches the case where the input is
- // padded with EQUALS_SIGN
- if (b4Posn != 0) {
- if (b4Posn == 1) {
- throw new Base64DecoderException("single trailing character at offset " + (len - 1));
- }
- b4[b4Posn++] = EQUALS_SIGN;
- outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
- }
-
- byte[] out = new byte[outBuffPosn];
- System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
- return out;
- }
+ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet)
+ throws Base64DecoderException {
+ int len34 = len * 3 / 4;
+ byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output
+ int outBuffPosn = 0;
+
+ byte[] b4 = new byte[4];
+ int b4Posn = 0;
+ int i = 0;
+ byte sbiCrop = 0;
+ byte sbiDecode = 0;
+ for (i = 0; i < len; i++) {
+ sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits
+ sbiDecode = decodabet[sbiCrop];
+
+ if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better
+ if (sbiDecode >= EQUALS_SIGN_ENC) {
+ // An equals sign (for padding) must not occur at position 0 or 1
+ // and must be the last byte[s] in the encoded value
+ if (sbiCrop == EQUALS_SIGN) {
+ int bytesLeft = len - i;
+ byte lastByte = (byte) (source[len - 1 + off] & 0x7f);
+ if (b4Posn == 0 || b4Posn == 1) {
+ throw new Base64DecoderException(
+ "invalid padding byte '=' at byte offset " + i);
+ } else if ((b4Posn == 3 && bytesLeft > 2)
+ || (b4Posn == 4 && bytesLeft > 1)) {
+ throw new Base64DecoderException(
+ "padding byte '=' falsely signals end of encoded value "
+ + "at offset " + i);
+ } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) {
+ throw new Base64DecoderException(
+ "encoded value has invalid trailing byte");
+ }
+ break;
+ }
+
+ b4[b4Posn++] = sbiCrop;
+ if (b4Posn == 4) {
+ outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
+ b4Posn = 0;
+ }
+ }
+ } else {
+ throw new Base64DecoderException("Bad Base64 input character at " + i
+ + ": " + source[i + off] + "(decimal)");
+ }
+ }
+
+ // Because web safe encoding allows non padding base64 encodes, we
+ // need to pad the rest of the b4 buffer with equal signs when
+ // b4Posn != 0. There can be at most 2 equal signs at the end of
+ // four characters, so the b4 buffer must have two or three
+ // characters. This also catches the case where the input is
+ // padded with EQUALS_SIGN
+ if (b4Posn != 0) {
+ if (b4Posn == 1) {
+ throw new Base64DecoderException("single trailing character at offset "
+ + (len - 1));
+ }
+ b4[b4Posn++] = EQUALS_SIGN;
+ outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
+ }
+
+ byte[] out = new byte[outBuffPosn];
+ System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
+ return out;
+ }
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/util/Base64DecoderException.java b/platform/android/java/src/com/google/android/vending/licensing/util/Base64DecoderException.java
index 50724a9b05..1aef1b54b8 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/util/Base64DecoderException.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/util/Base64DecoderException.java
@@ -20,13 +20,13 @@ package com.google.android.vending.licensing.util;
* @author nelson
*/
public class Base64DecoderException extends Exception {
- public Base64DecoderException() {
- super();
- }
+ public Base64DecoderException() {
+ super();
+ }
- public Base64DecoderException(String s) {
- super(s);
- }
+ public Base64DecoderException(String s) {
+ super(s);
+ }
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
}
diff --git a/platform/android/java/src/com/google/android/vending/licensing/util/URIQueryDecoder.java b/platform/android/java/src/com/google/android/vending/licensing/util/URIQueryDecoder.java
index 4f908b472c..5155bf5ac3 100644
--- a/platform/android/java/src/com/google/android/vending/licensing/util/URIQueryDecoder.java
+++ b/platform/android/java/src/com/google/android/vending/licensing/util/URIQueryDecoder.java
@@ -25,36 +25,36 @@ import java.util.Map;
import java.util.Scanner;
public class URIQueryDecoder {
- private static final String TAG = "URIQueryDecoder";
+ private static final String TAG = "URIQueryDecoder";
- /**
+ /**
* Decodes the query portion of the passed-in URI.
*
* @param encodedURI the URI containing the query to decode
* @param results a map containing all query parameters. Query parameters that do not have a
* value will map to a null string
*/
- static public void DecodeQuery(URI encodedURI, Map<String, String> results) {
- Scanner scanner = new Scanner(encodedURI.getRawQuery());
- scanner.useDelimiter("&");
- try {
- while (scanner.hasNext()) {
- String param = scanner.next();
- String[] valuePair = param.split("=");
- String name, value;
- if (valuePair.length == 1) {
- value = null;
- } else if (valuePair.length == 2) {
- value = URLDecoder.decode(valuePair[1], "UTF-8");
- } else {
- throw new IllegalArgumentException("query parameter invalid");
- }
- name = URLDecoder.decode(valuePair[0], "UTF-8");
- results.put(name, value);
- }
- } catch (UnsupportedEncodingException e) {
- // This should never happen.
- Log.e(TAG, "UTF-8 Not Recognized as a charset. Device configuration Error.");
- }
- }
+ static public void DecodeQuery(URI encodedURI, Map<String, String> results) {
+ Scanner scanner = new Scanner(encodedURI.getRawQuery());
+ scanner.useDelimiter("&");
+ try {
+ while (scanner.hasNext()) {
+ String param = scanner.next();
+ String[] valuePair = param.split("=");
+ String name, value;
+ if (valuePair.length == 1) {
+ value = null;
+ } else if (valuePair.length == 2) {
+ value = URLDecoder.decode(valuePair[1], "UTF-8");
+ } else {
+ throw new IllegalArgumentException("query parameter invalid");
+ }
+ name = URLDecoder.decode(valuePair[0], "UTF-8");
+ results.put(name, value);
+ }
+ } catch (UnsupportedEncodingException e) {
+ // This should never happen.
+ Log.e(TAG, "UTF-8 Not Recognized as a charset. Device configuration Error.");
+ }
+ }
}
diff --git a/platform/android/java/src/org/godotengine/godot/Godot.java b/platform/android/java/src/org/godotengine/godot/Godot.java
index 6e1841fa8b..1b3239777c 100644
--- a/platform/android/java/src/org/godotengine/godot/Godot.java
+++ b/platform/android/java/src/org/godotengine/godot/Godot.java
@@ -31,6 +31,7 @@
package org.godotengine.godot;
import android.Manifest;
+import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
@@ -56,7 +57,10 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Messenger;
+import android.os.VibrationEffect;
+import android.os.Vibrator;
import android.provider.Settings.Secure;
+import android.support.annotation.Keep;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.KeyEvent;
@@ -98,8 +102,8 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
static final int MAX_SINGLETONS = 64;
static final int REQUEST_RECORD_AUDIO_PERMISSION = 1;
static final int REQUEST_CAMERA_PERMISSION = 2;
+ static final int REQUEST_VIBRATE_PERMISSION = 3;
private IStub mDownloaderClientStub;
- private IDownloaderService mRemoteService;
private TextView mStatusText;
private TextView mProgressFraction;
private TextView mProgressPercent;
@@ -222,15 +226,9 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
private Sensor mMagnetometer;
private Sensor mGyroscope;
- public FrameLayout layout;
-
public static GodotIO io;
- public static void setWindowTitle(String title) {
- //setTitle(title);
- }
-
- static SingletonBase singletons[] = new SingletonBase[MAX_SINGLETONS];
+ static SingletonBase[] singletons = new SingletonBase[MAX_SINGLETONS];
static int singleton_count = 0;
public interface ResultCallback {
@@ -266,13 +264,14 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
}
};
- public void onVideoInit() {
+ /**
+ * Used by the native code (java_godot_lib_jni.cpp) to complete initialization of the GLSurfaceView view and renderer.
+ */
+ @Keep
+ private void onVideoInit() {
boolean use_gl3 = getGLESVersionCode() >= 0x00030000;
- //mView = new GodotView(getApplication(),io,use_gl3);
- //setContentView(mView);
-
- layout = new FrameLayout(this);
+ final FrameLayout layout = new FrameLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setContentView(layout);
@@ -324,6 +323,26 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
});
}
+ /**
+ * Used by the native code (java_godot_wrapper.h) to vibrate the device.
+ * @param durationMs
+ */
+ @SuppressLint("MissingPermission")
+ @Keep
+ private void vibrate(int durationMs) {
+ if (requestPermission("VIBRATE")) {
+ Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
+ if (v != null) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ v.vibrate(VibrationEffect.createOneShot(durationMs, VibrationEffect.DEFAULT_AMPLITUDE));
+ } else {
+ //deprecated in API 26
+ v.vibrate(durationMs);
+ }
+ }
+ }
+ }
+
public void restart() {
// HACK:
//
@@ -405,6 +424,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
/**
* Used by the native code (java_godot_wrapper.h) to check whether the activity is resumed or paused.
*/
+ @Keep
private boolean isActivityResumed() {
return activityResumed;
}
@@ -412,10 +432,20 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
/**
* Used by the native code (java_godot_wrapper.h) to access the Android surface.
*/
+ @Keep
private Surface getSurface() {
return mView.getHolder().getSurface();
}
+ /**
+ * Used by the native code (java_godot_wrapper.h) to access the input fallback mapping.
+ * @return The input fallback mapping for the current XR mode.
+ */
+ @Keep
+ private String getInputFallbackMapping() {
+ return xrMode.inputFallbackMapping;
+ }
+
String expansion_pack_path;
private void initializeGodot() {
@@ -463,8 +493,8 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
@Override
public void onServiceConnected(Messenger m) {
- mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
- mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
+ IDownloaderService remoteService = DownloaderServiceMarshaller.CreateProxy(m);
+ remoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
@Override
@@ -472,7 +502,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
super.onCreate(icicle);
Window window = getWindow();
- //window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
mClipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
@@ -598,7 +627,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
mWiFiSettingsButton = (Button)findViewById(com.godot.game.R.id.wifiSettingsButton);
return;
- } else {
}
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
@@ -610,8 +638,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
mCurrentIntent = getIntent();
initializeGodot();
-
- //instanceSingleton( new GodotFacebook(this) );
}
@Override
@@ -625,6 +651,10 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
GodotLib.ondestroy(this);
super.onDestroy();
+
+ // TODO: This is a temp solution. The proper fix will involve tracking down and properly shutting down each
+ // native Godot components that is started in Godot#onVideoInit.
+ forceQuit();
}
@Override
@@ -816,8 +846,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
}
}
- public void forceQuit() {
-
+ private void forceQuit() {
System.exit(0);
}
@@ -864,7 +893,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
}
}
- //@Override public boolean dispatchTouchEvent (MotionEvent event) {
public boolean gotTouchEvent(final MotionEvent event) {
final int evcount = event.getPointerCount();
@@ -935,8 +963,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
for (int i = cc.length; --i >= 0; cnt += cc[i] != 0 ? 1 : 0)
;
if (cnt == 0) return super.onKeyMultiple(inKeyCode, repeatCount, event);
- final Activity me = this;
- queueEvent(new Runnable() {
+ mView.queueEvent(new Runnable() {
// This method will be called on the rendering thread:
public void run() {
for (int i = 0, n = cc.length; i < n; i++) {
@@ -952,20 +979,10 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
return true;
}
- private void queueEvent(Runnable runnable) {
- // TODO Auto-generated method stub
- }
-
public PaymentsManager getPaymentsManager() {
return mPaymentsManager;
}
- /*
- public void setPaymentsManager(PaymentsManager mPaymentsManager) {
- this.mPaymentsManager = mPaymentsManager;
- }
- */
-
public boolean requestPermission(String p_name) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Not necessary, asked on install already
@@ -985,6 +1002,13 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
return false;
}
}
+
+ if (p_name.equals("VIBRATE")) {
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(new String[] { Manifest.permission.VIBRATE }, REQUEST_VIBRATE_PERMISSION);
+ return false;
+ }
+ }
return true;
}
@@ -1003,7 +1027,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC
switch (newState) {
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
- // safe to start making calls via mRemoteService.
+ // safe to start making remote service calls.
paused = false;
indeterminate = true;
break;
diff --git a/platform/android/java/src/org/godotengine/godot/GodotLib.java b/platform/android/java/src/org/godotengine/godot/GodotLib.java
index 81c98bcc79..af51c840cb 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotLib.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotLib.java
@@ -30,8 +30,14 @@
package org.godotengine.godot;
-// Wrapper for native library
+import android.app.Activity;
+import android.hardware.SensorEvent;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+/**
+ * Wrapper for native library
+ */
public class GodotLib {
public static GodotIO io;
@@ -41,36 +47,168 @@ public class GodotLib {
}
/**
- * @param width the current view width
- * @param height the current view height
- */
-
+ * Invoked on the main thread to initialize Godot native layer.
+ */
public static native void initialize(Godot p_instance, Object p_asset_manager, boolean use_apk_expansion);
+
+ /**
+ * Invoked on the main thread to clean up Godot native layer.
+ * @see Activity#onDestroy()
+ */
public static native void ondestroy(Godot p_instance);
+
+ /**
+ * Invoked on the GL thread to complete setup for the Godot native layer logic.
+ * @param p_cmdline Command line arguments used to configure Godot native layer components.
+ */
public static native void setup(String[] p_cmdline);
+
+ /**
+ * Invoked on the GL thread when the underlying Android surface has changed size.
+ * @param width
+ * @param height
+ * @see android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
+ */
public static native void resize(int width, int height);
+
+ /**
+ * Invoked on the GL thread when the underlying Android surface is created or recreated.
+ * @param p_32_bits
+ * @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)
+ */
public static native void newcontext(boolean p_32_bits);
+
+ /**
+ * Forward {@link Activity#onBackPressed()} event from the main thread to the GL thread.
+ */
public static native void back();
+
+ /**
+ * Invoked on the GL thread to draw the current frame.
+ * @see android.opengl.GLSurfaceView.Renderer#onDrawFrame(GL10)
+ */
public static native void step();
+
+ /**
+ * Forward touch events from the main thread to the GL thread.
+ */
public static native void touch(int what, int pointer, int howmany, int[] arr);
+
+ /**
+ * Forward accelerometer sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
public static native void accelerometer(float x, float y, float z);
+
+ /**
+ * Forward gravity sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
public static native void gravity(float x, float y, float z);
+
+ /**
+ * Forward magnetometer sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
public static native void magnetometer(float x, float y, float z);
+
+ /**
+ * Forward gyroscope sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
public static native void gyroscope(float x, float y, float z);
+
+ /**
+ * Forward regular key events from the main thread to the GL thread.
+ */
public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed);
+
+ /**
+ * Forward game device's key events from the main thread to the GL thread.
+ */
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
+
+ /**
+ * Forward joystick devices axis motion events from the main thread to the GL thread.
+ */
public static native void joyaxis(int p_device, int p_axis, float p_value);
+
+ /**
+ * Forward joystick devices hat motion events from the main thread to the GL thread.
+ */
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
+
+ /**
+ * Fires when a joystick device is added or removed.
+ */
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
+
+ /**
+ * Invoked when the Android activity resumes.
+ * @see Activity#onResume()
+ */
public static native void focusin();
+
+ /**
+ * Invoked when the Android activity pauses.
+ * @see Activity#onPause()
+ */
public static native void focusout();
+
+ /**
+ * Invoked when the audio thread is started.
+ */
public static native void audio();
+
+ /**
+ * Used to setup a {@link org.godotengine.godot.Godot.SingletonBase} instance.
+ * @param p_name Name of the instance.
+ * @param p_object Reference to the singleton instance.
+ */
public static native void singleton(String p_name, Object p_object);
+
+ /**
+ * Used to complete registration of the {@link org.godotengine.godot.Godot.SingletonBase} instance's methods.
+ * @param p_sname Name of the instance
+ * @param p_name Name of the method to register
+ * @param p_ret Return type of the registered method
+ * @param p_params Method parameters types
+ */
public static native void method(String p_sname, String p_name, String p_ret, String[] p_params);
+
+ /**
+ * Used to access Godot global properties.
+ * @param p_key Property key
+ * @return String value of the property
+ */
public static native String getGlobal(String p_key);
+
+ /**
+ * Invoke method |p_method| on the Godot object specified by |p_id|
+ * @param p_id Id of the Godot object to invoke
+ * @param p_method Name of the method to invoke
+ * @param p_params Parameters to use for method invocation
+ */
public static native void callobject(int p_id, String p_method, Object[] p_params);
+
+ /**
+ * Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
+ * @param p_id Id of the Godot object to invoke
+ * @param p_method Name of the method to invoke
+ * @param p_params Parameters to use for method invocation
+ */
public static native void calldeferred(int p_id, String p_method, Object[] p_params);
+
+ /**
+ * Forward the results from a permission request.
+ * @see Activity#onRequestPermissionsResult(int, String[], int[])
+ * @param p_permission Request permission
+ * @param p_result True if the permission was granted, false otherwise
+ */
public static native void requestPermissionResult(String p_permission, boolean p_result);
+ /**
+ * Invoked on the GL thread to configure the height of the virtual keyboard.
+ */
public static native void setVirtualKeyboardHeight(int p_height);
}
diff --git a/platform/android/java/src/org/godotengine/godot/xr/XRMode.java b/platform/android/java/src/org/godotengine/godot/xr/XRMode.java
index dd5701af7d..5896b23ac3 100644
--- a/platform/android/java/src/org/godotengine/godot/xr/XRMode.java
+++ b/platform/android/java/src/org/godotengine/godot/xr/XRMode.java
@@ -34,16 +34,18 @@ package org.godotengine.godot.xr;
* Godot available XR modes.
*/
public enum XRMode {
- REGULAR(0, "Regular", "--xr_mode_regular"), // Regular/flatscreen
- OVR(1, "Oculus Mobile VR", "--xr_mode_ovr");
+ REGULAR(0, "Regular", "--xr_mode_regular", "Default Android Gamepad"), // Regular/flatscreen
+ OVR(1, "Oculus Mobile VR", "--xr_mode_ovr", "");
final int index;
final String label;
public final String cmdLineArg;
+ public final String inputFallbackMapping;
- XRMode(int index, String label, String cmdLineArg) {
+ XRMode(int index, String label, String cmdLineArg, String inputFallbackMapping) {
this.index = index;
this.label = label;
this.cmdLineArg = cmdLineArg;
+ this.inputFallbackMapping = inputFallbackMapping;
}
}
diff --git a/platform/android/java_godot_lib_jni.cpp b/platform/android/java_godot_lib_jni.cpp
index 1159e93166..f53df7afe9 100644
--- a/platform/android/java_godot_lib_jni.cpp
+++ b/platform/android/java_godot_lib_jni.cpp
@@ -644,7 +644,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *en
godot_java->on_video_init(env);
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env, jobject obj, jobject activity) {
// lets cleanup
if (godot_io_java) {
delete godot_io_java;
diff --git a/platform/android/java_godot_lib_jni.h b/platform/android/java_godot_lib_jni.h
index f99935bf7c..66591a2cb2 100644
--- a/platform/android/java_godot_lib_jni.h
+++ b/platform/android/java_godot_lib_jni.h
@@ -38,7 +38,7 @@
// See java/src/org/godotengine/godot/GodotLib.java for the JAVA side of this (yes that's why we have the long names)
extern "C" {
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *env, jobject obj, jobject activity, jobject p_asset_manager, jboolean p_use_apk_expansion);
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env, jobject obj, jobject activity);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jobject obj, jobjectArray p_cmdline);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jobject obj, jint width, jint height);
JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jobject obj, bool p_32_bits);
diff --git a/platform/android/java_godot_wrapper.cpp b/platform/android/java_godot_wrapper.cpp
index 339b14974c..8194ee6ecf 100644
--- a/platform/android/java_godot_wrapper.cpp
+++ b/platform/android/java_godot_wrapper.cpp
@@ -62,6 +62,8 @@ GodotJavaWrapper::GodotJavaWrapper(JNIEnv *p_env, jobject p_godot_instance) {
_init_input_devices = p_env->GetMethodID(cls, "initInputDevices", "()V");
_get_surface = p_env->GetMethodID(cls, "getSurface", "()Landroid/view/Surface;");
_is_activity_resumed = p_env->GetMethodID(cls, "isActivityResumed", "()Z");
+ _vibrate = p_env->GetMethodID(cls, "vibrate", "(I)V");
+ _get_input_fallback_mapping = p_env->GetMethodID(cls, "getInputFallbackMapping", "()Ljava/lang/String;");
}
GodotJavaWrapper::~GodotJavaWrapper() {
@@ -165,6 +167,16 @@ String GodotJavaWrapper::get_clipboard() {
}
}
+String GodotJavaWrapper::get_input_fallback_mapping() {
+ if (_get_input_fallback_mapping) {
+ JNIEnv *env = ThreadAndroid::get_env();
+ jstring fallback_mapping = (jstring)env->CallObjectMethod(godot_instance, _get_input_fallback_mapping);
+ return jstring_to_string(fallback_mapping, env);
+ } else {
+ return String();
+ }
+}
+
bool GodotJavaWrapper::has_set_clipboard() {
return _set_clipboard != 0;
}
@@ -211,3 +223,10 @@ bool GodotJavaWrapper::is_activity_resumed() {
return false;
}
}
+
+void GodotJavaWrapper::vibrate(int p_duration_ms) {
+ if (_vibrate) {
+ JNIEnv *env = ThreadAndroid::get_env();
+ env->CallVoidMethod(godot_instance, _vibrate, p_duration_ms);
+ }
+}
diff --git a/platform/android/java_godot_wrapper.h b/platform/android/java_godot_wrapper.h
index 82c2a5d122..b1bd9b7f48 100644
--- a/platform/android/java_godot_wrapper.h
+++ b/platform/android/java_godot_wrapper.h
@@ -57,6 +57,8 @@ private:
jmethodID _init_input_devices = 0;
jmethodID _get_surface = 0;
jmethodID _is_activity_resumed = 0;
+ jmethodID _vibrate = 0;
+ jmethodID _get_input_fallback_mapping = 0;
public:
GodotJavaWrapper(JNIEnv *p_env, jobject p_godot_instance);
@@ -82,6 +84,8 @@ public:
void init_input_devices();
jobject get_surface();
bool is_activity_resumed();
+ void vibrate(int p_duration_ms);
+ String get_input_fallback_mapping();
};
#endif /* !JAVA_GODOT_WRAPPER_H */
diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp
index 701a351203..49ab0ea84a 100644
--- a/platform/android/os_android.cpp
+++ b/platform/android/os_android.cpp
@@ -173,7 +173,7 @@ Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int
AudioDriverManager::initialize(p_audio_driver);
input = memnew(InputDefault);
- input->set_fallback_mapping("Default Android Gamepad");
+ input->set_fallback_mapping(godot_java->get_input_fallback_mapping());
///@TODO implement a subclass for Android and instantiate that instead
camera_server = memnew(CameraServer);
@@ -700,6 +700,10 @@ String OS_Android::get_joy_guid(int p_device) const {
return input->get_joy_guid_remapped(p_device);
}
+void OS_Android::vibrate_handheld(int p_duration_ms) {
+ godot_java->vibrate(p_duration_ms);
+}
+
bool OS_Android::_check_internal_feature_support(const String &p_feature) {
if (p_feature == "mobile") {
//TODO support etc2 only if GLES3 driver is selected
diff --git a/platform/android/os_android.h b/platform/android/os_android.h
index e74d4cfd43..a17941f7c0 100644
--- a/platform/android/os_android.h
+++ b/platform/android/os_android.h
@@ -198,6 +198,7 @@ public:
virtual bool is_joy_known(int p_device);
virtual String get_joy_guid(int p_device) const;
void joy_connection_changed(int p_device, bool p_connected, String p_name);
+ void vibrate_handheld(int p_duration_ms);
virtual bool _check_internal_feature_support(const String &p_feature);
OS_Android(GodotJavaWrapper *p_godot_java, GodotIOJavaWrapper *p_godot_io_java, bool p_use_apk_expansion);
diff --git a/platform/iphone/app_delegate.mm b/platform/iphone/app_delegate.mm
index 64405bfa5b..3f1230faa8 100644
--- a/platform/iphone/app_delegate.mm
+++ b/platform/iphone/app_delegate.mm
@@ -37,6 +37,7 @@
#include "os_iphone.h"
#import "GameController/GameController.h"
+#import <AudioToolbox/AudioServices.h>
#define kFilteringFactor 0.1
#define kRenderingFrequency 60
@@ -61,6 +62,10 @@ void _set_keep_screen_on(bool p_enabled) {
[[UIApplication sharedApplication] setIdleTimerDisabled:(BOOL)p_enabled];
};
+void _vibrate() {
+ AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
+};
+
@implementation AppDelegate
@synthesize window;
diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp
index 825342f911..353078c51c 100644
--- a/platform/iphone/os_iphone.cpp
+++ b/platform/iphone/os_iphone.cpp
@@ -470,6 +470,7 @@ extern void _show_keyboard(String p_existing);
extern void _hide_keyboard();
extern Error _shell_open(String p_uri);
extern void _set_keep_screen_on(bool p_enabled);
+extern void _vibrate();
void OSIPhone::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
_show_keyboard(p_existing_text);
@@ -585,6 +586,11 @@ void OSIPhone::native_video_stop() {
_stop_video();
}
+void OSIPhone::vibrate_handheld(int p_duration_ms) {
+ // iOS does not support duration for vibration
+ _vibrate();
+}
+
bool OSIPhone::_check_internal_feature_support(const String &p_feature) {
return p_feature == "mobile";
diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h
index c16c29a858..804ba0b1af 100644
--- a/platform/iphone/os_iphone.h
+++ b/platform/iphone/os_iphone.h
@@ -195,6 +195,7 @@ public:
virtual void native_video_unpause();
virtual void native_video_focus_out();
virtual void native_video_stop();
+ virtual void vibrate_handheld(int p_duration_ms = 500);
virtual bool _check_internal_feature_support(const String &p_feature);
OSIPhone(int width, int height, String p_data_dir);
diff --git a/platform/iphone/view_controller.h b/platform/iphone/view_controller.h
index fc18661f62..68e3bc64fc 100644
--- a/platform/iphone/view_controller.h
+++ b/platform/iphone/view_controller.h
@@ -39,6 +39,10 @@
- (void)didReceiveMemoryWarning;
+- (void)viewDidLoad;
+
+- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures;
+
- (BOOL)prefersStatusBarHidden;
@end
diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm
index 0358abf9e2..e52ad92bf2 100644
--- a/platform/iphone/view_controller.mm
+++ b/platform/iphone/view_controller.mm
@@ -83,6 +83,18 @@ int add_cmdline(int p_argc, char **p_args) {
printf("*********** did receive memory warning!\n");
};
+- (void)viewDidLoad {
+ [super viewDidLoad];
+
+ if (@available(iOS 11.0, *)) {
+ [self setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
+ }
+}
+
+- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures {
+ return UIRectEdgeAll;
+}
+
- (BOOL)shouldAutorotate {
switch (OS::get_singleton()->get_screen_orientation()) {
case OS::SCREEN_SENSOR:
diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h
index 9cb2915701..f1f37e24d2 100644
--- a/platform/osx/os_osx.h
+++ b/platform/osx/os_osx.h
@@ -157,6 +157,26 @@ public:
int video_driver_index;
virtual int get_current_video_driver() const;
+ struct GlobalMenuItem {
+ String label;
+ Variant signal;
+ Variant meta;
+
+ GlobalMenuItem() {
+ //NOP
+ }
+
+ GlobalMenuItem(const String &p_label, const Variant &p_signal, const Variant &p_meta) {
+ label = p_label;
+ signal = p_signal;
+ meta = p_meta;
+ }
+ };
+
+ Map<String, Vector<GlobalMenuItem> > global_menus;
+
+ void _update_global_menu();
+
protected:
virtual void initialize_core();
virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
@@ -168,6 +188,11 @@ protected:
public:
static OS_OSX *singleton;
+ void global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta);
+ void global_menu_add_separator(const String &p_menu);
+ void global_menu_remove_item(const String &p_menu, int p_idx);
+ void global_menu_clear(const String &p_menu);
+
void wm_minimized(bool p_minimized);
virtual String get_name() const;
diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm
index ab77897b08..f48d4a307d 100644
--- a/platform/osx/os_osx.mm
+++ b/platform/osx/os_osx.mm
@@ -204,11 +204,53 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
}
}
+- (void)globalMenuCallback:(id)sender {
+
+ if (![sender representedObject])
+ return;
+
+ OS_OSX::GlobalMenuItem *item = (OS_OSX::GlobalMenuItem *)[[sender representedObject] pointerValue];
+
+ if (!item)
+ return;
+
+ OS_OSX::singleton->main_loop->global_menu_action(item->signal, item->meta);
+}
+
+- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
+
+ NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
+
+ Vector<OS_OSX::GlobalMenuItem> &E = OS_OSX::singleton->global_menus["_dock"];
+ for (int i = 0; i < E.size(); i++) {
+ if (E[i].label == String()) {
+ [menu addItem:[NSMenuItem separatorItem]];
+ } else {
+ NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:E[i].label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
+ [menu_item setRepresentedObject:[NSValue valueWithPointer:&(E[i])]];
+ }
+ }
+
+ return menu;
+}
+
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
- // Note: called before main loop init!
+ // Note: may be called called before main loop init!
char *utfs = strdup([filename UTF8String]);
OS_OSX::singleton->open_with_filename.parse_utf8(utfs);
free(utfs);
+
+#ifdef TOOLS_ENABLED
+ // Open new instance
+ if (OS_OSX::singleton->get_main_loop()) {
+ List<String> args;
+ args.push_back(OS_OSX::singleton->open_with_filename);
+ String exec = OS::get_singleton()->get_executable_path();
+
+ OS::ProcessID pid = 0;
+ OS::get_singleton()->execute(exec, args, false, &pid);
+ }
+#endif
return YES;
}
@@ -1266,6 +1308,56 @@ inline void sendPanEvent(double dx, double dy, int modifierFlags) {
@end
+void OS_OSX::_update_global_menu() {
+
+ NSMenu *main_menu = [NSApp mainMenu];
+
+ for (int i = 1; i < [main_menu numberOfItems]; i++) {
+ [main_menu removeItemAtIndex:i];
+ }
+ for (Map<String, Vector<GlobalMenuItem> >::Element *E = global_menus.front(); E; E = E->next()) {
+ if (E->key() != "_dock") {
+ NSMenu *menu = [[[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:E->key().utf8().get_data()]] autorelease];
+ for (int i = 0; i < E->get().size(); i++) {
+ if (E->get()[i].label == String()) {
+ [menu addItem:[NSMenuItem separatorItem]];
+ } else {
+ NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:E->get()[i].label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
+ [menu_item setRepresentedObject:[NSValue valueWithPointer:&(E->get()[i])]];
+ }
+ }
+ NSMenuItem *menu_item = [main_menu addItemWithTitle:[NSString stringWithUTF8String:E->key().utf8().get_data()] action:nil keyEquivalent:@""];
+ [main_menu setSubmenu:menu forItem:menu_item];
+ }
+ }
+}
+
+void OS_OSX::global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta) {
+
+ global_menus[p_menu].push_back(GlobalMenuItem(p_label, p_signal, p_meta));
+ _update_global_menu();
+}
+
+void OS_OSX::global_menu_add_separator(const String &p_menu) {
+
+ global_menus[p_menu].push_back(GlobalMenuItem());
+ _update_global_menu();
+}
+
+void OS_OSX::global_menu_remove_item(const String &p_menu, int p_idx) {
+
+ ERR_FAIL_INDEX(p_idx, global_menus[p_menu].size());
+
+ global_menus[p_menu].remove(p_idx);
+ _update_global_menu();
+}
+
+void OS_OSX::global_menu_clear(const String &p_menu) {
+
+ global_menus[p_menu].clear();
+ _update_global_menu();
+}
+
Point2 OS_OSX::get_ime_selection() const {
return im_selection;
diff --git a/platform/uwp/export/export.cpp b/platform/uwp/export/export.cpp
index 662ee49935..ea110b11ca 100644
--- a/platform/uwp/export/export.cpp
+++ b/platform/uwp/export/export.cpp
@@ -30,9 +30,9 @@
#include "export.h"
#include "core/bind/core_bind.h"
+#include "core/crypto/crypto_core.h"
#include "core/io/marshalls.h"
#include "core/io/zip_io.h"
-#include "core/math/crypto_core.h"
#include "core/object.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
diff --git a/scene/2d/navigation_2d.cpp b/scene/2d/navigation_2d.cpp
index f644db462b..5cf28d6c89 100644
--- a/scene/2d/navigation_2d.cpp
+++ b/scene/2d/navigation_2d.cpp
@@ -551,7 +551,7 @@ Vector<Vector2> Navigation2D::get_simple_path(const Vector2 &p_start, const Vect
left_poly = p;
portal_left = apex_point;
portal_right = apex_point;
- if (!path.size() || !Math::is_zero_approx(path[path.size() - 1].distance_to(apex_point)))
+ if (!path.size() || path[path.size() - 1] != apex_point)
path.push_back(apex_point);
skip = true;
}
@@ -569,7 +569,7 @@ Vector<Vector2> Navigation2D::get_simple_path(const Vector2 &p_start, const Vect
right_poly = p;
portal_right = apex_point;
portal_left = apex_point;
- if (!path.size() || !Math::is_zero_approx(path[path.size() - 1].distance_to(apex_point)))
+ if (!path.size() || path[path.size() - 1] != apex_point)
path.push_back(apex_point);
}
}
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index f2f53d4354..55c8c7f229 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -110,7 +110,7 @@ void Path2D::_notification(int p_what) {
real_t frac = j / 8.0;
Vector2 p = curve->interpolate(i, frac);
- draw_line(prev_p, p, color, line_width);
+ draw_line(prev_p, p, color, line_width, true);
prev_p = p;
}
}
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index 49da709a47..7cc937a64a 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -594,7 +594,7 @@ real_t RigidBody2D::get_mass() const {
void RigidBody2D::set_inertia(real_t p_inertia) {
- ERR_FAIL_COND(p_inertia <= 0);
+ ERR_FAIL_COND(p_inertia < 0);
Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA, p_inertia);
}
@@ -1266,7 +1266,7 @@ Vector2 KinematicBody2D::move_and_slide(const Vector2 &p_linear_velocity, const
//all is a wall
on_wall = true;
} else {
- if (collision.normal.dot(p_floor_direction) >= Math::cos(p_floor_max_angle + FLOOR_ANGLE_THRESHOLD)) { //floor
+ if (Math::acos(collision.normal.dot(p_floor_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //floor
on_floor = true;
on_floor_body = collision.collider_rid;
@@ -1281,7 +1281,7 @@ Vector2 KinematicBody2D::move_and_slide(const Vector2 &p_linear_velocity, const
}
}
- } else if (collision.normal.dot(-p_floor_direction) >= Math::cos(p_floor_max_angle + FLOOR_ANGLE_THRESHOLD)) { //ceiling
+ } else if (Math::acos(collision.normal.dot(-p_floor_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //ceiling
on_ceiling = true;
} else {
on_wall = true;
diff --git a/scene/3d/collision_polygon.cpp b/scene/3d/collision_polygon.cpp
index db07059b32..37aa95fb43 100644
--- a/scene/3d/collision_polygon.cpp
+++ b/scene/3d/collision_polygon.cpp
@@ -151,6 +151,8 @@ float CollisionPolygon::get_depth() const {
void CollisionPolygon::set_disabled(bool p_disabled) {
disabled = p_disabled;
+ update_gizmo();
+
if (parent) {
parent->shape_owner_set_disabled(owner_id, p_disabled);
}
diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp
index 19d5f1dd3c..ebac968cb4 100644
--- a/scene/3d/physics_body.cpp
+++ b/scene/3d/physics_body.cpp
@@ -1192,7 +1192,7 @@ Vector3 KinematicBody::move_and_slide(const Vector3 &p_linear_velocity, const Ve
//all is a wall
on_wall = true;
} else {
- if (collision.normal.dot(p_floor_direction) >= Math::cos(p_floor_max_angle + FLOOR_ANGLE_THRESHOLD)) { //floor
+ if (Math::acos(collision.normal.dot(p_floor_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //floor
on_floor = true;
on_floor_body = collision.collider_rid;
@@ -1209,7 +1209,7 @@ Vector3 KinematicBody::move_and_slide(const Vector3 &p_linear_velocity, const Ve
is_on_slope = true;
- } else if (collision.normal.dot(-p_floor_direction) >= Math::cos(p_floor_max_angle + FLOOR_ANGLE_THRESHOLD)) { //ceiling
+ } else if (Math::acos(collision.normal.dot(-p_floor_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //ceiling
on_ceiling = true;
} else {
on_wall = true;
diff --git a/scene/3d/physics_body.h b/scene/3d/physics_body.h
index aa6030d44e..0e2e614717 100644
--- a/scene/3d/physics_body.h
+++ b/scene/3d/physics_body.h
@@ -162,6 +162,7 @@ protected:
ShapePair(int p_bs, int p_ls) {
body_shape = p_bs;
local_shape = p_ls;
+ tagged = false;
}
};
struct RigidBody_RemoveAction {
diff --git a/scene/3d/ray_cast.cpp b/scene/3d/ray_cast.cpp
index 10f92058e0..30eed8f1a7 100644
--- a/scene/3d/ray_cast.cpp
+++ b/scene/3d/ray_cast.cpp
@@ -102,6 +102,8 @@ Vector3 RayCast::get_collision_normal() const {
void RayCast::set_enabled(bool p_enabled) {
enabled = p_enabled;
+ update_gizmo();
+
if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint())
set_physics_process_internal(p_enabled);
if (!p_enabled)
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index 30aeebfdac..051f832882 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -1200,7 +1200,9 @@ void AnimationPlayer::play(const StringName &p_name, float p_custom_blend, float
}
}
- _stop_playing_caches();
+ if (get_current_animation() != p_name) {
+ _stop_playing_caches();
+ }
c.current.from = &animation_set[name];
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index 6745b57cff..bb7c400cfe 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -1412,6 +1412,7 @@ void AnimationTree::_update_properties_for_node(const String &p_base_path, Ref<A
Vector<Activity> activity;
for (int i = 0; i < node->get_input_count(); i++) {
Activity a;
+ a.activity = 0;
a.last_pass = 0;
activity.push_back(a);
}
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index b197971b61..1d529f4e72 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -247,15 +247,19 @@ void ColorPicker::_update_color(bool p_update_sliders) {
}
void ColorPicker::_update_presets() {
+ presets_per_row = 10;
Size2 size = bt_add_preset->get_size();
- Size2 preset_size = Size2(size.width * presets.size(), size.height);
+ Size2 preset_size = Size2(MIN(size.width * presets.size(), presets_per_row * size.width), size.height * (Math::ceil((float)presets.size() / presets_per_row)));
preset->set_custom_minimum_size(preset_size);
-
- preset->draw_texture_rect(get_icon("preset_bg", "ColorPicker"), Rect2(Point2(), preset_size), true);
+ preset_container->set_custom_minimum_size(preset_size);
+ preset->draw_rect(Rect2(Point2(), preset_size), Color(1, 1, 1, 0));
for (int i = 0; i < presets.size(); i++) {
- preset->draw_rect(Rect2(Point2(size.width * i, 0), size), presets[i]);
+ int x = (i % presets_per_row) * size.width;
+ int y = (Math::floor((float)i / presets_per_row)) * size.height;
+ preset->draw_rect(Rect2(Point2(x, y), size), presets[i]);
}
+ _notification(NOTIFICATION_VISIBILITY_CHANGED);
}
void ColorPicker::_text_type_toggled() {
@@ -288,8 +292,6 @@ void ColorPicker::add_preset(const Color &p_color) {
presets.push_back(p_color);
}
preset->update();
- if (presets.size() == 10)
- bt_add_preset->hide();
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
@@ -533,14 +535,20 @@ void ColorPicker::_preset_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> bev = p_event;
if (bev.is_valid()) {
-
+ int index = 0;
if (bev->is_pressed() && bev->get_button_index() == BUTTON_LEFT) {
- int index = bev->get_position().x / (preset->get_size().x / presets.size());
+ for (int i = 0; i < presets.size(); i++) {
+ int x = (i % presets_per_row) * bt_add_preset->get_size().x;
+ int y = (Math::floor((float)i / presets_per_row)) * bt_add_preset->get_size().y;
+ if (bev->get_position().x > x && bev->get_position().x < x + preset->get_size().x && bev->get_position().y > y && bev->get_position().y < y + preset->get_size().y) {
+ index = i;
+ }
+ }
set_pick_color(presets[index]);
_update_color();
emit_signal("color_changed", color);
} else if (bev->is_pressed() && bev->get_button_index() == BUTTON_RIGHT && presets_enabled) {
- int index = bev->get_position().x / (preset->get_size().x / presets.size());
+ index = bev->get_position().x / (preset->get_size().x / presets.size());
Color clicked_preset = presets[index];
erase_preset(clicked_preset);
emit_signal("preset_removed", clicked_preset);
@@ -841,6 +849,7 @@ ColorPicker::ColorPicker() :
add_child(preset_separator);
preset_container = memnew(HBoxContainer);
+ preset_container->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(preset_container);
preset = memnew(TextureRect);
@@ -848,8 +857,11 @@ ColorPicker::ColorPicker() :
preset->connect("gui_input", this, "_preset_input");
preset->connect("draw", this, "_update_presets");
+ preset_container2 = memnew(HBoxContainer);
+ preset_container2->set_h_size_flags(SIZE_EXPAND_FILL);
+ add_child(preset_container2);
bt_add_preset = memnew(Button);
- preset_container->add_child(bt_add_preset);
+ preset_container2->add_child(bt_add_preset);
bt_add_preset->set_tooltip(TTR("Add current color as a preset."));
bt_add_preset->connect("pressed", this, "_add_preset_pressed");
}
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index 3af27a9856..167f7b33b3 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -54,6 +54,7 @@ private:
TextureRect *sample;
TextureRect *preset;
HBoxContainer *preset_container;
+ HBoxContainer *preset_container2;
HSeparator *preset_separator;
Button *bt_add_preset;
List<Color> presets;
@@ -68,6 +69,7 @@ private:
bool edit_alpha;
Size2i ms;
bool text_is_constructor;
+ int presets_per_row;
Color color;
bool raw_mode_enabled;
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index 9b9fc863dd..034e9266f6 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -2918,17 +2918,21 @@ void Control::_bind_methods() {
BIND_VMETHOD(MethodInfo("_gui_input", PropertyInfo(Variant::OBJECT, "event", PROPERTY_HINT_RESOURCE_TYPE, "InputEvent")));
BIND_VMETHOD(MethodInfo(Variant::VECTOR2, "_get_minimum_size"));
- BIND_VMETHOD(MethodInfo(Variant::OBJECT, "get_drag_data", PropertyInfo(Variant::VECTOR2, "position")));
+
+ MethodInfo get_drag_data = MethodInfo("get_drag_data", PropertyInfo(Variant::VECTOR2, "position"));
+ get_drag_data.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ BIND_VMETHOD(get_drag_data);
+
BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_drop_data", PropertyInfo(Variant::VECTOR2, "position"), PropertyInfo(Variant::NIL, "data")));
BIND_VMETHOD(MethodInfo("drop_data", PropertyInfo(Variant::VECTOR2, "position"), PropertyInfo(Variant::NIL, "data")));
BIND_VMETHOD(MethodInfo(Variant::OBJECT, "_make_custom_tooltip", PropertyInfo(Variant::STRING, "for_text")));
BIND_VMETHOD(MethodInfo(Variant::BOOL, "_clips_input"));
ADD_GROUP("Anchor", "anchor_");
- ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_left", PROPERTY_HINT_RANGE, "0,1,0.01,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_top", PROPERTY_HINT_RANGE, "0,1,0.01,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_TOP);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_right", PROPERTY_HINT_RANGE, "0,1,0.01,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_RIGHT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_bottom", PROPERTY_HINT_RANGE, "0,1,0.01,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_BOTTOM);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_left", PROPERTY_HINT_RANGE, "0,1,0.001,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_top", PROPERTY_HINT_RANGE, "0,1,0.001,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_right", PROPERTY_HINT_RANGE, "0,1,0.001,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_bottom", PROPERTY_HINT_RANGE, "0,1,0.001,or_lesser,or_greater"), "_set_anchor", "get_anchor", MARGIN_BOTTOM);
ADD_GROUP("Margin", "margin_");
ADD_PROPERTYI(PropertyInfo(Variant::INT, "margin_left", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin", "get_margin", MARGIN_LEFT);
diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp
index f1bdbb5ff5..9bc593ea3b 100644
--- a/scene/gui/file_dialog.cpp
+++ b/scene/gui/file_dialog.cpp
@@ -400,6 +400,7 @@ void FileDialog::update_file_list() {
TreeItem *root = tree->create_item();
Ref<Texture> folder = get_icon("folder");
+ const Color folder_color = get_color("folder_icon_modulate");
List<String> files;
List<String> dirs;
@@ -429,6 +430,7 @@ void FileDialog::update_file_list() {
TreeItem *ti = tree->create_item(root);
ti->set_text(0, dir_name);
ti->set_icon(0, folder);
+ ti->set_icon_modulate(0, folder_color);
Dictionary d;
d["name"] = dir_name;
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index 38005f1322..fdffb26cb5 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -776,10 +776,16 @@ void GraphEdit::_top_layer_draw() {
_draw_cos_line(top_layer, pos, topos, col, col);
}
- if (box_selecting)
+ if (box_selecting) {
top_layer->draw_rect(
box_selecting_rect,
- get_color("accent_color", "Editor") * Color(1, 1, 1, 0.375));
+ get_color("box_selection_fill_color", "Editor"));
+
+ top_layer->draw_rect(
+ box_selecting_rect,
+ get_color("box_selection_stroke_color", "Editor"),
+ false);
+ }
}
void GraphEdit::set_selected(Node *p_child) {
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index c0eaf21215..1d434e5a2a 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -129,7 +129,7 @@ void TextEdit::Text::_update_line_cache(int p_line) const {
int len = text[p_line].data.length();
const CharType *str = text[p_line].data.c_str();
- //update width
+ // Update width.
for (int i = 0; i < len; i++) {
w += get_char_width(str[i], str[i + 1], w);
@@ -139,7 +139,7 @@ void TextEdit::Text::_update_line_cache(int p_line) const {
text.write[p_line].wrap_amount_cache = -1;
- //update regions
+ // Update regions.
text.write[p_line].region_info.clear();
@@ -148,7 +148,7 @@ void TextEdit::Text::_update_line_cache(int p_line) const {
if (!_is_symbol(str[i]))
continue;
if (str[i] == '\\') {
- i++; //skip quoted anything
+ i++; // Skip quoted anything.
continue;
}
@@ -275,7 +275,7 @@ void TextEdit::Text::clear() {
}
int TextEdit::Text::get_max_width(bool p_exclude_hidden) const {
- //quite some work.. but should be fast enough.
+ // Quite some work, but should be fast enough.
int max = 0;
for (int i = 0; i < text.size(); i++) {
@@ -323,7 +323,7 @@ int TextEdit::Text::get_char_width(CharType c, CharType next_c, int px) const {
if (left == 0)
w = tab_w;
else
- w = tab_w - px % tab_w; // is right...
+ w = tab_w - px % tab_w; // Is right.
} else {
w = font->get_char_size(c, next_c).width;
@@ -367,23 +367,25 @@ void TextEdit::_update_scrollbars() {
total_width += cache.fold_gutter_width;
}
+ if (draw_minimap) {
+ total_width += cache.minimap_width;
+ }
+
bool use_hscroll = true;
bool use_vscroll = true;
+ // Thanks yessopie for this clever bit of logic.
if (total_rows <= visible_rows && total_width <= visible_width) {
- //thanks yessopie for this clever bit of logic
+
use_hscroll = false;
use_vscroll = false;
-
} else {
if (total_rows > visible_rows && total_width <= visible_width) {
- //thanks yessopie for this clever bit of logic
use_hscroll = false;
}
if (total_rows <= visible_rows && total_width > visible_width) {
- //thanks yessopie for this clever bit of logic
use_vscroll = false;
}
}
@@ -459,6 +461,7 @@ void TextEdit::_click_selection_held() {
}
void TextEdit::_update_selection_mode_pointer() {
+ dragging_selection = true;
Point2 mp = get_local_mouse_position();
int row, col;
@@ -474,6 +477,7 @@ void TextEdit::_update_selection_mode_pointer() {
}
void TextEdit::_update_selection_mode_word() {
+ dragging_selection = true;
Point2 mp = get_local_mouse_position();
int row, col;
@@ -481,7 +485,7 @@ void TextEdit::_update_selection_mode_word() {
String line = text[row];
int beg = CLAMP(col, 0, line.length());
- // if its the first selection and on whitespace make sure we grab the word instead..
+ // If its the first selection and on whitespace make sure we grab the word instead.
if (!selection.active) {
while (beg > 0 && line[beg] <= 32) {
beg--;
@@ -490,7 +494,7 @@ void TextEdit::_update_selection_mode_word() {
int end = beg;
bool symbol = beg < line.length() && _is_symbol(line[beg]);
- // get the word end and begin points
+ // Get the word end and begin points.
while (beg > 0 && line[beg - 1] > 32 && (symbol == _is_symbol(line[beg - 1]))) {
beg--;
}
@@ -501,7 +505,7 @@ void TextEdit::_update_selection_mode_word() {
end += 1;
}
- // initial selection
+ // Initial selection.
if (!selection.active) {
select(row, beg, row, end);
selection.selecting_column = beg;
@@ -530,6 +534,7 @@ void TextEdit::_update_selection_mode_word() {
}
void TextEdit::_update_selection_mode_line() {
+ dragging_selection = true;
Point2 mp = get_local_mouse_position();
int row, col;
@@ -537,11 +542,11 @@ void TextEdit::_update_selection_mode_line() {
col = 0;
if (row < selection.selecting_line) {
- // cursor is above us
+ // Cursor is above us.
cursor_set_line(row - 1, false);
selection.selecting_column = text[selection.selecting_line].length();
} else {
- // cursor is below us
+ // Cursor is below us.
cursor_set_line(row + 1, false);
selection.selecting_column = 0;
col = text[row].length();
@@ -554,6 +559,48 @@ void TextEdit::_update_selection_mode_line() {
click_select_held->start();
}
+void TextEdit::_update_minimap_click() {
+ Point2 mp = get_local_mouse_position();
+
+ int xmargin_end = get_size().width - cache.style_normal->get_margin(MARGIN_RIGHT);
+ if (!dragging_minimap && (mp.x < xmargin_end - minimap_width || mp.y > xmargin_end)) {
+ minimap_clicked = false;
+ return;
+ }
+ minimap_clicked = true;
+ dragging_minimap = true;
+
+ int row;
+ _get_minimap_mouse_row(Point2i(mp.x, mp.y), row);
+
+ if (row >= get_first_visible_line() && (row < get_last_visible_line() || row >= (text.size() - 1))) {
+ minimap_scroll_ratio = v_scroll->get_as_ratio();
+ minimap_scroll_click_pos = mp.y;
+ can_drag_minimap = true;
+ return;
+ }
+
+ int wi;
+ int first_line = row - num_lines_from_rows(row, 0, -get_visible_rows() / 2, wi) + 1;
+ double delta = get_scroll_pos_for_line(first_line, wi) - get_v_scroll();
+ if (delta < 0) {
+ _scroll_up(-delta);
+ } else {
+ _scroll_down(delta);
+ }
+}
+
+void TextEdit::_update_minimap_drag() {
+
+ if (!can_drag_minimap) {
+ return;
+ }
+
+ Point2 mp = get_local_mouse_position();
+ double diff = (mp.y - minimap_scroll_click_pos) / _get_control_height();
+ v_scroll->set_as_ratio(minimap_scroll_ratio + diff);
+}
+
void TextEdit::_notification(int p_what) {
switch (p_what) {
@@ -569,12 +616,13 @@ void TextEdit::_notification(int p_what) {
case NOTIFICATION_RESIZED: {
_update_scrollbars();
- call_deferred("_update_wrap_at");
+ _update_wrap_at();
} break;
case NOTIFICATION_THEME_CHANGED: {
_update_caches();
_update_wrap_at();
+ syntax_highlighting_cache.clear();
} break;
case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
window_has_focus = true;
@@ -590,24 +638,26 @@ void TextEdit::_notification(int p_what) {
if (scrolling && get_v_scroll() != target_v_scroll) {
double target_y = target_v_scroll - get_v_scroll();
double dist = sqrt(target_y * target_y);
- double vel = ((target_y / dist) * v_scroll_speed) * get_physics_process_delta_time();
+ // To ensure minimap is responsive overide the speed setting.
+ double vel = ((target_y / dist) * ((minimap_clicked) ? 3000 : v_scroll_speed)) * get_physics_process_delta_time();
if (Math::abs(vel) >= dist) {
set_v_scroll(target_v_scroll);
scrolling = false;
+ minimap_clicked = false;
set_physics_process_internal(false);
} else {
set_v_scroll(get_v_scroll() + vel);
}
} else {
scrolling = false;
+ minimap_clicked = false;
set_physics_process_internal(false);
}
} break;
case NOTIFICATION_DRAW: {
-
if (first_draw) {
- //size may not be the final one, so attempts to ensure cursor was visible may have failed
+ // Size may not be the final one, so attempts to ensure cursor was visible may have failed.
adjust_viewport_to_cursor();
first_draw = false;
}
@@ -637,6 +687,11 @@ void TextEdit::_notification(int p_what) {
cache.fold_gutter_width = 0;
}
+ cache.minimap_width = 0;
+ if (draw_minimap) {
+ cache.minimap_width = minimap_width;
+ }
+
int line_number_char_count = 0;
{
@@ -660,8 +715,9 @@ void TextEdit::_notification(int p_what) {
RID ci = get_canvas_item();
VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(), true);
int xmargin_beg = cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width + cache.info_gutter_width;
- int xmargin_end = size.width - cache.style_normal->get_margin(MARGIN_RIGHT);
- //let's do it easy for now:
+
+ int xmargin_end = size.width - cache.style_normal->get_margin(MARGIN_RIGHT) - cache.minimap_width;
+ // Let's do it easy for now.
cache.style_normal->draw(ci, Rect2(Point2(), size));
if (readonly) {
cache.style_readonly->draw(ci, Rect2(Point2(), size));
@@ -701,7 +757,7 @@ void TextEdit::_notification(int p_what) {
if (brace_matching_enabled && cursor.line >= 0 && cursor.line < text.size() && cursor.column >= 0) {
if (cursor.column < text[cursor.line].length()) {
- //check for open
+ // Check for open.
CharType c = text[cursor.line][cursor.column];
CharType closec = 0;
@@ -723,7 +779,7 @@ void TextEdit::_notification(int p_what) {
for (int j = from; j < text[i].length(); j++) {
CharType cc = text[i][j];
- //ignore any brackets inside a string
+ // Ignore any brackets inside a string.
if (cc == '"' || cc == '\'') {
CharType quotation = cc;
do {
@@ -732,7 +788,7 @@ void TextEdit::_notification(int p_what) {
break;
}
cc = text[i][j];
- //skip over escaped quotation marks inside strings
+ // Skip over escaped quotation marks inside strings.
if (cc == '\\') {
bool escaped = true;
while (j + 1 < text[i].length() && text[i][j + 1] == '\\') {
@@ -789,7 +845,7 @@ void TextEdit::_notification(int p_what) {
for (int j = from; j >= 0; j--) {
CharType cc = text[i][j];
- //ignore any brackets inside a string
+ // Ignore any brackets inside a string.
if (cc == '"' || cc == '\'') {
CharType quotation = cc;
do {
@@ -798,7 +854,7 @@ void TextEdit::_notification(int p_what) {
break;
}
cc = text[i][j];
- //skip over escaped quotation marks inside strings
+ // Skip over escaped quotation marks inside strings.
if (cc == quotation) {
bool escaped = false;
while (j - 1 >= 0 && text[i][j - 1] == '\\') {
@@ -837,10 +893,10 @@ void TextEdit::_notification(int p_what) {
Point2 cursor_pos;
int cursor_insert_offset_y = 0;
- // get the highlighted words
+ // Get the highlighted words.
String highlighted_text = get_selection_text();
- // check if highlighted words contains only whitespaces (tabs or spaces)
+ // Check if highlighted words contains only whitespaces (tabs or spaces).
bool only_whitespaces_highlighted = highlighted_text.strip_edges() == String();
String line_num_padding = line_numbers_zero_padded ? "0" : " ";
@@ -849,9 +905,156 @@ void TextEdit::_notification(int p_what) {
FontDrawer drawer(cache.font, Color(1, 1, 1));
- int line = get_first_visible_line() - 1;
+ int first_visible_line = get_first_visible_line() - 1;
int draw_amount = visible_rows + (smooth_scroll_enabled ? 1 : 0);
- draw_amount += times_line_wraps(line + 1);
+ draw_amount += times_line_wraps(first_visible_line + 1);
+
+ // minimap
+ if (draw_minimap) {
+ int minimap_visible_lines = _get_minimap_visible_rows();
+ int minimap_line_height = (minimap_char_size.y + minimap_line_spacing);
+ int minimap_tab_size = minimap_char_size.x * indent_size;
+
+ // calculate viewport size and y offset
+ int viewport_height = (draw_amount - 1) * minimap_line_height;
+ int control_height = _get_control_height() - viewport_height;
+ int viewport_offset_y = round(get_scroll_pos_for_line(first_visible_line) * control_height) / ((v_scroll->get_max() <= minimap_visible_lines) ? (minimap_visible_lines - draw_amount) : (v_scroll->get_max() - draw_amount));
+
+ // calculate the first line.
+ int num_lines_before = round((viewport_offset_y) / minimap_line_height);
+ int wi;
+ int minimap_line = (v_scroll->get_max() <= minimap_visible_lines) ? -1 : first_visible_line;
+ if (minimap_line >= 0) {
+ minimap_line -= num_lines_from_rows(first_visible_line, 0, -num_lines_before, wi);
+ minimap_line -= (smooth_scroll_enabled ? 1 : 0);
+ }
+ int minimap_draw_amount = minimap_visible_lines + times_line_wraps(minimap_line + 1);
+
+ // draw the minimap
+ Color viewport_color = (cache.background_color.get_v() < 0.5) ? Color(1, 1, 1, 0.1) : Color(0, 0, 0, 0.1);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2((xmargin_end + 2), viewport_offset_y, cache.minimap_width, viewport_height), viewport_color);
+ for (int i = 0; i < minimap_draw_amount; i++) {
+
+ minimap_line++;
+
+ if (minimap_line < 0 || minimap_line >= (int)text.size()) {
+ break;
+ }
+
+ while (is_line_hidden(minimap_line)) {
+ minimap_line++;
+ if (minimap_line < 0 || minimap_line >= (int)text.size()) {
+ break;
+ }
+ }
+
+ Map<int, HighlighterInfo> color_map;
+ if (syntax_coloring) {
+ color_map = _get_line_syntax_highlighting(minimap_line);
+ }
+
+ Color current_color = cache.font_color;
+ if (readonly) {
+ current_color = cache.font_color_readonly;
+ }
+
+ Vector<String> wrap_rows = get_wrap_rows_text(minimap_line);
+ int line_wrap_amount = times_line_wraps(minimap_line);
+ int last_wrap_column = 0;
+
+ for (int line_wrap_index = 0; line_wrap_index < line_wrap_amount + 1; line_wrap_index++) {
+ if (line_wrap_index != 0) {
+ i++;
+ if (i >= minimap_draw_amount)
+ break;
+ }
+
+ const String &str = wrap_rows[line_wrap_index];
+ int indent_px = line_wrap_index != 0 ? get_indent_level(minimap_line) : 0;
+ if (indent_px >= wrap_at) {
+ indent_px = 0;
+ }
+ indent_px = minimap_char_size.x * indent_px;
+
+ if (line_wrap_index > 0) {
+ last_wrap_column += wrap_rows[line_wrap_index - 1].length();
+ }
+
+ if (minimap_line == cursor.line && cursor_wrap_index == line_wrap_index && highlight_current_line) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2((xmargin_end + 2), i * 3, cache.minimap_width, 2), cache.current_line_color);
+ }
+
+ Color previous_color;
+ int characters = 0;
+ int tabs = 0;
+ for (int j = 0; j < str.length(); j++) {
+ if (syntax_coloring) {
+ if (color_map.has(last_wrap_column + j)) {
+ current_color = color_map[last_wrap_column + j].color;
+ if (readonly) {
+ current_color.a = cache.font_color_readonly.a;
+ }
+ }
+ color = current_color;
+ }
+
+ if (j == 0) {
+ previous_color = color;
+ }
+
+ int xpos = indent_px + ((xmargin_end + minimap_char_size.x) + (minimap_char_size.x * j)) + tabs;
+ bool out_of_bounds = (xpos >= xmargin_end + cache.minimap_width);
+
+ bool is_whitespace = _is_whitespace(str[j]);
+ if (!is_whitespace) {
+ characters++;
+
+ if (j < str.length() - 1 && color == previous_color && !out_of_bounds) {
+ continue;
+ }
+
+ // If we've changed colour we are at the start of a new section, therefore we need to go back to the end
+ // of the previous section to draw it, we'll also add the character back on.
+ if (color != previous_color) {
+ characters--;
+ j--;
+
+ if (str[j] == '\t') {
+ tabs -= minimap_tab_size;
+ }
+ }
+ }
+
+ if (characters > 0) {
+ previous_color.a *= 0.6;
+ // take one for zero indexing, and if we hit whitespace / the end of a word.
+ int chars = MAX(0, (j - (characters - 1)) - (is_whitespace ? 1 : 0)) + 1;
+ int char_x_ofs = indent_px + ((xmargin_end + minimap_char_size.x) + (minimap_char_size.x * chars)) + tabs;
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(char_x_ofs, minimap_line_height * i), Point2(minimap_char_size.x * characters, minimap_char_size.y)), previous_color);
+ }
+
+ if (out_of_bounds) {
+ break;
+ }
+
+ // re-adjust if we went backwards.
+ if (color != previous_color && !is_whitespace) {
+ characters++;
+ }
+
+ if (str[j] == '\t') {
+ tabs += minimap_tab_size;
+ }
+
+ previous_color = color;
+ characters = 0;
+ }
+ }
+ }
+ }
+
+ // draw main text
+ int line = first_visible_line;
for (int i = 0; i < draw_amount; i++) {
line++;
@@ -875,7 +1078,7 @@ void TextEdit::_notification(int p_what) {
if (syntax_coloring) {
color_map = _get_line_syntax_highlighting(line);
}
- // ensure we at least use the font color
+ // Ensure we at least use the font color.
Color current_color = readonly ? cache.font_color_readonly : cache.font_color;
bool underlined = false;
@@ -916,7 +1119,7 @@ void TextEdit::_notification(int p_what) {
if (smooth_scroll_enabled)
ofs_y += (-get_v_scroll_offset()) * get_row_height();
- // check if line contains highlighted word
+ // Check if line contains highlighted word.
int highlighted_text_col = -1;
int search_text_col = -1;
int highlighted_word_col = -1;
@@ -938,25 +1141,25 @@ void TextEdit::_notification(int p_what) {
}
if (str.length() == 0) {
- // draw line background if empty as we won't loop at at all
+ // Draw line background if empty as we won't loop at at all.
if (line == cursor.line && cursor_wrap_index == line_wrap_index && highlight_current_line) {
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(ofs_x, ofs_y, xmargin_end, get_row_height()), cache.current_line_color);
}
- // give visual indication of empty selected line
+ // Give visual indication of empty selected line.
if (selection.active && line >= selection.from_line && line <= selection.to_line && char_margin >= xmargin_beg) {
int char_w = cache.font->get_char_size(' ').width;
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, char_w, get_row_height()), cache.selection_color);
}
} else {
- // if it has text, then draw current line marker in the margin, as line number etc will draw over it, draw the rest of line marker later.
+ // If it has text, then draw current line marker in the margin, as line number etc will draw over it, draw the rest of line marker later.
if (line == cursor.line && cursor_wrap_index == line_wrap_index && highlight_current_line) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(0, ofs_y, xmargin_beg, get_row_height()), cache.current_line_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(0, ofs_y, xmargin_beg + ofs_x, get_row_height()), cache.current_line_color);
}
}
if (line_wrap_index == 0) {
- // only do these if we are on the first wrapped part of a line
+ // Only do these if we are on the first wrapped part of a line.
if (text.is_breakpoint(line) && !draw_breakpoint_gutter) {
#ifdef TOOLS_ENABLED
@@ -966,7 +1169,7 @@ void TextEdit::_notification(int p_what) {
#endif
}
- // draw bookmark marker
+ // Draw bookmark marker.
if (text.is_bookmark(line)) {
if (draw_bookmark_gutter) {
int vertical_gap = (get_row_height() * 40) / 100;
@@ -976,26 +1179,26 @@ void TextEdit::_notification(int p_what) {
}
}
- // draw breakpoint marker
+ // Draw breakpoint marker.
if (text.is_breakpoint(line)) {
if (draw_breakpoint_gutter) {
int vertical_gap = (get_row_height() * 40) / 100;
int horizontal_gap = (cache.breakpoint_gutter_width * 30) / 100;
int marker_height = get_row_height() - (vertical_gap * 2);
int marker_width = cache.breakpoint_gutter_width - (horizontal_gap * 2);
- // no transparency on marker
+ // No transparency on marker.
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cache.style_normal->get_margin(MARGIN_LEFT) + horizontal_gap - 2, ofs_y + vertical_gap, marker_width, marker_height), Color(cache.breakpoint_color.r, cache.breakpoint_color.g, cache.breakpoint_color.b));
}
}
- // draw info icons
+ // Draw info icons.
if (draw_info_gutter && text.has_info_icon(line)) {
int vertical_gap = (get_row_height() * 40) / 100;
int horizontal_gap = (cache.info_gutter_width * 30) / 100;
int gutter_left = cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width;
Ref<Texture> info_icon = text.get_info_icon(line);
- // ensure the icon fits the gutter size
+ // Ensure the icon fits the gutter size.
Size2i icon_size = info_icon->get_size();
if (icon_size.width > cache.info_gutter_width - horizontal_gap) {
icon_size.width = cache.info_gutter_width - horizontal_gap;
@@ -1013,7 +1216,7 @@ void TextEdit::_notification(int p_what) {
draw_texture_rect(info_icon, Rect2(icon_pos, icon_size));
}
- // draw execution marker
+ // Draw execution marker.
if (executing_line == line) {
if (draw_breakpoint_gutter) {
int icon_extra_size = 4;
@@ -1031,7 +1234,7 @@ void TextEdit::_notification(int p_what) {
}
}
- // draw fold markers
+ // Draw fold markers.
if (draw_fold_gutter) {
int horizontal_gap = (cache.fold_gutter_width * 30) / 100;
int gutter_left = cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width + cache.line_number_w + cache.info_gutter_width;
@@ -1046,7 +1249,7 @@ void TextEdit::_notification(int p_what) {
}
}
- // draw line numbers
+ // Draw line numbers.
if (cache.line_number_w) {
int yofs = ofs_y + (get_row_height() - cache.font->get_height()) / 2;
String fc = String::num(line + 1);
@@ -1058,32 +1261,35 @@ void TextEdit::_notification(int p_what) {
}
}
- //loop through characters in one line
+ // Loop through characters in one line.
for (int j = 0; j < str.length(); j++) {
if (syntax_coloring) {
if (color_map.has(last_wrap_column + j)) {
- current_color = readonly ? cache.font_color_readonly : color_map[last_wrap_column + j].color;
+ current_color = color_map[last_wrap_column + j].color;
+ if (readonly && current_color.a > cache.font_color_readonly.a) {
+ current_color.a = cache.font_color_readonly.a;
+ }
}
color = current_color;
}
int char_w;
- //handle tabulator
+ // Handle tabulator.
char_w = text.get_char_width(str[j], str[j + 1], char_ofs);
if ((char_ofs + char_margin) < xmargin_beg) {
char_ofs += char_w;
- // line highlighting handle horizontal clipping
+ // Line highlighting handle horizontal clipping.
if (line == cursor.line && cursor_wrap_index == line_wrap_index && highlight_current_line) {
if (j == str.length() - 1) {
- // end of line when last char is skipped
+ // End of line when last char is skipped.
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, xmargin_end - (char_ofs + char_margin + char_w), get_row_height()), cache.current_line_color);
} else if ((char_ofs + char_margin) > xmargin_beg) {
- // char next to margin is skipped
+ // Char next to margin is skipped.
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, (char_ofs + char_margin) - (xmargin_beg + ofs_x), get_row_height()), cache.current_line_color);
}
}
@@ -1097,7 +1303,7 @@ void TextEdit::_notification(int p_what) {
bool in_search_result = false;
if (search_text_col != -1) {
- // if we are at the end check for new search result on same line
+ // If we are at the end check for new search result on same line.
if (j >= search_text_col + search_text.length())
search_text_col = _get_column_pos_of_word(search_text, str, search_flags, j);
@@ -1108,19 +1314,19 @@ void TextEdit::_notification(int p_what) {
}
}
- //current line highlighting
+ // Current line highlighting.
bool in_selection = (selection.active && line >= selection.from_line && line <= selection.to_line && (line > selection.from_line || last_wrap_column + j >= selection.from_column) && (line < selection.to_line || last_wrap_column + j < selection.to_column));
if (line == cursor.line && cursor_wrap_index == line_wrap_index && highlight_current_line) {
- // draw the wrap indent offset highlight
+ // Draw the wrap indent offset highlight.
if (line_wrap_index != 0 && j == 0) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(char_ofs + char_margin - indent_px, ofs_y, indent_px, get_row_height()), cache.current_line_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(char_ofs + char_margin + ofs_x - indent_px, ofs_y, indent_px, get_row_height()), cache.current_line_color);
}
- // if its the last char draw to end of the line
+ // If its the last char draw to end of the line.
if (j == str.length() - 1) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(char_ofs + char_margin + char_w, ofs_y, xmargin_end - (char_ofs + char_margin + char_w), get_row_height()), cache.current_line_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(char_ofs + char_margin + char_w + ofs_x, ofs_y, xmargin_end - (char_ofs + char_margin + char_w), get_row_height()), cache.current_line_color);
}
- // actual text
+ // Actual text.
if (!in_selection) {
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(char_w, get_row_height())), cache.current_line_color);
}
@@ -1145,14 +1351,14 @@ void TextEdit::_notification(int p_what) {
if (highlight_all_occurrences && !only_whitespaces_highlighted) {
if (highlighted_text_col != -1) {
- // if we are at the end check for new word on same line
+ // If we are at the end check for new word on same line.
if (j > highlighted_text_col + highlighted_text.length()) {
highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, j);
}
bool in_highlighted_word = (j >= highlighted_text_col && j < highlighted_text_col + highlighted_text.length());
- // if this is the original highlighted text we don't want to highlight it again
+ // If this is the original highlighted text we don't want to highlight it again.
if (cursor.line == line && cursor_wrap_index == line_wrap_index && (cursor.column >= highlighted_text_col && cursor.column <= highlighted_text_col + highlighted_text.length())) {
in_highlighted_word = false;
}
@@ -1349,7 +1555,7 @@ void TextEdit::_notification(int p_what) {
bool completion_below = false;
if (completion_active) {
- // code completion box
+ // Code completion box.
Ref<StyleBox> csb = get_stylebox("completion");
int maxlines = get_constant("completion_lines");
int cmax_width = get_constant("completion_max_width") * cache.font->get_char_size('x').x;
@@ -1371,7 +1577,7 @@ void TextEdit::_notification(int p_what) {
w = cmax_width;
}
- // Add space for completion icons
+ // Add space for completion icons.
const int icon_hsep = get_constant("hseparation", "ItemList");
Size2 icon_area_size(get_row_height(), get_row_height());
w += icon_area_size.width + icon_hsep;
@@ -1418,7 +1624,7 @@ void TextEdit::_notification(int p_what) {
int yofs = (get_row_height() - cache.font->get_height()) / 2;
Point2 title_pos(completion_rect.position.x, completion_rect.position.y + i * get_row_height() + cache.font->get_ascent() + yofs);
- //draw completion icon if it is valid
+ // Draw completion icon if it is valid.
Ref<Texture> icon = completion_options[l].icon;
Rect2 icon_area(completion_rect.position.x, completion_rect.position.y + i * get_row_height(), icon_area_size.width, icon_area_size.height);
if (icon.is_valid()) {
@@ -1434,7 +1640,7 @@ void TextEdit::_notification(int p_what) {
}
if (scrollw) {
- //draw a small scroll rectangle to show a position in the options
+ // Draw a small scroll rectangle to show a position in the options.
float r = maxlines / (float)completion_options.size();
float o = line_from / (float)completion_options.size();
draw_rect(Rect2(completion_rect.position.x + completion_rect.size.width, completion_rect.position.y + o * completion_rect.size.y, scrollw, completion_rect.size.y * r), scrollc);
@@ -1443,7 +1649,7 @@ void TextEdit::_notification(int p_what) {
completion_line_ofs = line_from;
}
- // check to see if the hint should be drawn
+ // Check to see if the hint should be drawn.
bool show_hint = false;
if (completion_hint != "") {
if (completion_active) {
@@ -1520,7 +1726,6 @@ void TextEdit::_notification(int p_what) {
OS::get_singleton()->set_ime_active(true);
OS::get_singleton()->set_ime_position(get_global_position() + cursor_pos + Point2(0, get_row_height()));
}
-
} break;
case NOTIFICATION_FOCUS_ENTER: {
@@ -1662,9 +1867,9 @@ void TextEdit::backspace_at_cursor() {
_is_pair_left_symbol(text[cursor.line][cursor.column - 1])) {
_consume_backspace_for_pair_symbol(prev_line, prev_column);
} else {
- // handle space indentation
+ // Handle space indentation.
if (cursor.column != 0 && indent_using_spaces) {
- // check if there are no other chars before cursor, just indentation
+ // Check if there are no other chars before cursor, just indentation.
bool unindent = true;
int i = 0;
while (i < cursor.column && i < text[cursor.line].length()) {
@@ -1675,10 +1880,9 @@ void TextEdit::backspace_at_cursor() {
i++;
}
- // then we can remove all spaces as a single character.
+ // Then we can remove all spaces as a single character.
if (unindent) {
- // we want to remove spaces up to closest indent
- // or whole indent if cursor is pointing at it
+ // We want to remove spaces up to closest indent, or whole indent if cursor is pointing at it.
int spaces_to_delete = _calculate_spaces_till_next_left_indent(cursor.column);
prev_column = cursor.column - spaces_to_delete;
_remove_text(cursor.line, prev_column, cursor.line, cursor.column);
@@ -1699,8 +1903,8 @@ void TextEdit::indent_right() {
int start_line;
int end_line;
- // this value informs us by how much we changed selection position by indenting right
- // default is 1 for tab indentation
+ // This value informs us by how much we changed selection position by indenting right.
+ // Default is 1 for tab indentation.
int selection_offset = 1;
begin_complex_operation();
@@ -1712,7 +1916,7 @@ void TextEdit::indent_right() {
end_line = start_line;
}
- // ignore if the cursor is not past the first column
+ // Ignore if the cursor is not past the first column.
if (is_selection_active() && get_selection_to_column() == 0) {
end_line--;
}
@@ -1720,10 +1924,10 @@ void TextEdit::indent_right() {
for (int i = start_line; i <= end_line; i++) {
String line_text = get_line(i);
if (indent_using_spaces) {
- // we don't really care where selection is - we just need to know indentation level at the beginning of the line
+ // We don't really care where selection is - we just need to know indentation level at the beginning of the line.
int left = _find_first_non_whitespace_column_of_line(line_text);
int spaces_to_add = _calculate_spaces_till_next_right_indent(left);
- // since we will add this much spaces we want move whole selection and cursor by this much
+ // Since we will add this much spaces we want move whole selection and cursor by this much.
selection_offset = spaces_to_add;
for (int j = 0; j < spaces_to_add; j++)
line_text = ' ' + line_text;
@@ -1733,7 +1937,7 @@ void TextEdit::indent_right() {
set_line(i, line_text);
}
- // fix selection and cursor being off after shifting selection right
+ // Fix selection and cursor being off after shifting selection right.
if (is_selection_active()) {
select(selection.from_line, selection.from_column + selection_offset, selection.to_line, selection.to_column + selection_offset);
}
@@ -1747,10 +1951,9 @@ void TextEdit::indent_left() {
int start_line;
int end_line;
- // moving cursor and selection after unindenting can get tricky
- // because changing content of line can move cursor and selection on it's own (if new line ends before previous position of either)
- // therefore we just remember initial values
- // and at the end of the operation offset them by number of removed characters
+ // Moving cursor and selection after unindenting can get tricky because
+ // changing content of line can move cursor and selection on it's own (if new line ends before previous position of either),
+ // therefore we just remember initial values and at the end of the operation offset them by number of removed characters.
int removed_characters = 0;
int initial_selection_end_column = selection.to_column;
int initial_cursor_column = cursor.column;
@@ -1765,7 +1968,7 @@ void TextEdit::indent_left() {
end_line = start_line;
}
- // ignore if the cursor is not past the first column
+ // Ignore if the cursor is not past the first column.
if (is_selection_active() && get_selection_to_column() == 0) {
end_line--;
}
@@ -1779,12 +1982,12 @@ void TextEdit::indent_left() {
set_line(i, line_text);
removed_characters = 1;
} else if (line_text.begins_with(" ")) {
- // when unindenting we aim to remove spaces before line that has selection no matter what is selected
+ // When unindenting we aim to remove spaces before line that has selection no matter what is selected,
// so we start of by finding first non whitespace character of line
int left = _find_first_non_whitespace_column_of_line(line_text);
- // here we remove only enough spaces to align text to nearest full multiple of indentation_size
- // in case where selection begins at the start of indentation_size multiple we remove whole indentation level
+ // Here we remove only enough spaces to align text to nearest full multiple of indentation_size.
+ // In case where selection begins at the start of indentation_size multiple we remove whole indentation level.
int spaces_to_remove = _calculate_spaces_till_next_left_indent(left);
line_text = line_text.substr(spaces_to_remove, line_text.length());
@@ -1793,7 +1996,7 @@ void TextEdit::indent_left() {
}
}
- // fix selection and cursor being off by one on the last line
+ // Fix selection and cursor being off by one on the last line.
if (is_selection_active() && last_line_text != get_line(end_line)) {
select(selection.from_line, selection.from_column - removed_characters,
selection.to_line, initial_selection_end_column - removed_characters);
@@ -1834,7 +2037,7 @@ void TextEdit::_get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) co
}
if (row < 0)
- row = 0; //todo
+ row = 0; // TODO.
int col = 0;
@@ -1848,7 +2051,7 @@ void TextEdit::_get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) co
colx += cursor.x_ofs;
col = get_char_pos_for_line(colx, row, wrap_index);
if (is_wrap_enabled() && wrap_index < times_line_wraps(row)) {
- // move back one if we are at the end of the row
+ // Move back one if we are at the end of the row.
Vector<String> rows2 = get_wrap_rows_text(row);
int row_end_col = 0;
for (int i = 0; i < wrap_index + 1; i++) {
@@ -1863,6 +2066,61 @@ void TextEdit::_get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) co
r_col = col;
}
+void TextEdit::_get_minimap_mouse_row(const Point2i &p_mouse, int &r_row) const {
+
+ float rows = p_mouse.y;
+ rows -= cache.style_normal->get_margin(MARGIN_TOP);
+ rows /= (minimap_char_size.y + minimap_line_spacing);
+ rows += get_v_scroll_offset();
+
+ // calculate visible lines
+ int minimap_visible_lines = _get_minimap_visible_rows();
+ int visible_rows = get_visible_rows() + 1;
+ int first_visible_line = get_first_visible_line() - 1;
+ int draw_amount = visible_rows + (smooth_scroll_enabled ? 1 : 0);
+ draw_amount += times_line_wraps(first_visible_line + 1);
+ int minimap_line_height = (minimap_char_size.y + minimap_line_spacing);
+
+ // calculate viewport size and y offset
+ int viewport_height = (draw_amount - 1) * minimap_line_height;
+ int control_height = _get_control_height() - viewport_height;
+ int viewport_offset_y = round(get_scroll_pos_for_line(first_visible_line) * control_height) / ((v_scroll->get_max() <= minimap_visible_lines) ? (minimap_visible_lines - draw_amount) : (v_scroll->get_max() - draw_amount));
+
+ // calculate the first line.
+ int num_lines_before = round((viewport_offset_y) / minimap_line_height);
+ int wi;
+ int minimap_line = (v_scroll->get_max() <= minimap_visible_lines) ? -1 : first_visible_line;
+ if (first_visible_line > 0 && minimap_line >= 0) {
+ minimap_line -= num_lines_from_rows(first_visible_line, 0, -num_lines_before, wi);
+ minimap_line -= (smooth_scroll_enabled ? 1 : 0);
+ } else {
+ minimap_line = 0;
+ }
+
+ int row = minimap_line + Math::floor(rows);
+ int wrap_index = 0;
+
+ if (is_wrap_enabled() || is_hiding_enabled()) {
+
+ int f_ofs = num_lines_from_rows(minimap_line, cursor.wrap_ofs, rows + (1 * SGN(rows)), wrap_index) - 1;
+ if (rows < 0) {
+ row = minimap_line - f_ofs;
+ } else {
+ row = minimap_line + f_ofs;
+ }
+ }
+
+ if (row < 0) {
+ row = 0;
+ }
+
+ if (row >= text.size()) {
+ row = text.size() - 1;
+ }
+
+ r_row = row;
+}
+
void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
double prev_v_scroll = v_scroll->get_value();
@@ -1942,7 +2200,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
return;
}
- // toggle breakpoint on gutter click
+ // Toggle breakpoint on gutter click.
if (draw_breakpoint_gutter) {
int gutter = cache.style_normal->get_margin(MARGIN_LEFT);
if (mb->get_position().x > gutter - 6 && mb->get_position().x <= gutter + cache.breakpoint_gutter_width - 3) {
@@ -1952,7 +2210,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
- // emit info clicked
+ // Emit info clicked.
if (draw_info_gutter && text.has_info_icon(row)) {
int left_margin = cache.style_normal->get_margin(MARGIN_LEFT);
int gutter_left = left_margin + cache.breakpoint_gutter_width;
@@ -1962,7 +2220,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
- // toggle fold on gutter click if can
+ // Toggle fold on gutter click if can.
if (draw_fold_gutter) {
int left_margin = cache.style_normal->get_margin(MARGIN_LEFT);
@@ -1977,7 +2235,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
- // unfold on folded icon click
+ // Unfold on folded icon click.
if (is_folded(row)) {
int line_width = text.get_line_width(row);
line_width += cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.info_gutter_width + cache.fold_gutter_width - cursor.x_ofs;
@@ -1987,6 +2245,14 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
+ // minimap
+ if (draw_minimap) {
+ _update_minimap_click();
+ if (dragging_minimap) {
+ return;
+ }
+ }
+
int prev_col = cursor.column;
int prev_line = cursor.line;
@@ -2044,9 +2310,6 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} else {
- //if sel active and dblick last time < something
-
- //else
selection.active = false;
selection.selecting_mode = Selection::MODE_POINTER;
selection.selecting_line = row;
@@ -2054,14 +2317,14 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
if (!mb->is_doubleclick() && (OS::get_singleton()->get_ticks_msec() - last_dblclk) < 600 && cursor.line == prev_line) {
- //tripleclick select line
+
+ // Triple-click select line.
selection.selecting_mode = Selection::MODE_LINE;
_update_selection_mode_line();
last_dblclk = 0;
-
} else if (mb->is_doubleclick() && text[cursor.line].length()) {
- //doubleclick select word
+ // Double-click select word.
selection.selecting_mode = Selection::MODE_WORD;
_update_selection_mode_word();
last_dblclk = OS::get_singleton()->get_ticks_msec();
@@ -2086,7 +2349,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
int to_column = get_selection_to_column();
if (row < from_line || row > to_line || (row == from_line && col < from_column) || (row == to_line && col > to_column)) {
- // Right click is outside the selected text
+ // Right click is outside the selected text.
deselect();
}
}
@@ -2104,10 +2367,14 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
} else {
- if (mb->get_button_index() == BUTTON_LEFT)
+ if (mb->get_button_index() == BUTTON_LEFT) {
+ dragging_minimap = false;
+ dragging_selection = false;
+ can_drag_minimap = false;
click_select_held->stop();
+ }
- // notify to show soft keyboard
+ // Notify to show soft keyboard.
notification(NOTIFICATION_FOCUS_ENTER);
}
}
@@ -2123,7 +2390,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
h_scroll->set_value(h_scroll->get_value() + pan_gesture->get_delta().x * 100);
if (v_scroll->get_value() != prev_v_scroll || h_scroll->get_value() != prev_h_scroll)
- accept_event(); //accept event if scroll changed
+ accept_event(); // Accept event if scroll changed.
return;
}
@@ -2148,34 +2415,40 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
- if (mm->get_button_mask() & BUTTON_MASK_LEFT && get_viewport()->gui_get_drag_data() == Variant()) { //ignore if dragging
+ if (mm->get_button_mask() & BUTTON_MASK_LEFT && get_viewport()->gui_get_drag_data() == Variant()) { // Ignore if dragging.
_reset_caret_blink_timer();
- switch (selection.selecting_mode) {
- case Selection::MODE_POINTER: {
- _update_selection_mode_pointer();
- } break;
- case Selection::MODE_WORD: {
- _update_selection_mode_word();
- } break;
- case Selection::MODE_LINE: {
- _update_selection_mode_line();
- } break;
- default: {
- break;
+ if (draw_minimap && !dragging_selection) {
+ _update_minimap_drag();
+ }
+
+ if (!dragging_minimap) {
+ switch (selection.selecting_mode) {
+ case Selection::MODE_POINTER: {
+ _update_selection_mode_pointer();
+ } break;
+ case Selection::MODE_WORD: {
+ _update_selection_mode_word();
+ } break;
+ case Selection::MODE_LINE: {
+ _update_selection_mode_line();
+ } break;
+ default: {
+ break;
+ }
}
}
}
}
if (v_scroll->get_value() != prev_v_scroll || h_scroll->get_value() != prev_h_scroll)
- accept_event(); //accept event if scroll changed
+ accept_event(); // Accept event if scroll changed.
Ref<InputEventKey> k = p_gui_input;
if (k.is_valid()) {
- k = k->duplicate(); //it will be modified later on
+ k = k->duplicate(); // It will be modified later on.
#ifdef OSX_ENABLED
if (k->get_scancode() == KEY_META) {
@@ -2311,11 +2584,11 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
_consume_pair_symbol(chr[0]);
} else {
- // remove the old character if in insert mode
+ // Remove the old character if in insert mode.
if (insert_mode) {
begin_complex_operation();
- // make sure we don't try and remove empty space
+ // Make sure we don't try and remove empty space.
if (cursor.column < get_line(cursor.line).length()) {
_remove_text(cursor.line, cursor.column, cursor.line, cursor.column + 1);
}
@@ -2337,9 +2610,9 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
_cancel_completion();
}
- /* TEST CONTROL FIRST!! */
+ /* TEST CONTROL FIRST! */
- // some remaps for duplicate functions..
+ // Some remaps for duplicate functions.
if (k->get_command() && !k->get_shift() && !k->get_alt() && !k->get_metakey() && k->get_scancode() == KEY_INSERT) {
k->set_scancode(KEY_C);
@@ -2383,10 +2656,10 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
_reset_caret_blink_timer();
- // save here for insert mode, just in case it is cleared in the following section
+ // Save here for insert mode, just in case it is cleared in the following section.
bool had_selection = selection.active;
- // stuff to do when selection is active..
+ // Stuff to do when selection is active.
if (!readonly && selection.active) {
bool clear = false;
@@ -2406,7 +2679,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} break;
case KEY_X:
case KEY_C:
- //special keys often used with control, wait...
+ // Special keys often used with control, wait.
clear = (!k->get_command() || k->get_shift() || k->get_alt());
break;
case KEY_DELETE:
@@ -2431,7 +2704,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
case KEY_PAGEDOWN:
case KEY_HOME:
case KEY_END:
- // ignore arrows if any modifiers are held (shift = selecting, others may be used for editor hotkeys)
+ // Ignore arrows if any modifiers are held (shift = selecting, others may be used for editor hotkeys).
if (k->get_command() || k->get_shift() || k->get_alt())
break;
unselect = true;
@@ -2469,7 +2742,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
bool scancode_handled = true;
- // special scancode test...
+ // Special scancode test.
switch (k->get_scancode()) {
@@ -2481,7 +2754,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
String ins = "\n";
- //keep indentation
+ // Keep indentation.
int space_count = 0;
for (int i = 0; i < cursor.column; i++) {
if (text[cursor.line][i] == '\t') {
@@ -2512,10 +2785,10 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
bool brace_indent = false;
- // no need to indent if we are going upwards.
+ // No need to indent if we are going upwards.
if (auto_indent && !(k->get_command() && k->get_shift())) {
- // indent once again if previous line will end with ':' or '{' and the line is not a comment
- // (i.e. colon/brace precedes current cursor position)
+ // Indent once again if previous line will end with ':' or '{' and the line is not a comment
+ // (i.e. colon/brace precedes current cursor position).
if (cursor.column > 0 && (text[cursor.line][cursor.column - 1] == ':' || text[cursor.line][cursor.column - 1] == '{') && !is_line_comment(cursor.line)) {
if (indent_using_spaces) {
ins += space_indent;
@@ -2523,7 +2796,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
ins += "\t";
}
- // no need to move the brace below if we are not taking the text with us.
+ // No need to move the brace below if we are not taking the text with us.
if (text[cursor.line][cursor.column] == '}' && !k->get_command()) {
brace_indent = true;
ins += "\n" + ins.substr(1, ins.length() - 2);
@@ -2565,7 +2838,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
}
} break;
case KEY_TAB: {
- if (k->get_command()) break; // avoid tab when command
+ if (k->get_command()) break; // Avoid tab when command.
if (readonly)
break;
@@ -2579,7 +2852,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} else {
if (k->get_shift()) {
- // simple unindent
+ // Simple unindent.
int cc = cursor.column;
const String &line = text[cursor.line];
@@ -2591,17 +2864,17 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
if (cc > 0 && cc <= text[cursor.line].length()) {
if (text[cursor.line][cc - 1] == '\t') {
- // tabs unindentation
+ // Tabs unindentation.
_remove_text(cursor.line, cc - 1, cursor.line, cc);
if (cursor.column >= left)
cursor_set_column(MAX(0, cursor.column - 1));
update();
} else {
- // spaces unindentation
+ // Spaces unindentation.
int spaces_to_remove = _calculate_spaces_till_next_left_indent(cc);
if (spaces_to_remove > 0) {
_remove_text(cursor.line, cc - spaces_to_remove, cursor.line, cc);
- if (cursor.column > left - spaces_to_remove) // inside text?
+ if (cursor.column > left - spaces_to_remove) // Inside text?
cursor_set_column(MAX(0, cursor.column - spaces_to_remove));
update();
}
@@ -2611,9 +2884,9 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
update();
}
} else {
- // simple indent
+ // Simple indent.
if (indent_using_spaces) {
- // insert only as much spaces as needed till next indentation level
+ // Insert only as much spaces as needed till next indentation level.
int spaces_to_add = _calculate_spaces_till_next_right_indent(cursor.column);
String indent_to_insert = String();
for (int i = 0; i < spaces_to_add; i++)
@@ -2641,20 +2914,20 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
int line = cursor.line;
int column = cursor.column;
- // check if we are removing a single whitespace, if so remove it and the next char type
- // else we just remove the whitespace
+ // Check if we are removing a single whitespace, if so remove it and the next char type,
+ // else we just remove the whitespace.
bool only_whitespace = false;
if (_is_whitespace(text[line][column - 1]) && _is_whitespace(text[line][column - 2])) {
only_whitespace = true;
} else if (_is_whitespace(text[line][column - 1])) {
- // remove the single whitespace
+ // Remove the single whitespace.
column--;
}
- // check if its a text char
+ // Check if its a text char.
bool only_char = (_is_text_char(text[line][column - 1]) && !only_whitespace);
- // if its not whitespace or char then symbol.
+ // If its not whitespace or char then symbol.
bool only_symbols = !(only_whitespace || only_char);
while (column > 0) {
@@ -2940,7 +3213,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
int curline_len = text[cursor.line].length();
if (cursor.line == text.size() - 1 && cursor.column == curline_len)
- break; //nothing to do
+ break; // Nothing to do.
int next_line = cursor.column < curline_len ? cursor.line : cursor.line + 1;
int next_column;
@@ -2957,20 +3230,20 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
int line = cursor.line;
int column = cursor.column;
- // check if we are removing a single whitespace, if so remove it and the next char type
- // else we just remove the whitespace
+ // Check if we are removing a single whitespace, if so remove it and the next char type,
+ // else we just remove the whitespace.
bool only_whitespace = false;
if (_is_whitespace(text[line][column]) && _is_whitespace(text[line][column + 1])) {
only_whitespace = true;
} else if (_is_whitespace(text[line][column])) {
- // remove the single whitespace
+ // Remove the single whitespace.
column++;
}
- // check if its a text char
+ // Check if its a text char.
bool only_char = (_is_text_char(text[line][column]) && !only_whitespace);
- // if its not whitespace or char then symbol.
+ // If its not whitespace or char then symbol.
bool only_symbols = !(only_whitespace || only_char);
while (column < curline_len) {
@@ -3029,7 +3302,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
cursor_set_column(0);
} else {
- // move cursor column to start of wrapped row and then to start of text
+ // Move cursor column to start of wrapped row and then to start of text.
Vector<String> rows = get_wrap_rows_text(cursor.line);
int wi = get_cursor_wrap_index();
int row_start_col = 0;
@@ -3037,7 +3310,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
row_start_col += rows[i].length();
}
if (cursor.column == row_start_col || wi == 0) {
- // compute whitespace symbols seq length
+ // Compute whitespace symbols seq length.
int current_line_whitespace_len = 0;
while (current_line_whitespace_len < text[cursor.line].length()) {
CharType c = text[cursor.line][current_line_whitespace_len];
@@ -3088,7 +3361,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
if (k->get_command())
cursor_set_line(get_last_unhidden_line(), true, false, 9999);
- // move cursor column to end of wrapped row and then to end of text
+ // Move cursor column to end of wrapped row and then to end of text.
Vector<String> rows = get_wrap_rows_text(cursor.line);
int wi = get_cursor_wrap_index();
int row_end_col = -1;
@@ -3241,6 +3514,10 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} break;
case KEY_Z: {
+ if (readonly) {
+ break;
+ }
+
if (!k->get_command()) {
scancode_handled = false;
break;
@@ -3253,6 +3530,10 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} break;
case KEY_Y: {
+ if (readonly) {
+ break;
+ }
+
if (!k->get_command()) {
scancode_handled = false;
break;
@@ -3274,7 +3555,7 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
} break;
case KEY_SPACE: {
#ifdef OSX_ENABLED
- if (completion_enabled && k->get_metakey()) { //cmd-space is spotlight shortcut in OSX
+ if (completion_enabled && k->get_metakey()) { // cmd-space is spotlight shortcut in OSX
#else
if (completion_enabled && k->get_command()) {
#endif
@@ -3302,18 +3583,18 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
return;
}
- if (!scancode_handled && !k->get_command()) { //for German kbds
+ if (!scancode_handled && !k->get_command()) { // For German keyboards.
if (k->get_unicode() >= 32) {
if (readonly)
return;
- // remove the old character if in insert mode and no selection
+ // Remove the old character if in insert mode and no selection.
if (insert_mode && !had_selection) {
begin_complex_operation();
- // make sure we don't try and remove empty space
+ // Make sure we don't try and remove empty space.
if (cursor.column < get_line(cursor.line).length()) {
_remove_text(cursor.line, cursor.column, cursor.line, cursor.column + 1);
}
@@ -3347,8 +3628,10 @@ void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) {
void TextEdit::_scroll_up(real_t p_delta) {
- if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(-p_delta))
+ if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(-p_delta)) {
scrolling = false;
+ minimap_clicked = false;
+ }
if (scrolling) {
target_v_scroll = (target_v_scroll - p_delta);
@@ -3373,8 +3656,10 @@ void TextEdit::_scroll_up(real_t p_delta) {
void TextEdit::_scroll_down(real_t p_delta) {
- if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(p_delta))
+ if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(p_delta)) {
scrolling = false;
+ minimap_clicked = false;
+ }
if (scrolling) {
target_v_scroll = (target_v_scroll + p_delta);
@@ -3423,11 +3708,12 @@ void TextEdit::_post_shift_selection() {
void TextEdit::_scroll_lines_up() {
scrolling = false;
+ minimap_clicked = false;
- // adjust the vertical scroll
+ // Adjust the vertical scroll.
set_v_scroll(get_v_scroll() - 1);
- // adjust the cursor to viewport
+ // Adjust the cursor to viewport.
if (!selection.active) {
int cur_line = cursor.line;
int cur_wrap = get_cursor_wrap_index();
@@ -3442,11 +3728,12 @@ void TextEdit::_scroll_lines_up() {
void TextEdit::_scroll_lines_down() {
scrolling = false;
+ minimap_clicked = false;
- // adjust the vertical scroll
+ // Adjust the vertical scroll.
set_v_scroll(get_v_scroll() + 1);
- // adjust the cursor to viewport
+ // Adjust the cursor to viewport.
if (!selection.active) {
int cur_line = cursor.line;
int cur_wrap = get_cursor_wrap_index();
@@ -3463,15 +3750,15 @@ void TextEdit::_scroll_lines_down() {
void TextEdit::_base_insert_text(int p_line, int p_char, const String &p_text, int &r_end_line, int &r_end_column) {
- //save for undo...
+ // Save for undo.
ERR_FAIL_INDEX(p_line, text.size());
ERR_FAIL_COND(p_char < 0);
- /* STEP 1 remove \r from source text and separate in substrings */
+ /* STEP 1: Remove \r from source text and separate in substrings. */
Vector<String> substrings = p_text.replace("\r", "").split("\n");
- /* STEP 2 fire breakpoint_toggled signals */
+ /* STEP 2: Fire breakpoint_toggled signals. */
// Is this just a new empty line?
bool shift_first_line = p_char == 0 && p_text.replace("\r", "") == "\n";
@@ -3487,19 +3774,19 @@ void TextEdit::_base_insert_text(int p_line, int p_char, const String &p_text, i
}
}
- /* STEP 3 add spaces if the char is greater than the end of the line */
+ /* STEP 3: Add spaces if the char is greater than the end of the line. */
while (p_char > text[p_line].length()) {
text.set(p_line, text[p_line] + String::chr(' '));
}
- /* STEP 4 separate dest string in pre and post text */
+ /* STEP 4: Separate dest string in pre and post text. */
String preinsert_text = text[p_line].substr(0, p_char);
String postinsert_text = text[p_line].substr(p_char, text[p_line].size());
for (int j = 0; j < substrings.size(); j++) {
- //insert the substrings
+ // Insert the substrings.
if (j == 0) {
@@ -3544,8 +3831,8 @@ String TextEdit::_base_get_text(int p_from_line, int p_from_column, int p_to_lin
ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, String());
ERR_FAIL_INDEX_V(p_to_line, text.size(), String());
ERR_FAIL_INDEX_V(p_to_column, text[p_to_line].length() + 1, String());
- ERR_FAIL_COND_V(p_to_line < p_from_line, String()); // from > to
- ERR_FAIL_COND_V(p_to_line == p_from_line && p_to_column < p_from_column, String()); // from > to
+ ERR_FAIL_COND_V(p_to_line < p_from_line, String()); // 'from > to'.
+ ERR_FAIL_COND_V(p_to_line == p_from_line && p_to_column < p_from_column, String()); // 'from > to'.
String ret;
@@ -3568,8 +3855,8 @@ void TextEdit::_base_remove_text(int p_from_line, int p_from_column, int p_to_li
ERR_FAIL_INDEX(p_from_column, text[p_from_line].length() + 1);
ERR_FAIL_INDEX(p_to_line, text.size());
ERR_FAIL_INDEX(p_to_column, text[p_to_line].length() + 1);
- ERR_FAIL_COND(p_to_line < p_from_line); // from > to
- ERR_FAIL_COND(p_to_line == p_from_line && p_to_column < p_from_column); // from > to
+ ERR_FAIL_COND(p_to_line < p_from_line); // 'from > to'.
+ ERR_FAIL_COND(p_to_line == p_from_line && p_to_column < p_from_column); // 'from > to'.
String pre_text = text[p_from_line].substr(0, p_from_column);
String post_text = text[p_to_line].substr(p_to_column, text[p_to_line].length());
@@ -3631,22 +3918,22 @@ void TextEdit::_insert_text(int p_line, int p_char, const String &p_text, int *r
op.chain_forward = false;
op.chain_backward = false;
- //see if it should just be set as current op
+ // See if it should just be set as current op.
if (current_op.type != op.type) {
op.prev_version = get_version();
_push_current_op();
current_op = op;
- return; //set as current op, return
+ return; // Set as current op, return.
}
- //see if it can be merged
+ // See if it can be merged.
if (current_op.to_line != p_line || current_op.to_column != p_char) {
op.prev_version = get_version();
_push_current_op();
current_op = op;
- return; //set as current op, return
+ return; // Set as current op, return.
}
- //merge current op
+ // Merge current op.
current_op.text += p_text;
current_op.to_column = retchar;
@@ -3670,7 +3957,7 @@ void TextEdit::_remove_text(int p_from_line, int p_from_column, int p_to_line, i
if (!undo_enabled)
return;
- /* UNDO!! */
+ /* UNDO! */
TextOperation op;
op.type = TextOperation::TYPE_REMOVE;
op.from_line = p_from_line;
@@ -3682,27 +3969,20 @@ void TextEdit::_remove_text(int p_from_line, int p_from_column, int p_to_line, i
op.chain_forward = false;
op.chain_backward = false;
- //see if it should just be set as current op
+ // See if it should just be set as current op.
if (current_op.type != op.type) {
op.prev_version = get_version();
_push_current_op();
current_op = op;
- return; //set as current op, return
+ return; // Set as current op, return.
}
- //see if it can be merged
+ // See if it can be merged.
if (current_op.from_line == p_to_line && current_op.from_column == p_to_column) {
- //basckace or similar
+ // Backspace or similar.
current_op.text = text + current_op.text;
current_op.from_line = p_from_line;
current_op.from_column = p_from_column;
- return; //update current op
- }
- if (current_op.from_line == p_from_line && current_op.from_column == p_from_column) {
-
- //current_op.text=text+current_op.text;
- //current_op.from_line=p_from_line;
- //current_op.from_column=p_from_column;
- //return; //update current op
+ return; // Update current op.
}
op.prev_version = get_version();
@@ -3725,6 +4005,15 @@ void TextEdit::_line_edited_from(int p_line) {
for (int i = p_line; i < cache_size; i++) {
color_region_cache.erase(i);
}
+
+ if (syntax_highlighting_cache.size() > 0) {
+ cache_size = syntax_highlighting_cache.back()->key();
+ for (int i = p_line - 1; i <= cache_size; i++) {
+ if (syntax_highlighting_cache.has(i)) {
+ syntax_highlighting_cache.erase(i);
+ }
+ }
+ }
}
int TextEdit::get_char_count() {
@@ -3734,11 +4023,11 @@ int TextEdit::get_char_count() {
for (int i = 0; i < text.size(); i++) {
if (i > 0)
- totalsize++; // incliude \n
+ totalsize++; // Include \n.
totalsize += text[i].length();
}
- return totalsize; // omit last \n
+ return totalsize; // Omit last \n.
}
Size2 TextEdit::get_minimum_size() const {
@@ -3746,19 +4035,26 @@ Size2 TextEdit::get_minimum_size() const {
return cache.style_normal->get_minimum_size();
}
+int TextEdit::_get_control_height() const {
+ int control_height = get_size().height;
+ control_height -= cache.style_normal->get_minimum_size().height;
+ if (h_scroll->is_visible_in_tree()) {
+ control_height -= h_scroll->get_size().height;
+ }
+ return control_height;
+}
+
int TextEdit::get_visible_rows() const {
+ return _get_control_height() / get_row_height();
+}
- int total = get_size().height;
- total -= cache.style_normal->get_minimum_size().height;
- if (h_scroll->is_visible_in_tree())
- total -= h_scroll->get_size().height;
- total /= get_row_height();
- return total;
+int TextEdit::_get_minimap_visible_rows() const {
+ return _get_control_height() / (minimap_char_size.y + minimap_line_spacing);
}
int TextEdit::get_total_visible_rows() const {
- // returns the total amount of rows we need in the editor.
+ // Returns the total amount of rows we need in the editor.
// This skips hidden lines and counts each wrapping of a line.
if (!is_hiding_enabled() && !is_wrap_enabled())
return text.size();
@@ -3775,12 +4071,12 @@ int TextEdit::get_total_visible_rows() const {
void TextEdit::_update_wrap_at() {
- wrap_at = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width - wrap_right_offset;
+ wrap_at = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width - cache.minimap_width - wrap_right_offset;
update_cursor_wrap_offset();
text.clear_wrap_cache();
for (int i = 0; i < text.size(); i++) {
- // update all values that wrap
+ // Update all values that wrap.
if (!line_wraps(i))
continue;
Vector<String> rows = get_wrap_rows_text(i);
@@ -3790,8 +4086,9 @@ void TextEdit::_update_wrap_at() {
void TextEdit::adjust_viewport_to_cursor() {
- // make sure cursor is visible on the screen
+ // Make sure cursor is visible on the screen.
scrolling = false;
+ minimap_clicked = false;
int cur_line = cursor.line;
int cur_wrap = get_cursor_wrap_index();
@@ -3802,20 +4099,20 @@ void TextEdit::adjust_viewport_to_cursor() {
int last_vis_wrap = get_last_visible_line_wrap_index();
if (cur_line < first_vis_line || (cur_line == first_vis_line && cur_wrap < first_vis_wrap)) {
- // cursor is above screen
+ // Cursor is above screen.
set_line_as_first_visible(cur_line, cur_wrap);
} else if (cur_line > last_vis_line || (cur_line == last_vis_line && cur_wrap > last_vis_wrap)) {
- // cursor is below screen
+ // Cursor is below screen.
set_line_as_last_visible(cur_line, cur_wrap);
}
- int visible_width = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width;
+ int visible_width = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width - cache.minimap_width;
if (v_scroll->is_visible_in_tree())
visible_width -= v_scroll->get_combined_minimum_size().width;
- visible_width -= 20; // give it a little more space
+ visible_width -= 20; // Give it a little more space.
if (!is_wrap_enabled()) {
- // adjust x offset
+ // Adjust x offset.
int cursor_x = get_column_x_offset(cursor.column, text[cursor.line]);
if (cursor_x > (cursor.x_ofs + visible_width))
@@ -3833,20 +4130,21 @@ void TextEdit::adjust_viewport_to_cursor() {
void TextEdit::center_viewport_to_cursor() {
- // move viewport so the cursor is in the center of the screen
+ // Move viewport so the cursor is in the center of the screen.
scrolling = false;
+ minimap_clicked = false;
if (is_line_hidden(cursor.line))
unfold_line(cursor.line);
set_line_as_center_visible(cursor.line, get_cursor_wrap_index());
- int visible_width = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width;
+ int visible_width = get_size().width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width - cache.info_gutter_width - cache.minimap_width;
if (v_scroll->is_visible_in_tree())
visible_width -= v_scroll->get_combined_minimum_size().width;
- visible_width -= 20; // give it a little more space
+ visible_width -= 20; // Give it a little more space.
if (is_wrap_enabled()) {
- // center x offset
+ // Center x offset.
int cursor_x = get_column_x_offset_for_line(cursor.column, cursor.line);
if (cursor_x > (cursor.x_ofs + visible_width))
@@ -3888,7 +4186,7 @@ int TextEdit::times_line_wraps(int line) const {
int wrap_amount = text.get_line_wrap_amount(line);
if (wrap_amount == -1) {
- // update the value
+ // Update the value.
Vector<String> rows = get_wrap_rows_text(line);
wrap_amount = rows.size() - 1;
text.set_line_wrap_amount(line, wrap_amount);
@@ -3928,7 +4226,7 @@ Vector<String> TextEdit::get_wrap_rows_text(int p_line) const {
int indent_ofs = (cur_wrap_index != 0 ? tab_offset_px : 0);
if (indent_ofs + word_px + w > wrap_at) {
- // not enough space to add this char; start next line
+ // Not enough space to add this char; start next line.
wrap_substring += word_str;
lines.push_back(wrap_substring);
cur_wrap_index++;
@@ -3942,7 +4240,7 @@ Vector<String> TextEdit::get_wrap_rows_text(int p_line) const {
word_str += c;
word_px += w;
if (c == ' ') {
- // end of a word; add this word to the substring
+ // End of a word; add this word to the substring.
wrap_substring += word_str;
px += word_px;
word_str = "";
@@ -3950,9 +4248,9 @@ Vector<String> TextEdit::get_wrap_rows_text(int p_line) const {
}
if (indent_ofs + px + word_px > wrap_at) {
- // this word will be moved to the next line
+ // This word will be moved to the next line.
lines.push_back(wrap_substring);
- // reset for next wrap
+ // Reset for next wrap.
cur_wrap_index++;
wrap_substring = "";
px = 0;
@@ -3960,11 +4258,11 @@ Vector<String> TextEdit::get_wrap_rows_text(int p_line) const {
}
col++;
}
- // line ends before hit wrap_at; add this word to the substring
+ // Line ends before hit wrap_at; add this word to the substring.
wrap_substring += word_str;
lines.push_back(wrap_substring);
- // update cache
+ // Update cache.
text.set_line_wrap_amount(p_line, lines.size() - 1);
return lines;
@@ -3982,7 +4280,7 @@ int TextEdit::get_line_wrap_index_at_col(int p_line, int p_column) const {
if (!line_wraps(p_line))
return 0;
- // loop through wraps in the line text until we get to the column
+ // Loop through wraps in the line text until we get to the column.
int wrap_index = 0;
int col = 0;
Vector<String> rows = get_wrap_rows_text(p_line);
@@ -4123,6 +4421,7 @@ bool TextEdit::is_right_click_moving_caret() const {
void TextEdit::_v_scroll_input() {
scrolling = false;
+ minimap_clicked = false;
}
void TextEdit::_scroll_moved(double p_to_val) {
@@ -4134,7 +4433,7 @@ void TextEdit::_scroll_moved(double p_to_val) {
cursor.x_ofs = h_scroll->get_value();
if (v_scroll->is_visible_in_tree()) {
- // set line ofs and wrap ofs
+ // Set line ofs and wrap ofs.
int v_scroll_i = floor(get_v_scroll());
int sc = 0;
int n_line;
@@ -4289,12 +4588,12 @@ Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const {
_get_mouse_pos(p_pos, row, col);
int left_margin = cache.style_normal->get_margin(MARGIN_LEFT);
- // breakpoint icon
+ // Breakpoint icon.
if (draw_breakpoint_gutter && p_pos.x > left_margin - 6 && p_pos.x <= left_margin + cache.breakpoint_gutter_width - 3) {
return CURSOR_POINTING_HAND;
}
- // info icons
+ // Info icons.
int gutter_left = left_margin + cache.breakpoint_gutter_width + cache.info_gutter_width;
if (draw_info_gutter && p_pos.x > left_margin + cache.breakpoint_gutter_width - 6 && p_pos.x <= gutter_left - 3) {
if (text.has_info_icon(row)) {
@@ -4303,7 +4602,7 @@ Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const {
return CURSOR_ARROW;
}
- // fold icon
+ // Fold icon.
if (draw_fold_gutter && p_pos.x > gutter_left + cache.line_number_w - 6 && p_pos.x <= gutter_left + cache.line_number_w + cache.fold_gutter_width - 3) {
if (is_folded(row) || can_fold(row))
return CURSOR_POINTING_HAND;
@@ -4313,9 +4612,14 @@ Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const {
return CURSOR_ARROW;
} else {
+ int xmargin_end = get_size().width - cache.style_normal->get_margin(MARGIN_RIGHT);
+ if (p_pos.x > xmargin_end - minimap_width && p_pos.x <= xmargin_end) {
+ return CURSOR_ARROW;
+ }
+
int row, col;
_get_mouse_pos(p_pos, row, col);
- // eol fold icon
+ // EOL fold icon.
if (is_folded(row)) {
int line_width = text.get_line_width(row);
line_width += cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width + cache.info_gutter_width - cursor.x_ofs;
@@ -4349,8 +4653,6 @@ void TextEdit::set_text(String p_text) {
update();
setting_text = false;
-
- //get_range()->set(0);
};
String TextEdit::get_text() {
@@ -4377,7 +4679,7 @@ String TextEdit::get_text_for_lookup_completion() {
if (i == row) {
longthing += text[i].substr(0, col);
- longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
longthing += text[i].substr(col, text[i].size());
} else {
@@ -4399,7 +4701,7 @@ String TextEdit::get_text_for_completion() {
if (i == cursor.line) {
longthing += text[i].substr(0, cursor.column);
- longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
longthing += text[i].substr(cursor.column, text[i].size());
} else {
@@ -4582,17 +4884,18 @@ void TextEdit::_set_syntax_highlighting(SyntaxHighlighter *p_syntax_highlighter)
syntax_highlighter->set_text_editor(this);
syntax_highlighter->_update_cache();
}
+ syntax_highlighting_cache.clear();
update();
}
int TextEdit::_is_line_in_region(int p_line) {
- // do we have in cache?
+ // Do we have in cache?
if (color_region_cache.has(p_line)) {
return color_region_cache[p_line];
}
- // if not find the closest line we have
+ // If not find the closest line we have.
int previous_line = p_line - 1;
for (; previous_line > -1; previous_line--) {
if (color_region_cache.has(p_line)) {
@@ -4600,7 +4903,7 @@ int TextEdit::_is_line_in_region(int p_line) {
}
}
- // calculate up to line we need and update the cache along the way.
+ // Calculate up to line we need and update the cache along the way.
int in_region = color_region_cache[previous_line];
if (previous_line == -1) {
in_region = -1;
@@ -4648,6 +4951,7 @@ void TextEdit::clear_colors() {
keywords.clear();
color_regions.clear();
color_region_cache.clear();
+ syntax_highlighting_cache.clear();
text.clear_width_cache();
}
@@ -4728,7 +5032,7 @@ void TextEdit::cut() {
OS::get_singleton()->set_clipboard(clipboard);
_remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
- cursor_set_line(selection.from_line); // set afterwards else it causes the view to be offset
+ cursor_set_line(selection.from_line); // Set afterwards else it causes the view to be offset.
cursor_set_column(selection.from_column);
selection.active = false;
@@ -4957,7 +5261,7 @@ int TextEdit::_get_column_pos_of_word(const String &p_key, const String &p_searc
col = p_search.findn(p_key, p_from_column);
}
- // whole words only
+ // Whole words only.
if (col != -1 && p_search_flags & SEARCH_WHOLE_WORDS) {
p_from_column = col;
@@ -4997,14 +5301,12 @@ bool TextEdit::search(const String &p_key, uint32_t p_search_flags, int p_from_l
ERR_FAIL_INDEX_V(p_from_line, text.size(), false);
ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, false);
- //search through the whole document, but start by current line
+ // Search through the whole document, but start by current line.
int line = p_from_line;
int pos = -1;
for (int i = 0; i < text.size() + 1; i++) {
- //backwards is broken...
- //int idx=(p_search_flags&SEARCH_BACKWARDS)?(text.size()-i):i; //do backwards seearch
if (line < 0) {
line = text.size() - 1;
@@ -5018,7 +5320,7 @@ bool TextEdit::search(const String &p_key, uint32_t p_search_flags, int p_from_l
if (line == p_from_line) {
if (i == text.size()) {
- //wrapped
+ // Wrapped.
if (p_search_flags & SEARCH_BACKWARDS) {
from_column = text_line.length();
@@ -5066,7 +5368,7 @@ bool TextEdit::search(const String &p_key, uint32_t p_search_flags, int p_from_l
bool is_match = true;
if (pos != -1 && (p_search_flags & SEARCH_WHOLE_WORDS)) {
- //validate for whole words
+ // Validate for whole words.
if (pos > 0 && _is_text_char(text_line[pos - 1]))
is_match = false;
else if (pos + p_key.length() < text_line.length() && _is_text_char(text_line[pos + p_key.length()]))
@@ -5264,7 +5566,7 @@ void TextEdit::unhide_all_lines() {
int TextEdit::num_lines_from(int p_line_from, int visible_amount) const {
- // returns the number of lines (hidden and unhidden) from p_line_from to (p_line_from + visible_amount of unhidden lines)
+ // Returns the number of lines (hidden and unhidden) from p_line_from to (p_line_from + visible_amount of unhidden lines).
ERR_FAIL_INDEX_V(p_line_from, text.size(), ABS(visible_amount));
if (!is_hiding_enabled())
@@ -5297,8 +5599,8 @@ int TextEdit::num_lines_from(int p_line_from, int visible_amount) const {
int TextEdit::num_lines_from_rows(int p_line_from, int p_wrap_index_from, int visible_amount, int &wrap_index) const {
- // returns the number of lines (hidden and unhidden) from (p_line_from + p_wrap_index_from) row to (p_line_from + visible_amount of unhidden and wrapped rows)
- // wrap index is set to the wrap index of the last line
+ // Returns the number of lines (hidden and unhidden) from (p_line_from + p_wrap_index_from) row to (p_line_from + visible_amount of unhidden and wrapped rows).
+ // Wrap index is set to the wrap index of the last line.
wrap_index = 0;
ERR_FAIL_INDEX_V(p_line_from, text.size(), ABS(visible_amount));
@@ -5344,7 +5646,7 @@ int TextEdit::num_lines_from_rows(int p_line_from, int p_wrap_index_from, int vi
int TextEdit::get_last_unhidden_line() const {
- // returns the last line in the text that is not hidden
+ // Returns the last line in the text that is not hidden.
if (!is_hiding_enabled())
return text.size() - 1;
@@ -5361,7 +5663,7 @@ int TextEdit::get_indent_level(int p_line) const {
ERR_FAIL_INDEX_V(p_line, text.size(), 0);
- // counts number of tabs and spaces before line starts
+ // Counts number of tabs and spaces before line starts.
int tab_count = 0;
int whitespace_count = 0;
int line_length = text[p_line].size();
@@ -5379,7 +5681,7 @@ int TextEdit::get_indent_level(int p_line) const {
bool TextEdit::is_line_comment(int p_line) const {
- // checks to see if this line is the start of a comment
+ // Checks to see if this line is the start of a comment.
ERR_FAIL_INDEX_V(p_line, text.size(), false);
const Map<int, Text::ColorRegionInfo> &cri_map = text.get_color_region_info(p_line);
@@ -5459,7 +5761,7 @@ void TextEdit::fold_line(int p_line) {
if (!can_fold(p_line))
return;
- // hide lines below this one
+ // Hide lines below this one.
int start_indent = get_indent_level(p_line);
int last_line = start_indent;
for (int i = p_line + 1; i < text.size(); i++) {
@@ -5477,7 +5779,7 @@ void TextEdit::fold_line(int p_line) {
set_line_as_hidden(i, true);
}
- // fix selection
+ // Fix selection.
if (is_selection_active()) {
if (is_line_hidden(selection.from_line) && is_line_hidden(selection.to_line)) {
deselect();
@@ -5488,7 +5790,7 @@ void TextEdit::fold_line(int p_line) {
}
}
- // reset cursor
+ // Reset cursor.
if (is_line_hidden(cursor.line)) {
cursor_set_line(p_line, false, false);
cursor_set_column(get_line(p_line).length(), false);
@@ -5549,8 +5851,8 @@ void TextEdit::_do_text_op(const TextOperation &p_op, bool p_reverse) {
int check_line;
int check_column;
_base_insert_text(p_op.from_line, p_op.from_column, p_op.text, check_line, check_column);
- ERR_FAIL_COND(check_line != p_op.to_line); // BUG
- ERR_FAIL_COND(check_column != p_op.to_column); // BUG
+ ERR_FAIL_COND(check_line != p_op.to_line); // BUG.
+ ERR_FAIL_COND(check_column != p_op.to_column); // BUG.
} else {
_base_remove_text(p_op.from_line, p_op.from_column, p_op.to_line, p_op.to_column);
@@ -5560,7 +5862,7 @@ void TextEdit::_do_text_op(const TextOperation &p_op, bool p_reverse) {
void TextEdit::_clear_redo() {
if (undo_stack_pos == NULL)
- return; //nothing to clear
+ return; // Nothing to clear.
_push_current_op();
@@ -5578,12 +5880,12 @@ void TextEdit::undo() {
if (undo_stack_pos == NULL) {
if (!undo_stack.size())
- return; //nothing to undo
+ return; // Nothing to undo.
undo_stack_pos = undo_stack.back();
} else if (undo_stack_pos == undo_stack.front())
- return; // at the bottom of the undo stack
+ return; // At the bottom of the undo stack.
else
undo_stack_pos = undo_stack_pos->prev();
@@ -5624,7 +5926,7 @@ void TextEdit::redo() {
_push_current_op();
if (undo_stack_pos == NULL)
- return; //nothing to do.
+ return; // Nothing to do.
deselect();
@@ -5678,7 +5980,7 @@ void TextEdit::end_complex_operation() {
void TextEdit::_push_current_op() {
if (current_op.type == TextOperation::TYPE_NONE)
- return; // do nothing
+ return; // Nothing to do.
if (next_operation_is_complex) {
current_op.chain_forward = true;
@@ -5778,7 +6080,7 @@ double TextEdit::get_scroll_pos_for_line(int p_line, int p_wrap_index) const {
if (!is_wrap_enabled() && !is_hiding_enabled())
return p_line;
- // count the number of visible lines up to this line
+ // Count the number of visible lines up to this line.
double new_line_scroll_pos = 0;
int to = CLAMP(p_line, 0, text.size() - 1);
for (int i = 0; i < to; i++) {
@@ -5838,10 +6140,7 @@ int TextEdit::get_last_visible_line_wrap_index() const {
double TextEdit::get_visible_rows_offset() const {
- double total = get_size().height;
- total -= cache.style_normal->get_minimum_size().height;
- if (h_scroll->is_visible_in_tree())
- total -= h_scroll->get_size().height;
+ double total = _get_control_height();
total /= (double)get_row_height();
total = total - floor(total);
total = -CLAMP(total, 0.001, 1) + 1;
@@ -5979,7 +6278,7 @@ void TextEdit::_update_completion_candidates() {
String s;
- //look for keywords first
+ // Look for keywords first.
bool inquote = false;
int first_quote = -1;
@@ -6004,7 +6303,7 @@ void TextEdit::_update_completion_candidates() {
bool cancel = false;
if (!inquote && first_quote == cofs - 1) {
- //no completion here
+ // No completion here.
cancel = true;
} else if (inquote && first_quote != -1) {
@@ -6042,11 +6341,12 @@ void TextEdit::_update_completion_candidates() {
bool prev_is_prefix = false;
if (cofs > 0 && completion_prefixes.has(String::chr(l[cofs - 1])))
prev_is_prefix = true;
- if (cofs > 1 && l[cofs - 1] == ' ' && completion_prefixes.has(String::chr(l[cofs - 2]))) //check with one space before prefix, to allow indent
+ // Check with one space before prefix, to allow indent.
+ if (cofs > 1 && l[cofs - 1] == ' ' && completion_prefixes.has(String::chr(l[cofs - 2])))
prev_is_prefix = true;
if (cancel || (!pre_keyword && s == "" && (cofs == 0 || !prev_is_prefix))) {
- //none to complete, cancel
+ // None to complete, cancel.
_cancel_completion();
return;
}
@@ -6096,18 +6396,18 @@ void TextEdit::_update_completion_candidates() {
}
if (completion_options.size() == 0) {
- //no options to complete, cancel
+ // No options to complete, cancel.
_cancel_completion();
return;
}
if (completion_options.size() == 1 && s == completion_options[0].display) {
- // A perfect match, stop completion
+ // A perfect match, stop completion.
_cancel_completion();
return;
}
- // The top of the list is the best match
+ // The top of the list is the best match.
completion_current = completion_options[0];
completion_enabled = true;
}
@@ -6126,10 +6426,30 @@ void TextEdit::query_code_comple() {
c--;
}
- if (ofs > 0 && (inquote || _is_completable(l[ofs - 1]) || completion_prefixes.has(String::chr(l[ofs - 1]))))
- emit_signal("request_completion");
- else if (ofs > 1 && l[ofs - 1] == ' ' && completion_prefixes.has(String::chr(l[ofs - 2]))) //make it work with a space too, it's good enough
- emit_signal("request_completion");
+ bool ignored = completion_active && !completion_options.empty();
+ if (ignored) {
+ ScriptCodeCompletionOption::Kind kind = ScriptCodeCompletionOption::KIND_PLAIN_TEXT;
+ const ScriptCodeCompletionOption *previous_option = NULL;
+ for (int i = 0; i < completion_options.size(); i++) {
+ const ScriptCodeCompletionOption &current_option = completion_options[i];
+ if (!previous_option) {
+ previous_option = &current_option;
+ kind = current_option.kind;
+ }
+ if (previous_option->kind != current_option.kind) {
+ ignored = false;
+ break;
+ }
+ }
+ ignored = ignored && (kind == ScriptCodeCompletionOption::KIND_FILE_PATH || kind == ScriptCodeCompletionOption::KIND_NODE_PATH || kind == ScriptCodeCompletionOption::KIND_SIGNAL);
+ }
+
+ if (!ignored) {
+ if (ofs > 0 && (inquote || _is_completable(l[ofs - 1]) || completion_prefixes.has(String::chr(l[ofs - 1]))))
+ emit_signal("request_completion");
+ else if (ofs > 1 && l[ofs - 1] == ' ' && completion_prefixes.has(String::chr(l[ofs - 2]))) // Make it work with a space too, it's good enough.
+ emit_signal("request_completion");
+ }
}
void TextEdit::set_code_hint(const String &p_hint) {
@@ -6230,9 +6550,21 @@ void TextEdit::set_line(int line, String new_text) {
}
void TextEdit::insert_at(const String &p_text, int at) {
- cursor_set_column(0);
- cursor_set_line(at, false, true);
_insert_text(at, 0, p_text + "\n");
+ if (cursor.line >= at) {
+ // offset cursor when located after inserted line
+ ++cursor.line;
+ }
+ if (is_selection_active()) {
+ if (selection.from_line >= at) {
+ // offset selection when located after inserted line
+ ++selection.from_line;
+ ++selection.to_line;
+ } else if (selection.to_line >= at) {
+ // extend selection that includes inserted line
+ ++selection.to_line;
+ }
+ }
}
void TextEdit::set_show_line_numbers(bool p_show) {
@@ -6324,6 +6656,24 @@ int TextEdit::get_info_gutter_width() const {
return info_gutter_width;
}
+void TextEdit::set_draw_minimap(bool p_draw) {
+ draw_minimap = p_draw;
+ update();
+}
+
+bool TextEdit::is_drawing_minimap() const {
+ return draw_minimap;
+}
+
+void TextEdit::set_minimap_width(int p_minimap_width) {
+ minimap_width = p_minimap_width;
+ update();
+}
+
+int TextEdit::get_minimap_width() const {
+ return minimap_width;
+}
+
void TextEdit::set_hiding_enabled(bool p_enabled) {
if (!p_enabled)
unhide_all_lines();
@@ -6453,8 +6803,6 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_wrap_enabled", "enable"), &TextEdit::set_wrap_enabled);
ClassDB::bind_method(D_METHOD("is_wrap_enabled"), &TextEdit::is_wrap_enabled);
- // ClassDB::bind_method(D_METHOD("set_max_chars", "amount"), &TextEdit::set_max_chars);
- // ClassDB::bind_method(D_METHOD("get_max_char"), &TextEdit::get_max_chars);
ClassDB::bind_method(D_METHOD("set_context_menu_enabled", "enable"), &TextEdit::set_context_menu_enabled);
ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &TextEdit::is_context_menu_enabled);
@@ -6530,6 +6878,11 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_breakpoints"), &TextEdit::get_breakpoints_array);
ClassDB::bind_method(D_METHOD("remove_breakpoints"), &TextEdit::remove_breakpoints);
+ ClassDB::bind_method(D_METHOD("draw_minimap", "draw"), &TextEdit::set_draw_minimap);
+ ClassDB::bind_method(D_METHOD("is_drawing_minimap"), &TextEdit::is_drawing_minimap);
+ ClassDB::bind_method(D_METHOD("set_minimap_width", "width"), &TextEdit::set_minimap_width);
+ ClassDB::bind_method(D_METHOD("get_minimap_width"), &TextEdit::get_minimap_width);
+
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT), "set_text", "get_text");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "readonly"), "set_readonly", "is_readonly");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "highlight_current_line"), "set_highlight_current_line", "is_highlight_current_line_enabled");
@@ -6546,7 +6899,10 @@ void TextEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::REAL, "v_scroll_speed"), "set_v_scroll_speed", "get_v_scroll_speed");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "hiding_enabled"), "set_hiding_enabled", "is_hiding_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "wrap_enabled"), "set_wrap_enabled", "is_wrap_enabled");
- // ADD_PROPERTY(PropertyInfo(Variant::BOOL, "max_chars"), "set_max_chars", "get_max_chars");
+
+ ADD_GROUP("Minimap", "minimap_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "minimap_draw"), "draw_minimap", "is_drawing_minimap");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "minimap_width"), "set_minimap_width", "get_minimap_width");
ADD_GROUP("Caret", "caret_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_block_mode"), "cursor_set_block_mode", "cursor_is_block_mode");
@@ -6571,7 +6927,7 @@ void TextEdit::_bind_methods() {
BIND_ENUM_CONSTANT(MENU_MAX);
GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec", 3);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/text_edit_idle_detect_sec", PropertyInfo(Variant::REAL, "gui/timers/text_edit_idle_detect_sec", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater")); // No negative numbers
+ ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/text_edit_idle_detect_sec", PropertyInfo(Variant::REAL, "gui/timers/text_edit_idle_detect_sec", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater")); // No negative numbers.
}
TextEdit::TextEdit() {
@@ -6684,13 +7040,23 @@ TextEdit::TextEdit() {
select_identifiers_enabled = false;
smooth_scroll_enabled = false;
scrolling = false;
+ minimap_clicked = false;
+ dragging_minimap = false;
+ can_drag_minimap = false;
+ minimap_scroll_ratio = 0;
+ minimap_scroll_click_pos = 0;
+ dragging_selection = false;
target_v_scroll = 0;
v_scroll_speed = 80;
+ draw_minimap = false;
+ minimap_width = 80;
+ minimap_char_size = Point2(1, 2);
+ minimap_line_spacing = 1;
context_menu_enabled = true;
menu = memnew(PopupMenu);
add_child(menu);
- readonly = true; // initialise to opposite first, so we get past the early-out in set_readonly
+ readonly = true; // Initialise to opposite first, so we get past the early-out in set_readonly.
set_readonly(false);
menu->connect("id_pressed", this, "menu_option");
first_draw = true;
@@ -6704,8 +7070,14 @@ TextEdit::~TextEdit() {
///////////////////////////////////////////////////////////////////////////////
Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int p_line) {
+ if (syntax_highlighting_cache.has(p_line)) {
+ return syntax_highlighting_cache[p_line];
+ }
+
if (syntax_highlighter != NULL) {
- return syntax_highlighter->_get_line_syntax_highlighting(p_line);
+ Map<int, HighlighterInfo> color_map = syntax_highlighter->_get_line_syntax_highlighting(p_line);
+ syntax_highlighting_cache[p_line] = color_map;
+ return color_map;
}
Map<int, HighlighterInfo> color_map;
@@ -6751,14 +7123,14 @@ Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int
bool is_symbol = _is_symbol(str[j]);
bool is_number = _is_number(str[j]);
- // allow ABCDEF in hex notation
+ // Allow ABCDEF in hex notation.
if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {
is_number = true;
} else {
is_hex_notation = false;
}
- // check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation
+ // Check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation.
if ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'f' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
is_number = true;
is_symbol = false;
@@ -6788,7 +7160,7 @@ Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int
if (!cri.end) {
in_region = cri.region;
}
- } else if (in_region == cri.region && !color_regions[cri.region].line_only) { //ignore otherwise
+ } else if (in_region == cri.region && !color_regions[cri.region].line_only) { // Ignore otherwise.
if (cri.end || color_regions[cri.region].eq) {
deregion = color_regions[cri.region].eq ? color_regions[cri.region].begin_key.length() : color_regions[cri.region].end_key.length();
}
@@ -6816,7 +7188,7 @@ Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int
if (col) {
for (int k = j - 1; k >= 0; k--) {
if (str[k] == '.') {
- col = NULL; //member indexing not allowed
+ col = NULL; // Member indexing not allowed.
break;
} else if (str[k] > 32) {
break;
@@ -6838,7 +7210,7 @@ Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int
k++;
}
- // check for space between name and bracket
+ // Check for space between name and bracket.
while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
k++;
}
@@ -6887,6 +7259,7 @@ Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int
}
}
+ syntax_highlighting_cache[p_line] = color_map;
return color_map;
}
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index b47dac0902..9c568acd93 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -211,9 +211,11 @@ private:
int breakpoint_gutter_width;
int fold_gutter_width;
int info_gutter_width;
+ int minimap_width;
} cache;
Map<int, int> color_region_cache;
+ Map<int, Map<int, HighlighterInfo> > syntax_highlighting_cache;
struct TextOperation {
@@ -313,6 +315,10 @@ private:
bool hiding_enabled;
bool draw_info_gutter;
int info_gutter_width;
+ bool draw_minimap;
+ int minimap_width;
+ Point2 minimap_char_size;
+ int minimap_line_spacing;
bool highlight_all_occurrences;
bool scroll_past_end_of_file_enabled;
@@ -326,6 +332,12 @@ private:
bool smooth_scroll_enabled;
bool scrolling;
+ bool dragging_selection;
+ bool dragging_minimap;
+ bool can_drag_minimap;
+ bool minimap_clicked;
+ double minimap_scroll_ratio;
+ double minimap_scroll_click_pos;
float target_v_scroll;
float v_scroll_speed;
@@ -360,6 +372,8 @@ private:
int get_visible_rows() const;
int get_total_visible_rows() const;
+ int _get_minimap_visible_rows() const;
+
void update_cursor_wrap_offset();
void _update_wrap_at();
bool line_wraps(int line) const;
@@ -395,6 +409,8 @@ private:
void _update_selection_mode_word();
void _update_selection_mode_line();
+ void _update_minimap_click();
+ void _update_minimap_drag();
void _scroll_up(real_t p_delta);
void _scroll_down(real_t p_delta);
@@ -406,6 +422,7 @@ private:
//void mouse_motion(const Point& p_pos, const Point& p_rel, int p_button_mask);
Size2 get_minimum_size() const;
+ int _get_control_height() const;
int get_row_height() const;
@@ -484,6 +501,7 @@ public:
virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const;
void _get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) const;
+ void _get_minimap_mouse_row(const Point2i &p_mouse, int &r_row) const;
//void delete_char();
//void delete_line();
@@ -697,6 +715,12 @@ public:
void set_info_gutter_width(int p_gutter_width);
int get_info_gutter_width() const;
+ void set_draw_minimap(bool p_draw);
+ bool is_drawing_minimap() const;
+
+ void set_minimap_width(int p_minimap_width);
+ int get_minimap_width() const;
+
void set_hiding_enabled(bool p_enabled);
bool is_hiding_enabled() const;
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index 6c8aa35e3c..b7451faad3 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -224,14 +224,14 @@ Rect2 TreeItem::get_icon_region(int p_column) const {
return cells[p_column].icon_region;
}
-void TreeItem::set_icon_color(int p_column, const Color &p_icon_color) {
+void TreeItem::set_icon_modulate(int p_column, const Color &p_modulate) {
ERR_FAIL_INDEX(p_column, cells.size());
- cells.write[p_column].icon_color = p_icon_color;
+ cells.write[p_column].icon_color = p_modulate;
_changed_notify(p_column);
}
-Color TreeItem::get_icon_color(int p_column) const {
+Color TreeItem::get_icon_modulate(int p_column) const {
ERR_FAIL_INDEX_V(p_column, cells.size(), Color());
return cells[p_column].icon_color;
@@ -744,6 +744,9 @@ void TreeItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_icon_max_width", "column", "width"), &TreeItem::set_icon_max_width);
ClassDB::bind_method(D_METHOD("get_icon_max_width", "column"), &TreeItem::get_icon_max_width);
+ ClassDB::bind_method(D_METHOD("set_icon_modulate", "column", "modulate"), &TreeItem::set_icon_modulate);
+ ClassDB::bind_method(D_METHOD("get_icon_modulate", "column"), &TreeItem::get_icon_modulate);
+
ClassDB::bind_method(D_METHOD("set_range", "column", "value"), &TreeItem::set_range);
ClassDB::bind_method(D_METHOD("get_range", "column"), &TreeItem::get_range);
ClassDB::bind_method(D_METHOD("set_range_config", "column", "min", "max", "step", "expr"), &TreeItem::set_range_config, DEFVAL(false));
@@ -1259,10 +1262,9 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
check_ofs.y += Math::floor((real_t)(item_rect.size.y - checked->get_height()) / 2);
if (p_item->cells[i].checked) {
-
- checked->draw(ci, check_ofs, icon_col);
+ checked->draw(ci, check_ofs);
} else {
- unchecked->draw(ci, check_ofs, icon_col);
+ unchecked->draw(ci, check_ofs);
}
int check_w = checked->get_width() + cache.hseparation;
@@ -1274,8 +1276,6 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
draw_item_rect(p_item->cells[i], item_rect, col, icon_col);
- //font->draw( ci, text_pos, p_item->cells[i].text, col,item_rect.size.x-check_w );
-
} break;
case TreeItem::CELL_MODE_RANGE: {
if (p_item->cells[i].text != "") {
@@ -1305,18 +1305,16 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
font->draw(ci, text_pos, s, col, item_rect.size.x - downarrow->get_width());
- //?
Point2i arrow_pos = item_rect.position;
arrow_pos.x += item_rect.size.x - downarrow->get_width();
arrow_pos.y += Math::floor(((item_rect.size.y - downarrow->get_height())) / 2.0);
- downarrow->draw(ci, arrow_pos, icon_col);
+ downarrow->draw(ci, arrow_pos);
} else {
Ref<Texture> updown = cache.updown;
String valtext = String::num(p_item->cells[i].val, Math::range_step_decimals(p_item->cells[i].step));
- //String valtext = rtos( p_item->cells[i].val );
if (p_item->cells[i].suffix != String())
valtext += " " + p_item->cells[i].suffix;
@@ -1330,7 +1328,7 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
updown_pos.x += item_rect.size.x - updown->get_width();
updown_pos.y += Math::floor(((item_rect.size.y - updown->get_height())) / 2.0);
- updown->draw(ci, updown_pos, icon_col);
+ updown->draw(ci, updown_pos);
}
} break;
@@ -1348,13 +1346,10 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
icon_ofs += item_rect.position;
draw_texture_rect(p_item->cells[i].icon, Rect2(icon_ofs, icon_size), false, icon_col);
- //p_item->cells[i].icon->draw(ci, icon_ofs);
} break;
case TreeItem::CELL_MODE_CUSTOM: {
- //int option = (int)p_item->cells[i].val;
-
if (p_item->cells[i].custom_draw_obj) {
Object *cdo = ObjectDB::get_instance(p_item->cells[i].custom_draw_obj);
@@ -1429,10 +1424,6 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
arrow->draw(ci, p_pos + p_draw_ofs + Point2i(0, (label_h - arrow->get_height()) / 2) - cache.offset);
}
- //separator
- //get_painter()->draw_fill_rect( Point2i(0,pos.y),Size2i(get_size().width,1),color( COLOR_TREE_GRID) );
-
- //pos=p_pos; //reset pos
}
Point2 children_pos = p_pos;
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index b57923e24b..fdc6da5055 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -193,8 +193,8 @@ public:
void set_icon_region(int p_column, const Rect2 &p_icon_region);
Rect2 get_icon_region(int p_column) const;
- void set_icon_color(int p_column, const Color &p_icon_color);
- Color get_icon_color(int p_column) const;
+ void set_icon_modulate(int p_column, const Color &p_modulate);
+ Color get_icon_modulate(int p_column) const;
void set_icon_max_width(int p_column, int p_max);
int get_icon_max_width(int p_column) const;
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 0aaba5491a..0b3a193d18 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -1716,14 +1716,17 @@ void Node::get_groups(List<GroupInfo> *p_groups) const {
}
}
-bool Node::has_persistent_groups() const {
+int Node::get_persistent_group_count() const {
+
+ int count = 0;
for (const Map<StringName, GroupData>::Element *E = data.grouped.front(); E; E = E->next()) {
- if (E->get().persistent)
- return true;
+ if (E->get().persistent) {
+ count += 1;
+ }
}
- return false;
+ return count;
}
void Node::_print_tree_pretty(const String &prefix, const bool last) {
diff --git a/scene/main/node.h b/scene/main/node.h
index 982bfcd620..67b40f6dfc 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -300,7 +300,7 @@ public:
};
void get_groups(List<GroupInfo> *p_groups) const;
- bool has_persistent_groups() const;
+ int get_persistent_group_count() const;
void move_child(Node *p_child, int p_pos);
void raise();
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 98d63650d3..617a703855 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -1673,6 +1673,12 @@ void SceneTree::drop_files(const Vector<String> &p_files, int p_from_screen) {
MainLoop::drop_files(p_files, p_from_screen);
}
+void SceneTree::global_menu_action(const Variant &p_id, const Variant &p_meta) {
+
+ emit_signal("global_menu_action", p_id, p_meta);
+ MainLoop::global_menu_action(p_id, p_meta);
+}
+
Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pause) {
Ref<SceneTreeTimer> stt;
@@ -1894,6 +1900,7 @@ void SceneTree::_bind_methods() {
ADD_SIGNAL(MethodInfo("physics_frame"));
ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen")));
+ ADD_SIGNAL(MethodInfo("global_menu_action", PropertyInfo(Variant::NIL, "id"), PropertyInfo(Variant::NIL, "meta")));
ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
ADD_SIGNAL(MethodInfo("connected_to_server"));
diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h
index afb653e242..42a87545a6 100644
--- a/scene/main/scene_tree.h
+++ b/scene/main/scene_tree.h
@@ -407,6 +407,7 @@ public:
static SceneTree *get_singleton() { return singleton; }
void drop_files(const Vector<String> &p_files, int p_from_screen = 0);
+ void global_menu_action(const Variant &p_id, const Variant &p_meta);
//network API
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index 6c858e9d9a..06d84302a3 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -304,6 +304,7 @@ void register_scene_types() {
ClassDB::register_class<TextureRect>();
ClassDB::register_class<ColorRect>();
ClassDB::register_class<NinePatchRect>();
+ ClassDB::register_class<ReferenceRect>();
ClassDB::register_class<TabContainer>();
ClassDB::register_class<Tabs>();
ClassDB::register_virtual_class<Separator>();
@@ -339,7 +340,6 @@ void register_scene_types() {
ClassDB::register_virtual_class<TreeItem>();
ClassDB::register_class<OptionButton>();
ClassDB::register_class<SpinBox>();
- ClassDB::register_class<ReferenceRect>();
ClassDB::register_class<ColorPicker>();
ClassDB::register_class<ColorPickerButton>();
ClassDB::register_class<RichTextLabel>();
@@ -530,6 +530,7 @@ void register_scene_types() {
ClassDB::register_class<VisualShaderNodeSwitch>();
ClassDB::register_class<VisualShaderNodeFresnel>();
ClassDB::register_class<VisualShaderNodeExpression>();
+ ClassDB::register_class<VisualShaderNodeGlobalExpression>();
ClassDB::register_class<VisualShaderNodeIs>();
ClassDB::register_class<VisualShaderNodeCompare>();
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index 8c8552ac54..985b38f913 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -2870,9 +2870,9 @@ bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0, cons
const Vector3 &v1 = t1.value.loc;
const Vector3 &v2 = t2.value.loc;
- if (Math::is_zero_approx(v0.distance_to(v2))) {
+ if (v0 == v2) {
//0 and 2 are close, let's see if 1 is close
- if (!Math::is_zero_approx(v0.distance_to(v1))) {
+ if (v0 != v1) {
//not close, not optimizable
return false;
}
@@ -2959,9 +2959,9 @@ bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0, cons
const Vector3 &v1 = t1.value.scale;
const Vector3 &v2 = t2.value.scale;
- if (Math::is_zero_approx(v0.distance_to(v2))) {
+ if (v0 == v2) {
//0 and 2 are close, let's see if 1 is close
- if (!Math::is_zero_approx(v0.distance_to(v1))) {
+ if (v0 != v1) {
//not close, not optimizable
return false;
}
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index fb0fb4f8e3..1a5f57ce48 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -760,6 +760,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
// FileDialog
theme->set_icon("folder", "FileDialog", make_icon(icon_folder_png));
+ theme->set_color("folder_icon_modulate", "FileDialog", Color(1, 1, 1));
theme->set_color("files_disabled", "FileDialog", Color(0, 0, 0, 0.7));
// colorPicker
@@ -892,8 +893,9 @@ void make_default_theme(bool p_hidpi, Ref<Font> p_font) {
void clear_default_theme() {
- Theme::set_default(Ref<Theme>());
- Theme::set_default_icon(Ref<Texture>());
- Theme::set_default_style(Ref<StyleBox>());
- Theme::set_default_font(Ref<Font>());
+ Theme::set_project_default(NULL);
+ Theme::set_default(NULL);
+ Theme::set_default_icon(NULL);
+ Theme::set_default_style(NULL);
+ Theme::set_default_font(NULL);
}
diff --git a/scene/resources/dynamic_font.cpp b/scene/resources/dynamic_font.cpp
index df8d4a7fed..2364a4a8a3 100644
--- a/scene/resources/dynamic_font.cpp
+++ b/scene/resources/dynamic_font.cpp
@@ -193,14 +193,6 @@ Error DynamicFontAtSize::_load() {
ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);
- /*error = FT_Set_Char_Size(face,0,64*size,512,512);
-
- if ( error ) {
- FT_Done_FreeType( library );
- ERR_EXPLAIN(TTR("Invalid font size."));
- ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
- }*/
-
if (FT_HAS_COLOR(face)) {
int best_match = 0;
int diff = ABS(id.size - ((int64_t)face->available_sizes[0].width));
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index 389011c095..699410719c 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -612,6 +612,25 @@ String VisualShader::generate_preview_shader(Type p_type, int p_node, int p_port
global_code += String() + "shader_type canvas_item;\n";
+ String global_expressions;
+ for (int i = 0, index = 0; i < TYPE_MAX; i++) {
+ for (Map<int, Node>::Element *E = graph[i].nodes.front(); E; E = E->next()) {
+ Ref<VisualShaderNodeGlobalExpression> global_expression = Object::cast_to<VisualShaderNodeGlobalExpression>(E->get().node.ptr());
+ if (global_expression.is_valid()) {
+
+ String expr = "";
+ expr += "// " + global_expression->get_caption() + ":" + itos(index++) + "\n";
+ expr += global_expression->generate_global(get_mode(), Type(i), -1);
+ expr = expr.replace("\n", "\n\t");
+ expr += "\n";
+ global_expressions += expr;
+ }
+ }
+ }
+
+ global_code += "\n";
+ global_code += global_expressions;
+
//make it faster to go around through shader
VMap<ConnectionKey, const List<Connection>::Element *> input_connections;
VMap<ConnectionKey, const List<Connection>::Element *> output_connections;
@@ -1205,6 +1224,22 @@ void VisualShader::_update_shader() const {
static const char *func_name[TYPE_MAX] = { "vertex", "fragment", "light" };
+ String global_expressions;
+ for (int i = 0, index = 0; i < TYPE_MAX; i++) {
+ for (Map<int, Node>::Element *E = graph[i].nodes.front(); E; E = E->next()) {
+ Ref<VisualShaderNodeGlobalExpression> global_expression = Object::cast_to<VisualShaderNodeGlobalExpression>(E->get().node.ptr());
+ if (global_expression.is_valid()) {
+
+ String expr = "";
+ expr += "// " + global_expression->get_caption() + ":" + itos(index++) + "\n";
+ expr += global_expression->generate_global(get_mode(), Type(i), -1);
+ expr = expr.replace("\n", "\n\t");
+ expr += "\n";
+ global_expressions += expr;
+ }
+ }
+ }
+
for (int i = 0; i < TYPE_MAX; i++) {
//make it faster to go around through shader
@@ -1239,6 +1274,7 @@ void VisualShader::_update_shader() const {
global_code += "\n\n";
String final_code = global_code;
final_code += global_code_per_node;
+ final_code += global_expressions;
String tcode = code;
for (int i = 0; i < TYPE_MAX; i++) {
tcode = tcode.insert(insertion_pos[i], global_code_per_func[Type(i)]);
@@ -1249,6 +1285,10 @@ void VisualShader::_update_shader() const {
for (int i = 0; i < default_tex_params.size(); i++) {
const_cast<VisualShader *>(this)->set_default_texture_param(default_tex_params[i].name, default_tex_params[i].param);
}
+ if (previous_code != final_code) {
+ const_cast<VisualShader *>(this)->emit_signal("changed");
+ }
+ previous_code = final_code;
}
void VisualShader::_queue_update() {
@@ -2333,6 +2373,14 @@ void VisualShaderNodeGroupBase::_apply_port_changes() {
}
}
+void VisualShaderNodeGroupBase::set_editable(bool p_enabled) {
+ editable = p_enabled;
+}
+
+bool VisualShaderNodeGroupBase::is_editable() const {
+ return editable;
+}
+
void VisualShaderNodeGroupBase::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_size", "size"), &VisualShaderNodeGroupBase::set_size);
@@ -2368,6 +2416,11 @@ void VisualShaderNodeGroupBase::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_control", "control", "index"), &VisualShaderNodeGroupBase::set_control);
ClassDB::bind_method(D_METHOD("get_control", "index"), &VisualShaderNodeGroupBase::get_control);
+
+ ClassDB::bind_method(D_METHOD("set_editable", "enabled"), &VisualShaderNodeGroupBase::set_editable);
+ ClassDB::bind_method(D_METHOD("is_editable"), &VisualShaderNodeGroupBase::is_editable);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
}
String VisualShaderNodeGroupBase::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
@@ -2378,6 +2431,7 @@ VisualShaderNodeGroupBase::VisualShaderNodeGroupBase() {
size = Size2(0, 0);
inputs = "";
outputs = "";
+ editable = false;
}
////////////// Expression
@@ -2504,4 +2558,19 @@ void VisualShaderNodeExpression::_bind_methods() {
VisualShaderNodeExpression::VisualShaderNodeExpression() {
expression = "";
+ set_editable(true);
+}
+
+////////////// Global Expression
+
+String VisualShaderNodeGlobalExpression::get_caption() const {
+ return "GlobalExpression";
+}
+
+String VisualShaderNodeGlobalExpression::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+ return expression;
+}
+
+VisualShaderNodeGlobalExpression::VisualShaderNodeGlobalExpression() {
+ set_editable(false);
}
diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h
index a89e3295fc..45beb8e6ca 100644
--- a/scene/resources/visual_shader.h
+++ b/scene/resources/visual_shader.h
@@ -73,6 +73,7 @@ private:
} graph[TYPE_MAX];
Shader::Mode shader_mode;
+ mutable String previous_code;
Array _get_node_connections(Type p_type) const;
@@ -371,6 +372,7 @@ protected:
Vector2 size;
String inputs;
String outputs;
+ bool editable;
struct Port {
PortType type;
@@ -426,6 +428,9 @@ public:
void set_control(Control *p_control, int p_index);
Control *get_control(int p_index);
+ void set_editable(bool p_enabled);
+ bool is_editable() const;
+
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const;
VisualShaderNodeGroupBase();
@@ -434,10 +439,9 @@ public:
class VisualShaderNodeExpression : public VisualShaderNodeGroupBase {
GDCLASS(VisualShaderNodeExpression, VisualShaderNodeGroupBase);
-private:
+protected:
String expression;
-protected:
static void _bind_methods();
public:
@@ -453,4 +457,15 @@ public:
VisualShaderNodeExpression();
};
+class VisualShaderNodeGlobalExpression : public VisualShaderNodeExpression {
+ GDCLASS(VisualShaderNodeGlobalExpression, VisualShaderNodeExpression);
+
+public:
+ virtual String get_caption() const;
+
+ virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const;
+
+ VisualShaderNodeGlobalExpression();
+};
+
#endif // VISUAL_SHADER_H
diff --git a/servers/arvr/arvr_interface.h b/servers/arvr/arvr_interface.h
index ffafa4fcf5..85556b2757 100644
--- a/servers/arvr/arvr_interface.h
+++ b/servers/arvr/arvr_interface.h
@@ -39,7 +39,7 @@
/**
@author Bastiaan Olij <mux213@gmail.com>
- The ARVR interface is a template class ontop of which we build interface to differt AR, VR and tracking SDKs.
+ The ARVR interface is a template class ontop of which we build interface to different AR, VR and tracking SDKs.
The idea is that we subclass this class, implement the logic, and then instantiate a singleton of each interface
when Godot starts. These instances do not initialize themselves but register themselves with the AR/VR server.
diff --git a/servers/physics/body_sw.cpp b/servers/physics/body_sw.cpp
index 172a2a3429..a3bb581cb5 100644
--- a/servers/physics/body_sw.cpp
+++ b/servers/physics/body_sw.cpp
@@ -266,6 +266,7 @@ void BodySW::set_mode(PhysicsServer::BodyMode p_mode) {
_inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
+ angular_velocity = Vector3();
} break;
}
diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp
index b9ebd30021..6ba159ca0a 100644
--- a/servers/physics_2d/body_2d_sw.cpp
+++ b/servers/physics_2d/body_2d_sw.cpp
@@ -47,8 +47,10 @@ void Body2DSW::update_inertias() {
case Physics2DServer::BODY_MODE_RIGID: {
- if (user_inertia) break;
-
+ if (user_inertia) {
+ _inv_inertia = inertia > 0 ? (1.0 / inertia) : 0;
+ break;
+ }
//update tensor for allshapes, not the best way but should be somehow OK. (inspired from bullet)
real_t total_area = 0;
@@ -57,7 +59,7 @@ void Body2DSW::update_inertias() {
total_area += get_shape_aabb(i).get_area();
}
- real_t _inertia = 0;
+ inertia = 0;
for (int i = 0; i < get_shape_count(); i++) {
@@ -73,15 +75,10 @@ void Body2DSW::update_inertias() {
Transform2D mtx = get_shape_transform(i);
Vector2 scale = mtx.get_scale();
- _inertia += shape->get_moment_of_inertia(mass, scale) + mass * mtx.get_origin().length_squared();
- //Rect2 ab = get_shape_aabb(i);
- //_inertia+=mass*ab.size.dot(ab.size)/12.0f;
+ inertia += shape->get_moment_of_inertia(mass, scale) + mass * mtx.get_origin().length_squared();
}
- if (_inertia != 0)
- _inv_inertia = 1.0 / _inertia;
- else
- _inv_inertia = 0.0; //wathever
+ _inv_inertia = inertia > 0 ? (1.0 / inertia) : 0;
if (mass)
_inv_mass = 1.0 / mass;
@@ -160,6 +157,7 @@ void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value)
_update_inertia();
} else {
user_inertia = true;
+ inertia = p_value;
_inv_inertia = 1.0 / p_value;
}
} break;
@@ -194,7 +192,7 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
return mass;
}
case Physics2DServer::BODY_PARAM_INERTIA: {
- return _inv_inertia == 0 ? 0 : 1.0 / _inv_inertia;
+ return inertia;
}
case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: {
return gravity_scale;
@@ -226,6 +224,7 @@ void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) {
_set_inv_transform(get_transform().affine_inverse());
_inv_mass = 0;
+ _inv_inertia = 0;
_set_static(p_mode == Physics2DServer::BODY_MODE_STATIC);
set_active(p_mode == Physics2DServer::BODY_MODE_KINEMATIC && contacts.size());
linear_velocity = Vector2();
@@ -237,17 +236,21 @@ void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) {
case Physics2DServer::BODY_MODE_RIGID: {
_inv_mass = mass > 0 ? (1.0 / mass) : 0;
+ _inv_inertia = inertia > 0 ? (1.0 / inertia) : 0;
_set_static(false);
} break;
case Physics2DServer::BODY_MODE_CHARACTER: {
_inv_mass = mass > 0 ? (1.0 / mass) : 0;
+ _inv_inertia = 0;
_set_static(false);
+ angular_velocity = 0;
} break;
}
-
- _update_inertia();
+ if (p_mode == Physics2DServer::BODY_MODE_RIGID && _inv_inertia == 0) {
+ _update_inertia();
+ }
/*
if (get_space())
_update_queries();
@@ -668,6 +671,7 @@ Body2DSW::Body2DSW() :
angular_velocity = 0;
biased_angular_velocity = 0;
mass = 1;
+ inertia = 0;
user_inertia = false;
_inv_inertia = 0;
_inv_mass = 1;
diff --git a/servers/physics_2d/body_2d_sw.h b/servers/physics_2d/body_2d_sw.h
index 8c64dc9230..5df184c894 100644
--- a/servers/physics_2d/body_2d_sw.h
+++ b/servers/physics_2d/body_2d_sw.h
@@ -52,6 +52,7 @@ class Body2DSW : public CollisionObject2DSW {
real_t gravity_scale;
real_t mass;
+ real_t inertia;
real_t bounce;
real_t friction;
diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp
index 1dd6699851..e9d85c7eb0 100644
--- a/servers/visual/shader_language.cpp
+++ b/servers/visual/shader_language.cpp
@@ -283,6 +283,7 @@ const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[] = {
{ TK_CF_DO, "do" },
{ TK_CF_SWITCH, "switch" },
{ TK_CF_CASE, "case" },
+ { TK_CF_DEFAULT, "default" },
{ TK_CF_BREAK, "break" },
{ TK_CF_CONTINUE, "continue" },
{ TK_CF_RETURN, "return" },
@@ -3778,6 +3779,14 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, Bui
TkPos pos = _get_tkpos();
Token tk = _get_token();
+
+ if (p_block && p_block->block_type == BlockNode::BLOCK_TYPE_SWITCH) {
+ if (tk.type != TK_CF_CASE && tk.type != TK_CF_DEFAULT && tk.type != TK_CURLY_BRACKET_CLOSE) {
+ _set_error("Switch may contains only case and default blocks");
+ return ERR_PARSE_ERROR;
+ }
+ }
+
if (tk.type == TK_CURLY_BRACKET_CLOSE) { //end of block
if (p_just_one) {
_set_error("Unexpected '}'");
@@ -4132,6 +4141,183 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, Bui
} else {
_set_tkpos(pos); //rollback
}
+ } else if (tk.type == TK_CF_SWITCH) {
+ // switch() {}
+ tk = _get_token();
+ if (tk.type != TK_PARENTHESIS_OPEN) {
+ _set_error("Expected '(' after switch");
+ return ERR_PARSE_ERROR;
+ }
+ ControlFlowNode *cf = alloc_node<ControlFlowNode>();
+ cf->flow_op = FLOW_OP_SWITCH;
+ Node *n = _parse_and_reduce_expression(p_block, p_builtin_types);
+ if (!n)
+ return ERR_PARSE_ERROR;
+ if (n->get_datatype() != TYPE_INT) {
+ _set_error("Expected integer expression");
+ return ERR_PARSE_ERROR;
+ }
+ tk = _get_token();
+ if (tk.type != TK_PARENTHESIS_CLOSE) {
+ _set_error("Expected ')' after expression");
+ return ERR_PARSE_ERROR;
+ }
+ tk = _get_token();
+ if (tk.type != TK_CURLY_BRACKET_OPEN) {
+ _set_error("Expected '{' after switch statement");
+ return ERR_PARSE_ERROR;
+ }
+ BlockNode *switch_block = alloc_node<BlockNode>();
+ switch_block->block_type = BlockNode::BLOCK_TYPE_SWITCH;
+ switch_block->parent_block = p_block;
+ cf->expressions.push_back(n);
+ cf->blocks.push_back(switch_block);
+ p_block->statements.push_back(cf);
+
+ int prev_type = TK_CF_CASE;
+ while (true) { // Go-through multiple cases.
+
+ if (_parse_block(switch_block, p_builtin_types, true, true, false) != OK) {
+ return ERR_PARSE_ERROR;
+ }
+ pos = _get_tkpos();
+ tk = _get_token();
+ if (tk.type == TK_CF_CASE || tk.type == TK_CF_DEFAULT) {
+ if (prev_type == TK_CF_DEFAULT) {
+ if (tk.type == TK_CF_CASE) {
+ _set_error("Cases must be defined before default case.");
+ return ERR_PARSE_ERROR;
+ } else if (prev_type == TK_CF_DEFAULT) {
+ _set_error("Default case must be defined only once.");
+ return ERR_PARSE_ERROR;
+ }
+ }
+ prev_type = tk.type;
+ _set_tkpos(pos);
+ continue;
+ } else {
+ Set<int> constants;
+ for (int i = 0; i < switch_block->statements.size(); i++) { // Checks for duplicates.
+ ControlFlowNode *flow = (ControlFlowNode *)switch_block->statements[i];
+ if (flow) {
+ if (flow->flow_op == FLOW_OP_CASE) {
+ ConstantNode *n2 = static_cast<ConstantNode *>(flow->expressions[0]);
+ if (!n2) {
+ return ERR_PARSE_ERROR;
+ }
+ if (n2->values.empty()) {
+ return ERR_PARSE_ERROR;
+ }
+ if (constants.has(n2->values[0].sint)) {
+ _set_error("Duplicated case label: '" + itos(n2->values[0].sint) + "'");
+ return ERR_PARSE_ERROR;
+ }
+ constants.insert(n2->values[0].sint);
+ } else if (flow->flow_op == FLOW_OP_DEFAULT) {
+ continue;
+ } else {
+ return ERR_PARSE_ERROR;
+ }
+ } else {
+ return ERR_PARSE_ERROR;
+ }
+ }
+ break;
+ }
+ }
+
+ } else if (tk.type == TK_CF_CASE) {
+ // case x : break; | return;
+
+ if (p_block && p_block->block_type == BlockNode::BLOCK_TYPE_CASE) {
+ _set_tkpos(pos);
+ return OK;
+ }
+
+ if (!p_block || (p_block->block_type != BlockNode::BLOCK_TYPE_SWITCH)) {
+ _set_error("case must be placed within switch block");
+ return ERR_PARSE_ERROR;
+ }
+
+ tk = _get_token();
+
+ int sign = 1;
+
+ if (tk.type == TK_OP_SUB) {
+ sign = -1;
+ tk = _get_token();
+ }
+
+ if (tk.type != TK_INT_CONSTANT) {
+ _set_error("Expected integer constant");
+ return ERR_PARSE_ERROR;
+ }
+
+ int constant = (int)tk.constant * sign;
+
+ tk = _get_token();
+
+ if (tk.type != TK_COLON) {
+ _set_error("Expected ':'");
+ return ERR_PARSE_ERROR;
+ }
+
+ ControlFlowNode *cf = alloc_node<ControlFlowNode>();
+ cf->flow_op = FLOW_OP_CASE;
+
+ ConstantNode *n = alloc_node<ConstantNode>();
+ ConstantNode::Value v;
+ v.sint = constant;
+ n->values.push_back(v);
+ n->datatype = TYPE_INT;
+
+ BlockNode *case_block = alloc_node<BlockNode>();
+ case_block->block_type = BlockNode::BLOCK_TYPE_CASE;
+ case_block->parent_block = p_block;
+ cf->expressions.push_back(n);
+ cf->blocks.push_back(case_block);
+ p_block->statements.push_back(cf);
+
+ Error err = _parse_block(case_block, p_builtin_types, false, true, false);
+ if (err)
+ return err;
+
+ return OK;
+
+ } else if (tk.type == TK_CF_DEFAULT) {
+
+ if (p_block && p_block->block_type == BlockNode::BLOCK_TYPE_CASE) {
+ _set_tkpos(pos);
+ return OK;
+ }
+
+ if (!p_block || (p_block->block_type != BlockNode::BLOCK_TYPE_SWITCH)) {
+ _set_error("default must be placed within switch block");
+ return ERR_PARSE_ERROR;
+ }
+
+ tk = _get_token();
+
+ if (tk.type != TK_COLON) {
+ _set_error("Expected ':'");
+ return ERR_PARSE_ERROR;
+ }
+
+ ControlFlowNode *cf = alloc_node<ControlFlowNode>();
+ cf->flow_op = FLOW_OP_DEFAULT;
+
+ BlockNode *default_block = alloc_node<BlockNode>();
+ default_block->block_type = BlockNode::BLOCK_TYPE_DEFAULT;
+ default_block->parent_block = p_block;
+ cf->blocks.push_back(default_block);
+ p_block->statements.push_back(cf);
+
+ Error err = _parse_block(default_block, p_builtin_types, false, true, false);
+ if (err)
+ return err;
+
+ return OK;
+
} else if (tk.type == TK_CF_DO || tk.type == TK_CF_WHILE) {
// do {} while()
// while() {}
@@ -4299,6 +4485,9 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, Bui
}
p_block->statements.push_back(flow);
+ if (p_block->block_type == BlockNode::BLOCK_TYPE_CASE || p_block->block_type == BlockNode::BLOCK_TYPE_DEFAULT) {
+ return OK;
+ }
} else if (tk.type == TK_CF_DISCARD) {
//check return type
@@ -4345,9 +4534,13 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, Bui
}
p_block->statements.push_back(flow);
+ if (p_block->block_type == BlockNode::BLOCK_TYPE_CASE || p_block->block_type == BlockNode::BLOCK_TYPE_DEFAULT) {
+ return OK;
+ }
+
} else if (tk.type == TK_CF_CONTINUE) {
- if (!p_can_break) {
+ if (!p_can_continue) {
//all is good
_set_error("Continuing is not allowed here");
}
diff --git a/servers/visual/shader_language.h b/servers/visual/shader_language.h
index 36c691c3ae..b71788513e 100644
--- a/servers/visual/shader_language.h
+++ b/servers/visual/shader_language.h
@@ -125,6 +125,7 @@ public:
TK_CF_DO,
TK_CF_SWITCH,
TK_CF_CASE,
+ TK_CF_DEFAULT,
TK_CF_BREAK,
TK_CF_CONTINUE,
TK_CF_RETURN,
@@ -266,6 +267,8 @@ public:
FLOW_OP_DO,
FLOW_OP_BREAK,
FLOW_OP_SWITCH,
+ FLOW_OP_CASE,
+ FLOW_OP_DEFAULT,
FLOW_OP_CONTINUE,
FLOW_OP_DISCARD
};
@@ -420,6 +423,15 @@ public:
FunctionNode *parent_function;
BlockNode *parent_block;
+ enum BlockType {
+ BLOCK_TYPE_STANDART,
+ BLOCK_TYPE_SWITCH,
+ BLOCK_TYPE_CASE,
+ BLOCK_TYPE_DEFAULT,
+ };
+
+ int block_type;
+
struct Variable {
DataType type;
DataPrecision precision;
@@ -436,6 +448,7 @@ public:
Node(TYPE_BLOCK),
parent_function(NULL),
parent_block(NULL),
+ block_type(BLOCK_TYPE_STANDART),
single_statement(false) {}
};